提交 d66249e0 编写于 作者: Q qiang

Merge branch 'dev' of github.com:dcloudio/uni-app into dev

......@@ -7183,8 +7183,10 @@ var serviceContext = (function () {
quit();
} else if (currentPage.$page.id === 1 && __uniConfig.realEntryPagePath) {
// condition
__uniConfig.entryPagePath = __uniConfig.realEntryPagePath;
delete __uniConfig.realEntryPagePath;
uni.reLaunch({
url: '/' + __uniConfig.realEntryPagePath
url: '/' + __uniConfig.entryPagePath
});
} else {
back(delta, animationType, animationDuration);
......@@ -7890,9 +7892,9 @@ var serviceContext = (function () {
if (
openType === 'reLaunch' ||
(
openType === 'redirect' &&
!__uniConfig.realEntryPagePath &&
pages.length === 0
) // 首页 redirect
)
) {
routeOptions.meta.isQuit = true;
} else if (!routeOptions.meta.isTabBar) {
......@@ -8018,7 +8020,15 @@ var serviceContext = (function () {
animationDuration
}, callbackId) {
const urls = url.split('?');
const path = urls[0];
const path = urls[0];
const routeStyles = __uniRoutes.find(route => route.path === path).window;
const globalStyle = __uniConfig.window;
if (!animationType) {
animationType = routeStyles.animationType || globalStyle.animationType || ANI_SHOW;
}
if (!animationDuration) {
animationDuration = routeStyles.animationDuration || globalStyle.animationDuration || ANI_DURATION;
}
const query = parseQuery(urls[1] || '');
navigate(path, function () {
_navigateTo({
......
......@@ -10,7 +10,8 @@
},
"files": [
"lib",
"template"
"template",
"components"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
......
......@@ -353,33 +353,26 @@ var baseApi = /*#__PURE__*/Object.freeze({
// 不支持的 API 列表
const todos = [
'saveImageToPhotosAlbum',
'getRecorderManager',
'getBackgroundAudioManager',
'createInnerAudioContext',
'createVideoContext',
'createCameraContext',
'createLivePlayerContext',
'openDocument',
'onMemoryWarning',
'startAccelerometer',
'startCompass',
'addPhoneContact',
'authorize',
'chooseAddress',
'chooseInvoiceTitle',
'addTemplate',
'deleteTemplate',
'getTemplateLibraryById',
'getTemplateLibraryList',
'getTemplateList',
'sendTemplateMessage',
'setEnableDebug',
'getExtConfig',
'getExtConfigSync',
'onWindowResize',
'offWindowResize',
'saveVideoToPhotosAlbum'
// 'getRecorderManager',
// 'getBackgroundAudioManager',
// 'createInnerAudioContext',
// 'createCameraContext',
// 'createLivePlayerContext',
// 'startAccelerometer',
// 'startCompass',
// 'authorize',
// 'chooseInvoiceTitle',
// 'addTemplate',
// 'deleteTemplate',
// 'getTemplateLibraryById',
// 'getTemplateLibraryList',
// 'getTemplateList',
// 'sendTemplateMessage',
// 'setEnableDebug',
// 'getExtConfig',
// 'getExtConfigSync',
// 'onWindowResize',
// 'offWindowResize'
];
// 存在兼容性的 API 列表
......@@ -398,7 +391,14 @@ const canIUses = [
'createIntersectionObserver',
'getUpdateManager',
'setBackgroundColor',
'setBackgroundTextStyle'
'setBackgroundTextStyle',
'checkIsSupportSoterAuthentication',
'startSoterAuthentication',
'checkIsSoterEnrolledInDevice',
'openDocument',
'createVideoContext',
'onMemoryWarning',
'addPhoneContact'
];
function _handleNetworkInfo (result) {
......@@ -755,6 +755,29 @@ const protocols = { // 需要做转换的 API 列表
},
hideHomeButton: {
name: 'hideBackHome'
},
saveImageToPhotosAlbum: {
name: 'saveImage',
args: {
filePath: 'url'
}
},
saveVideoToPhotosAlbum: {
args: {
filePath: 'src'
}
},
chooseAddress: {
name: 'getAddress',
returnValue (result) {
let info = result.result || {};
result.userName = info.fullname;
result.provinceName = info.prov;
result.cityName = info.city;
result.detailInfo = info.address;
result.telNumber = info.mobilePhone;
result.errMsg = result.resultStatus;
}
}
};
......@@ -1970,6 +1993,12 @@ function parsePage (vuePageOptions) {
onUnload () {
this.$vm.__call_hook('onUnload');
this.$vm.$destroy();
},
events: {
// 支付宝小程序有些页面事件只能放在events下
onBack () {
this.$vm.__call_hook('onBackPress');
}
},
__r: handleRef,
__e: handleEvent,
......
......@@ -387,37 +387,37 @@ var previewImage = {
// 不支持的 API 列表
const todos = [
'hideKeyboard',
'onGyroscopeChange',
'startGyroscope',
'stopGyroscope',
'openBluetoothAdapter',
'startBluetoothDevicesDiscovery',
'onBluetoothDeviceFound',
'stopBluetoothDevicesDiscovery',
'onBluetoothAdapterStateChange',
'getConnectedBluetoothDevices',
'getBluetoothDevices',
'getBluetoothAdapterState',
'closeBluetoothAdapter',
'writeBLECharacteristicValue',
'readBLECharacteristicValue',
'onBLEConnectionStateChange',
'onBLECharacteristicValueChange',
'notifyBLECharacteristicValueChange',
'getBLEDeviceServices',
'getBLEDeviceCharacteristics',
'createBLEConnection',
'closeBLEConnection',
'onBeaconServiceChange',
'onBeaconUpdate',
'getBeacons',
'startBeaconDiscovery',
'stopBeaconDiscovery',
'hideShareMenu',
'onWindowResize',
'offWindowResize',
'vibrate'
// 'hideKeyboard',
// 'onGyroscopeChange',
// 'startGyroscope',
// 'stopGyroscope',
// 'openBluetoothAdapter',
// 'startBluetoothDevicesDiscovery',
// 'onBluetoothDeviceFound',
// 'stopBluetoothDevicesDiscovery',
// 'onBluetoothAdapterStateChange',
// 'getConnectedBluetoothDevices',
// 'getBluetoothDevices',
// 'getBluetoothAdapterState',
// 'closeBluetoothAdapter',
// 'writeBLECharacteristicValue',
// 'readBLECharacteristicValue',
// 'onBLEConnectionStateChange',
// 'onBLECharacteristicValueChange',
// 'notifyBLECharacteristicValueChange',
// 'getBLEDeviceServices',
// 'getBLEDeviceCharacteristics',
// 'createBLEConnection',
// 'closeBLEConnection',
// 'onBeaconServiceChange',
// 'onBeaconUpdate',
// 'getBeacons',
// 'startBeaconDiscovery',
// 'stopBeaconDiscovery',
// 'hideShareMenu',
// 'onWindowResize',
// 'offWindowResize',
// 'vibrate'
];
// 存在兼容性的 API 列表
......
......@@ -389,48 +389,40 @@ const protocols = {
previewImage
};
const todos = [
'createLivePlayerContext',
'createLivePusherContext',
'loadFontFace',
'onMemoryWarning',
'onNetworkStatusChange',
'startBeaconDiscovery',
'stopBeaconDiscovery',
'getBeacons',
'onBeaconUpdate',
'onBeaconServiceChange',
'addPhoneContact',
'getHCEState',
'startHCE',
'stopHCE',
'onHCEMessage',
'sendHCEMessage',
'startWifi',
'stopWifi',
'connectWifi',
'getWifiList',
'onGetWifiList',
'setWifiList',
'onWifiConnected',
'getConnectedWifi',
'setNavigationBarColor',
'setTopBarText',
'getExtConfig',
'getExtConfigSync',
'getPhoneNumber',
'chooseAddress',
'addCard',
'openCard',
'getWeRunData',
'launchApp',
'chooseInvoiceTitle',
'checkIsSupportSoterAuthentication',
'startSoterAuthentication',
'checkIsSoterEnrolledInDevice',
'reportMonitor',
'getLogManager',
'reportAnalytics',
'vibrate'
// 'startBeaconDiscovery',
// 'stopBeaconDiscovery',
// 'getBeacons',
// 'onBeaconUpdate',
// 'onBeaconServiceChange',
// 'addPhoneContact',
// 'getHCEState',
// 'startHCE',
// 'stopHCE',
// 'onHCEMessage',
// 'sendHCEMessage',
// 'startWifi',
// 'stopWifi',
// 'connectWifi',
// 'getWifiList',
// 'onGetWifiList',
// 'setWifiList',
// 'onWifiConnected',
// 'getConnectedWifi',
// 'setTopBarText',
// 'getPhoneNumber',
// 'chooseAddress',
// 'addCard',
// 'openCard',
// 'getWeRunData',
// 'launchApp',
// 'chooseInvoiceTitle',
// 'checkIsSupportSoterAuthentication',
// 'startSoterAuthentication',
// 'checkIsSoterEnrolledInDevice',
// 'vibrate',
// 'loadFontFace',
// 'getExtConfig',
// 'getExtConfigSync'
];
const canIUses = [
'scanCode',
......@@ -455,7 +447,15 @@ const canIUses = [
'onSocketClose',
'openDocument',
'updateShareMenu',
'getShareInfo'
'getShareInfo',
'createLivePlayerContext',
'createLivePusherContext',
'setNavigationBarColor',
'onMemoryWarning',
'onNetworkStatusChange',
'reportMonitor',
'getLogManager',
'reportAnalytics'
];
const CALLBACKS = ['success', 'fail', 'cancel', 'complete'];
......
......@@ -387,65 +387,64 @@ var previewImage = {
// 不支持的 API 列表
const todos = [
'createCameraContext',
'createLivePlayerContext',
'getSavedFileInfo',
'createMapContext',
'onMemoryWarning',
'onGyroscopeChange',
'startGyroscope',
'stopGyroscope',
'setScreenBrightness',
'getScreenBrightness',
'addPhoneContact',
'openBluetoothAdapter',
'startBluetoothDevicesDiscovery',
'onBluetoothDeviceFound',
'stopBluetoothDevicesDiscovery',
'onBluetoothAdapterStateChange',
'getConnectedBluetoothDevices',
'getBluetoothDevices',
'getBluetoothAdapterState',
'closeBluetoothAdapter',
'writeBLECharacteristicValue',
'readBLECharacteristicValue',
'onBLEConnectionStateChange',
'onBLECharacteristicValueChange',
'notifyBLECharacteristicValueChange',
'getBLEDeviceServices',
'getBLEDeviceCharacteristics',
'createBLEConnection',
'closeBLEConnection',
'onBeaconServiceChange',
'onBeaconUpdate',
'getBeacons',
'startBeaconDiscovery',
'stopBeaconDiscovery',
'setNavigationBarColor',
'showNavigationBarLoading',
'hideNavigationBarLoading',
'setTabBarItem',
'setTabBarStyle',
'hideTabBar',
'showTabBar',
'setTabBarBadge',
'removeTabBarBadge',
'showTabBarRedDot',
'hideTabBarRedDot',
'setBackgroundColor',
'setBackgroundTextStyle',
'chooseInvoiceTitle',
'addTemplate',
'deleteTemplate',
'getTemplateLibraryById',
'getTemplateLibraryList',
'getTemplateList',
'sendTemplateMessage',
'setEnableDebug',
'onWindowResize',
'offWindowResize',
'createOffscreenCanvas',
'vibrate'
// 'createCameraContext',
// 'createLivePlayerContext',
// 'getSavedFileInfo',
// 'createMapContext',
// 'onMemoryWarning',
// 'onGyroscopeChange',
// 'startGyroscope',
// 'stopGyroscope',
// 'setScreenBrightness',
// 'getScreenBrightness',
// 'addPhoneContact',
// 'openBluetoothAdapter',
// 'startBluetoothDevicesDiscovery',
// 'onBluetoothDeviceFound',
// 'stopBluetoothDevicesDiscovery',
// 'onBluetoothAdapterStateChange',
// 'getConnectedBluetoothDevices',
// 'getBluetoothDevices',
// 'getBluetoothAdapterState',
// 'closeBluetoothAdapter',
// 'writeBLECharacteristicValue',
// 'readBLECharacteristicValue',
// 'onBLEConnectionStateChange',
// 'onBLECharacteristicValueChange',
// 'notifyBLECharacteristicValueChange',
// 'getBLEDeviceServices',
// 'getBLEDeviceCharacteristics',
// 'createBLEConnection',
// 'closeBLEConnection',
// 'onBeaconServiceChange',
// 'onBeaconUpdate',
// 'getBeacons',
// 'startBeaconDiscovery',
// 'stopBeaconDiscovery',
// 'showNavigationBarLoading',
// 'hideNavigationBarLoading',
// 'setTabBarItem',
// 'setTabBarStyle',
// 'hideTabBar',
// 'showTabBar',
// 'setTabBarBadge',
// 'removeTabBarBadge',
// 'showTabBarRedDot',
// 'hideTabBarRedDot',
// 'setBackgroundColor',
// 'setBackgroundTextStyle',
// 'chooseInvoiceTitle',
// 'addTemplate',
// 'deleteTemplate',
// 'getTemplateLibraryById',
// 'getTemplateLibraryList',
// 'getTemplateList',
// 'sendTemplateMessage',
// 'setEnableDebug',
// 'onWindowResize',
// 'offWindowResize',
// 'createOffscreenCanvas',
// 'vibrate'
];
// 存在兼容性的 API 列表
......@@ -472,6 +471,7 @@ const canIUses = [
// 'openDocument',
// 'onUserCaptureScreen',
// 'getBackgroundAudioManager',
// 'setNavigationBarColor',
];
// 需要做转换的 API 列表
......@@ -538,9 +538,9 @@ const protocols = {
}
},
requestPayment: {
name: tt.canIUse && tt.canIUse('pay') ? 'pay' : 'requestPayment',
name: tt.pay ? 'pay' : 'requestPayment',
args: {
orderInfo: tt.canIUse && tt.canIUse('pay') ? 'orderInfo' : 'data'
orderInfo: tt.pay ? 'orderInfo' : 'data'
}
},
getFileInfo: {
......
......@@ -9,8 +9,8 @@ const {
// nvue override
moduleAlias.addAlias('weex-styler', path.resolve(__dirname, 'packages/weex-styler'))
moduleAlias.addAlias('weex-template-compiler', path.resolve(__dirname, 'packages/weex-template-compiler'))
moduleAlias.addAlias('./compileTemplate', require.resolve(
'@dcloudio/vue-cli-plugin-uni/packages/@vue/component-compiler-utils/dist/compileTemplate'))
moduleAlias.addAlias('@vue/component-compiler-utils', require.resolve('@dcloudio/vue-cli-plugin-uni/packages/@vue/component-compiler-utils'))
moduleAlias.addAlias('@vue/component-compiler-utils/package.json', require.resolve('@dcloudio/vue-cli-plugin-uni/packages/@vue/component-compiler-utils/package.json'))
if (isInHBuilderX) {
moduleAlias.addAlias('typescript', path.resolve(process.env.UNI_HBUILDERX_PLUGINS,
......
......@@ -555,7 +555,7 @@ function parseHTML (html, options) {
var splitRE = /\r?\n/g;
var replaceRE = /./g;
var isSpecialTag = makeMap('script,style,template', true);
var isCustomBlock = makeMap('wxs,filter,sjs', true);// fixed by xxxxxx
var isCustomBlock = makeMap('wxs,filter,sjs,renderjs', true);// fixed by xxxxxx
/**
* Parse a single-file component (*.vue) file into an SFC Descriptor Object.
......@@ -2779,7 +2779,13 @@ var uid = 0;
* directives subscribing to it.
*/
var Dep = function Dep () {
this.id = uid++;
// fixed by xxxxxx (nvue vuex)
/* eslint-disable no-undef */
if(typeof SharedObject !== 'undefined'){
this.id = SharedObject.uid++;
} else {
this.id = uid++;
}
this.subs = [];
};
......
......@@ -88,6 +88,13 @@ const v3 = {
loader: path.resolve(__dirname,
'../../packages/webpack-uni-app-loader/view/script')
})
// view 层 renderjs
rules.push({
resourceQuery: [/lang=renderjs/, /blockType=renderjs/],
use: [{
loader: path.resolve(__dirname, '../../packages/webpack-uni-app-loader/view/renderjs')
}]
})
}
scriptLoaders.push({
loader: path.resolve(__dirname,
......@@ -245,11 +252,13 @@ const v3 = {
compilerOptions
}, cacheConfig))
.end()
.use('uniapp-custom-block-loader')
.loader(require.resolve('@dcloudio/vue-cli-plugin-uni/packages/webpack-custom-block-loader'))
.options({
compiler: getPlatformCompiler()
})
// .use('uniapp-custom-block-loader')
// .loader(require.resolve('@dcloudio/vue-cli-plugin-uni/packages/webpack-custom-block-loader'))
// .options({
// isAppService,
// isAppView,
// compiler: getPlatformCompiler()
// })
// 是否启用 cache
if (process.env.UNI_USING_CACHE) {
......
......@@ -35,11 +35,11 @@ module.exports = function modifyVueLoader (webpackConfig, compilerOptions, api)
}, compilerOptions)
}, cacheConfig))
.end()
.use('uniapp-custom-block-loader')
.loader(require.resolve('@dcloudio/vue-cli-plugin-uni/packages/webpack-custom-block-loader'))
.options({
compiler: getPlatformCompiler()
})
// .use('uniapp-custom-block-loader')
// .loader(require.resolve('@dcloudio/vue-cli-plugin-uni/packages/webpack-custom-block-loader'))
// .options({
// compiler: getPlatformCompiler()
// })
// h5 框架需要使用 scoped 样式,其他平台编译时识别是否 nvue 文件且注入 flex 相关样式
if (process.env.UNI_PLATFORM === 'h5') {
......
......@@ -24,6 +24,7 @@
"envinfo": "^6.0.1",
"hash-sum": "^1.0.2",
"loader-utils": "^1.1.0",
"lru-cache": "^4.1.2",
"mkdirp": "^0.5.1",
"module-alias": "^2.1.0",
"postcss": "^7.0.7",
......
# [3.1.0](https://github.com/vuejs/component-compiler-utils/compare/v3.0.2...v3.1.0) (2019-12-08)
### Features
* include filename in `finalCompilerOptions` ([#74](https://github.com/vuejs/component-compiler-utils/issues/74)) ([3dda72d](https://github.com/vuejs/component-compiler-utils/commit/3dda72d))
* support AST for template compile ([#68](https://github.com/vuejs/component-compiler-utils/issues/68)) ([ed44d6f](https://github.com/vuejs/component-compiler-utils/commit/ed44d6f))
* support audio src in `transformAssetUrls` option by default ([#72](https://github.com/vuejs/component-compiler-utils/issues/72)) ([47f1341](https://github.com/vuejs/component-compiler-utils/commit/47f1341))
## [3.0.2](https://github.com/vuejs/component-compiler-utils/compare/v3.0.1...v3.0.2) (2019-11-06)
### Bug Fixes
* also include "lib" folder for type definitions ([dd42df1](https://github.com/vuejs/component-compiler-utils/commit/dd42df1)), closes [#73](https://github.com/vuejs/component-compiler-utils/issues/73)
## [3.0.1](https://github.com/vuejs/component-compiler-utils/compare/v3.0.0...v3.0.1) (2019-11-04)
### Bug Fixes
* should not crash when prettier failed ([89e7900](https://github.com/vuejs/component-compiler-utils/commit/89e7900))
* unpin prettier version ([59a01bb](https://github.com/vuejs/component-compiler-utils/commit/59a01bb))
# [3.0.0](https://github.com/vuejs/component-compiler-utils/compare/v2.6.0...v3.0.0) (2019-04-11)
### Features
* Replace node-sass to sass ([#56](https://github.com/vuejs/component-compiler-utils/issues/56)) ([3e4e3fc](https://github.com/vuejs/component-compiler-utils/commit/3e4e3fc)), closes [#50](https://github.com/vuejs/component-compiler-utils/issues/50)
### BREAKING CHANGES
* Using `sass` instead of `node-sass` package.
# [2.6.0](https://github.com/vuejs/component-compiler-utils/compare/v2.5.2...v2.6.0) (2019-02-21)
### Features
* implement ::v-deep as a shadow piercing combinator ([#54](https://github.com/vuejs/component-compiler-utils/issues/54)) ([8b2c646](https://github.com/vuejs/component-compiler-utils/commit/8b2c646))
# [2.6.0](https://github.com/vuejs/component-compiler-utils/compare/v2.5.2...v2.6.0) (2019-02-21)
### Features
* implement ::v-deep as a shadow piercing combinator ([#54](https://github.com/vuejs/component-compiler-utils/issues/54)) ([8b2c646](https://github.com/vuejs/component-compiler-utils/commit/8b2c646))
## [2.5.2](https://github.com/vuejs/component-compiler-utils/compare/v2.5.0...v2.5.2) (2019-01-31)
### Bug Fixes
* fix sourceMap path separator on Windows, default sourceRoot to "" ([#51](https://github.com/vuejs/component-compiler-utils/issues/51)) ([df32cd9](https://github.com/vuejs/component-compiler-utils/commit/df32cd9)), closes [#47](https://github.com/vuejs/component-compiler-utils/issues/47)
* generate correct source-map when content is not padded ([#52](https://github.com/vuejs/component-compiler-utils/issues/52)) ([81be0ca](https://github.com/vuejs/component-compiler-utils/commit/81be0ca))
## [2.5.1](https://github.com/vuejs/component-compiler-utils/compare/v2.5.0...v2.5.1) (2019-01-25)
### Bug Fixes
* fix sourceMap path separator on Windows, default sourceRoot to "" ([#51](https://github.com/vuejs/component-compiler-utils/issues/51)) ([df32cd9](https://github.com/vuejs/component-compiler-utils/commit/df32cd9)), closes [#47](https://github.com/vuejs/component-compiler-utils/issues/47)
# [2.5.0](https://github.com/vuejs/component-compiler-utils/compare/v2.4.0...v2.5.0) (2019-01-08)
### Features
* add 'use' tag of SVG to 'transformAssetUrls' option as default ([#45](https://github.com/vuejs/component-compiler-utils/issues/45)) ([f4e3336](https://github.com/vuejs/component-compiler-utils/commit/f4e3336))
# [2.4.0](https://github.com/vuejs/component-compiler-utils/compare/v2.0.0...v2.4.0) (2019-01-02)
### Bug Fixes
* do not insert newline if style is already minified ([2603ee2](https://github.com/vuejs/component-compiler-utils/commit/2603ee2))
* Forward preprocessor options to less ([#25](https://github.com/vuejs/component-compiler-utils/issues/25)) ([3b19c1e](https://github.com/vuejs/component-compiler-utils/commit/3b19c1e)), closes [#24](https://github.com/vuejs/component-compiler-utils/issues/24)
* Move trim and scoped postcss plugins at the start of plugin list ([#36](https://github.com/vuejs/component-compiler-utils/issues/36)) ([0d52d86](https://github.com/vuejs/component-compiler-utils/commit/0d52d86))
* pin prettier version ([5f138a6](https://github.com/vuejs/component-compiler-utils/commit/5f138a6))
* remove space after selector when inserting scoped attribute ([5b299ed](https://github.com/vuejs/component-compiler-utils/commit/5b299ed)), closes [vue-loader/#1370](https://github.com/vuejs/component-compiler-utils/issues/1370)
* should work with variable named render (close [#23](https://github.com/vuejs/component-compiler-utils/issues/23)) ([273827b](https://github.com/vuejs/component-compiler-utils/commit/273827b))
* support standalone pseudo element selectors ([#33](https://github.com/vuejs/component-compiler-utils/issues/33)) ([d6cfbbf](https://github.com/vuejs/component-compiler-utils/commit/d6cfbbf))
* Typings for SFCDescriptor and SFCCustomBlock ([#29](https://github.com/vuejs/component-compiler-utils/issues/29)) ([bb09115](https://github.com/vuejs/component-compiler-utils/commit/bb09115))
### Features
* **scoped-css:** support leading >>> or /deep/ in selectors ([1a3b5bb](https://github.com/vuejs/component-compiler-utils/commit/1a3b5bb))
* add `prettify ` option ([#42](https://github.com/vuejs/component-compiler-utils/issues/42)) ([db3655b](https://github.com/vuejs/component-compiler-utils/commit/db3655b))
* Support `stylus` as `<style>` lang ([#18](https://github.com/vuejs/component-compiler-utils/issues/18)) ([986084e](https://github.com/vuejs/component-compiler-utils/commit/986084e))
<a name="2.3.1"></a>
## [2.3.1](https://github.com/vuejs/component-compiler-utils/compare/v2.3.0...v2.3.1) (2018-12-11)
### Bug Fixes
* do not insert newline if style is already minified ([2603ee2](https://github.com/vuejs/component-compiler-utils/commit/2603ee2))
* Move trim and scoped postcss plugins at the start of plugin list ([#36](https://github.com/vuejs/component-compiler-utils/issues/36)) ([0d52d86](https://github.com/vuejs/component-compiler-utils/commit/0d52d86))
<a name="2.3.0"></a>
# [2.3.0](https://github.com/vuejs/component-compiler-utils/compare/v2.2.0...v2.3.0) (2018-10-22)
### Bug Fixes
* support standalone pseudo element selectors ([#33](https://github.com/vuejs/component-compiler-utils/issues/33)) ([d6cfbbf](https://github.com/vuejs/component-compiler-utils/commit/d6cfbbf))
* Typings for SFCDescriptor and SFCCustomBlock ([#29](https://github.com/vuejs/component-compiler-utils/issues/29)) ([bb09115](https://github.com/vuejs/component-compiler-utils/commit/bb09115))
<a name="2.2.0"></a>
# [2.2.0](https://github.com/vuejs/component-compiler-utils/compare/v2.1.2...v2.2.0) (2018-08-16)
### Features
* **scoped-css:** support leading >>> or /deep/ in selectors ([1a3b5bb](https://github.com/vuejs/component-compiler-utils/commit/1a3b5bb))
<a name="2.1.2"></a>
## [2.1.2](https://github.com/vuejs/component-compiler-utils/compare/v2.1.1...v2.1.2) (2018-08-09)
### Bug Fixes
* pin prettier version ([5f138a6](https://github.com/vuejs/component-compiler-utils/commit/5f138a6))
<a name="2.1.1"></a>
## [2.1.1](https://github.com/vuejs/component-compiler-utils/compare/v2.1.0...v2.1.1) (2018-08-07)
### Bug Fixes
* remove space after selector when inserting scoped attribute ([5b299ed](https://github.com/vuejs/component-compiler-utils/commit/5b299ed)), closes [vue-loader/#1370](https://github.com/vuejs/component-compiler-utils/issues/1370)
<a name="2.1.0"></a>
# [2.1.0](https://github.com/vuejs/component-compiler-utils/compare/v2.0.0...v2.1.0) (2018-07-03)
### Bug Fixes
* Forward preprocessor options to less ([#25](https://github.com/vuejs/component-compiler-utils/issues/25)) ([3b19c1e](https://github.com/vuejs/component-compiler-utils/commit/3b19c1e)), closes [#24](https://github.com/vuejs/component-compiler-utils/issues/24)
* should work with variable named render (close [#23](https://github.com/vuejs/component-compiler-utils/issues/23)) ([273827b](https://github.com/vuejs/component-compiler-utils/commit/273827b))
### Features
* Support `stylus` as `<style>` lang ([#18](https://github.com/vuejs/component-compiler-utils/issues/18)) ([986084e](https://github.com/vuejs/component-compiler-utils/commit/986084e))
<a name="2.0.0"></a>
# [2.0.0](https://github.com/vuejs/component-compiler-utils/compare/v1.3.1...v2.0.0) (2018-06-03)
### Features
* Add async style compilation support ([#13](https://github.com/vuejs/component-compiler-utils/issues/13)) ([54464d6](https://github.com/vuejs/component-compiler-utils/commit/54464d6))
* allow/require compiler to be passed in for `parse` ([caa1538](https://github.com/vuejs/component-compiler-utils/commit/caa1538))
### BREAKING CHANGES
* vue template compiler must now be passed to `parse`
via options.
<a name="1.3.1"></a>
## [1.3.1](https://github.com/vuejs/component-compiler-utils/compare/v1.3.0...v1.3.1) (2018-05-28)
### Bug Fixes
* default parser was removed from prettier ([#15](https://github.com/vuejs/component-compiler-utils/issues/15)) ([598224d](https://github.com/vuejs/component-compiler-utils/commit/598224d))
<a name="1.3.0"></a>
# [1.3.0](https://github.com/vuejs/component-compiler-utils/compare/v1.2.1...v1.3.0) (2018-05-22)
### Features
* include href for <image> in transformAssetUrls (close [#12](https://github.com/vuejs/component-compiler-utils/issues/12)) ([86fddc2](https://github.com/vuejs/component-compiler-utils/commit/86fddc2))
* Provide installation instructions on missing language preprocessors ([#10](https://github.com/vuejs/component-compiler-utils/issues/10)) ([97e772c](https://github.com/vuejs/component-compiler-utils/commit/97e772c))
<a name="1.2.1"></a>
## [1.2.1](https://github.com/vuejs/component-compiler-utils/compare/v1.2.0...v1.2.1) (2018-04-26)
### Bug Fixes
* postcss import ([c845a80](https://github.com/vuejs/component-compiler-utils/commit/c845a80))
<a name="1.2.0"></a>
# [1.2.0](https://github.com/vuejs/component-compiler-utils/compare/v1.1.0...v1.2.0) (2018-04-26)
### Bug Fixes
* compile only lib directory ([#6](https://github.com/vuejs/component-compiler-utils/issues/6)) ([4f787b3](https://github.com/vuejs/component-compiler-utils/commit/4f787b3))
### Features
* accept postcss options and plugins ([#7](https://github.com/vuejs/component-compiler-utils/issues/7)) ([1456e3d](https://github.com/vuejs/component-compiler-utils/commit/1456e3d))
<a name="1.1.0"></a>
# [1.1.0](https://github.com/vuejs/component-compiler-utils/compare/9204f16...v1.1.0) (2018-04-24)
### Bug Fixes
* use more strict regex for matching css animation rules ([4644727](https://github.com/vuejs/component-compiler-utils/commit/4644727))
### Features
* adds stylus & less preprocessor ([#5](https://github.com/vuejs/component-compiler-utils/issues/5)) ([f2fd8b9](https://github.com/vuejs/component-compiler-utils/commit/f2fd8b9))
* preprocess scss/sass styles with node-sass ([#4](https://github.com/vuejs/component-compiler-utils/issues/4)) ([9204f16](https://github.com/vuejs/component-compiler-utils/commit/9204f16))
dist/compileTemplate
dist/parse
dist/parseCustomBlocks
\ No newline at end of file
# @vue/component-compiler-utils [![Build Status](https://circleci.com/gh/vuejs/component-compiler-utils/tree/master.svg?style=shield)](https://circleci.com/gh/vuejs/component-compiler-utils/)
> Lower level utilities for compiling Vue single file components
This package contains lower level utilities that you can use if you are writing a plugin / transform for a bundler or module system that compiles Vue single file components into JavaScript. It is used in [vue-loader](https://github.com/vuejs/vue-loader) version 15 and above.
The API surface is intentionally minimal - the goal is to reuse as much as possible while being as flexible as possible.
## Why isn't `vue-template-compiler` a peerDependency?
Since this package is more often used as a low-level utility, it is usually a transitive dependency in an actual Vue project. It is therefore the responsibility of the higher-level package (e.g. `vue-loader`) to inject `vue-template-compiler` via options when calling the `parse` and `compileTemplate` methods.
Not listing it as a peer depedency also allows tooling authors to use a non-default template compiler instead of `vue-template-compiler` without having to include it just to fullfil the peer dep requirement.
## API
### parse(ParseOptions): SFCDescriptor
Parse raw single file component source into a descriptor with source maps. The actual compiler (`vue-template-compiler`) must be passed in via the `compiler` option so that the specific version used can be determined by the end user.
``` ts
interface ParseOptions {
source: string
filename?: string
compiler: VueTemplateCompiler
// https://github.com/vuejs/vue/tree/dev/packages/vue-template-compiler#compilerparsecomponentfile-options
// default: { pad: 'line' }
compilerParseOptions?: VueTemplateCompilerParseOptions
sourceRoot?: string
needMap?: boolean
}
interface SFCDescriptor {
template: SFCBlock | null
script: SFCBlock | null
styles: SFCBlock[]
customBlocks: SFCCustomBlock[]
}
interface SFCCustomBlock {
type: string
content: string
attrs: { [key: string]: string | true }
start: number
end: number
map?: RawSourceMap
}
interface SFCBlock extends SFCCustomBlock {
lang?: string
src?: string
scoped?: boolean
module?: string | boolean
}
```
### compileTemplate(TemplateCompileOptions): TemplateCompileResults
Takes raw template source and compile it into JavaScript code. The actual compiler (`vue-template-compiler`) must be passed in via the `compiler` option so that the specific version used can be determined by the end user.
It can also optionally perform pre-processing for any templating engine supported by [consolidate](https://github.com/tj/consolidate.js/).
``` ts
interface TemplateCompileOptions {
source: string
filename: string
compiler: VueTemplateCompiler
// https://github.com/vuejs/vue/tree/dev/packages/vue-template-compiler#compilercompiletemplate-options
// default: {}
compilerOptions?: VueTemplateCompilerOptions
// Template preprocessor
preprocessLang?: string
preprocessOptions?: any
// Transform asset urls found in the template into `require()` calls
// This is off by default. If set to true, the default value is
// {
// audio: 'src',
// video: ['src', 'poster'],
// source: 'src',
// img: 'src',
// image: ['xlink:href', 'href'],
// use: ['xlink:href', 'href']
// }
transformAssetUrls?: AssetURLOptions | boolean
// For vue-template-es2015-compiler, which is a fork of Buble
transpileOptions?: any
isProduction?: boolean // default: false
isFunctional?: boolean // default: false
optimizeSSR?: boolean // default: false
// Whether prettify compiled render function or not (development only)
// default: true
prettify?: boolean
}
interface TemplateCompileResult {
ast: Object | undefined
code: string
source: string
tips: string[]
errors: string[]
}
interface AssetURLOptions {
[name: string]: string | string[]
}
```
#### Handling the Output
The resulting JavaScript code will look like this:
``` js
var render = function (h) { /* ... */}
var staticRenderFns = [function (h) { /* ... */}, function (h) { /* ... */}]
```
It **does NOT** assume any module system. It is your responsibility to handle the exports, if needed.
### compileStyle(StyleCompileOptions)
Take input raw CSS and applies scoped CSS transform. It does NOT handle pre-processors. If the component doesn't use scoped CSS then this step can be skipped.
``` ts
interface StyleCompileOptions {
source: string
filename: string
id: string
map?: any
scoped?: boolean
trim?: boolean
preprocessLang?: string
preprocessOptions?: any
postcssOptions?: any
postcssPlugins?: any[]
}
interface StyleCompileResults {
code: string
map: any | void
rawResult: LazyResult | void // raw lazy result from PostCSS
errors: string[]
}
```
### compileStyleAsync(StyleCompileOptions)
Same as `compileStyle(StyleCompileOptions)` but it returns a Promise resolving to `StyleCompileResults`. It can be used with async postcss plugins.
import { LazyResult } from 'postcss';
export interface StyleCompileOptions {
source: string;
filename: string;
id: string;
map?: any;
scoped?: boolean;
trim?: boolean;
preprocessLang?: string;
preprocessOptions?: any;
postcssOptions?: any;
postcssPlugins?: any[];
}
export interface AsyncStyleCompileOptions extends StyleCompileOptions {
isAsync?: boolean;
}
export interface StyleCompileResults {
code: string;
map: any | void;
rawResult: LazyResult | void;
errors: string[];
}
export declare function compileStyle(options: StyleCompileOptions): StyleCompileResults;
export declare function compileStyleAsync(options: StyleCompileOptions): Promise<StyleCompileResults>;
export declare function doCompileStyle(options: AsyncStyleCompileOptions): StyleCompileResults;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const postcss = require('postcss');
const trim_1 = __importDefault(require("./stylePlugins/trim"));
const scoped_1 = __importDefault(require("./stylePlugins/scoped"));
const styleProcessors_1 = require("./styleProcessors");
function compileStyle(options) {
return doCompileStyle(Object.assign({}, options, { isAsync: false }));
}
exports.compileStyle = compileStyle;
function compileStyleAsync(options) {
return Promise.resolve(doCompileStyle(Object.assign({}, options, { isAsync: true })));
}
exports.compileStyleAsync = compileStyleAsync;
function doCompileStyle(options) {
const { filename, id, scoped = true, trim = true, preprocessLang, postcssOptions, postcssPlugins } = options;
const preprocessor = preprocessLang && styleProcessors_1.processors[preprocessLang];
const preProcessedSource = preprocessor && preprocess(options, preprocessor);
const map = preProcessedSource ? preProcessedSource.map : options.map;
const source = preProcessedSource ? preProcessedSource.code : options.source;
const plugins = (postcssPlugins || []).slice();
if (trim) {
plugins.push(trim_1.default());
}
if (scoped) {
plugins.push(scoped_1.default(id));
}
const postCSSOptions = Object.assign({}, postcssOptions, { to: filename, from: filename });
if (map) {
postCSSOptions.map = {
inline: false,
annotation: false,
prev: map
};
}
let result, code, outMap;
const errors = [];
if (preProcessedSource && preProcessedSource.errors.length) {
errors.push(...preProcessedSource.errors);
}
try {
result = postcss(plugins).process(source, postCSSOptions);
// In async mode, return a promise.
if (options.isAsync) {
return result
.then((result) => ({
code: result.css || '',
map: result.map && result.map.toJSON(),
errors,
rawResult: result
}))
.catch((error) => ({
code: '',
map: undefined,
errors: [...errors, error.message],
rawResult: undefined
}));
}
// force synchronous transform (we know we only have sync plugins)
code = result.css;
outMap = result.map;
}
catch (e) {
errors.push(e);
}
return {
code: code || ``,
map: outMap && outMap.toJSON(),
errors,
rawResult: result
};
}
exports.doCompileStyle = doCompileStyle;
function preprocess(options, preprocessor) {
return preprocessor.render(options.source, options.map, Object.assign({
filename: options.filename
}, options.preprocessOptions));
}
import { VueTemplateCompiler, VueTemplateCompilerOptions, ErrorWithRange } from './types';
import { AssetURLOptions } from './templateCompilerModules/assetUrl';
export interface TemplateCompileOptions {
source: string;
filename: string;
compiler: VueTemplateCompiler;
compilerOptions?: VueTemplateCompilerOptions;
transformAssetUrls?: AssetURLOptions | boolean;
preprocessLang?: string;
preprocessOptions?: any;
transpileOptions?: any;
isProduction?: boolean;
isFunctional?: boolean;
optimizeSSR?: boolean;
prettify?: boolean;
}
export interface TemplateCompileResult {
ast: Object | undefined;
code: string;
source: string;
tips: (string | ErrorWithRange)[];
errors: (string | ErrorWithRange)[];
}
export declare function compileTemplate(options: TemplateCompileOptions): TemplateCompileResult;
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const assetUrl_1 = __importDefault(require("./templateCompilerModules/assetUrl"));
const srcset_1 = __importDefault(require("./templateCompilerModules/srcset"));
const consolidate = require('consolidate');
const transpile = require('vue-template-es2015-compiler');
function compileTemplate(options) {
const { preprocessLang } = options;
const preprocessor = preprocessLang && consolidate[preprocessLang];
if (preprocessor) {
return actuallyCompile(Object.assign({}, options, {
source: preprocess(options, preprocessor)
}));
}
else if (preprocessLang) {
return { // fixed by xxxxxx recyclableRender,components
code: `var render = function () {}\n` + `var staticRenderFns = []\n` + `var recyclableRender\n` + `var components\n`,
source: options.source,
tips: [
`Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
],
errors: [
`Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
]
};
}
else {
return actuallyCompile(options);
}
}
exports.compileTemplate = compileTemplate;
function preprocess(options, preprocessor) {
const { source, filename, preprocessOptions } = options;
const finalPreprocessOptions = Object.assign({
filename
}, preprocessOptions);
// Consolidate exposes a callback based API, but the callback is in fact
// called synchronously for most templating engines. In our case, we have to
// expose a synchronous API so that it is usable in Jest transforms (which
// have to be sync because they are applied via Node.js require hooks)
let res, err;
preprocessor.render(source, finalPreprocessOptions, (_err, _res) => {
if (_err)
err = _err;
res = _res;
});
if (err)
throw err;
return res;
}
function actuallyCompile(options) {
const { source, compiler, compilerOptions = {}, transpileOptions = {}, transformAssetUrls, isProduction = process.env.NODE_ENV === 'production', isFunctional = false, optimizeSSR = false, prettify = true } = options;
const compile = optimizeSSR && compiler.ssrCompile ? compiler.ssrCompile : compiler.compile;
let finalCompilerOptions = compilerOptions;
if (transformAssetUrls) {
const builtInModules = [
transformAssetUrls === true
? assetUrl_1.default()
: assetUrl_1.default(transformAssetUrls),
srcset_1.default()
];
finalCompilerOptions = Object.assign({}, compilerOptions, {
modules: [...builtInModules, ...(compilerOptions.modules || [])]
});
}
// fixed by xxxxxx
const { render, staticRenderFns, tips, errors, '@render': recyclableRender, components } = compile(source, finalCompilerOptions);
if (errors && errors.length) {
return { // fixed by xxxxxx recyclableRender,components
code: `var render = function () {}\n` + `var staticRenderFns = []\n` + `var recyclableRender\n` + `var components\n`,
source,
tips,
errors
};
}
else {
const finalTranspileOptions = Object.assign({}, transpileOptions, {
transforms: Object.assign({}, transpileOptions.transforms, {
stripWithFunctional: isFunctional
})
});
const toFunction = (code) => {
return `function (${isFunctional ? `_h,_vm` : ``}) {${code}}`;
};
// fixed by xxxxxx
// transpile code with vue-template-es2015-compiler, which is a forked
// version of Buble that applies ES2015 transforms + stripping `with` usage
let code = transpile(`var __render__ = ${toFunction(render)}\n` +
`var __recyclableRender__ = ${recyclableRender ? toFunction(recyclableRender) : 'false'}\n` +
`var __staticRenderFns__ = [${staticRenderFns.map(toFunction)}]`, finalTranspileOptions) + `\n`;
// #23 we use __render__ to avoid `render` not being prefixed by the
// transpiler when stripping with, but revert it back to `render` to
// maintain backwards compat
code = code.replace(/\s__(render|recyclableRender|staticRenderFns)__\s/g, ' $1 ');
code = (components || '') + '\n' + code // fixed by xxxxxx
if (!isProduction) {
// mark with stripped (this enables Vue to use correct runtime proxy
// detection)
code += `render._withStripped = true`;
if (prettify) {
code = require('prettier').format(code, {
semi: false,
parser: 'babel'
});
}
}
return {
code,
source,
tips,
errors
};
}
}
import { parse, SFCBlock, SFCCustomBlock, SFCDescriptor } from './parse';
import { compileTemplate, TemplateCompileOptions, TemplateCompileResult } from './compileTemplate';
import { compileStyle, compileStyleAsync, StyleCompileOptions, StyleCompileResults } from './compileStyle';
export { parse, compileTemplate, compileStyle, compileStyleAsync };
export { SFCBlock, SFCCustomBlock, SFCDescriptor, TemplateCompileOptions, TemplateCompileResult, StyleCompileOptions, StyleCompileResults };
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const parse_1 = require("./parse");
exports.parse = parse_1.parse;
const compileTemplate_1 = require("./compileTemplate");
exports.compileTemplate = compileTemplate_1.compileTemplate;
const compileStyle_1 = require("./compileStyle");
exports.compileStyle = compileStyle_1.compileStyle;
exports.compileStyleAsync = compileStyle_1.compileStyleAsync;
import { RawSourceMap, VueTemplateCompiler, VueTemplateCompilerParseOptions } from './types';
export interface ParseOptions {
source: string;
filename?: string;
compiler: VueTemplateCompiler;
compilerParseOptions?: VueTemplateCompilerParseOptions;
sourceRoot?: string;
needMap?: boolean;
}
export interface SFCCustomBlock {
type: string;
content: string;
attrs: {
[key: string]: string | true;
};
start: number;
end: number;
map?: RawSourceMap;
}
export interface SFCBlock extends SFCCustomBlock {
lang?: string;
src?: string;
scoped?: boolean;
module?: string | boolean;
}
export interface SFCDescriptor {
template: SFCBlock | null;
script: SFCBlock | null;
styles: SFCBlock[];
customBlocks: SFCCustomBlock[];
}
export declare function parse(options: ParseOptions): SFCDescriptor;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const source_map_1 = require("source-map");
const hash = require('hash-sum');
const cache = require('lru-cache')(100);
const splitRE = /\r?\n/g;
const emptyRE = /^(?:\/\/)?\s*$/;
function parse(options) {
const { source, filename = '', compiler, compilerParseOptions = { pad: 'line' }, sourceRoot = '', needMap = true } = options;
const cacheKey = hash(filename + source);
let output = cache.get(cacheKey);
if (output)
return output;
// fixed by xxxxxx
output = require('./parseCustomBlocks')(compiler.parseComponent(source, compilerParseOptions), options);
if (needMap) {
if (output.script && !output.script.src) {
output.script.map = generateSourceMap(filename, source, output.script.content, sourceRoot, compilerParseOptions.pad);
}
if (output.styles) {
output.styles.forEach(style => {
if (!style.src) {
style.map = generateSourceMap(filename, source, style.content, sourceRoot, compilerParseOptions.pad);
}
});
}
}
cache.set(cacheKey, output);
return output;
}
exports.parse = parse;
function generateSourceMap(filename, source, generated, sourceRoot, pad) {
const map = new source_map_1.SourceMapGenerator({
file: filename.replace(/\\/g, '/'),
sourceRoot: sourceRoot.replace(/\\/g, '/')
});
let offset = 0;
if (!pad) {
offset =
source
.split(generated)
.shift()
.split(splitRE).length - 1;
}
map.setSourceContent(filename, source);
generated.split(splitRE).forEach((line, index) => {
if (!emptyRE.test(line)) {
map.addMapping({
source: filename,
original: {
line: index + 1 + offset,
column: 0
},
generated: {
line: index + 1,
column: 0
}
});
}
});
return JSON.parse(map.toString());
}
const {
getPlatformFilterTag,
normalizeNodeModules
} = require('@dcloudio/uni-cli-shared/lib/platform')
const FILTER_TAG = getPlatformFilterTag()
module.exports = function parseCustomBlocks(descriptor, options) {
if (!descriptor.template || !FILTER_TAG || options.isAppNVue) {
// delete customBlocks
descriptor.customBlocks.length = 0
return descriptor
}
const modules = Object.create(null)
descriptor.customBlocks = descriptor.customBlocks.filter(block => {
if (
block.attrs.module &&
(
block.type === FILTER_TAG ||
block.attrs.lang === FILTER_TAG
)
) {
modules[block.attrs.module] = block
return true
}
if ( // renderjs
options.isAppView &&
(
block.type === 'renderjs' ||
block.attrs.lang === 'renderjs'
)
) {
return true
}
})
if (Object.keys(modules).length) {
const filterModules = JSON.parse(JSON.stringify(modules))
Object.keys(filterModules).forEach(name => {
const filterModule = filterModules[name]
if (filterModule.attrs.src) {
filterModule.attrs.src = normalizeNodeModules(filterModule.attrs.src)
}
})
descriptor.template.attrs['filter-modules'] = JSON.stringify(filterModules)
}
return descriptor
}
import * as postcss from 'postcss';
declare const _default: postcss.Plugin<any>;
export default _default;
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const postcss = __importStar(require("postcss"));
// postcss-selector-parser does have typings but it's problematic to work with.
const selectorParser = require('postcss-selector-parser');
exports.default = postcss.plugin('add-id', (options) => (root) => {
const id = options;
const keyframes = Object.create(null);
root.each(function rewriteSelector(node) {
if (!node.selector) {
// handle media queries
if (node.type === 'atrule') {
if (node.name === 'media' || node.name === 'supports') {
node.each(rewriteSelector);
}
else if (/-?keyframes$/.test(node.name)) {
// register keyframes
keyframes[node.params] = node.params = node.params + '-' + id;
}
}
return;
}
node.selector = selectorParser((selectors) => {
selectors.each((selector) => {
let node = null;
// find the last child node to insert attribute selector
selector.each((n) => {
// ">>>" combinator
// and /deep/ alias for >>>, since >>> doesn't work in SASS
if (n.type === 'combinator' &&
(n.value === '>>>' || n.value === '/deep/')) {
n.value = ' ';
n.spaces.before = n.spaces.after = '';
return false;
}
// in newer versions of sass, /deep/ support is also dropped, so add a ::v-deep alias
if (n.type === 'pseudo' && n.value === '::v-deep') {
n.value = n.spaces.before = n.spaces.after = '';
return false;
}
if (n.type !== 'pseudo' && n.type !== 'combinator') {
node = n;
}
});
if (node) {
node.spaces.after = '';
}
else {
// For deep selectors & standalone pseudo selectors,
// the attribute selectors are prepended rather than appended.
// So all leading spaces must be eliminated to avoid problems.
selector.first.spaces.before = '';
}
selector.insertAfter(node, selectorParser.attribute({
attribute: id
}));
});
}).processSync(node.selector);
});
// If keyframes are found in this <style>, find and rewrite animation names
// in declarations.
// Caveat: this only works for keyframes and animation rules in the same
// <style> element.
if (Object.keys(keyframes).length) {
root.walkDecls(decl => {
// individual animation-name declaration
if (/^(-\w+-)?animation-name$/.test(decl.prop)) {
decl.value = decl.value
.split(',')
.map(v => keyframes[v.trim()] || v.trim())
.join(',');
}
// shorthand
if (/^(-\w+-)?animation$/.test(decl.prop)) {
decl.value = decl.value
.split(',')
.map(v => {
const vals = v.trim().split(/\s+/);
const i = vals.findIndex(val => keyframes[val]);
if (i !== -1) {
vals.splice(i, 1, keyframes[vals[i]]);
return vals.join(' ');
}
else {
return v;
}
})
.join(',');
}
});
}
});
import * as postcss from 'postcss';
declare const _default: postcss.Plugin<unknown>;
export default _default;
"use strict";
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const postcss = __importStar(require("postcss"));
exports.default = postcss.plugin('trim', () => (css) => {
css.walk(({ type, raws }) => {
if (type === 'rule' || type === 'atrule') {
if (raws.before)
raws.before = '\n';
if (raws.after)
raws.after = '\n';
}
});
});
export interface StylePreprocessor {
render(source: string, map: any | null, options: any): StylePreprocessorResults;
}
export interface StylePreprocessorResults {
code: string;
map?: any;
errors: Array<Error>;
}
export declare const processors: {
[key: string]: StylePreprocessor;
};
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const merge = require('merge-source-map');
// .scss/.sass processor
const scss = {
render(source, map, options) {
const nodeSass = require('sass');
const finalOptions = Object.assign({}, options, {
data: source,
file: options.filename,
outFile: options.filename,
sourceMap: !!map
});
try {
const result = nodeSass.renderSync(finalOptions);
if (map) {
return {
code: result.css.toString(),
map: merge(map, JSON.parse(result.map.toString())),
errors: []
};
}
return { code: result.css.toString(), errors: [] };
}
catch (e) {
return { code: '', errors: [e] };
}
}
};
const sass = {
render(source, map, options) {
return scss.render(source, map, Object.assign({}, options, { indentedSyntax: true }));
}
};
// .less
const less = {
render(source, map, options) {
const nodeLess = require('less');
let result;
let error = null;
nodeLess.render(source, Object.assign({}, options, { syncImport: true }), (err, output) => {
error = err;
result = output;
});
if (error)
return { code: '', errors: [error] };
if (map) {
return {
code: result.css.toString(),
map: merge(map, result.map),
errors: []
};
}
return { code: result.css.toString(), errors: [] };
}
};
// .styl
const styl = {
render(source, map, options) {
const nodeStylus = require('stylus');
try {
const ref = nodeStylus(source);
Object.keys(options).forEach(key => ref.set(key, options[key]));
if (map)
ref.set('sourcemap', { inline: false, comment: false });
const result = ref.render();
if (map) {
return {
code: result,
map: merge(map, ref.sourcemap),
errors: []
};
}
return { code: result, errors: [] };
}
catch (e) {
return { code: '', errors: [e] };
}
}
};
exports.processors = {
less,
sass,
scss,
styl,
stylus: styl
};
import { ASTNode } from './utils';
export interface AssetURLOptions {
[name: string]: string | string[];
}
declare const _default: (userOptions?: AssetURLOptions | undefined) => {
postTransformNode: (node: ASTNode) => void;
};
export default _default;
"use strict";
// vue compiler module for transforming `<tag>:<attribute>` to `require`
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
const defaultOptions = {
audio: 'src',
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: ['xlink:href', 'href'],
use: ['xlink:href', 'href']
};
exports.default = (userOptions) => {
const options = userOptions
? Object.assign({}, defaultOptions, userOptions)
: defaultOptions;
return {
postTransformNode: (node) => {
transform(node, options);
}
};
};
function transform(node, options) {
for (const tag in options) {
if ((tag === '*' || node.tag === tag) && node.attrs) {
const attributes = options[tag];
if (typeof attributes === 'string') {
node.attrs.some(attr => rewrite(attr, attributes));
}
else if (Array.isArray(attributes)) {
attributes.forEach(item => node.attrs.some(attr => rewrite(attr, item)));
}
}
}
}
function rewrite(attr, name) {
if (attr.name === name) {
const value = attr.value;
// only transform static URLs
if (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') {
attr.value = utils_1.urlToRequire(value.slice(1, -1));
return true;
}
}
return false;
}
import { ASTNode } from './utils';
declare const _default: () => {
postTransformNode: (node: ASTNode) => void;
};
export default _default;
"use strict";
// vue compiler module for transforming `img:srcset` to a number of `require`s
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
exports.default = () => ({
postTransformNode: (node) => {
transform(node);
}
});
// http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g;
function transform(node) {
const tags = ['img', 'source'];
if (tags.indexOf(node.tag) !== -1 && node.attrs) {
node.attrs.forEach(attr => {
if (attr.name === 'srcset') {
// same logic as in transform-require.js
const value = attr.value;
const isStatic = value.charAt(0) === '"' && value.charAt(value.length - 1) === '"';
if (!isStatic) {
return;
}
const imageCandidates = value
.substr(1, value.length - 2)
.split(',')
.map(s => {
// The attribute value arrives here with all whitespace, except
// normal spaces, represented by escape sequences
const [url, descriptor] = s
.replace(escapedSpaceCharacters, ' ')
.trim()
.split(' ', 2);
return { require: utils_1.urlToRequire(url), descriptor };
});
// "require(url1)"
// "require(url1) 1x"
// "require(url1), require(url2)"
// "require(url1), require(url2) 2x"
// "require(url1) 1x, require(url2)"
// "require(url1) 1x, require(url2) 2x"
const code = imageCandidates
.map(({ require, descriptor }) => `${require} + "${descriptor ? ' ' + descriptor : ''}, " + `)
.join('')
.slice(0, -6)
.concat('"')
.replace(/ \+ ""$/, '');
attr.value = code;
}
});
}
}
export interface Attr {
name: string;
value: string;
}
export interface ASTNode {
tag: string;
attrs: Attr[];
}
export declare function urlToRequire(url: string): string;
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const url_1 = require("url");
function urlToRequire(url) {
const returnValue = `"${url}"`;
// same logic as in transform-require.js
const firstChar = url.charAt(0);
if (firstChar === '.' || firstChar === '~' || firstChar === '@') {
if (firstChar === '~') {
const secondChar = url.charAt(1);
url = url.slice(secondChar === '/' ? 2 : 1);
}
const uriParts = parseUriParts(url);
if (!uriParts.hash) {
return `require("${url}")`;
}
else {
// support uri fragment case by excluding it from
// the require and instead appending it as string;
// assuming that the path part is sufficient according to
// the above caseing(t.i. no protocol-auth-host parts expected)
return `require("${uriParts.path}") + "${uriParts.hash}"`;
}
}
return returnValue;
}
exports.urlToRequire = urlToRequire;
/**
* vuejs/component-compiler-utils#22 Support uri fragment in transformed require
* @param urlString an url as a string
*/
function parseUriParts(urlString) {
// initialize return value
const returnValue = url_1.parse('');
if (urlString) {
// A TypeError is thrown if urlString is not a string
// @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
if ('string' === typeof urlString) {
// check is an uri
return url_1.parse(urlString); // take apart the uri
}
}
return returnValue;
}
import { SFCDescriptor } from './parse';
export interface StartOfSourceMap {
file?: string;
sourceRoot?: string;
}
export interface RawSourceMap extends StartOfSourceMap {
version: string;
sources: string[];
names: string[];
sourcesContent?: string[];
mappings: string;
}
export interface VueTemplateCompiler {
parseComponent(source: string, options?: any): SFCDescriptor;
compile(template: string, options: VueTemplateCompilerOptions): VueTemplateCompilerResults;
ssrCompile(template: string, options: VueTemplateCompilerOptions): VueTemplateCompilerResults;
}
export interface VueTemplateCompilerOptions {
modules?: Object[];
outputSourceRange?: boolean;
whitespace?: 'preserve' | 'condense';
directives?: {
[key: string]: Function;
};
}
export interface VueTemplateCompilerParseOptions {
pad?: 'line' | 'space';
}
export interface ErrorWithRange {
msg: string;
start: number;
end: number;
}
export interface VueTemplateCompilerResults {
ast: Object | undefined;
render: string;
staticRenderFns: string[];
errors: (string | ErrorWithRange)[];
tips: (string | ErrorWithRange)[];
}
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const postcss = require('postcss')
import { ProcessOptions, LazyResult } from 'postcss'
import trimPlugin from './stylePlugins/trim'
import scopedPlugin from './stylePlugins/scoped'
import {
processors,
StylePreprocessor,
StylePreprocessorResults
} from './styleProcessors'
export interface StyleCompileOptions {
source: string
filename: string
id: string
map?: any
scoped?: boolean
trim?: boolean
preprocessLang?: string
preprocessOptions?: any
postcssOptions?: any
postcssPlugins?: any[]
}
export interface AsyncStyleCompileOptions extends StyleCompileOptions {
isAsync?: boolean
}
export interface StyleCompileResults {
code: string
map: any | void
rawResult: LazyResult | void
errors: string[]
}
export function compileStyle(
options: StyleCompileOptions
): StyleCompileResults {
return doCompileStyle({ ...options, isAsync: false })
}
export function compileStyleAsync(
options: StyleCompileOptions
): Promise<StyleCompileResults> {
return Promise.resolve(doCompileStyle({ ...options, isAsync: true }))
}
export function doCompileStyle(
options: AsyncStyleCompileOptions
): StyleCompileResults {
const {
filename,
id,
scoped = true,
trim = true,
preprocessLang,
postcssOptions,
postcssPlugins
} = options
const preprocessor = preprocessLang && processors[preprocessLang]
const preProcessedSource = preprocessor && preprocess(options, preprocessor)
const map = preProcessedSource ? preProcessedSource.map : options.map
const source = preProcessedSource ? preProcessedSource.code : options.source
const plugins = (postcssPlugins || []).slice()
if (trim) {
plugins.push(trimPlugin())
}
if (scoped) {
plugins.push(scopedPlugin(id))
}
const postCSSOptions: ProcessOptions = {
...postcssOptions,
to: filename,
from: filename
}
if (map) {
postCSSOptions.map = {
inline: false,
annotation: false,
prev: map
}
}
let result, code, outMap
const errors: any[] = []
if (preProcessedSource && preProcessedSource.errors.length) {
errors.push(...preProcessedSource.errors)
}
try {
result = postcss(plugins).process(source, postCSSOptions)
// In async mode, return a promise.
if (options.isAsync) {
return result
.then(
(result: LazyResult): StyleCompileResults => ({
code: result.css || '',
map: result.map && result.map.toJSON(),
errors,
rawResult: result
})
)
.catch(
(error: Error): StyleCompileResults => ({
code: '',
map: undefined,
errors: [...errors, error.message],
rawResult: undefined
})
)
}
// force synchronous transform (we know we only have sync plugins)
code = result.css
outMap = result.map
} catch (e) {
errors.push(e)
}
return {
code: code || ``,
map: outMap && outMap.toJSON(),
errors,
rawResult: result
}
}
function preprocess(
options: StyleCompileOptions,
preprocessor: StylePreprocessor
): StylePreprocessorResults {
return preprocessor.render(
options.source,
options.map,
Object.assign(
{
filename: options.filename
},
options.preprocessOptions
)
)
}
import {
VueTemplateCompiler,
VueTemplateCompilerOptions,
ErrorWithRange
} from './types'
import assetUrlsModule, {
AssetURLOptions
} from './templateCompilerModules/assetUrl'
import srcsetModule from './templateCompilerModules/srcset'
const consolidate = require('consolidate')
const transpile = require('vue-template-es2015-compiler')
export interface TemplateCompileOptions {
source: string
filename: string
compiler: VueTemplateCompiler
compilerOptions?: VueTemplateCompilerOptions
transformAssetUrls?: AssetURLOptions | boolean
preprocessLang?: string
preprocessOptions?: any
transpileOptions?: any
isProduction?: boolean
isFunctional?: boolean
optimizeSSR?: boolean
prettify?: boolean
}
export interface TemplateCompileResult {
ast: Object | undefined
code: string
source: string
tips: (string | ErrorWithRange)[]
errors: (string | ErrorWithRange)[]
}
export function compileTemplate(
options: TemplateCompileOptions
): TemplateCompileResult {
const { preprocessLang } = options
const preprocessor = preprocessLang && consolidate[preprocessLang]
if (preprocessor) {
return actuallyCompile(
Object.assign({}, options, {
source: preprocess(options, preprocessor)
})
)
} else if (preprocessLang) {
return {
ast: {},
code: `var render = function () {}\n` + `var staticRenderFns = []\n`,
source: options.source,
tips: [
`Component ${options.filename} uses lang ${preprocessLang} for template. Please install the language preprocessor.`
],
errors: [
`Component ${options.filename} uses lang ${preprocessLang} for template, however it is not installed.`
]
}
} else {
return actuallyCompile(options)
}
}
function preprocess(
options: TemplateCompileOptions,
preprocessor: any
): string {
const { source, filename, preprocessOptions } = options
const finalPreprocessOptions = Object.assign(
{
filename
},
preprocessOptions
)
// Consolidate exposes a callback based API, but the callback is in fact
// called synchronously for most templating engines. In our case, we have to
// expose a synchronous API so that it is usable in Jest transforms (which
// have to be sync because they are applied via Node.js require hooks)
let res: any, err
preprocessor.render(
source,
finalPreprocessOptions,
(_err: Error | null, _res: string) => {
if (_err) err = _err
res = _res
}
)
if (err) throw err
return res
}
function actuallyCompile(
options: TemplateCompileOptions
): TemplateCompileResult {
const {
source,
compiler,
compilerOptions = {},
transpileOptions = {},
transformAssetUrls,
isProduction = process.env.NODE_ENV === 'production',
isFunctional = false,
optimizeSSR = false,
prettify = true
} = options
const compile =
optimizeSSR && compiler.ssrCompile ? compiler.ssrCompile : compiler.compile
let finalCompilerOptions = compilerOptions
if (transformAssetUrls) {
const builtInModules = [
transformAssetUrls === true
? assetUrlsModule()
: assetUrlsModule(transformAssetUrls),
srcsetModule()
]
finalCompilerOptions = Object.assign({}, compilerOptions, {
modules: [...builtInModules, ...(compilerOptions.modules || [])],
filename: options.filename
})
}
const { ast, render, staticRenderFns, tips, errors } = compile(
source,
finalCompilerOptions
)
if (errors && errors.length) {
return {
ast,
code: `var render = function () {}\n` + `var staticRenderFns = []\n`,
source,
tips,
errors
}
} else {
const finalTranspileOptions = Object.assign({}, transpileOptions, {
transforms: Object.assign({}, transpileOptions.transforms, {
stripWithFunctional: isFunctional
})
})
const toFunction = (code: string): string => {
return `function (${isFunctional ? `_h,_vm` : ``}) {${code}}`
}
// transpile code with vue-template-es2015-compiler, which is a forked
// version of Buble that applies ES2015 transforms + stripping `with` usage
let code =
transpile(
`var __render__ = ${toFunction(render)}\n` +
`var __staticRenderFns__ = [${staticRenderFns.map(toFunction)}]`,
finalTranspileOptions
) + `\n`
// #23 we use __render__ to avoid `render` not being prefixed by the
// transpiler when stripping with, but revert it back to `render` to
// maintain backwards compat
code = code.replace(/\s__(render|staticRenderFns)__\s/g, ' $1 ')
if (!isProduction) {
// mark with stripped (this enables Vue to use correct runtime proxy
// detection)
code += `render._withStripped = true`
if (prettify) {
try {
code = require('prettier').format(code, {
semi: false,
parser: 'babel'
})
} catch (e) {
tips.push(
`Failed to prettify component ${options.filename} template source after compilation.`
)
}
}
}
return {
ast,
code,
source,
tips,
errors
}
}
}
import { parse, SFCBlock, SFCCustomBlock, SFCDescriptor } from './parse'
import {
compileTemplate,
TemplateCompileOptions,
TemplateCompileResult
} from './compileTemplate'
import {
compileStyle,
compileStyleAsync,
StyleCompileOptions,
StyleCompileResults
} from './compileStyle'
// API
export { parse, compileTemplate, compileStyle, compileStyleAsync }
// types
export {
SFCBlock,
SFCCustomBlock,
SFCDescriptor,
TemplateCompileOptions,
TemplateCompileResult,
StyleCompileOptions,
StyleCompileResults
}
import { SourceMapGenerator } from 'source-map'
import {
RawSourceMap,
VueTemplateCompiler,
VueTemplateCompilerParseOptions
} from './types'
const hash = require('hash-sum')
const cache = require('lru-cache')(100)
const splitRE = /\r?\n/g
const emptyRE = /^(?:\/\/)?\s*$/
export interface ParseOptions {
source: string
filename?: string
compiler: VueTemplateCompiler
compilerParseOptions?: VueTemplateCompilerParseOptions
sourceRoot?: string
needMap?: boolean
}
export interface SFCCustomBlock {
type: string
content: string
attrs: { [key: string]: string | true }
start: number
end: number
map?: RawSourceMap
}
export interface SFCBlock extends SFCCustomBlock {
lang?: string
src?: string
scoped?: boolean
module?: string | boolean
}
export interface SFCDescriptor {
template: SFCBlock | null
script: SFCBlock | null
styles: SFCBlock[]
customBlocks: SFCCustomBlock[]
}
export function parse(options: ParseOptions): SFCDescriptor {
const {
source,
filename = '',
compiler,
compilerParseOptions = { pad: 'line' } as VueTemplateCompilerParseOptions,
sourceRoot = '',
needMap = true
} = options
const cacheKey = hash(filename + source)
let output: SFCDescriptor = cache.get(cacheKey)
if (output) return output
output = compiler.parseComponent(source, compilerParseOptions)
if (needMap) {
if (output.script && !output.script.src) {
output.script.map = generateSourceMap(
filename,
source,
output.script.content,
sourceRoot,
compilerParseOptions.pad
)
}
if (output.styles) {
output.styles.forEach(style => {
if (!style.src) {
style.map = generateSourceMap(
filename,
source,
style.content,
sourceRoot,
compilerParseOptions.pad
)
}
})
}
}
cache.set(cacheKey, output)
return output
}
function generateSourceMap(
filename: string,
source: string,
generated: string,
sourceRoot: string,
pad?: 'line' | 'space'
): RawSourceMap {
const map = new SourceMapGenerator({
file: filename.replace(/\\/g, '/'),
sourceRoot: sourceRoot.replace(/\\/g, '/')
})
let offset = 0
if (!pad) {
offset =
source
.split(generated)
.shift()!
.split(splitRE).length - 1
}
map.setSourceContent(filename, source)
generated.split(splitRE).forEach((line, index) => {
if (!emptyRE.test(line)) {
map.addMapping({
source: filename,
original: {
line: index + 1 + offset,
column: 0
},
generated: {
line: index + 1,
column: 0
}
})
}
})
return JSON.parse(map.toString())
}
import { Root } from 'postcss'
import * as postcss from 'postcss'
// postcss-selector-parser does have typings but it's problematic to work with.
const selectorParser = require('postcss-selector-parser')
export default postcss.plugin('add-id', (options: any) => (root: Root) => {
const id: string = options
const keyframes = Object.create(null)
root.each(function rewriteSelector(node: any) {
if (!node.selector) {
// handle media queries
if (node.type === 'atrule') {
if (node.name === 'media' || node.name === 'supports') {
node.each(rewriteSelector)
} else if (/-?keyframes$/.test(node.name)) {
// register keyframes
keyframes[node.params] = node.params = node.params + '-' + id
}
}
return
}
node.selector = selectorParser((selectors: any) => {
selectors.each((selector: any) => {
let node: any = null
// find the last child node to insert attribute selector
selector.each((n: any) => {
// ">>>" combinator
// and /deep/ alias for >>>, since >>> doesn't work in SASS
if (
n.type === 'combinator' &&
(n.value === '>>>' || n.value === '/deep/')
) {
n.value = ' '
n.spaces.before = n.spaces.after = ''
return false
}
// in newer versions of sass, /deep/ support is also dropped, so add a ::v-deep alias
if (n.type === 'pseudo' && n.value === '::v-deep') {
n.value = n.spaces.before = n.spaces.after = ''
return false
}
if (n.type !== 'pseudo' && n.type !== 'combinator') {
node = n
}
})
if (node) {
node.spaces.after = ''
} else {
// For deep selectors & standalone pseudo selectors,
// the attribute selectors are prepended rather than appended.
// So all leading spaces must be eliminated to avoid problems.
selector.first.spaces.before = ''
}
selector.insertAfter(
node,
selectorParser.attribute({
attribute: id
})
)
})
}).processSync(node.selector)
})
// If keyframes are found in this <style>, find and rewrite animation names
// in declarations.
// Caveat: this only works for keyframes and animation rules in the same
// <style> element.
if (Object.keys(keyframes).length) {
root.walkDecls(decl => {
// individual animation-name declaration
if (/^(-\w+-)?animation-name$/.test(decl.prop)) {
decl.value = decl.value
.split(',')
.map(v => keyframes[v.trim()] || v.trim())
.join(',')
}
// shorthand
if (/^(-\w+-)?animation$/.test(decl.prop)) {
decl.value = decl.value
.split(',')
.map(v => {
const vals = v.trim().split(/\s+/)
const i = vals.findIndex(val => keyframes[val])
if (i !== -1) {
vals.splice(i, 1, keyframes[vals[i]])
return vals.join(' ')
} else {
return v
}
})
.join(',')
}
})
}
})
import { Root } from 'postcss'
import * as postcss from 'postcss'
export default postcss.plugin('trim', () => (css: Root) => {
css.walk(({ type, raws }) => {
if (type === 'rule' || type === 'atrule') {
if (raws.before) raws.before = '\n'
if (raws.after) raws.after = '\n'
}
})
})
const merge = require('merge-source-map')
export interface StylePreprocessor {
render(
source: string,
map: any | null,
options: any
): StylePreprocessorResults
}
export interface StylePreprocessorResults {
code: string
map?: any
errors: Array<Error>
}
// .scss/.sass processor
const scss: StylePreprocessor = {
render(
source: string,
map: any | null,
options: any
): StylePreprocessorResults {
const nodeSass = require('sass')
const finalOptions = Object.assign({}, options, {
data: source,
file: options.filename,
outFile: options.filename,
sourceMap: !!map
})
try {
const result = nodeSass.renderSync(finalOptions)
if (map) {
return {
code: result.css.toString(),
map: merge(map, JSON.parse(result.map.toString())),
errors: []
}
}
return { code: result.css.toString(), errors: [] }
} catch (e) {
return { code: '', errors: [e] }
}
}
}
const sass = {
render(
source: string,
map: any | null,
options: any
): StylePreprocessorResults {
return scss.render(
source,
map,
Object.assign({}, options, { indentedSyntax: true })
)
}
}
// .less
const less = {
render(
source: string,
map: any | null,
options: any
): StylePreprocessorResults {
const nodeLess = require('less')
let result: any
let error: Error | null = null
nodeLess.render(
source,
Object.assign({}, options, { syncImport: true }),
(err: Error | null, output: any) => {
error = err
result = output
}
)
if (error) return { code: '', errors: [error] }
if (map) {
return {
code: result.css.toString(),
map: merge(map, result.map),
errors: []
}
}
return { code: result.css.toString(), errors: [] }
}
}
// .styl
const styl = {
render(
source: string,
map: any | null,
options: any
): StylePreprocessorResults {
const nodeStylus = require('stylus')
try {
const ref = nodeStylus(source)
Object.keys(options).forEach(key => ref.set(key, options[key]))
if (map) ref.set('sourcemap', { inline: false, comment: false })
const result = ref.render()
if (map) {
return {
code: result,
map: merge(map, ref.sourcemap),
errors: []
}
}
return { code: result, errors: [] }
} catch (e) {
return { code: '', errors: [e] }
}
}
}
export const processors: { [key: string]: StylePreprocessor } = {
less,
sass,
scss,
styl,
stylus: styl
}
// vue compiler module for transforming `<tag>:<attribute>` to `require`
import { urlToRequire, ASTNode, Attr } from './utils'
export interface AssetURLOptions {
[name: string]: string | string[]
}
const defaultOptions: AssetURLOptions = {
audio: 'src',
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: ['xlink:href', 'href'],
use: ['xlink:href', 'href']
}
export default (userOptions?: AssetURLOptions) => {
const options = userOptions
? Object.assign({}, defaultOptions, userOptions)
: defaultOptions
return {
postTransformNode: (node: ASTNode) => {
transform(node, options)
}
}
}
function transform(node: ASTNode, options: AssetURLOptions) {
for (const tag in options) {
if ((tag === '*' || node.tag === tag) && node.attrs) {
const attributes = options[tag]
if (typeof attributes === 'string') {
node.attrs.some(attr => rewrite(attr, attributes))
} else if (Array.isArray(attributes)) {
attributes.forEach(item => node.attrs.some(attr => rewrite(attr, item)))
}
}
}
}
function rewrite(attr: Attr, name: string) {
if (attr.name === name) {
const value = attr.value
// only transform static URLs
if (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') {
attr.value = urlToRequire(value.slice(1, -1))
return true
}
}
return false
}
// vue compiler module for transforming `img:srcset` to a number of `require`s
import { urlToRequire, ASTNode } from './utils'
interface ImageCandidate {
require: string
descriptor: string
}
export default () => ({
postTransformNode: (node: ASTNode) => {
transform(node)
}
})
// http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g
function transform(node: ASTNode) {
const tags = ['img', 'source']
if (tags.indexOf(node.tag) !== -1 && node.attrs) {
node.attrs.forEach(attr => {
if (attr.name === 'srcset') {
// same logic as in transform-require.js
const value = attr.value
const isStatic =
value.charAt(0) === '"' && value.charAt(value.length - 1) === '"'
if (!isStatic) {
return
}
const imageCandidates: ImageCandidate[] = value
.substr(1, value.length - 2)
.split(',')
.map(s => {
// The attribute value arrives here with all whitespace, except
// normal spaces, represented by escape sequences
const [url, descriptor] = s
.replace(escapedSpaceCharacters, ' ')
.trim()
.split(' ', 2)
return { require: urlToRequire(url), descriptor }
})
// "require(url1)"
// "require(url1) 1x"
// "require(url1), require(url2)"
// "require(url1), require(url2) 2x"
// "require(url1) 1x, require(url2)"
// "require(url1) 1x, require(url2) 2x"
const code = imageCandidates
.map(
({ require, descriptor }) =>
`${require} + "${descriptor ? ' ' + descriptor : ''}, " + `
)
.join('')
.slice(0, -6)
.concat('"')
.replace(/ \+ ""$/, '')
attr.value = code
}
})
}
}
export interface Attr {
name: string
value: string
}
export interface ASTNode {
tag: string
attrs: Attr[]
}
import { UrlWithStringQuery, parse as uriParse } from 'url'
export function urlToRequire(url: string): string {
const returnValue = `"${url}"`
// same logic as in transform-require.js
const firstChar = url.charAt(0)
if (firstChar === '.' || firstChar === '~' || firstChar === '@') {
if (firstChar === '~') {
const secondChar = url.charAt(1)
url = url.slice(secondChar === '/' ? 2 : 1)
}
const uriParts = parseUriParts(url)
if (!uriParts.hash) {
return `require("${url}")`
} else {
// support uri fragment case by excluding it from
// the require and instead appending it as string;
// assuming that the path part is sufficient according to
// the above caseing(t.i. no protocol-auth-host parts expected)
return `require("${uriParts.path}") + "${uriParts.hash}"`
}
}
return returnValue
}
/**
* vuejs/component-compiler-utils#22 Support uri fragment in transformed require
* @param urlString an url as a string
*/
function parseUriParts(urlString: string): UrlWithStringQuery {
// initialize return value
const returnValue: UrlWithStringQuery = uriParse('')
if (urlString) {
// A TypeError is thrown if urlString is not a string
// @see https://nodejs.org/api/url.html#url_url_parse_urlstring_parsequerystring_slashesdenotehost
if ('string' === typeof urlString) {
// check is an uri
return uriParse(urlString) // take apart the uri
}
}
return returnValue
}
import { SFCDescriptor } from './parse'
export interface StartOfSourceMap {
file?: string
sourceRoot?: string
}
export interface RawSourceMap extends StartOfSourceMap {
version: string
sources: string[]
names: string[]
sourcesContent?: string[]
mappings: string
}
export interface VueTemplateCompiler {
parseComponent(source: string, options?: any): SFCDescriptor
compile(
template: string,
options: VueTemplateCompilerOptions
): VueTemplateCompilerResults
ssrCompile(
template: string,
options: VueTemplateCompilerOptions
): VueTemplateCompilerResults
}
// we'll just shim this much for now - in the future these types
// should come from vue-template-compiler directly, or this package should be
// part of the vue monorepo.
export interface VueTemplateCompilerOptions {
modules?: Object[]
outputSourceRange?: boolean
whitespace?: 'preserve' | 'condense'
directives?: { [key: string]: Function }
}
export interface VueTemplateCompilerParseOptions {
pad?: 'line' | 'space'
}
export interface ErrorWithRange {
msg: string
start: number
end: number
}
export interface VueTemplateCompilerResults {
ast: Object | undefined
render: string
staticRenderFns: string[]
errors: (string | ErrorWithRange)[]
tips: (string | ErrorWithRange)[]
}
# 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.
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.
# 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
'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'];
\ No newline at end of file
"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"];
\ No newline at end of file
"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;
}
\ No newline at end of file
'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'];
\ No newline at end of file
'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'];
\ No newline at end of file
'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'];
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册