_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q58900
|
getEnginesNode
|
validation
|
function getEnginesNode(filename) {
const info = getPackageJson(filename)
return getSemverRange(info && info.engines && info.engines.node)
}
|
javascript
|
{
"resource": ""
}
|
q58901
|
existsCaseSensitive
|
validation
|
function existsCaseSensitive(filePath) {
let dirPath = filePath
while (dirPath !== "" && !ROOT.test(dirPath)) {
const fileName = path.basename(dirPath)
dirPath = path.dirname(dirPath)
if (fs.readdirSync(dirPath).indexOf(fileName) === -1) {
return false
}
}
return true
}
|
javascript
|
{
"resource": ""
}
|
q58902
|
get
|
validation
|
function get(option) {
if (option && option.resolvePaths && Array.isArray(option.resolvePaths)) {
return option.resolvePaths.map(String)
}
return null
}
|
javascript
|
{
"resource": ""
}
|
q58903
|
checkFile
|
validation
|
function checkFile(path) {
const formatter = path.match(/\.md$/) ? prettierFormat : clangFormat;
const source = fs.readFileSync(path, 'utf8');
const formatted = formatter(path, source);
if (source !== formatted) {
return formatted;
}
return null;
}
|
javascript
|
{
"resource": ""
}
|
q58904
|
serializeAttrs
|
validation
|
function serializeAttrs(attributes, opts) {
if (!attributes) {
return;
}
let output = '';
let value;
Object.keys(attributes).forEach(key => {
value = attributes[key];
if (output) {
output += ' ';
}
let isBoolAttr = value && typeof value === 'boolean';
if (isBoolAttr) {
output += key;
}
else {
output += key + '="' + (opts.decodeEntities ? entities.encodeXML(value) : value) + '"';
}
});
return output;
}
|
javascript
|
{
"resource": ""
}
|
q58905
|
getRequireExpressionModuleId
|
validation
|
function getRequireExpressionModuleId(node, t) {
if (t.isCallExpression(node)) {
let {arguments: args, callee} = node;
if (t.isIdentifier(callee)
&& callee.name === 'require'
&& args.length === 1
&& t.isLiteral(args[0])
) {
let id = args[0].value;
return id;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58906
|
removeVariableDeclaration
|
validation
|
function removeVariableDeclaration(t, bindVar, removeOpts) {
let refPaths = bindVar.referencePaths || [];
let removed;
// try to remove the bind variable in multiple variable declarations
refPaths.forEach(item => {
let parentPath = item.getStatementParent();
if (t.isVariableDeclaration(parentPath) && t.isIdentifier(item)) {
removeNode(t, item.parentPath, removeOpts);
removeComments(t, parentPath, 'leadingComments');
removed = true;
}
});
// if not multiple variable declarations,
// remove the single variable declaration statement
if (!removed) {
removeNode(t, bindVar.path.getStatementParent(), removeOpts);
}
}
|
javascript
|
{
"resource": ""
}
|
q58907
|
getRequiredModulePath
|
validation
|
function getRequiredModulePath(valuePath, moduleName, t, removeRequireDeclaration = false) {
let bindVar = valuePath.scope.bindings[moduleName];
if (!bindVar) {
throw valuePath.buildCodeFrameError(`the variable ${moduleName} import declaration is not found`);
}
let declareNodePath = bindVar.path;
let parentStatementPath = bindVar.path.getStatementParent();
// check import statement
if (t.isImportDeclaration(parentStatementPath)) {
let id = parentStatementPath.node.source.value;
if (removeRequireDeclaration) {
let toRemovePath = declareNodePath;
if (t.isImportDefaultSpecifier(declareNodePath.node)) {
toRemovePath = declareNodePath.parentPath;
}
removeNode(t, toRemovePath, {tail: true});
}
return id;
}
else if (t.isVariableDeclarator(declareNodePath)) {
// check require statement
let initNode = declareNodePath.node.init;
let id = getRequireExpressionModuleId(initNode, t);
if (id) {
removeRequireDeclaration && removeVariableDeclaration(
t, bindVar, {tail: true}
);
return id;
}
}
throw valuePath.buildCodeFrameError(`the variable ${moduleName} import declaration is not found`);
}
|
javascript
|
{
"resource": ""
}
|
q58908
|
transformFilterInAttribute
|
validation
|
function transformFilterInAttribute(element, tplOpts, options) {
let attrs = element.attribs;
let filterAttrs = element._hasFilterAttrs;
if (!filterAttrs || !filterAttrs.length) {
return;
}
let {logger, file} = tplOpts;
let {filters} = options;
filterAttrs.forEach(k => {
let value = attrs[k];
attrs[k] = updateFilterCall(filters, logger, file, value);
});
}
|
javascript
|
{
"resource": ""
}
|
q58909
|
processFile
|
validation
|
function processFile(file, processor, buildManager) {
let {compileContext, logger} = buildManager;
let {handler, options: opts, rext} = processor;
logger.debug(`compile file ${file.path}, using ${processor.name}: `, opts);
let result = handler(file, Object.assign({
config: opts
}, compileContext));
if (!result) {
return;
}
rext && (file.rext = rext);
if (isPromise(result)) {
buildManager.addAsyncTask(file, result);
return;
}
if (result.isSfcComponent) {
compileComponent(result, file, buildManager);
result = {content: file.content};
}
buildManager.updateFileCompileResult(file, result);
}
|
javascript
|
{
"resource": ""
}
|
q58910
|
getCustomComponentTags
|
validation
|
function getCustomComponentTags(config) {
let {usingComponents} = config || {};
if (!usingComponents) {
return;
}
return Object.keys(usingComponents).map(k => toHyphen(k));
}
|
javascript
|
{
"resource": ""
}
|
q58911
|
getImportFilterModules
|
validation
|
function getImportFilterModules(usedFilters, scriptFile, buildManager) {
if (!usedFilters) {
return;
}
let filterModules = [];
let {file: filterFile, filterNames: definedFilters} = scriptFile.filters || {};
let hasFilterUsed = definedFilters && usedFilters.some(item => {
if (definedFilters.includes(item)) {
return true;
}
return false;
});
if (!hasFilterUsed) {
return filterModules;
}
if (filterFile) {
let src = relative(filterFile.path, scriptFile.dirname);
if (src.charAt(0) !== '.') {
src = './' + src;
}
filterModules.push({src, filters: definedFilters});
}
else {
filterModules.push({filters: definedFilters});
}
return filterModules;
}
|
javascript
|
{
"resource": ""
}
|
q58912
|
getIncludeTemplateElement
|
validation
|
function getIncludeTemplateElement(tplFile) {
let ast = tplFile.ast;
if (!ast) {
ast = tplFile.ast = parseDom(tplFile.content.toString());
}
let children = ast.children;
for (let i = 0, len = children.length; i < len; i++) {
let node = children[i];
if (node.type === 'tag' && node.name === 'template') {
return node;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58913
|
processAppSpecifiedMediaRule
|
validation
|
function processAppSpecifiedMediaRule(allAppTypes, appType, rule) {
let result = matchAppMediaParams(allAppTypes, appType, rule.params);
if (!result) {
return;
}
let {removed, params} = result;
params && (params = params.trim());
if (removed) {
// remove media rule, not current app media query target
rule.remove();
}
else if (params) {
// remove current app media query params
rule.params = params;
}
else {
// remove current app media query rule wrapping
let children = rule.parent.nodes;
let currRuleIdx = children.indexOf(rule);
rule.nodes.forEach(item => {
item.parent = rule.parent; // up parent
let itemRaws = item.raws;
let subNodes = item.nodes;
// up raw style format
subNodes && subNodes.forEach(
sub => sub.raws.before = itemRaws.before
);
itemRaws.before = '\n';
itemRaws.after = '\n';
});
children.splice(currRuleIdx, 1, ...rule.nodes);
rule.nodes = null;
rule.parent = null;
}
}
|
javascript
|
{
"resource": ""
}
|
q58914
|
removeUnUseDecl
|
validation
|
function removeUnUseDecl(decl, toRemovePropName) {
let nodes = decl.parent.nodes;
let currIdx = nodes.indexOf(decl);
for (let i = currIdx - 1; i >= 0; i--) {
let item = nodes[i];
if (item.type === 'decl' && item.prop === toRemovePropName) {
item.remove();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58915
|
processAppSpecifiedDeclaration
|
validation
|
function processAppSpecifiedDeclaration(allAppTypes, appType, decl) {
let {prop, parent} = decl;
let result;
if ((result = SPECIFIED_APP_PROP_DECL_REGEXP.exec(prop))) {
let propApp = result[1];
let isMatchApp = appType === propApp;
if (allAppTypes.includes(propApp) && !isMatchApp) {
// remove not current app build type style declaration
decl.remove();
}
else if (isMatchApp) {
// remove the previous property style declaration that has same
// style property name declaration that ignore app type prefix
// and remove the specified app type prefix of the property
let newPropName = prop.replace(SPECIFIED_APP_PROP_DECL_REGEXP, '');
removeUnUseDecl(decl, newPropName);
decl.prop = newPropName;
}
// remove empty rule
if (!parent.nodes || !parent.nodes.length) {
parent.remove();
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58916
|
doMixin
|
validation
|
function doMixin(target, source, k, opts) {
let {
mixinAttrName = MIXIN_ATTR_NAME,
lifecycleHookMap,
mixinStrategy
} = opts;
if (k === mixinAttrName) {
return;
}
let mixinHandler = mixinStrategy && mixinStrategy[k];
if (mixinHandler) {
target[k] = mixinHandler(target[k], source[k]);
}
else if (lifecycleHookMap[k]) {
let child = target[k];
let parent = source[k];
if (!Array.isArray(child)) {
child = child ? [child] : [];
}
if (!Array.isArray(parent)) {
parent = parent ? [parent] : [];
}
child.unshift.apply(child, parent);
target[k] = child;
}
else if (!target.hasOwnProperty(k)) {
target[k] = source[k];
}
}
|
javascript
|
{
"resource": ""
}
|
q58917
|
flattenMixins
|
validation
|
function flattenMixins(mixins, target, opts) {
mixins.forEach(item => {
if (typeof item === 'function') {
item = item(true, opts); // return okam mixin definition
}
if (!item || typeof item !== 'object') {
return;
}
let submixins = item.mixins;
if (Array.isArray(submixins) && submixins.length) {
item = Object.assign({}, item);
flattenMixins(submixins, item, opts);
}
Object.keys(item).forEach(
k => doMixin(target, item, k, opts)
);
});
}
|
javascript
|
{
"resource": ""
}
|
q58918
|
addBuiltinPlugin
|
validation
|
function addBuiltinPlugin(pluginName, appType, plugins, insertAtTop) {
let pluginInfo = BUILTIN_PLUGINS[pluginName];
if (typeof pluginInfo === 'object') {
pluginInfo = pluginInfo[appType] || pluginInfo.default;
}
pluginInfo = normalizeViewPlugins([pluginInfo], appType)[0];
let plugin = Array.isArray(pluginInfo) ? pluginInfo[0] : pluginInfo;
let hasBuiltinPlugin = plugins.some(
item => (plugin === (Array.isArray(item) ? item[0] : item))
);
if (!hasBuiltinPlugin) {
plugins[insertAtTop ? 'unshift' : 'push'](pluginInfo);
}
}
|
javascript
|
{
"resource": ""
}
|
q58919
|
normalizeViewPlugins
|
validation
|
function normalizeViewPlugins(plugins, appType) {
return plugins.map(pluginInfo => {
let pluginItem = pluginInfo;
let pluginOptions;
if (Array.isArray(pluginInfo)) {
pluginItem = pluginInfo[0];
pluginOptions = pluginInfo[1];
}
if (typeof pluginItem === 'string') {
let pluginPath = BUILTIN_PLUGINS[pluginItem];
if (typeof pluginPath === 'function') {
pluginPath = pluginPath(appType);
}
else if (pluginPath && typeof pluginPath === 'object') {
pluginPath = pluginPath[appType] || pluginPath.default;
}
if (pluginPath && Array.isArray(pluginPath)) {
pluginOptions = pluginPath[1];
pluginPath = pluginPath[0];
}
pluginPath && (pluginItem = pluginPath);
}
if (typeof pluginItem === 'string') {
pluginItem = require(pluginItem);
}
return pluginOptions ? [pluginItem, pluginOptions] : pluginItem;
});
}
|
javascript
|
{
"resource": ""
}
|
q58920
|
handleOnTag
|
validation
|
function handleOnTag(file, tagName, replaceTagName) {
let tags = file.tags;
tags || (tags = file.tags = {});
if (replaceTagName && tags.hasOwnProperty(replaceTagName)) {
delete tags[replaceTagName];
}
tags[tagName] = true;
}
|
javascript
|
{
"resource": ""
}
|
q58921
|
handleOnFilter
|
validation
|
function handleOnFilter(file, filterName) {
let usedFilters = file.filters;
usedFilters || (usedFilters = file.filters = []);
if (!usedFilters.includes(filterName)) {
usedFilters.push(filterName);
}
}
|
javascript
|
{
"resource": ""
}
|
q58922
|
initViewTransformOptions
|
validation
|
function initViewTransformOptions(file, processOpts, buildManager, isNativeView) {
let plugins = processOpts.plugins;
let {appType, componentConf, buildConf} = buildManager;
if (isNativeView) {
return Object.assign({}, processOpts, {
plugins: normalizeViewPlugins(plugins, appType)
});
}
let templateConf = (componentConf && componentConf.template) || {};
if (!plugins || !plugins.length) {
plugins = ['syntax'];
if (templateConf.transformTags) {
plugins.push('tagTransform');
}
// vuePrefix 需要在第一位,v- directives 处理成 directives 再处理
if (templateConf.useVuePrefix) {
plugins.unshift('vuePrefix');
}
}
plugins = normalizeViewPlugins(plugins, appType);
let isSupportRef = buildManager.isEnableRefSupport();
isSupportRef && addBuiltinPlugin('ref', appType, plugins);
let isSupportVHtml = buildManager.isEnableVHtmlSupport();
isSupportVHtml && addBuiltinPlugin('vhtml', appType, plugins);
addBuiltinPlugin('resource', appType, plugins, true);
processOpts.plugins = plugins;
let filterOptions = buildManager.getFilterTransformOptions();
if (filterOptions) {
filterOptions = Object.assign({
onFilter: handleOnFilter.bind(null, file)
}, filterOptions);
}
return Object.assign(
{},
processOpts,
{
framework: buildConf.framework || [],
plugins,
filter: filterOptions,
template: templateConf,
onTag: handleOnTag.bind(null, file)
}
);
}
|
javascript
|
{
"resource": ""
}
|
q58923
|
navigateTo
|
validation
|
function navigateTo(options) {
let {url, params} = options;
let queryIdx = url.indexOf('?');
if (queryIdx !== -1) {
let query = url.substr(queryIdx + 1);
url = url.substring(0, queryIdx);
if (query) {
query = parseQuery(query);
params = Object.assign({}, query, params);
}
}
if (url.charAt(0) === '/') {
let urlParts = url.split('/');
urlParts.pop(); // remove component name
url = urlParts.join('/');
}
router.push({
uri: url,
params
});
}
|
javascript
|
{
"resource": ""
}
|
q58924
|
compile
|
validation
|
function compile(file, options) {
let config = options.config || {};
let presets = config.presets || [];
let tsPreset = '@babel/preset-typescript';
if (!presets.includes(tsPreset)) {
config.presets = [tsPreset].concat(presets);
options.config = config;
}
return parserHelper.compile(file, options, 7);
}
|
javascript
|
{
"resource": ""
}
|
q58925
|
createInitCallArgs
|
validation
|
function createInitCallArgs(declarationPath, config, opts, t) {
let {isPage, isComponent, isApp, getInitOptions} = opts;
let callArgs = [declarationPath.node];
let initOptions;
if (opts.tplRefs) {
initOptions = {refs: opts.tplRefs};
}
let extraInitOpts = getInitOptions && getInitOptions(
config, {isPage, isComponent, isApp}
);
if (extraInitOpts) {
initOptions || (initOptions = {});
Object.assign(initOptions, extraInitOpts);
}
if (initOptions) {
// insert the `ref` information defined in template to the constructor
callArgs.push(
createSimpleObjectExpression(
initOptions, t
)
);
}
return callArgs;
}
|
javascript
|
{
"resource": ""
}
|
q58926
|
transformMiniProgram
|
validation
|
function transformMiniProgram(t, path, declarationPath, config, opts) {
if (t.isObjectExpression(declarationPath)) {
// extract the config information defined in the code
declarationPath.traverse(
getCodeTraverseVisitors(t, config, opts)
);
}
else if (opts.isExtension) {
return;
}
else {
throw path.buildCodeFrameError('export require plain object');
}
let baseClassName = path.scope.generateUid(opts.baseName);
let rootPath = path.findParent(p => t.isProgram(p));
let bodyPath = rootPath.get('body.0');
// ensure the inserted import declaration is after the leading comment
removeComments(t, bodyPath, 'leadingComments');
// insert the base name import statement
bodyPath.insertBefore(
createImportDeclaration(baseClassName, opts.baseId, t)
);
if (opts.isApp) {
// insert the app extension use statements
appTransformer.extendAppFramework(
t, path, bodyPath, baseClassName, opts
);
}
let callArgs = createInitCallArgs(declarationPath, config.config, opts, t);
let needExport = opts.needExport || !opts.baseClass;
let toReplacePath = needExport
? path.get('declaration')
: path;
// wrap the export module using the base name
let callExpression = t.callExpression(
t.identifier(baseClassName),
callArgs
);
if (opts.isBehavior || !opts.baseClass) {
toReplacePath.replaceWith(t.expressionStatement(
callExpression
));
}
else {
toReplacePath.replaceWith(
t.expressionStatement(
t.callExpression(
t.identifier(opts.baseClass),
[
callExpression
]
)
)
);
}
// stop traverse to avoid the new created export default statement above
// that be revisited in this plugin `ExportDefaultDeclaration` visitor
// path.stop();
}
|
javascript
|
{
"resource": ""
}
|
q58927
|
getTransformOptions
|
validation
|
function getTransformOptions(options, state) {
let transformOpts = Object.assign({}, options, state.opts);
transformOpts.baseId = options.extensionName
? getFrameworkExtendId(transformOpts.appType, options.extensionName, true)
: getBaseId(transformOpts.appType, transformOpts.baseName);
return transformOpts;
}
|
javascript
|
{
"resource": ""
}
|
q58928
|
getPageInfo
|
validation
|
function getPageInfo(pagePath, prefix) {
let parts = pagePath.split('/');
let componentName = parts.pop();
let pageName = parts.join('/');
prefix && (pageName = `${prefix}/${pageName}`);
return {
pageName,
componentName
};
}
|
javascript
|
{
"resource": ""
}
|
q58929
|
normalizePages
|
validation
|
function normalizePages(result, pages, prefix) {
let entryPageName;
pages.forEach((item, idx) => {
let filter;
if (typeof item === 'object') {
let {path, filter: pageFilter} = item;
item = path;
filter = pageFilter;
}
let {pageName, componentName} = getPageInfo(item, prefix);
let pageInfo = {
component: componentName
};
filter && (pageInfo.filter = filter);
result[pageName] = pageInfo;
if (idx === 0) {
entryPageName = pageName;
}
});
return entryPageName;
}
|
javascript
|
{
"resource": ""
}
|
q58930
|
normalizeRouteInfo
|
validation
|
function normalizeRouteInfo(pages, subPackages) {
let result = {};
let entryPageName = normalizePages(result, pages);
subPackages && subPackages.forEach(item => {
let {root, pages: subPages} = item;
normalizePages(result, subPages, root);
});
return {
entry: entryPageName,
pages: result
};
}
|
javascript
|
{
"resource": ""
}
|
q58931
|
addDisplayPageConfig
|
validation
|
function addDisplayPageConfig(pages, sourceDir, configFile) {
let path = relative(configFile.fullPath, sourceDir);
let {pageName} = getPageInfo(path);
let currPageDisplayInfo = pages[pageName];
let pageConfig = JSON.parse(configFile.content);
let result = {};
// filter the illegal not supported config item
// and map the weixin config name to quick app
Object.keys(pageConfig).forEach(k => {
let newKey = DISPLAY_PAGE_CONFIG_MAP[k];
if (newKey) {
result[newKey] = pageConfig[k];
}
});
// merge the page config, the config defined in page has higher priority
// than the app config
pages[pageName] = Object.assign({}, currPageDisplayInfo, result);
}
|
javascript
|
{
"resource": ""
}
|
q58932
|
normalizeWindowConfig
|
validation
|
function normalizeWindowConfig(windowConfig) {
if (!windowConfig) {
return;
}
let result = {};
// filter the illegal not supported config item
// and map the weixin config name to quick app
Object.keys(windowConfig).forEach(k => {
let newKey = DISPLAY_PAGE_CONFIG_MAP[k];
if (newKey) {
result[newKey] = windowConfig[k];
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58933
|
addFeatureItem
|
validation
|
function addFeatureItem(logger, existed, name, params) {
if (!existed[name]) {
existed[name] = true;
let feature = {name};
params && (feature.params = params);
return feature;
}
logger.debug('duplicated feature declaration', name);
return false;
}
|
javascript
|
{
"resource": ""
}
|
q58934
|
normalizeFeatureItem
|
validation
|
function normalizeFeatureItem(item, existed, result, logger) {
let addItem;
if (typeof item === 'string') {
addItem = addFeatureItem(logger, existed, item);
}
else if (Array.isArray(item)) {
let [name, params] = item;
addItem = addFeatureItem(logger, existed, name, params);
}
else if (item && typeof item === 'object') {
let {name, params} = item;
addItem = addFeatureItem(logger, existed, name, params);
}
if (addItem) {
result.push(addItem);
}
}
|
javascript
|
{
"resource": ""
}
|
q58935
|
compile
|
validation
|
function compile(file, options) {
if (!file.compileReady && !file.owner.processed) {
return {content: file.content};
}
let {
getAllPageConfigFiles,
sourceDir,
designWidth
} = options;
let obj = JSON.parse(file.content.toString());
// normalize router info
let routerInfo = normalizeRouteInfo(obj.pages);
delete obj.pages;
obj.router = routerInfo;
// normalize debug info
normalizeDebugConfig(obj);
// init designWidth
if (designWidth) {
obj.config || (obj.config = {});
if (!obj.config.designWidth) {
obj.config.designWidth = designWidth;
}
}
// normalize window config info
let displayInfo = obj.display;
let displayConfig = normalizeWindowConfig(obj.window);
// the display config has higher priority than window config
displayConfig && (displayInfo = Object.assign(displayConfig, displayInfo));
displayInfo && (obj.display = displayInfo);
delete obj.window;
// normalize display pages info
if (displayInfo && displayInfo.pages) {
displayInfo.pages = normalizeDisplayPages(displayInfo.pages);
}
// normalize features
let features = getUsedAPIFeatures(obj.features, options);
features && (obj.features = features);
// merge the page display config defined in page
let pageConfigFiles = getAllPageConfigFiles();
let currDisplayPages = (displayInfo && displayInfo.pages) || {};
pageConfigFiles.forEach(item => {
addDisplayPageConfig(currDisplayPages, sourceDir, item);
});
if (Object.keys(currDisplayPages).length) {
displayInfo || (obj.display = {});
obj.display.pages = currDisplayPages;
}
return {
content: JSON.stringify(obj, null, 4)
};
}
|
javascript
|
{
"resource": ""
}
|
q58936
|
normalizeQuickAppPage
|
validation
|
function normalizeQuickAppPage(pageInfo) {
pageInfo = normalizePage(pageInfo);
let {data, dataAccessType} = pageInfo;
if (data && !pageInfo[dataAccessType]) {
pageInfo[dataAccessType] = data;
delete pageInfo.data;
}
// extract the protected and public data props as the query props
let queryProps = [];
if (pageInfo.protected) {
queryProps = Object.keys(pageInfo.protected);
}
if (pageInfo.public) {
queryProps = queryProps.push.apply(
queryProps, Object.keys(pageInfo.public)
);
}
let privateData = pageInfo.private;
privateData || (privateData = pageInfo.private = {});
// we using `__` suffix as the inner data, as for `_` leading char is not allowed
// hook the data to the page context is also not allowed, so we need put it
// to the privateData
/* eslint-disable fecs-camelcase */
privateData.queryProps__ = queryProps;
return pageInfo;
}
|
javascript
|
{
"resource": ""
}
|
q58937
|
getImportTemplateElement
|
validation
|
function getImportTemplateElement(tplFile, name) {
if (!name) {
return;
}
let ast = tplFile.ast;
if (!ast) {
ast = tplFile.ast = parseDom(tplFile.content.toString());
}
let children = ast.children;
for (let i = 0, len = children.length; i < len; i++) {
let node = children[i];
if (node.type === 'tag' && node.name === 'template') {
let {attribs: attrs} = node;
if (attrs && attrs.name === name) {
return node;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q58938
|
parseTplDataInfo
|
validation
|
function parseTplDataInfo(value) {
value = value.substring(1, value.length - 1);
let items = value.split(',');
let dataObjAttrs = {};
items.forEach(item => {
let colonIdx = item.indexOf(':');
if (colonIdx !== -1) {
let key = item.substring(0, colonIdx).trim();
let value = item.substr(colonIdx + 1).trim();
key === value || (dataObjAttrs[key] = value);
}
});
return Object.keys(dataObjAttrs).length ? dataObjAttrs : null;
}
|
javascript
|
{
"resource": ""
}
|
q58939
|
replaceTemplateVariable
|
validation
|
function replaceTemplateVariable(value, data) {
return value.replace(/\{\{(.+)\}\}/g, (match, varName) => {
varName = varName.trim();
let newVarName = data[varName];
if (newVarName) {
return `{{${newVarName}}}`;
}
return match;
});
}
|
javascript
|
{
"resource": ""
}
|
q58940
|
replaceElementAttributeVariable
|
validation
|
function replaceElementAttributeVariable(attrs, data) {
let newAttrs = Object.assign({}, attrs);
attrs && Object.keys(attrs).forEach(k => {
let value = attrs[k];
if (k.startsWith(':')) {
// replace okam data variable
let newDataName = data[value];
newDataName && (newAttrs[k] = newDataName);
}
else {
value = replaceTemplateVariable(value, data);
newAttrs[k] = value;
}
});
return newAttrs;
}
|
javascript
|
{
"resource": ""
}
|
q58941
|
updateTemplateDataVariableName
|
validation
|
function updateTemplateDataVariableName(element, data) {
let {children} = element;
let result = [];
children && children.forEach(item => {
let {type} = item.type;
let newItem = Object.assign({}, item);
if (type === 'tag') {
let {attribs: attrs, children} = item;
newItem.attribs = replaceElementAttributeVariable(attrs, data);
if (children) {
let newChildren = updateTemplateDataVariableName(item, data);
newChildren && (newItem.children = newChildren);
}
}
else if (type === 'text') {
let {data: textValue} = item;
textValue = replaceTemplateVariable(textValue, data);
newItem.data = textValue;
}
result.push(newItem);
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58942
|
shouldPolyfill
|
validation
|
function shouldPolyfill(importName, name, path) {
let result;
if (Array.isArray(importName)) {
result = importName.some(item => (item === name));
}
else {
result = importName === name;
}
// ignore global variable, e.g., Array/Number/Promise etc.
return result && !path.scope.hasBinding(name, true);
}
|
javascript
|
{
"resource": ""
}
|
q58943
|
proxyDataGetter
|
validation
|
function proxyDataGetter(ctx, prop) {
let proxyProps = ctx.__proxyProps;
proxyProps || (proxyProps = ctx.__proxyProps = {});
if (proxyProps[prop]) {
return;
}
proxyProps[prop] = true;
let descriptor = Object.getOwnPropertyDescriptor(ctx, prop);
if (descriptor && descriptor.configurable) {
let newDescriptor = Object.assign({}, descriptor, {
get() {
ctx.__deps && ctx.__deps.push(prop);
return descriptor.get && descriptor.get.call(ctx);
}
});
Object.defineProperty(ctx, prop, newDescriptor);
}
else {
console.warn('cannot configure the data prop descriptor info:', prop);
}
}
|
javascript
|
{
"resource": ""
}
|
q58944
|
addDataChangeWatcher
|
validation
|
function addDataChangeWatcher(ctx, prop, deep) {
// in quick app, the watch handler does not support dynamic added methods
// let handler = '__handleDataChange$' + prop;
// ctx[handler] = (newVal, oldVal) => ctx.__handleDataChange(
// prop, newVal, oldVal
// );
// FIXME: array cannot support deep watch in quick app when change array item info
let handlerName = getInnerWatcher(prop);
watchDataChange.call(ctx, prop, handlerName, {deep});
}
|
javascript
|
{
"resource": ""
}
|
q58945
|
collectComputedPropDeps
|
validation
|
function collectComputedPropDeps(ctx, prop, getter) {
ctx.__deps = [];
let value = getter.call(ctx);
ctx.__computedDeps[prop] = ctx.__deps;
ctx.__deps = null;
return value;
}
|
javascript
|
{
"resource": ""
}
|
q58946
|
findChangeComputedProps
|
validation
|
function findChangeComputedProps(allDeps, changeProp) {
let result = [];
Object.keys(allDeps).forEach(k => {
let depList = allDeps[k];
if (k !== changeProp && depList.indexOf(changeProp) !== -1) {
result.push(k);
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58947
|
initGlobalComponents
|
validation
|
function initGlobalComponents(appType, componentConf, sourceDir) {
let {global: globalComponents} = componentConf;
if (!globalComponents) {
return;
}
let result = {};
Object.keys(globalComponents).forEach(k => {
let value = globalComponents[k];
value = value.replace(/^okam\//, BUILTIN_COMPONENTS_PACKAGE_ROOT + appType + '/');
let isRelMod = value.charAt(0) === '.';
if (isRelMod) {
value = pathUtil.join(sourceDir, value);
}
result[toHyphen(k)] = {
isNpmMod: !isRelMod,
modPath: value
};
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58948
|
compile
|
validation
|
function compile(file, options) {
let obj = json5.parse(file.content.toString());
let result = JSON.stringify(obj, null, 4);
return {
content: result
};
}
|
javascript
|
{
"resource": ""
}
|
q58949
|
initPlatformInfo
|
validation
|
function initPlatformInfo(callback) {
api.getSystemInfo({
success(info) {
callback && callback(null, info);
},
fail(err) {
callback && callback(err);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58950
|
createFile
|
validation
|
function createFile(fileInfo, rootDir) {
let {path: relPath, fullPath, data, isVirtual, isScript, isStyle, isTemplate} = fileInfo;
if (relPath && !fullPath) {
fullPath = path.resolve(rootDir, relPath);
}
let extname = path.extname(fullPath).slice(1).toLowerCase();
let vf = {
processor: FILE_EXT_PROCESSOR[extname],
dirname: path.dirname(fullPath),
extname,
fullPath,
path: relPath || relative(fullPath, rootDir),
rawContent: data,
isVirtual,
isScript: isScript == null ? isScriptType(extname) : isScript,
isStyle: isStyle == null ? isStyleType(extname) : isStyle,
isImg: isImgType(extname),
isTpl: isTemplate == null ? isTplType(extname) : isTemplate,
isJson: isJsonType(extname),
addDeps,
addSubFile,
reset: resetFile,
sourceMap: null
};
Object.defineProperties(vf, {
stream: {
get: getFileStream
},
content: {
get: loadFileContent,
set: updateFileContent
}
});
return vf;
}
|
javascript
|
{
"resource": ""
}
|
q58951
|
tryToResolveRequireModId
|
validation
|
function tryToResolveRequireModId(t, path, state) {
let opts = state.opts || {};
let resolveRequireId = opts.resolveDepRequireId;
let exportNode = path.node;
let source = exportNode.source;
if (!t.isStringLiteral(source)) {
return;
}
let modId = source.value;
let newModId = resolveRequireId(modId);
if (newModId && newModId !== modId) {
let requireIdNode = path.get('source');
requireIdNode.replaceWith(
t.stringLiteral(newModId)
);
}
}
|
javascript
|
{
"resource": ""
}
|
q58952
|
showEventNameLog
|
validation
|
function showEventNameLog(name, newName, eventModifiers, attrs, tplOpts) {
let {logger, file, appType} = tplOpts;
NOT_SUPPORT_MODIFIERS.forEach(item => {
if (eventModifiers.includes(item)) {
logger.warn(
`${file.path} template event attribute ${name}`,
`is not support with ${item} modifier in ${appType} env`
);
}
});
if (attrs.hasOwnProperty(newName)) {
logger.warn(`${file.path} template attribute ${name} is conflicted with ${newName}`);
}
}
|
javascript
|
{
"resource": ""
}
|
q58953
|
getRandomStringNotIn
|
validation
|
function getRandomStringNotIn(string) {
const randomString = Math.random().toString(36).substr(2);
if (string.indexOf(randomString) === -1) {
return randomString;
}
return getRandomStringNotIn(string);
}
|
javascript
|
{
"resource": ""
}
|
q58954
|
sortDefaultProcessors
|
validation
|
function sortDefaultProcessors(processorNames, processors) {
if (Array.isArray(processorNames)) {
processorNames.sort((a, b) => {
a = processors[a];
b = processors[b];
return (a.order || 0) - (b.order || 0);
});
}
}
|
javascript
|
{
"resource": ""
}
|
q58955
|
addFileExtnameAssociatedProcessor
|
validation
|
function addFileExtnameAssociatedProcessor(extnames, processorName, existedMap) {
if (!extnames) {
return;
}
if (!Array.isArray(extnames)) {
extnames = [extnames];
}
extnames.forEach(k => {
k = k.toLowerCase();
let processors = existedMap[k];
if (Array.isArray(processors)) {
processors.push(processorName);
}
else if (processors) {
existedMap[k] = [processors, processorName];
}
else {
existedMap[k] = processorName;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58956
|
removeFileExtnameAssociatedProcessor
|
validation
|
function removeFileExtnameAssociatedProcessor(extnames, processorName, existedMap) {
if (!extnames) {
return;
}
if (!Array.isArray(extnames)) {
extnames = [extnames];
}
extnames.forEach(k => {
let currItems = existedMap[k];
if (Array.isArray(currItems)) {
let idx = currItems.indexOf(processorName);
if (idx !== -1) {
currItems.splice(idx, 1);
currItems.length === 0 && (existedMap[k] = undefined);
}
}
else if (currItems === processorName) {
existedMap[k] = undefined;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58957
|
getFileExtnameAssociatedProcessor
|
validation
|
function getFileExtnameAssociatedProcessor(processors) {
let result = Object.keys(processors).reduce(
(lastValue, processorName) => {
let processor = processors[processorName];
let extnames = processor.extnames || [];
if (!Array.isArray(extnames)) {
extnames = [extnames];
}
addFileExtnameAssociatedProcessor(extnames, processorName, lastValue);
return lastValue;
},
{}
);
Object.keys(result).forEach(
k => sortDefaultProcessors(result[k], processors)
);
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58958
|
initProcessorInfo
|
validation
|
function initProcessorInfo(name, info, existedProcessors) {
let processor = info.processor;
if (!processor) {
return info;
}
if (typeof processor === 'string') {
// if the processor refer to the existed processor, merge the existed
// processor info with current processor
let old = existedProcessors[processor];
if (old) {
info.processor = undefined;
// remove undefined attributes
info = removeUndefinedAttributes(info);
let deps = info.deps;
deps && !Array.isArray(deps) && (deps = [deps]);
let oldDeps = old.deps;
oldDeps && !Array.isArray(oldDeps) && (oldDeps = [oldDeps]);
info = Object.assign({}, old, info);
info.deps = merge(deps || [], oldDeps || []);
return Object.assign({refer: processor}, old, info);
}
}
try {
info.processor = resolveProcessor(processor);
}
catch (ex) {
let msg = `processor \`${name}\` handler \`${processor}\` not `
+ `found: ${ex.message || ex.toString()}`;
throw new Error(msg);
}
return info;
}
|
javascript
|
{
"resource": ""
}
|
q58959
|
overrideObjectFunctions
|
validation
|
function overrideObjectFunctions(curr, old) {
if (!old) {
return curr;
}
if (!curr && curr !== undefined) {
return old;
}
let result = {};
Object.keys(curr).forEach(k => {
let v = curr[k];
let oldV = old[k];
if (typeof v === 'function' && typeof oldV === 'function') {
let currV = v;
v = function (...args) {
oldV.apply(this, args);
currV.apply(this, args);
};
}
result[k] = v;
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58960
|
overrideProcessor
|
validation
|
function overrideProcessor(existedProcessor, extnameProcessorMap, opts) {
let oldExtnames;
let newExtnames;
Object.keys(opts).forEach(k => {
let v = opts[k];
if (!v) {
return;
}
if (k === 'extnames') {
oldExtnames = existedProcessor[k];
newExtnames = v;
}
if (k === 'hook') {
v = overrideObjectFunctions(v, existedProcessor[k]);
}
existedProcessor[k] = v;
});
let processor = opts.processor;
if (processor) {
existedProcessor.processor = resolveProcessor(processor);
}
let processorName = opts.name;
removeFileExtnameAssociatedProcessor(
oldExtnames, processorName, extnameProcessorMap
);
addFileExtnameAssociatedProcessor(newExtnames, processorName, extnameProcessorMap);
}
|
javascript
|
{
"resource": ""
}
|
q58961
|
updateReferProcessorInfo
|
validation
|
function updateReferProcessorInfo(existedProcessors, processorName, referProcessorName) {
let currProcessor = existedProcessors[processorName];
if (!currProcessor || currProcessor.processor) {
return;
}
let referProcessorInfo = existedProcessors[referProcessorName];
if (!referProcessorInfo) {
return;
}
let deps = referProcessorInfo.deps;
deps && !Array.isArray(deps) && (deps = [deps]);
let oldDeps = currProcessor.deps;
oldDeps && !Array.isArray(oldDeps) && (oldDeps = [oldDeps]);
let old = Object.assign({}, currProcessor);
Object.assign(currProcessor, referProcessorInfo, old, {
refer: referProcessorName,
deps: merge(deps || [], oldDeps || []),
processor: referProcessorInfo.processor
});
}
|
javascript
|
{
"resource": ""
}
|
q58962
|
registerProcessor
|
validation
|
function registerProcessor(existedProcessors, extnameProcessorMap, opts) {
let {name, processor, deps, rext, extnames, options, order, hook} = opts;
if (!name) {
throw new Error('missing processor name to register');
}
if (existedProcessors.hasOwnProperty(name)) {
// override existed processor definition
overrideProcessor(
existedProcessors[name], extnameProcessorMap, opts
);
}
else {
existedProcessors[name] = initProcessorInfo(name, {
processor,
deps,
rext,
extnames,
options,
order,
hook
}, existedProcessors);
addFileExtnameAssociatedProcessor(extnames, name, extnameProcessorMap);
}
// resort the file extname associated processors execution order
if (extnames && !Array.isArray(extnames)) {
extnames = [extnames];
}
extnames && extnames.forEach(
k => sortDefaultProcessors(extnameProcessorMap[k], existedProcessors)
);
}
|
javascript
|
{
"resource": ""
}
|
q58963
|
generateFilterCode
|
validation
|
function generateFilterCode(filterObjAst, t, options) {
if (!filterObjAst.properties.length) {
return '';
}
let {format = 'es6', usingBabel6} = options || {};
let ast;
if (format === 'es6') {
ast = generateES6ModuleFilterCode(filterObjAst, t);
}
else {
ast = generateCommonJSModuleFilterCode(filterObjAst, t);
}
return generateCode(ast, {
auxiliaryCommentBefore: 'Auto generated filter code by okam'
}, usingBabel6).code;
}
|
javascript
|
{
"resource": ""
}
|
q58964
|
createAPIDoneHook
|
validation
|
function createAPIDoneHook(done, ctx) {
let hookInfo = {
resData: null,
resException: false,
hook: null
};
hookInfo.hook = (err, res, complete, shouldCatchException) => {
let result;
if (err != null) {
result = err;
if (shouldCatchException) {
try {
let data = done(result, null, ctx);
data == null || (result = data);
}
catch (ex) {
// cache exception info for promise
hookInfo.resException = true;
result = ex;
}
}
else {
let data = done(result, null, ctx);
data == null || (result = data);
}
}
else {
let data = done(null, res, ctx);
data == null || (res = data);
result = res;
}
// cache response data for promise
hookInfo.resData = result;
complete && complete(result); // call complete callback
return result;
};
return hookInfo;
}
|
javascript
|
{
"resource": ""
}
|
q58965
|
interceptPromiseResponse
|
validation
|
function interceptPromiseResponse(hasIntercepted, promise, doneHookInfo) {
let {hook} = doneHookInfo;
return promise.then(
res => (hasIntercepted ? doneHookInfo.resData : hook(null, res)),
err => {
// check whether is intercepted to avoid repeated interception
if (hasIntercepted) {
let {resException, resData} = doneHookInfo;
if (resException) {
throw resData;
}
return resData;
}
return hook(err || /* istanbul ignore next */ 'err');
}
);
}
|
javascript
|
{
"resource": ""
}
|
q58966
|
hookAPIInit
|
validation
|
function hookAPIInit(init, args, ctx) {
// API init interception
if (isFunction(init)) {
if (args.length > 1 || !isObject(args[0])) {
// convert as one array type argument to make the developer
// can modify the call arguments directly
args = [args];
}
return init.apply(this, [...args, ctx]);
}
}
|
javascript
|
{
"resource": ""
}
|
q58967
|
hookAPIDone
|
validation
|
function hookAPIDone(done, sync, args, ctx) {
// API done interception
let hasDoneHook = isFunction(done);
let hasIntercepted = false;
let doneHookInfo;
if (hasDoneHook) {
doneHookInfo = createAPIDoneHook(done, ctx);
// intercept async API based the args: `success`/`fail`/`complete` callback
hasIntercepted = interceptAsyncAPIDone(sync, args, doneHookInfo.hook);
}
return {
hasDoneHook,
hasIntercepted,
doneHookInfo
};
}
|
javascript
|
{
"resource": ""
}
|
q58968
|
queryComponentInstance
|
validation
|
function queryComponentInstance(ctx, id) {
let isSelectAll = Array.isArray(id);
isSelectAll && (id = id[0]);
// query multiple components is not supported
let key = id.substr(1);
return ctx.$child(key);
}
|
javascript
|
{
"resource": ""
}
|
q58969
|
initRelations
|
validation
|
function initRelations(component, isPage) {
let relations = component.relations;
if (!relations || isPage) {
// relations only support component, page is not supported
return;
}
// normalize relation `target` information
Object.keys(relations).forEach(k => {
let item = relations[k];
let {target} = item;
if (typeof target === 'function') {
target = target();
item.target = target.behavior;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58970
|
preparePolyfillSupport
|
validation
|
function preparePolyfillSupport(polyfill, rootDir, logger) {
if (!polyfill) {
return;
}
if (!Array.isArray(polyfill)) {
polyfill = [polyfill];
}
polyfill.forEach(info => {
try {
ensure(info.desc, info.deps, rootDir);
}
catch (ex) {
logger.warn(ex.toString());
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58971
|
getPlainObjectNodeValue
|
validation
|
function getPlainObjectNodeValue(node, path, t) {
let result;
if (t.isObjectExpression(node)) {
result = {};
let props = node.properties || [];
for (let i = 0, len = props.length; i < len; i++) {
let subNode = props[i];
let keyNode = subNode.key;
let key;
if (t.isLiteral(keyNode)) {
key = keyNode.value;
}
else if (t.isIdentifier(keyNode)) {
key = keyNode.name;
}
if (!key) {
continue;
}
result[key] = getPlainObjectNodeValue(subNode.value, path, t);
}
}
else if (t.isArrayExpression(node)) {
result = [];
node.elements.forEach(item => {
result.push(getPlainObjectNodeValue(item, path, t));
});
}
else if (t.isNullLiteral(node)) {
result = null;
}
else if (t.isLiteral(node)) {
result = node.value;
}
else {
throw path.buildCodeFrameError('only constant is supported');
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58972
|
createNode
|
validation
|
function createNode(value, t) {
if (t.isIdentifier(value)) {
return value;
}
if (Array.isArray(value)) {
let elements = [];
value.forEach(item => {
let node = createNode(item, t);
node && elements.push(node);
});
return t.arrayExpression(elements);
}
if (Object.prototype.toString.call(value) === '[object Object]') {
let props = [];
Object.keys(value).forEach(k => {
let node = createNode(value[k], t);
if (node) {
props.push(t.objectProperty(
t.identifier(`'${k}'`),
node
));
}
});
return t.objectExpression(props);
}
if (value == null) {
return t.nullLiteral();
}
let valueType = typeof value;
switch (valueType) {
case 'boolean':
return t.booleanLiteral(value);
case 'string':
return t.stringLiteral(value);
case 'number':
return t.numericLiteral(value);
}
}
|
javascript
|
{
"resource": ""
}
|
q58973
|
removeComments
|
validation
|
function removeComments(t, path, type) {
let commentPaths = path.get(type);
if (!commentPaths || !commentPaths.length) {
return;
}
let isLeadingType = type === LEADING_COMMENT_TYPE;
if (isLeadingType) {
let parentPath = path.parentPath;
let isParentProgram = parentPath && t.isProgram(parentPath.node);
// move leading comments to program
if (isParentProgram) {
parentPath.addComments(
'leading',
commentPaths.map(item => item.node)
);
}
}
commentPaths.forEach(item => item.remove());
}
|
javascript
|
{
"resource": ""
}
|
q58974
|
handleProxyEvent
|
validation
|
function handleProxyEvent(source, target, eventName, options) {
let {newEventName, prependSourceArg} = options || {};
source.on(eventName, function (...args) {
prependSourceArg && args.unshift(source);
if (typeof newEventName === 'function') {
newEventName.apply(target, args);
}
else {
newEventName || (newEventName = eventName);
args.unshift(newEventName);
target.emit.apply(target, args);
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58975
|
makeComputedObservable
|
validation
|
function makeComputedObservable(ctx) {
let computedInfo = ctx.$rawComputed || {};
if (typeof computedInfo === 'function') {
ctx.$rawComputed = computedInfo = computedInfo();
}
let observer = new ComputedObserver(ctx, computedInfo);
let ctxProps = {};
Object.keys(computedInfo).forEach(k => {
ctxProps[k] = {
get: observer.getGetter(k),
set: observer.getSetter(k),
enumerable: true
};
});
Object.defineProperties(ctx, ctxProps);
return observer;
}
|
javascript
|
{
"resource": ""
}
|
q58976
|
makePropsObservable
|
validation
|
function makePropsObservable(ctx) {
let props = ctx.$rawProps;
if (typeof props === 'function') {
props = ctx.$rawProps = props();
}
if (!props) {
return;
}
let observer = new Observer(
ctx,
ctx[propDataKey] || /* istanbul ignore next */ {},
null,
true
);
let propsObj = {};
Object.keys(props).reduce((last, item) => {
last[item] = true;
return last;
}, propsObj);
Object.defineProperties(ctx, proxyObject(observer, propsObj));
return observer;
}
|
javascript
|
{
"resource": ""
}
|
q58977
|
makeDataObservable
|
validation
|
function makeDataObservable(ctx) {
const data = ctx.data;
if (!data) {
return;
}
if (isPlainObject(data)) {
/* eslint-disable no-use-before-define */
let observer = new Observer(ctx, data);
Object.defineProperties(
ctx, proxyObject(observer, data, ctx)
);
return observer;
}
let err = new Error('data require plain object');
err.isTypeError = true;
throw err;
}
|
javascript
|
{
"resource": ""
}
|
q58978
|
initLocalPolyfillPlugins
|
validation
|
function initLocalPolyfillPlugins(polyfills, plugins) {
polyfills.forEach(item => {
let pluginItem = polyfillPlugin[item.type];
plugins.push([
pluginItem, {polyfill: item}
]);
});
}
|
javascript
|
{
"resource": ""
}
|
q58979
|
hasBabelDepPlugin
|
validation
|
function hasBabelDepPlugin(plugins) {
return plugins.some(item => {
let pluginItem = item;
if (Array.isArray(item)) {
pluginItem = item[0];
}
if (typeof pluginItem === 'string') {
return pluginItem === DEP_PLUGIN_NAME;
}
return pluginItem === programPlugins.resolveDep;
});
}
|
javascript
|
{
"resource": ""
}
|
q58980
|
normalizeBabelPlugins
|
validation
|
function normalizeBabelPlugins(plugins, file, buildManager) {
if (typeof plugins === 'function') {
plugins = plugins(file);
}
plugins = plugins ? [].concat(plugins) : [];
if (!hasBabelDepPlugin(plugins)) {
// add npm resolve plugin
plugins.push(DEP_PLUGIN_NAME);
}
return (plugins || []).map(item => {
if (typeof item === 'string') {
let result = BUILTIN_PLUGINS[item];
if (typeof result === 'function') {
return result(file, buildManager);
}
}
return item;
});
}
|
javascript
|
{
"resource": ""
}
|
q58981
|
initBabelProcessorOptions
|
validation
|
function initBabelProcessorOptions(file, processorOpts, buildManager) {
processorOpts = Object.assign(
{}, buildManager.babelConfig, processorOpts
);
// init plugins
let plugins = normalizeBabelPlugins(processorOpts.plugins, file, buildManager);
// init app/page/component transform plugin
let configInitHandler = initConfigInfo.bind(
null, buildManager, 'config', file
);
let appBaseClass = buildManager.getOutputAppBaseClass();
let pluginOpts = {
appType: buildManager.appType,
config: configInitHandler
};
let filterOptions = buildManager.getFilterTransformOptions();
let enableMixinSupport = buildManager.isEnableMixinSupport();
let {api, framework, localPolyfill, polyfill} = buildManager.buildConf;
let getInitOptions = buildManager.getAppBaseClassInitOptions.bind(
buildManager, file
);
if (file.isEntryScript) {
Object.assign(pluginOpts, {
framework,
registerApi: api,
baseClass: appBaseClass && appBaseClass.app
});
// polyfill using local variable is prior to global polyfill
localPolyfill || (pluginOpts.polyfill = polyfill);
pluginOpts.getInitOptions = getInitOptions;
plugins.push([
programPlugins.app,
pluginOpts
]);
}
else if (file.isPageScript) {
Object.assign(pluginOpts, {
enableMixinSupport,
filterOptions,
tplRefs: file.tplRefs,
baseClass: appBaseClass && appBaseClass.page,
getInitOptions
});
plugins.push([programPlugins.page, pluginOpts]);
}
else if (file.isComponentScript) {
Object.assign(pluginOpts, {
enableMixinSupport,
filterOptions,
tplRefs: file.tplRefs,
baseClass: appBaseClass && appBaseClass.component,
getInitOptions
});
plugins.push([programPlugins.component, pluginOpts]);
}
else if (file.isBehavior) {
plugins.push([programPlugins.behavior, pluginOpts]);
}
// init local polyfill plugins
if (localPolyfill && !file.compiled) {
initLocalPolyfillPlugins(localPolyfill, plugins);
}
processorOpts.plugins = plugins;
return processorOpts;
}
|
javascript
|
{
"resource": ""
}
|
q58982
|
startBuild
|
validation
|
function startBuild(buildConf, clear) {
// init build manager
let buildManager = BuildManager.create(buildConf.appType, buildConf);
if (clear) {
buildManager.clear();
}
startDevServer(buildConf, buildManager);
let doneHandler = function () {
startFileChangeMonitor(buildConf, buildManager);
};
// run build
return runBuild(buildConf, buildManager).then(
doneHandler,
doneHandler
);
}
|
javascript
|
{
"resource": ""
}
|
q58983
|
parseEventName
|
validation
|
function parseEventName(name, element, tplOpts, opts) {
let eventAttrName = name.replace(EVENT_REGEXP, '');
let [eventType, ...eventModifiers] = eventAttrName.split('.');
let eventMode = 'on';
eventType = transformMiniProgramEventType(element, eventType, opts);
let {logger, file} = tplOpts;
antNotSupportModifier.forEach(item => {
if (eventModifiers.includes(item)) {
logger.warn(
`${file.path} template event attribute ${name} using`,
`${item} is not supported in ant env`
);
}
});
if (eventModifiers.includes('capture')) {
eventMode = 'catch';
}
let nativeEvent = NATIVE_EVENT_MAP[eventType.toLowerCase()];
if (nativeEvent) {
eventType = nativeEvent;
}
let formatEventType = eventType.charAt(0).toUpperCase() + eventType.substr(1);
eventAttrName = eventMode + formatEventType;
return {
eventType,
eventAttrName,
eventModifiers
};
}
|
javascript
|
{
"resource": ""
}
|
q58984
|
initExtensions
|
validation
|
function initExtensions(type, instance, base) {
let cache = pluginCache;
if (process.env.APP_TYPE === 'quick') {
if (!appGlobal.okamPluginCache) {
appGlobal.okamPluginCache = pluginCache;
}
cache = appGlobal.okamPluginCache;
}
let existedBase = cache.baseClasses[type];
if (!existedBase) {
let plugins = cache.usedExtensions[type];
let args = [{}];
plugins && Array.prototype.push.apply(args, plugins);
args.push(base);
existedBase = mixin.apply(this, args);
cache.baseClasses[type] = existedBase;
}
return mixin.apply(this, [instance, existedBase]);
}
|
javascript
|
{
"resource": ""
}
|
q58985
|
initComponentData
|
validation
|
function initComponentData(instance, options, isPage) {
let data = instance.data;
if (isFunction(data)) {
instance.data = instance.data();
}
instance.$init && instance.$init(isPage, options);
}
|
javascript
|
{
"resource": ""
}
|
q58986
|
queryRefInstance
|
validation
|
function queryRefInstance(selector) {
let isSelectAll = Array.isArray(selector);
isSelectAll && (selector = selector[0]);
let result;
if (isSelectAll) {
if (typeof this.selectAllComponents === 'function') {
result = this.selectAllComponents(selector);
}
result || (result = []);
}
else if (typeof this.selectComponent === 'function') {
result = this.selectComponent(selector);
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58987
|
fetchData
|
validation
|
function fetchData(url, options) {
let {method = 'GET'} = options || {};
method = method.toUpperCase();
return httpApi.request(Object.assign({url}, options, {method}));
}
|
javascript
|
{
"resource": ""
}
|
q58988
|
normalizeTransformers
|
validation
|
function normalizeTransformers(transformerMap) {
let result = [];
transformerMap && Object.keys(transformerMap).forEach(k => {
let item = transformerMap[k];
if (item) {
item.transform.type = k;
result.push(
Object.assign({}, item, {name: k})
);
}
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q58989
|
transform
|
validation
|
function transform(transformers, element, tplOpts, options) {
let {config} = tplOpts;
let onTag = config.onTag;
if (onTag) {
onTag(element.name);
}
// transform element first
let transformer = findMatchElemTransformer(transformers.element, element);
transformer && transformer.call(this, element, tplOpts, options);
if (element.removed) {
return;
}
// transform element attributes
let {attribs: attrs} = element;
attrs && Object.keys(attrs).forEach(k => {
transformer = findMatchAttrTransformer(transformers.attribute, k);
if (transformer) {
transformer.call(this, attrs, k, tplOpts, options, element);
if (transformer.type === 'for') {
element.hasForLoop = true;
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58990
|
transformTextNode
|
validation
|
function transformTextNode(transformer, textNode, tplOpts, options) {
let handler = findMatchTransformer(transformer, textNode.data, textNode);
handler && handler.call(this, textNode, tplOpts, options);
}
|
javascript
|
{
"resource": ""
}
|
q58991
|
analyseNativeComponent
|
validation
|
function analyseNativeComponent(scriptFile, options) {
// check whether component is analysed, if true, ignore
if (scriptFile.isAnalysedComponents) {
return;
}
scriptFile.isAnalysedComponents = true;
let {appType} = options;
if (appType === 'quick') {
return;
}
// add native component definition files
addComponentSameNameFiles(scriptFile, options);
}
|
javascript
|
{
"resource": ""
}
|
q58992
|
compile
|
validation
|
function compile(file, options) {
const {resolve: resolveDep, logger} = options;
try {
let componentConf = JSON.parse(file.content.toString());
let usingComponents = componentConf[USING_COMPONENT_KEY];
if (!usingComponents || !file.component) {
return {content: file.content};
}
let result = {};
let scriptFile = file.component;
Object.keys(usingComponents).forEach(k => {
let value = usingComponents[k];
if (!value) {
return;
}
let resolvePath = resolveDep(
scriptFile, value
);
result[toHyphen(k)] = resolvePath || value;
let resolveModInfo = scriptFile.resolvedModIds[value];
let componentFile = resolveModInfo && resolveModInfo.file;
componentFile && analyseNativeComponent(componentFile, options);
});
// update usingComponent information
componentConf[USING_COMPONENT_KEY] = result;
return {
content: JSON.stringify(componentConf, null, 4)
};
}
catch (ex) {
logger.error(
`Parse component config ${file.path} fail`,
ex.stack || ex.toString()
);
}
return {content: file.content};
}
|
javascript
|
{
"resource": ""
}
|
q58993
|
updateArrayItem
|
validation
|
function updateArrayItem(observer, idx, value) {
observer.set(idx, value);
this[idx] = value;
}
|
javascript
|
{
"resource": ""
}
|
q58994
|
makeArrayObservable
|
validation
|
function makeArrayObservable(arr, observer, proxyArrApis) {
// Here, not using __proto__ implementation, there are two import reasons:
// First, considering __proto__ will be deprecated and is not recommended to use
// Second, some plugins like weixin contact plugin will change array definition,
// the array instance __proto__ property does not contains any like `push`
// `pop` API, and these API only existed in the instance context.
// So, like the code as the following will not work correctly,
// a = []; // a.__proto__.push is not defined, a.push is defined
// a.__proto__.push = function () {};
// a.push(2); // always call the native push, not the override push method
// Therefor, using __proto__ to proxy the array method will not work
Object.keys(proxyArrApis).forEach(method => {
let rawMethod = arr[method];
arr[method] = proxyArrApis[method].bind(arr, observer, rawMethod);
});
arr.setItem = updateArrayItem.bind(arr, observer);
arr.getItem = getArrayItem.bind(arr, observer);
return arr;
}
|
javascript
|
{
"resource": ""
}
|
q58995
|
watchDataChange
|
validation
|
function watchDataChange(expressOrFunc, callback, options) {
if (typeof expressOrFunc === 'function') {
expressOrFunc = this.__addComputedProp(expressOrFunc);
}
if (typeof callback === 'function') {
let handlerName = getAnonymousWatcherName(this);
this[handlerName] = callback;
callback = handlerName;
}
return this.__watchDataChange(expressOrFunc, callback, options);
}
|
javascript
|
{
"resource": ""
}
|
q58996
|
initJsProcessor
|
validation
|
function initJsProcessor(opts, defaultBabelProcessorName) {
let plugins = (opts && opts.plugins) || [jsPlugin];
registerProcessor({
name: (opts && opts.processor) || defaultBabelProcessorName, // override existed processor
hook: {
before(file, options) {
if (file.isWxCompScript) {
options.plugins || (options.plugins = []);
options.plugins.push.apply(options.plugins, plugins);
}
}
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58997
|
initTplProcessor
|
validation
|
function initTplProcessor(opts) {
registerProcessor({
name: 'wxml2swan',
// using the existed view processor
processor: 'view',
extnames: ['wxml'],
rext: 'swan',
options: opts || {
plugins: [
wxmlPlugin
]
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58998
|
initStyleProcessor
|
validation
|
function initStyleProcessor(opts) {
registerProcessor({
name: 'wxss2css',
// using the existed postcss processor
processor: 'postcss',
extnames: ['wxss'],
rext: 'css',
options: opts || {
plugins: [
wxssPlugin
]
}
});
}
|
javascript
|
{
"resource": ""
}
|
q58999
|
initWxsProcessor
|
validation
|
function initWxsProcessor(opts, defaultBabelProcessorName) {
registerProcessor({
name: 'wxs2filter',
processor(file, options) {
let content = file.content.toString();
return {
content: wxs2filter(content)
};
},
extnames: ['wxs'],
rext: 'filter.js'
});
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.