_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q15700
replaceImpureComputedKeys
train
function replaceImpureComputedKeys(path) { const impureComputedPropertyDeclarators = []; for (const propPath of path.get("properties")) { const key = propPath.get("key"); if (propPath.node.computed && !key.isPure()) { const name = path.scope.generateUidBasedOnNode(key.node); const declarator = t.variableDeclarator(t.identifier(name), key.node); impureComputedPropertyDeclarators.push(declarator); key.replaceWith(t.identifier(name)); } } return impureComputedPropertyDeclarators; }
javascript
{ "resource": "" }
q15701
createObjectSpread
train
function createObjectSpread(path, file, objRef) { const props = path.get("properties"); const last = props[props.length - 1]; t.assertRestElement(last.node); const restElement = t.cloneNode(last.node); last.remove(); const impureComputedPropertyDeclarators = replaceImpureComputedKeys(path); const { keys, allLiteral } = extractNormalizedKeys(path); if (keys.length === 0) { return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression(getExtendsHelper(file), [ t.objectExpression([]), t.cloneNode(objRef), ]), ]; } let keyExpression; if (!allLiteral) { // map to toPropertyKey to handle the possible non-string values keyExpression = t.callExpression( t.memberExpression(t.arrayExpression(keys), t.identifier("map")), [file.addHelper("toPropertyKey")], ); } else { keyExpression = t.arrayExpression(keys); } return [ impureComputedPropertyDeclarators, restElement.argument, t.callExpression( file.addHelper(`objectWithoutProperties${loose ? "Loose" : ""}`), [t.cloneNode(objRef), keyExpression], ), ]; }
javascript
{ "resource": "" }
q15702
buildInitStatement
train
function buildInitStatement(metadata, exportNames, initExpr) { return t.expressionStatement( exportNames.reduce( (acc, exportName) => template.expression`EXPORTS.NAME = VALUE`({ EXPORTS: metadata.exportName, NAME: exportName, VALUE: acc, }), initExpr, ), ); }
javascript
{ "resource": "" }
q15703
getDefs
train
function getDefs(chalk) { return { gutter: chalk.grey, marker: chalk.red.bold, message: chalk.red.bold, }; }
javascript
{ "resource": "" }
q15704
load
train
function load(url, successCallback, errorCallback) { const xhr = new XMLHttpRequest(); // async, however scripts will be executed in the order they are in the // DOM to mirror normal script loading. xhr.open("GET", url, true); if ("overrideMimeType" in xhr) { xhr.overrideMimeType("text/plain"); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { successCallback(xhr.responseText); } else { errorCallback(); throw new Error("Could not load " + url); } } }; return xhr.send(null); }
javascript
{ "resource": "" }
q15705
getPluginsOrPresetsFromScript
train
function getPluginsOrPresetsFromScript(script, attributeName) { const rawValue = script.getAttribute(attributeName); if (rawValue === "") { // Empty string means to not load ANY presets or plugins return []; } if (!rawValue) { // Any other falsy value (null, undefined) means we're not overriding this // setting, and should use the default. return null; } return rawValue.split(",").map(item => item.trim()); }
javascript
{ "resource": "" }
q15706
deopt
train
function deopt(path, state) { if (!state.confident) return; state.deoptPath = path; state.confident = false; }
javascript
{ "resource": "" }
q15707
getPrototypeOfExpression
train
function getPrototypeOfExpression(objectRef, isStatic, file, isPrivateMethod) { objectRef = t.cloneNode(objectRef); const targetRef = isStatic || isPrivateMethod ? objectRef : t.memberExpression(objectRef, t.identifier("prototype")); return t.callExpression(file.addHelper("getPrototypeOf"), [targetRef]); }
javascript
{ "resource": "" }
q15708
applyEnsureOrdering
train
function applyEnsureOrdering(path) { // TODO: This should probably also hoist computed properties. const decorators = (path.isClass() ? [path].concat(path.get("body.body")) : path.get("properties") ).reduce((acc, prop) => acc.concat(prop.node.decorators || []), []); const identDecorators = decorators.filter( decorator => !t.isIdentifier(decorator.expression), ); if (identDecorators.length === 0) return; return t.sequenceExpression( identDecorators .map(decorator => { const expression = decorator.expression; const id = (decorator.expression = path.scope.generateDeclaredUidIdentifier( "dec", )); return t.assignmentExpression("=", id, expression); }) .concat([path.node]), ); }
javascript
{ "resource": "" }
q15709
applyClassDecorators
train
function applyClassDecorators(classPath) { if (!hasClassDecorators(classPath.node)) return; const decorators = classPath.node.decorators || []; classPath.node.decorators = null; const name = classPath.scope.generateDeclaredUidIdentifier("class"); return decorators .map(dec => dec.expression) .reverse() .reduce(function(acc, decorator) { return buildClassDecorator({ CLASS_REF: t.cloneNode(name), DECORATOR: t.cloneNode(decorator), INNER: acc, }).expression; }, classPath.node); }
javascript
{ "resource": "" }
q15710
applyMethodDecorators
train
function applyMethodDecorators(path, state) { if (!hasMethodDecorators(path.node.body.body)) return; return applyTargetDecorators(path, state, path.node.body.body); }
javascript
{ "resource": "" }
q15711
applyObjectDecorators
train
function applyObjectDecorators(path, state) { if (!hasMethodDecorators(path.node.properties)) return; return applyTargetDecorators(path, state, path.node.properties); }
javascript
{ "resource": "" }
q15712
getDefs
train
function getDefs(chalk) { return { keyword: chalk.cyan, capitalized: chalk.yellow, jsx_tag: chalk.yellow, punctuator: chalk.yellow, // bracket: intentionally omitted. number: chalk.magenta, string: chalk.green, regex: chalk.magenta, comment: chalk.grey, invalid: chalk.white.bgRed.bold, }; }
javascript
{ "resource": "" }
q15713
getTokenType
train
function getTokenType(match) { const [offset, text] = match.slice(-2); const token = matchToToken(match); if (token.type === "name") { if (esutils.keyword.isReservedWordES6(token.value)) { return "keyword"; } if ( JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</") ) { return "jsx_tag"; } if (token.value[0] !== token.value[0].toLowerCase()) { return "capitalized"; } } if (token.type === "punctuator" && BRACKET.test(token.value)) { return "bracket"; } if ( token.type === "invalid" && (token.value === "@" || token.value === "#") ) { return "punctuator"; } return token.type; }
javascript
{ "resource": "" }
q15714
exchangePassword
train
function exchangePassword(client, username, password, scope, body, authInfo, done) { if (!client || !client.id) { return done(new common.errors.UnauthorizedError({ message: common.i18n.t('errors.middleware.auth.clientCredentialsNotProvided') }), false); } // Validate the user return models.User.check({email: username, password: password}) .then(function then(user) { return authUtils.createTokens({ clientId: client.id, userId: user.id }); }) .then(function then(response) { web.shared.middlewares.api.spamPrevention.userLogin() .reset(authInfo.ip, username + 'login'); return done(null, response.access_token, response.refresh_token, {expires_in: response.expires_in}); }) .catch(function (err) { done(err, false); }); }
javascript
{ "resource": "" }
q15715
assertSetupCompleted
train
function assertSetupCompleted(status) { return function checkPermission(__) { return checkSetup().then((isSetup) => { if (isSetup === status) { return __; } const completed = common.i18n.t('errors.api.authentication.setupAlreadyCompleted'), notCompleted = common.i18n.t('errors.api.authentication.setupMustBeCompleted'); function throwReason(reason) { throw new common.errors.NoPermissionError({message: reason}); } if (isSetup) { throwReason(completed); } else { throwReason(notCompleted); } }); }; }
javascript
{ "resource": "" }
q15716
_isCurrentUrl
train
function _isCurrentUrl(href, currentUrl) { if (!currentUrl) { return false; } var strippedHref = href.replace(/\/+$/, ''), strippedCurrentUrl = currentUrl.replace(/\/+$/, ''); return strippedHref === strippedCurrentUrl; }
javascript
{ "resource": "" }
q15717
parseDefaultSettings
train
function parseDefaultSettings() { var defaultSettingsInCategories = require('../data/schema/').defaultSettings, defaultSettingsFlattened = {}, dynamicDefault = { db_hash: uuid.v4(), public_hash: crypto.randomBytes(15).toString('hex'), // @TODO: session_secret would ideally be named "admin_session_secret" session_secret: crypto.randomBytes(32).toString('hex'), members_session_secret: crypto.randomBytes(32).toString('hex'), theme_session_secret: crypto.randomBytes(32).toString('hex') }; const membersKeypair = keypair({ bits: 1024 }); dynamicDefault.members_public_key = membersKeypair.public; dynamicDefault.members_private_key = membersKeypair.private; _.each(defaultSettingsInCategories, function each(settings, categoryName) { _.each(settings, function each(setting, settingName) { setting.type = categoryName; setting.key = settingName; if (dynamicDefault[setting.key]) { setting.defaultValue = dynamicDefault[setting.key]; } defaultSettingsFlattened[settingName] = setting; }); }); return defaultSettingsFlattened; }
javascript
{ "resource": "" }
q15718
parsePackageJson
train
function parsePackageJson(path) { return fs.readFile(path) .catch(function () { var err = new Error(common.i18n.t('errors.utils.parsepackagejson.couldNotReadPackage')); err.context = path; return Promise.reject(err); }) .then(function (source) { var hasRequiredKeys, json, err; try { json = JSON.parse(source); hasRequiredKeys = json.name && json.version; if (!hasRequiredKeys) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.nameOrVersionMissing')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } return json; } catch (parseError) { err = new Error(common.i18n.t('errors.utils.parsepackagejson.themeFileIsMalformed')); err.context = path; err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'}); return Promise.reject(err); } }); }
javascript
{ "resource": "" }
q15719
train
function (items) { return '+(' + _.reduce(items, function (memo, ext) { return memo !== '' ? memo + '|' + ext : ext; }, '') + ')'; }
javascript
{ "resource": "" }
q15720
train
function (directory) { // Globs match content in the root or inside a single directory var extMatchesBase = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_OR_SINGLE_DIR), {cwd: directory}), extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ), dirMatches = glob.sync( this.getDirectoryGlob(this.getDirectories(), ROOT_OR_SINGLE_DIR), {cwd: directory} ), oldRoonMatches = glob.sync(this.getDirectoryGlob(['drafts', 'published', 'deleted'], ROOT_OR_SINGLE_DIR), {cwd: directory}); // This is a temporary extra message for the old format roon export which doesn't work with Ghost if (oldRoonMatches.length > 0) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.unsupportedRoonExport')}); } // If this folder contains importable files or a content or images directory if (extMatchesBase.length > 0 || (dirMatches.length > 0 && extMatchesAll.length > 0)) { return true; } if (extMatchesAll.length < 1) { throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.noContentToImport')}); } throw new common.errors.UnsupportedMediaTypeError({message: common.i18n.t('errors.data.importer.index.invalidZipStructure')}); }
javascript
{ "resource": "" }
q15721
train
function (filePath) { const tmpDir = path.join(os.tmpdir(), uuid.v4()); this.fileToDelete = tmpDir; return Promise.promisify(extract)(filePath, {dir: tmpDir}).then(function () { return tmpDir; }); }
javascript
{ "resource": "" }
q15722
train
function (handler, directory) { var globPattern = this.getExtensionGlob(handler.extensions, ALL_DIRS); return _.map(glob.sync(globPattern, {cwd: directory}), function (file) { return {name: file, path: path.join(directory, file)}; }); }
javascript
{ "resource": "" }
q15723
train
function (directory) { // Globs match root level only var extMatches = glob.sync(this.getExtensionGlob(this.getExtensions(), ROOT_ONLY), {cwd: directory}), dirMatches = glob.sync(this.getDirectoryGlob(this.getDirectories(), ROOT_ONLY), {cwd: directory}), extMatchesAll; // There is no base directory if (extMatches.length > 0 || dirMatches.length > 0) { return; } // There is a base directory, grab it from any ext match extMatchesAll = glob.sync( this.getExtensionGlob(this.getExtensions(), ALL_DIRS), {cwd: directory} ); if (extMatchesAll.length < 1 || extMatchesAll[0].split('/') < 1) { throw new common.errors.ValidationError({message: common.i18n.t('errors.data.importer.index.invalidZipFileBaseDirectory')}); } return extMatchesAll[0].split('/')[0]; }
javascript
{ "resource": "" }
q15724
train
function (file, importOptions = {}) { var self = this; // Step 1: Handle converting the file to usable data return this.loadFile(file).then(function (importData) { // Step 2: Let the importers pre-process the data return self.preProcess(importData); }).then(function (importData) { // Step 3: Actually do the import // @TODO: It would be cool to have some sort of dry run flag here return self.doImport(importData, importOptions); }).then(function (importData) { // Step 4: Report on the import return self.generateReport(importData); }).finally(() => self.cleanUp()); // Step 5: Cleanup any files }
javascript
{ "resource": "" }
q15725
trimSchema
train
function trimSchema(schema) { var schemaObject = {}; _.each(schema, function (value, key) { if (value !== null && typeof value !== 'undefined') { schemaObject[key] = value; } }); return schemaObject; }
javascript
{ "resource": "" }
q15726
sequence
train
function sequence(tasks /* Any Arguments */) { const args = Array.prototype.slice.call(arguments, 1); return Promise.reduce(tasks, function (results, task) { const response = task.apply(this, args); if (response && response.then) { return response.then(function (result) { results.push(result); return results; }); } else { return Promise.resolve().then(() => { results.push(response); return results; }); } }, []); }
javascript
{ "resource": "" }
q15727
characterOccurance
train
function characterOccurance(stringToTest) { var chars = {}, allowedOccurancy, valid = true; stringToTest = _.toString(stringToTest); allowedOccurancy = stringToTest.length / 2; // Loop through string and accumulate character counts _.each(stringToTest, function (char) { if (!chars[char]) { chars[char] = 1; } else { chars[char] += 1; } }); // check if any of the accumulated chars exceed the allowed occurancy // of 50% of the words' length. _.forIn(chars, function (charCount) { if (charCount >= allowedOccurancy) { valid = false; } }); return valid; }
javascript
{ "resource": "" }
q15728
permittedAttributes
train
function permittedAttributes() { let filteredKeys = ghostBookshelf.Model.prototype.permittedAttributes.apply(this, arguments); this.relationships.forEach((key) => { filteredKeys.push(key); }); return filteredKeys; }
javascript
{ "resource": "" }
q15729
train
function (name) { const {app, proxy} = getAppByName(name); // Check for an activate() method on the app. if (!_.isFunction(app.activate)) { return Promise.reject(new Error(common.i18n.t('errors.apps.noActivateMethodLoadingApp.error', {name: name}))); } // Wrapping the activate() with a when because it's possible // to not return a promise from it. return Promise.resolve(app.activate(proxy)).return(app); }
javascript
{ "resource": "" }
q15730
getPostData
train
function getPostData(req, res, next) { req.body = req.body || {}; const urlWithoutSubdirectoryWithoutAmp = res.locals.relativeUrl.match(/(.*?\/)amp\/?$/)[1]; /** * @NOTE * * We have to figure out the target permalink, otherwise it would be possible to serve a post * which lives in two collections. * * @TODO: * * This is not optimal and caused by the fact how apps currently work. But apps weren't designed * for dynamic routing. * * I think if the responsible, target router would first take care fetching/determining the post, the * request could then be forwarded to this app. Then we don't have to: * * 1. care about fetching the post * 2. care about if the post can be served * 3. then this app would act like an extension * * The challenge is to design different types of apps e.g. extensions of routers, standalone pages etc. */ const permalinks = urlService.getPermalinkByUrl(urlWithoutSubdirectoryWithoutAmp, {withUrlOptions: true}); if (!permalinks) { return next(new common.errors.NotFoundError({ message: common.i18n.t('errors.errors.pageNotFound') })); } // @NOTE: amp is not supported for static pages // @TODO: https://github.com/TryGhost/Ghost/issues/10548 helpers.entryLookup(urlWithoutSubdirectoryWithoutAmp, {permalinks, query: {controller: 'postsPublic', resource: 'posts'}}, res.locals) .then((result) => { if (result && result.entry) { req.body.post = result.entry; } next(); }) .catch(next); }
javascript
{ "resource": "" }
q15731
getImageDimensions
train
function getImageDimensions(metaData) { var fetch = { coverImage: imageLib.imageSizeCache(metaData.coverImage.url), authorImage: imageLib.imageSizeCache(metaData.authorImage.url), ogImage: imageLib.imageSizeCache(metaData.ogImage.url), logo: imageLib.imageSizeCache(metaData.blog.logo.url) }; return Promise .props(fetch) .then(function (imageObj) { _.forEach(imageObj, function (key, value) { if (_.has(key, 'width') && _.has(key, 'height')) { // We have some restrictions for publisher.logo: // The image needs to be <=600px wide and <=60px high (ideally exactly 600px x 60px). // Unless we have proper image-handling (see https://github.com/TryGhost/Ghost/issues/4453), // we will fake it in some cases or not produce an imageObject at all. if (value === 'logo') { if (key.height <= 60 && key.width <= 600) { _.assign(metaData.blog[value], { dimensions: { width: key.width, height: key.height } }); } else if (key.width === key.height) { // CASE: the logo is too large, but it is a square. We fake it... _.assign(metaData.blog[value], { dimensions: { width: 60, height: 60 } }); } } else { _.assign(metaData[value], { dimensions: { width: key.width, height: key.height } }); } } }); return metaData; }); }
javascript
{ "resource": "" }
q15732
train
function (perm) { var permObjId; // Look for a matching action type and object type first if (perm.get('action_type') !== actType || perm.get('object_type') !== objType) { return false; } // Grab the object id (if specified, could be null) permObjId = perm.get('object_id'); // If we didn't specify a model (any thing) // or the permission didn't have an id scope set // then the "thing" has permission if (!modelId || !permObjId) { return true; } // Otherwise, check if the id's match // TODO: String vs Int comparison possibility here? return modelId === permObjId; }
javascript
{ "resource": "" }
q15733
sendMail
train
function sendMail(object) { if (!(mailer instanceof mail.GhostMailer)) { mailer = new mail.GhostMailer(); } return mailer.send(object.mail[0].message).catch((err) => { if (mailer.state.usingDirect) { notificationsAPI.add( { notifications: [{ type: 'warn', message: [ common.i18n.t('warnings.index.unableToSendEmail'), common.i18n.t('common.seeLinkForInstructions', {link: 'https://docs.ghost.org/mail/'}) ].join(' ') }] }, {context: {internal: true}} ); } return Promise.reject(err); }); }
javascript
{ "resource": "" }
q15734
errorHandler
train
function errorHandler(error, req, res, next) { req.body.email = ''; req.body.subscribed_url = santizeUrl(req.body.subscribed_url); req.body.subscribed_referrer = santizeUrl(req.body.subscribed_referrer); if (error.statusCode !== 404) { res.locals.error = error; return _renderer(req, res); } next(error); }
javascript
{ "resource": "" }
q15735
exportSubscribers
train
function exportSubscribers() { return models.Subscriber.findAll(options).then((data) => { return formatCSV(data.toJSON(options)); }).catch((err) => { return Promise.reject(new common.errors.GhostError({err: err})); }); }
javascript
{ "resource": "" }
q15736
t
train
function t(path, bindings) { let string, isTheme, msg; currentLocale = I18n.locale(); if (bindings !== undefined) { isTheme = bindings.isThemeString; delete bindings.isThemeString; } string = I18n.findString(path, {isThemeString: isTheme}); // If the path returns an array (as in the case with anything that has multiple paragraphs such as emails), then // loop through them and return an array of translated/formatted strings. Otherwise, just return the normal // translated/formatted string. if (Array.isArray(string)) { msg = []; string.forEach(function (s) { let m = new MessageFormat(s, currentLocale); try { m.format(bindings); } catch (err) { logging.error(err.message); // fallback m = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); m = msg.format(); } msg.push(m); }); } else { msg = new MessageFormat(string, currentLocale); try { msg = msg.format(bindings); } catch (err) { logging.error(err.message); // fallback msg = new MessageFormat(coreStrings.errors.errors.anErrorOccurred, currentLocale); msg = msg.format(); } } return msg; }
javascript
{ "resource": "" }
q15737
findString
train
function findString(msgPath, opts) { const options = merge({log: true}, opts || {}); let candidateString, matchingString, path; // no path? no string if (msgPath.length === 0 || !isString(msgPath)) { chalk.yellow('i18n.t() - received an empty path.'); return ''; } // If not in memory, load translations for core if (coreStrings === undefined) { I18n.init(); } if (options.isThemeString) { // If not in memory, load translations for theme if (themeStrings === undefined) { I18n.loadThemeTranslations(); } // Both jsonpath's dot-notation and bracket-notation start with '$' // E.g.: $.store.book.title or $['store']['book']['title'] // The {{t}} translation helper passes the default English text // The full Unicode jsonpath with '$' is built here // jp.stringify and jp.value are jsonpath methods // Info: https://www.npmjs.com/package/jsonpath path = jp.stringify(['$', msgPath]); candidateString = jp.value(themeStrings, path) || msgPath; } else { // Backend messages use dot-notation, and the '$.' prefix is added here // While bracket-notation allows any Unicode characters in keys for themes, // dot-notation allows only word characters in keys for backend messages // (that is \w or [A-Za-z0-9_] in RegExp) path = `$.${msgPath}`; candidateString = jp.value(coreStrings, path); } matchingString = candidateString || {}; if (isObject(matchingString) || isEqual(matchingString, {})) { if (options.log) { logging.error(new errors.IncorrectUsageError({ message: `i18n error: path "${msgPath}" was not found` })); } matchingString = coreStrings.errors.errors.anErrorOccurred; } return matchingString; }
javascript
{ "resource": "" }
q15738
onSaved
train
function onSaved(model, response, options) { ghostBookshelf.Model.prototype.onSaved.apply(this, arguments); if (options.method !== 'insert') { return; } var status = model.get('status'); model.emitChange('added', options); if (['published', 'scheduled'].indexOf(status) !== -1) { model.emitChange(status, options); } }
javascript
{ "resource": "" }
q15739
filterData
train
function filterData(data) { var filteredData = ghostBookshelf.Model.filterData.apply(this, arguments), extraData = _.pick(data, this.prototype.relationships); _.merge(filteredData, extraData); return filteredData; }
javascript
{ "resource": "" }
q15740
hideMembersOnlyContent
train
function hideMembersOnlyContent(attrs, frame) { const membersEnabled = labs.isSet('members'); if (!membersEnabled) { return PERMIT_CONTENT; } const postHasMemberTag = attrs.tags && attrs.tags.find((tag) => { return (tag.name === MEMBER_TAG); }); const requestFromMember = frame.original.context.member; if (!postHasMemberTag) { return PERMIT_CONTENT; } if (!requestFromMember) { return BLOCK_CONTENT; } const memberHasPlan = !!(frame.original.context.member.plans || []).length; if (!membersService.api.isPaymentConfigured()) { return PERMIT_CONTENT; } if (memberHasPlan) { return PERMIT_CONTENT; } return BLOCK_CONTENT; }
javascript
{ "resource": "" }
q15741
getVersionPath
train
function getVersionPath(options) { const apiVersions = config.get('api:versions'); let requestedVersion = options.version || 'v0.1'; let requestedVersionType = options.type || 'content'; let versionData = apiVersions[requestedVersion]; if (typeof versionData === 'string') { versionData = apiVersions[versionData]; } let versionPath = versionData[requestedVersionType]; return `/${versionPath}/`; }
javascript
{ "resource": "" }
q15742
getBlogUrl
train
function getBlogUrl(secure) { var blogUrl; if (secure) { blogUrl = config.get('url').replace('http://', 'https://'); } else { blogUrl = config.get('url'); } if (!blogUrl.match(/\/$/)) { blogUrl += '/'; } return blogUrl; }
javascript
{ "resource": "" }
q15743
getSubdir
train
function getSubdir() { // Parse local path location var localPath = url.parse(config.get('url')).path, subdir; // Remove trailing slash if (localPath !== '/') { localPath = localPath.replace(/\/$/, ''); } subdir = localPath === '/' ? '' : localPath; return subdir; }
javascript
{ "resource": "" }
q15744
replacePermalink
train
function replacePermalink(permalink, resource) { let output = permalink, primaryTagFallback = 'all', publishedAtMoment = moment.tz(resource.published_at || Date.now(), settingsCache.get('active_timezone')), permalinkLookUp = { year: function () { return publishedAtMoment.format('YYYY'); }, month: function () { return publishedAtMoment.format('MM'); }, day: function () { return publishedAtMoment.format('DD'); }, author: function () { return resource.primary_author.slug; }, primary_author: function () { return resource.primary_author ? resource.primary_author.slug : primaryTagFallback; }, primary_tag: function () { return resource.primary_tag ? resource.primary_tag.slug : primaryTagFallback; }, slug: function () { return resource.slug; }, id: function () { return resource.id; } }; // replace tags like :slug or :year with actual values output = output.replace(/(:[a-z_]+)/g, function (match) { if (_.has(permalinkLookUp, match.substr(1))) { return permalinkLookUp[match.substr(1)](); } }); return output; }
javascript
{ "resource": "" }
q15745
makeAbsoluteUrls
train
function makeAbsoluteUrls(html, siteUrl, itemUrl, options = {assetsOnly: false}) { html = html || ''; const htmlContent = cheerio.load(html, {decodeEntities: false}); const staticImageUrlPrefixRegex = new RegExp(STATIC_IMAGE_URL_PREFIX); // convert relative resource urls to absolute ['href', 'src'].forEach(function forEach(attributeName) { htmlContent('[' + attributeName + ']').each(function each(ix, el) { el = htmlContent(el); let attributeValue = el.attr(attributeName); // if URL is absolute move on to the next element try { const parsed = url.parse(attributeValue); if (parsed.protocol) { return; } // Do not convert protocol relative URLs if (attributeValue.lastIndexOf('//', 0) === 0) { return; } } catch (e) { return; } // CASE: don't convert internal links if (attributeValue[0] === '#') { return; } if (options.assetsOnly && !attributeValue.match(staticImageUrlPrefixRegex)) { return; } // compose an absolute URL // if the relative URL begins with a '/' use the blog URL (including sub-directory) // as the base URL, otherwise use the post's URL. const baseUrl = attributeValue[0] === '/' ? siteUrl : itemUrl; attributeValue = urlJoin(baseUrl, attributeValue); el.attr(attributeName, attributeValue); }); }); return htmlContent; }
javascript
{ "resource": "" }
q15746
initialize
train
function initialize() { var self = this; // NOTE: triggered before `creating`/`updating` this.on('saving', function onSaving(newObj, attrs, options) { if (options.method === 'insert') { // id = 0 is still a valid value for external usage if (_.isUndefined(newObj.id) || _.isNull(newObj.id)) { newObj.setId(); } } }); [ 'fetching', 'fetching:collection', 'fetched', 'fetched:collection', 'creating', 'created', 'updating', 'updated', 'destroying', 'destroyed', 'saving', 'saved' ].forEach(function (eventName) { var functionName = 'on' + eventName[0].toUpperCase() + eventName.slice(1); if (functionName.indexOf(':') !== -1) { functionName = functionName.slice(0, functionName.indexOf(':')) + functionName[functionName.indexOf(':') + 1].toUpperCase() + functionName.slice(functionName.indexOf(':') + 2); functionName = functionName.replace(':', ''); } if (!self[functionName]) { return; } self.on(eventName, self[functionName]); }); // @NOTE: Please keep here. If we don't initialize the parent, bookshelf-relations won't work. proto.initialize.call(this); }
javascript
{ "resource": "" }
q15747
onUpdating
train
function onUpdating(model, attr, options) { if (this.relationships) { model.changed = _.omit(model.changed, this.relationships); } if (schema.tables[this.tableName].hasOwnProperty('updated_by')) { if (!options.importing && !options.migrating) { this.set('updated_by', String(this.contextUser(options))); } } if (options && options.context && !options.context.internal && !options.importing) { if (schema.tables[this.tableName].hasOwnProperty('created_at')) { if (model.hasDateChanged('created_at', {beforeWrite: true})) { model.set('created_at', this.previous('created_at')); } } if (schema.tables[this.tableName].hasOwnProperty('created_by')) { if (model.hasChanged('created_by')) { model.set('created_by', String(this.previous('created_by'))); } } } // CASE: do not allow setting only the `updated_at` field, exception: importing if (schema.tables[this.tableName].hasOwnProperty('updated_at') && !options.importing) { if (options.migrating) { model.set('updated_at', model.previous('updated_at')); } else if (Object.keys(model.changed).length === 1 && model.changed.updated_at) { model.set('updated_at', model.previous('updated_at')); delete model.changed.updated_at; } } model._changed = _.cloneDeep(model.changed); return Promise.resolve(this.onValidate(model, attr, options)); }
javascript
{ "resource": "" }
q15748
fixDates
train
function fixDates(attrs) { var self = this; _.each(attrs, function each(value, key) { if (value !== null && schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'dateTime') { attrs[key] = moment(value).format('YYYY-MM-DD HH:mm:ss'); } }); return attrs; }
javascript
{ "resource": "" }
q15749
fixBools
train
function fixBools(attrs) { var self = this; _.each(attrs, function each(value, key) { if (schema.tables[self.tableName].hasOwnProperty(key) && schema.tables[self.tableName][key].type === 'bool') { attrs[key] = value ? true : false; } }); return attrs; }
javascript
{ "resource": "" }
q15750
contextUser
train
function contextUser(options) { options = options || {}; options.context = options.context || {}; if (options.context.user || ghostBookshelf.Model.isExternalUser(options.context.user)) { return options.context.user; } else if (options.context.integration) { /** * @NOTE: * * This is a dirty hotfix for v0.1 only. * The `x_by` columns are getting deprecated soon (https://github.com/TryGhost/Ghost/issues/10286). * * We return the owner ID '1' in case an integration updates or creates * resources. v0.1 will continue to use the `x_by` columns. v0.1 does not support integrations. * API v2 will introduce a new feature to solve inserting/updating resources * from users or integrations. API v2 won't expose `x_by` columns anymore. * * --- * * Why using ID '1'? WAIT. What??????? * * See https://github.com/TryGhost/Ghost/issues/9299. * * We currently don't read the correct owner ID from the database and assume it's '1'. * This is a leftover from switching from auto increment ID's to Object ID's. * But this takes too long to refactor out now. If an internal update happens, we also * use ID '1'. This logic exists for a LONG while now. The owner ID only changes from '1' to something else, * if you transfer ownership. */ return ghostBookshelf.Model.internalUser; } else if (options.context.internal) { return ghostBookshelf.Model.internalUser; } else if (this.get('id')) { return this.get('id'); } else if (options.context.external) { return ghostBookshelf.Model.externalUser; } else { throw new common.errors.NotFoundError({ message: common.i18n.t('errors.models.base.index.missingContext'), level: 'critical' }); } }
javascript
{ "resource": "" }
q15751
toJSON
train
function toJSON(unfilteredOptions) { const options = ghostBookshelf.Model.filterOptions(unfilteredOptions, 'toJSON'); options.omitPivot = true; // CASE: get JSON of previous attrs if (options.previous) { const clonedModel = _.cloneDeep(this); clonedModel.attributes = this._previousAttributes; if (this.relationships) { this.relationships.forEach((relation) => { if (this._previousRelations && this._previousRelations.hasOwnProperty(relation)) { clonedModel.related(relation).models = this._previousRelations[relation].models; } }); } return proto.toJSON.call(clonedModel, options); } return proto.toJSON.call(this, options); }
javascript
{ "resource": "" }
q15752
permittedOptions
train
function permittedOptions(methodName) { const baseOptions = ['context', 'withRelated']; const extraOptions = ['transacting', 'importing', 'forUpdate', 'migrating']; switch (methodName) { case 'toJSON': return baseOptions.concat('shallow', 'columns', 'previous'); case 'destroy': return baseOptions.concat(extraOptions, ['id', 'destroyBy', 'require']); case 'edit': return baseOptions.concat(extraOptions, ['id', 'require']); case 'findOne': return baseOptions.concat(extraOptions, ['columns', 'require']); case 'findAll': return baseOptions.concat(extraOptions, ['columns']); case 'findPage': return baseOptions.concat(extraOptions, ['filter', 'order', 'page', 'limit', 'columns']); default: return baseOptions.concat(extraOptions); } }
javascript
{ "resource": "" }
q15753
sanitizeData
train
function sanitizeData(data) { var tableName = _.result(this.prototype, 'tableName'), date; _.each(data, (value, property) => { if (value !== null && schema.tables[tableName].hasOwnProperty(property) && schema.tables[tableName][property].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: property}), code: 'DATE_INVALID' }); } data[property] = moment(value).toDate(); } if (this.prototype.relationships && this.prototype.relationships.indexOf(property) !== -1) { _.each(data[property], (relation, indexInArr) => { _.each(relation, (value, relationProperty) => { if (value !== null && schema.tables[this.prototype.relationshipBelongsTo[property]].hasOwnProperty(relationProperty) && schema.tables[this.prototype.relationshipBelongsTo[property]][relationProperty].type === 'dateTime' && typeof value === 'string' ) { date = new Date(value); // CASE: client sends `0000-00-00 00:00:00` if (isNaN(date)) { throw new common.errors.ValidationError({ message: common.i18n.t('errors.models.base.invalidDate', {key: relationProperty}), code: 'DATE_INVALID' }); } data[property][indexInArr][relationProperty] = moment(value).toDate(); } }); }); } }); return data; }
javascript
{ "resource": "" }
q15754
filterByVisibility
train
function filterByVisibility(items, visibility, explicit, fn) { var memo = _.isArray(items) ? [] : {}; if (_.includes(visibility, 'all')) { return fn ? _.map(items, fn) : items; } // We don't want to change the structure of what is returned return _.reduce(items, function (items, item, key) { if (!item.visibility && !explicit || _.includes(visibility, item.visibility)) { var newItem = fn ? fn(item) : item; if (_.isArray(items)) { memo.push(newItem); } else { memo[key] = newItem; } } return memo; }, memo); }
javascript
{ "resource": "" }
q15755
handleMessage
train
function handleMessage(message) { var type = message.data.type; var id = message.data.id; var payload = message.data.payload; switch(type) { case 'load-index': makeRequest(SEARCH_TERMS_URL, function(searchInfo) { index = createIndex(loadIndex(searchInfo)); self.postMessage({type: type, id: id, payload: true}); }); break; case 'query-index': self.postMessage({type: type, id: id, payload: {query: payload, results: queryIndex(payload)}}); break; default: self.postMessage({type: type, id: id, payload: {error: 'invalid message type'}}) } }
javascript
{ "resource": "" }
q15756
makeRequest
train
function makeRequest(url, callback) { // The JSON file that is loaded should be an array of PageInfo: var searchDataRequest = new XMLHttpRequest(); searchDataRequest.onload = function() { callback(JSON.parse(this.responseText)); }; searchDataRequest.open('GET', url); searchDataRequest.send(); }
javascript
{ "resource": "" }
q15757
loadIndex
train
function loadIndex(searchInfo /*: SearchInfo */) { return function(index) { // Store the pages data to be used in mapping query results back to pages // Add search terms from each page to the search index searchInfo.forEach(function(page /*: PageInfo */) { index.add(page); pages[page.path] = page; }); }; }
javascript
{ "resource": "" }
q15758
createImportTargets
train
function createImportTargets(importTargets, targetName, targetDirectory) { const importMap = {}; for (const x in importTargets) { importMap['rxjs/' + x] = ('rxjs-compat/' + targetName + importTargets[x]).replace(/\.js$/, ''); } const outputData = ` "use strict" var path = require('path'); var dir = path.resolve(__dirname); module.exports = function() { return ${JSON.stringify(importMap, null, 4)}; } ` fs.outputFileSync(targetDirectory + 'path-mapping.js', outputData); }
javascript
{ "resource": "" }
q15759
spinner
train
function spinner(promise, text = 'loading', spinnerIcon = 'monkey') { const spinner = ora({ spinner: spinnerIcon, text }).start(); return new Promise((resolve, reject) => { promise .then(resolved => { spinner.stop(); resolve(resolved); }) .catch(err => { spinner.stop(); reject(err); }); }); }
javascript
{ "resource": "" }
q15760
askTypeOfApplication
train
function askTypeOfApplication() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'applicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; return this.prompt(prompts).then(props => { const applicationType = props.applicationType; this.deploymentApplicationType = props.applicationType; if (applicationType) { this.log(applicationType); done(); } else { this.abort = true; done(); } }); }
javascript
{ "resource": "" }
q15761
askRegion
train
function askRegion() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'list', name: 'region', message: 'Which region?', choices: regionList, default: this.aws.region ? _.indexOf(regionList, this.aws.region) : this.awsFacts.defaultRegion } ]; return this.prompt(prompts).then(props => { const region = props.region; if (region) { this.aws.region = region; done(); } else { this.abort = true; done(); } }); }
javascript
{ "resource": "" }
q15762
askCloudFormation
train
function askCloudFormation() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'input', name: 'cloudFormationName', message: "Please enter your stack's name. (must be unique within a region)", default: this.aws.cloudFormationName || this.baseName, validate: input => { if (_.isEmpty(input) || !input.match(CLOUDFORMATION_STACK_NAME)) { return 'Stack name must contain letters, digits, or hyphens '; } return true; } } ]; return this.prompt(prompts).then(props => { const cloudFormationName = props.cloudFormationName; if (cloudFormationName) { this.aws.cloudFormationName = cloudFormationName; while (this.aws.cloudFormationName.includes('_')) { this.aws.cloudFormationName = _.replace(this.aws.cloudFormationName, '_', ''); } this.log(`CloudFormation Stack name will be ${this.aws.cloudFormationName}`); done(); } else { this.abort = true; done(); } }); }
javascript
{ "resource": "" }
q15763
askPerformances
train
function askPerformances() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptPerformance.call(this, config, awsConfig).then(performance => { awsConfig.performance = performance; awsConfig.fargate = { ...awsConfig.fargate, ...PERF_TO_CONFIG[performance].fargate }; awsConfig.database = { ...awsConfig.database, ...PERF_TO_CONFIG[performance].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
javascript
{ "resource": "" }
q15764
askScaling
train
function askScaling() { if (this.abort) return null; const done = this.async(); const chainPromises = index => { if (index === this.appConfigs.length) { done(); return null; } const config = this.appConfigs[index]; const awsConfig = this.aws.apps.find(a => a.baseName === config.baseName) || { baseName: config.baseName }; return promptScaling.call(this, config, awsConfig).then(scaling => { awsConfig.scaling = scaling; awsConfig.fargate = { ...awsConfig.fargate, ...SCALING_TO_CONFIG[scaling].fargate }; awsConfig.database = { ...awsConfig.database, ...SCALING_TO_CONFIG[scaling].database }; _.remove(this.aws.apps, a => _.isEqual(a, awsConfig)); this.aws.apps.push(awsConfig); return chainPromises(index + 1); }); }; return chainPromises(0); }
javascript
{ "resource": "" }
q15765
askVPC
train
function askVPC() { if (this.abort) return null; const done = this.async(); const vpcList = this.awsFacts.availableVpcs.map(vpc => { const friendlyName = _getFriendlyNameFromTag(vpc); return { name: `ID: ${vpc.VpcId} (${friendlyName ? `name: '${friendlyName}', ` : ''}default: ${vpc.IsDefault}, state: ${vpc.State})`, value: vpc.VpcId, short: vpc.VpcId }; }); const prompts = [ { type: 'list', name: 'targetVPC', message: 'Please select your target Virtual Private Network.', choices: vpcList, default: this.aws.vpc.id } ]; return this.prompt(prompts).then(props => { const targetVPC = props.targetVPC; if (targetVPC) { this.aws.vpc.id = targetVPC; this.aws.vpc.cidr = _.find(this.awsFacts.availableVpcs, ['VpcId', targetVPC]).CidrBlock; done(); } else { this.abort = true; done(); } }); }
javascript
{ "resource": "" }
q15766
askDeployNow
train
function askDeployNow() { if (this.abort) return null; const done = this.async(); const prompts = [ { type: 'confirm', name: 'deployNow', message: 'Would you like to deploy now?.', default: true } ]; return this.prompt(prompts).then(props => { this.deployNow = props.deployNow; done(); }); }
javascript
{ "resource": "" }
q15767
_doesEventContainsNestedStackId
train
function _doesEventContainsNestedStackId(stack) { if (stack.ResourceType !== 'AWS::CloudFormation::Stack') { return false; } if (stack.ResourceStatusReason !== 'Resource creation Initiated') { return false; } if (stack.ResourceStatus !== 'CREATE_IN_PROGRESS') { return false; } if (_.isNil(stack.PhysicalResourceId)) { return false; } return _hasLabelNestedStackName(stack.PhysicalResourceId); }
javascript
{ "resource": "" }
q15768
_formatStatus
train
function _formatStatus(status) { let statusColorFn = chalk.grey; if (_.endsWith(status, 'IN_PROGRESS')) { statusColorFn = chalk.yellow; } else if (_.endsWith(status, 'FAILED') || _.startsWith(status, 'DELETE')) { statusColorFn = chalk.red; } else if (_.endsWith(status, 'COMPLETE')) { statusColorFn = chalk.greenBright; } const sanitizedStatus = _.replace(status, '_', ' '); const paddedStatus = _.padEnd(sanitizedStatus, STACK_EVENT_STATUS_DISPLAY_LENGTH); return statusColorFn(paddedStatus); }
javascript
{ "resource": "" }
q15769
_getStackLogLine
train
function _getStackLogLine(stack, indentation = 0) { const time = chalk.blue(`${stack.Timestamp.toLocaleTimeString()}`); const spacing = _.repeat('\t', indentation); const status = _formatStatus(stack.ResourceStatus); const stackName = chalk.grey(stack.StackName); const resourceType = chalk.bold(stack.ResourceType); return `${time} ${spacing}${status} ${resourceType}\t${stackName}`; }
javascript
{ "resource": "" }
q15770
loginToAws
train
function loginToAws(region, accountId, username, password) { const commandLine = `docker login --username AWS --password ${password} https://${accountId}.dkr.ecr.${region}.amazonaws.com`; return new Promise( (resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }), { silent: true } ); }
javascript
{ "resource": "" }
q15771
pushImage
train
function pushImage(repository) { const commandLine = `docker push ${repository}`; return new Promise((resolve, reject) => command(commandLine, (err, stdout) => { if (err) { reject(err); } resolve(stdout); }) ); }
javascript
{ "resource": "" }
q15772
checkDocker
train
function checkDocker() { if (this.abort || this.skipChecks) return; const done = this.async(); shelljs.exec('docker -v', { silent: true }, (code, stdout, stderr) => { if (stderr) { this.log( chalk.red( 'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { const dockerVersion = stdout.split(' ')[2].replace(/,/g, ''); const dockerVersionMajor = dockerVersion.split('.')[0]; const dockerVersionMinor = dockerVersion.split('.')[1]; if (dockerVersionMajor < 1 || (dockerVersionMajor === 1 && dockerVersionMinor < 10)) { this.log( chalk.red( `${'Docker version 1.10.0 or later is not installed on your computer.\n' + ' Docker version found: '}${dockerVersion}\n` + ' Read http://docs.docker.com/engine/installation/#installation\n' ) ); this.abort = true; } else { this.log.ok('Docker is installed'); } } done(); }); }
javascript
{ "resource": "" }
q15773
checkImageExist
train
function checkImageExist(opts = { cwd: './', appConfig: null }) { if (this.abort) return; let imagePath = ''; this.warning = false; this.warningMessage = 'To generate the missing Docker image(s), please run:\n'; if (opts.appConfig.buildTool === 'maven') { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/target/docker`); this.dockerBuildCommand = './mvnw -Pprod verify jib:dockerBuild'; } else { imagePath = this.destinationPath(`${opts.cwd + opts.cwd}/build/docker`); this.dockerBuildCommand = './gradlew bootWar -Pprod jibDockerBuild'; } if (shelljs.ls(imagePath).length === 0) { this.warning = true; this.warningMessage += ` ${chalk.cyan(this.dockerBuildCommand)} in ${this.destinationPath(this.directoryPath + opts.cwd)}\n`; } }
javascript
{ "resource": "" }
q15774
importJDL
train
function importJDL() { logger.info('The JDL is being parsed.'); const jdlImporter = new jhiCore.JDLImporter(this.jdlFiles, { databaseType: this.prodDatabaseType, applicationType: this.applicationType, applicationName: this.baseName, generatorVersion: packagejs.version, forceNoFiltering: this.options.force }); let importState = { exportedEntities: [], exportedApplications: [], exportedDeployments: [] }; try { importState = jdlImporter.import(); logger.debug(`importState exportedEntities: ${importState.exportedEntities.length}`); logger.debug(`importState exportedApplications: ${importState.exportedApplications.length}`); logger.debug(`importState exportedDeployments: ${importState.exportedDeployments.length}`); updateDeploymentState(importState); if (importState.exportedEntities.length > 0) { const entityNames = _.uniq(importState.exportedEntities.map(exportedEntity => exportedEntity.name)).join(', '); logger.info(`Found entities: ${chalk.yellow(entityNames)}.`); } else { logger.info(chalk.yellow('No change in entity configurations, no entities were updated.')); } logger.info('The JDL has been successfully parsed'); } catch (error) { logger.debug('Error:', error); if (error) { const errorName = `${error.name}:` || ''; const errorMessage = error.message || ''; logger.log(chalk.red(`${errorName} ${errorMessage}`)); } logger.error(`Error while parsing applications and entities from the JDL ${error}`, error); } return importState; }
javascript
{ "resource": "" }
q15775
cleanupOldFiles
train
function cleanupOldFiles(generator) { if (generator.isJhipsterVersionLessThan('3.2.0')) { // removeFile and removeFolder methods should be called here for files and folders to cleanup generator.removeFile(`${ANGULAR_DIR}components/form/uib-pager.config.js`); generator.removeFile(`${ANGULAR_DIR}components/form/uib-pagination.config.js`); } if (generator.isJhipsterVersionLessThan('5.0.0')) { generator.removeFile(`${ANGULAR_DIR}/app.route.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/account.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-jwt.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/auth-session.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/csrf.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/state-storage.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/auth/user-route-access-service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.constants.ts`); generator.removeFile(`${ANGULAR_DIR}shared/language/language.helper.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/login/login.service.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/base-entity.ts`); generator.removeFile(`${ANGULAR_DIR}shared/model/request-util.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/account.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.model.ts`); generator.removeFile(`${ANGULAR_DIR}shared/user/user.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-management-dialog.component.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${ANGULAR_DIR}admin/user-management/user-modal.service.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/shared/user/user.service.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/user-management/user-management-dialog.component.spec.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/entry.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}karma.conf.js`); } if (generator.isJhipsterVersionLessThan('5.8.0')) { generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.html`); generator.removeFile(`${ANGULAR_DIR}admin/metrics/metrics-modal.component.ts`); generator.removeFile(`${CLIENT_TEST_SRC_DIR}spec/app/admin/metrics/metrics-modal.component.spec.ts`); } }
javascript
{ "resource": "" }
q15776
rewriteFile
train
function rewriteFile(args, generator) { args.path = args.path || process.cwd(); const fullPath = path.join(args.path, args.file); args.haystack = generator.fs.read(fullPath); const body = rewrite(args); generator.fs.write(fullPath, body); }
javascript
{ "resource": "" }
q15777
rewrite
train
function rewrite(args) { // check if splicable is already in the body text const re = new RegExp(args.splicable.map(line => `\\s*${escapeRegExp(line)}`).join('\n')); if (re.test(args.haystack)) { return args.haystack; } const lines = args.haystack.split('\n'); let otherwiseLineIndex = -1; lines.forEach((line, i) => { if (line.includes(args.needle)) { otherwiseLineIndex = i; } }); let spaces = 0; while (lines[otherwiseLineIndex].charAt(spaces) === ' ') { spaces += 1; } let spaceStr = ''; // eslint-disable-next-line no-cond-assign while ((spaces -= 1) >= 0) { spaceStr += ' '; } lines.splice(otherwiseLineIndex, 0, args.splicable.map(line => spaceStr + line).join('\n')); return lines.join('\n'); }
javascript
{ "resource": "" }
q15778
rewriteJSONFile
train
function rewriteJSONFile(filePath, rewriteFile, generator) { const jsonObj = generator.fs.readJSON(filePath); rewriteFile(jsonObj, generator); generator.fs.writeJSON(filePath, jsonObj, null, 2); }
javascript
{ "resource": "" }
q15779
copyWebResource
train
function copyWebResource(source, dest, regex, type, generator, opt = {}, template) { if (generator.enableTranslation) { generator.template(source, dest, generator, opt); } else { renderContent(source, generator, generator, opt, body => { body = body.replace(regex, ''); switch (type) { case 'html': body = replacePlaceholders(body, generator); break; case 'js': body = replaceTitle(body, generator); break; case 'jsx': body = replaceTranslation(body, generator); break; default: break; } generator.fs.write(dest, body); }); } }
javascript
{ "resource": "" }
q15780
getJavadoc
train
function getJavadoc(text, indentSize) { if (!text) { text = ''; } if (text.includes('"')) { text = text.replace(/"/g, '\\"'); } let javadoc = `${_.repeat(' ', indentSize)}/**`; const rows = text.split('\n'); for (let i = 0; i < rows.length; i++) { javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} * ${rows[i]}`; } javadoc = `${javadoc}\n${_.repeat(' ', indentSize)} */`; return javadoc; }
javascript
{ "resource": "" }
q15781
buildEnumInfo
train
function buildEnumInfo(field, angularAppName, packageName, clientRootFolder) { const fieldType = field.fieldType; field.enumInstance = _.lowerFirst(fieldType); const enumInfo = { enumName: fieldType, enumValues: field.fieldValues.split(',').join(', '), enumInstance: field.enumInstance, enums: field.fieldValues.replace(/\s/g, '').split(','), angularAppName, packageName, clientRootFolder: clientRootFolder ? `${clientRootFolder}-` : '' }; return enumInfo; }
javascript
{ "resource": "" }
q15782
getAllJhipsterConfig
train
function getAllJhipsterConfig(generator, force) { let configuration = generator && generator.config ? generator.config.getAll() || {} : {}; if ((force || !configuration.baseName) && jhiCore.FileUtils.doesFileExist('.yo-rc.json')) { const yoRc = JSON.parse(fs.readFileSync('.yo-rc.json', { encoding: 'utf-8' })); configuration = yoRc['generator-jhipster']; // merge the blueprint config if available if (configuration.blueprint) { configuration = { ...configuration, ...yoRc[configuration.blueprint] }; } } if (!configuration.get || typeof configuration.get !== 'function') { configuration = { ...configuration, getAll: () => configuration, get: key => configuration[key], set: (key, value) => { configuration[key] = value; } }; } return configuration; }
javascript
{ "resource": "" }
q15783
getDBTypeFromDBValue
train
function getDBTypeFromDBValue(db) { if (constants.SQL_DB_OPTIONS.map(db => db.value).includes(db)) { return 'sql'; } return db; }
javascript
{ "resource": "" }
q15784
askForRelationship
train
function askForRelationship(done) { const context = this.context; const name = context.name; this.log(chalk.green('\nGenerating relationships to other entities\n')); const fieldNamesUnderscored = context.fieldNamesUnderscored; const prompts = [ { type: 'confirm', name: 'relationshipAdd', message: 'Do you want to add a relationship to another entity?', default: true }, { when: response => response.relationshipAdd === true, type: 'input', name: 'otherEntityName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your other entity name cannot contain special characters'; } if (input === '') { return 'Your other entity name cannot be empty'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your other entity name cannot contain a Java reserved keyword'; } if (input.toLowerCase() === 'user' && context.applicationType === 'microservice') { return "Your entity cannot have a relationship with User because it's a gateway entity"; } return true; }, message: 'What is the name of the other entity?' }, { when: response => response.relationshipAdd === true, type: 'input', name: 'relationshipName', validate: input => { if (!/^([a-zA-Z0-9_]*)$/.test(input)) { return 'Your relationship cannot contain special characters'; } if (input === '') { return 'Your relationship cannot be empty'; } if (input.charAt(0) === input.charAt(0).toUpperCase()) { return 'Your relationship cannot start with an upper case letter'; } if (input === 'id' || fieldNamesUnderscored.includes(_.snakeCase(input))) { return 'Your relationship cannot use an already existing field name'; } if (jhiCore.isReservedKeyword(input, 'JAVA')) { return 'Your relationship cannot contain a Java reserved keyword'; } return true; }, message: 'What is the name of the relationship?', default: response => _.lowerFirst(response.otherEntityName) }, { when: response => response.relationshipAdd === true, type: 'list', name: 'relationshipType', message: 'What is the type of the relationship?', choices: response => { const opts = [ { value: 'many-to-one', name: 'many-to-one' }, { value: 'many-to-many', name: 'many-to-many' }, { value: 'one-to-one', name: 'one-to-one' } ]; if (response.otherEntityName.toLowerCase() !== 'user') { opts.unshift({ value: 'one-to-many', name: 'one-to-many' }); } return opts; }, default: 0 }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== 'user' && (response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one'), type: 'confirm', name: 'ownerSide', message: 'Is this entity the owner of the relationship?', default: false }, { when: response => context.databaseType === 'sql' && response.relationshipAdd === true && response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'), type: 'confirm', name: 'useJPADerivedIdentifier', message: 'Do you want to use JPA Derived Identifier - @MapsId?', default: false }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'one-to-many' || ((response.relationshipType === 'many-to-many' || response.relationshipType === 'one-to-one') && response.otherEntityName.toLowerCase() !== 'user')), type: 'input', name: 'otherEntityRelationshipName', message: 'What is the name of this relationship in the other entity?', default: response => _.lowerFirst(name) }, { when: response => response.relationshipAdd === true && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && response.ownerSide === true) || (response.relationshipType === 'one-to-one' && response.ownerSide === true)), type: 'input', name: 'otherEntityField', message: response => `When you display this relationship on client-side, which field from '${ response.otherEntityName }' do you want to use? This field will be displayed as a String, so it cannot be a Blob`, default: 'id' }, { when: response => response.relationshipAdd === true && response.otherEntityName.toLowerCase() !== context.name.toLowerCase() && (response.relationshipType === 'many-to-one' || (response.relationshipType === 'many-to-many' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user')) || (response.relationshipType === 'one-to-one' && (response.ownerSide === true || response.otherEntityName.toLowerCase() === 'user'))), type: 'confirm', name: 'relationshipValidate', message: 'Do you want to add any validation rules to this relationship?', default: false }, { when: response => response.relationshipValidate === true, type: 'checkbox', name: 'relationshipValidateRules', message: 'Which validation rules do you want to add?', choices: [ { name: 'Required', value: 'required' } ], default: 0 } ]; this.prompt(prompts).then(props => { if (props.relationshipAdd) { const relationship = { relationshipName: props.relationshipName, otherEntityName: _.lowerFirst(props.otherEntityName), relationshipType: props.relationshipType, relationshipValidateRules: props.relationshipValidateRules, otherEntityField: props.otherEntityField, ownerSide: props.ownerSide, useJPADerivedIdentifier: props.useJPADerivedIdentifier, otherEntityRelationshipName: props.otherEntityRelationshipName }; if (props.otherEntityName.toLowerCase() === 'user') { relationship.ownerSide = true; relationship.otherEntityField = 'login'; relationship.otherEntityRelationshipName = _.lowerFirst(name); } fieldNamesUnderscored.push(_.snakeCase(props.relationshipName)); context.relationships.push(relationship); } logFieldsAndRelationships.call(this); if (props.relationshipAdd) { askForRelationship.call(this, done); } else { this.log('\n'); done(); } }); }
javascript
{ "resource": "" }
q15785
logFieldsAndRelationships
train
function logFieldsAndRelationships() { const context = this.context; if (context.fields.length > 0 || context.relationships.length > 0) { this.log(chalk.red(chalk.white('\n================= ') + context.entityNameCapitalized + chalk.white(' ================='))); } if (context.fields.length > 0) { this.log(chalk.white('Fields')); context.fields.forEach(field => { const validationDetails = []; const fieldValidate = _.isArray(field.fieldValidateRules) && field.fieldValidateRules.length >= 1; if (fieldValidate === true) { if (field.fieldValidateRules.includes('required')) { validationDetails.push('required'); } if (field.fieldValidateRules.includes('unique')) { validationDetails.push('unique'); } if (field.fieldValidateRules.includes('minlength')) { validationDetails.push(`minlength='${field.fieldValidateRulesMinlength}'`); } if (field.fieldValidateRules.includes('maxlength')) { validationDetails.push(`maxlength='${field.fieldValidateRulesMaxlength}'`); } if (field.fieldValidateRules.includes('pattern')) { validationDetails.push(`pattern='${field.fieldValidateRulesPattern}'`); } if (field.fieldValidateRules.includes('min')) { validationDetails.push(`min='${field.fieldValidateRulesMin}'`); } if (field.fieldValidateRules.includes('max')) { validationDetails.push(`max='${field.fieldValidateRulesMax}'`); } if (field.fieldValidateRules.includes('minbytes')) { validationDetails.push(`minbytes='${field.fieldValidateRulesMinbytes}'`); } if (field.fieldValidateRules.includes('maxbytes')) { validationDetails.push(`maxbytes='${field.fieldValidateRulesMaxbytes}'`); } } this.log( chalk.red(field.fieldName) + chalk.white(` (${field.fieldType}${field.fieldTypeBlobContent ? ` ${field.fieldTypeBlobContent}` : ''}) `) + chalk.cyan(validationDetails.join(' ')) ); }); this.log(); } if (context.relationships.length > 0) { this.log(chalk.white('Relationships')); context.relationships.forEach(relationship => { const validationDetails = []; if (relationship.relationshipValidateRules && relationship.relationshipValidateRules.includes('required')) { validationDetails.push('required'); } this.log( `${chalk.red(relationship.relationshipName)} ${chalk.white(`(${_.upperFirst(relationship.otherEntityName)})`)} ${chalk.cyan( relationship.relationshipType )} ${chalk.cyan(validationDetails.join(' '))}` ); }); this.log(); } }
javascript
{ "resource": "" }
q15786
loadAWS
train
function loadAWS(generator) { return new Promise((resolve, reject) => { try { AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line } catch (e) { generator.log('Installing AWS dependencies'); let installCommand = 'yarn add aws-sdk@2.167.0 progress@2.0.0 ora@1.3.0'; if (generator.config.get('clientPackageManager') === 'npm') { installCommand = 'npm install aws-sdk@2.167.0 progress@2.0.0 ora@1.3.0--save'; } shelljs.exec(installCommand, { silent: false }, code => { if (code !== 0) { generator.error('Something went wrong while installing the dependencies\n'); reject(); } AWS = require('aws-sdk'); // eslint-disable-line ProgressBar = require('progress'); // eslint-disable-line ora = require('ora'); // eslint-disable-line }); } resolve(); }); }
javascript
{ "resource": "" }
q15787
initAwsStuff
train
function initAwsStuff(region = DEFAULT_REGION) { ec2 = new AWS.EC2({ region }); // ecr = new AWS.ECR({ region }); s3 = new AWS.S3(); sts = new AWS.STS(); SSM = new AwsSSM(region); ECR = new AwsECR(region); CF = new AwsCF(region); }
javascript
{ "resource": "" }
q15788
getDockerLogin
train
function getDockerLogin() { return spinner( new Promise((resolve, reject) => _getAuthorizationToken().then(authToken => sts .getCallerIdentity({}) .promise() .then(data => { const decoded = utils.decodeBase64(authToken.authorizationToken); const splitResult = decoded.split(':'); resolve({ username: splitResult[0], password: splitResult[1], accountId: data.Account }); }) .catch(() => reject(new Error("Couldn't retrieve the user informations"))) ) ) ); }
javascript
{ "resource": "" }
q15789
_getAuthorizationToken
train
function _getAuthorizationToken() { return spinner( new Promise((resolve, reject) => ECR.sdk .getAuthorizationToken({}) .promise() .then(data => { if (!_.has(data, 'authorizationData.0')) { reject(new Error('No authorization data found.')); return; } resolve(data.authorizationData[0]); }) ) ); }
javascript
{ "resource": "" }
q15790
createS3Bucket
train
function createS3Bucket(bucketName, region = DEFAULT_REGION) { const createBuckerParams = { Bucket: bucketName }; return spinner( new Promise((resolve, reject) => s3 .headBucket({ Bucket: bucketName }) .promise() .catch(error => { if (error.code !== 'NotFound') { reject( new Error( `The S3 Bucket ${chalk.bold(bucketName)} in region ${chalk.bold( region )} already exists and you don't have access to it. Error code: ${chalk.bold(error.code)}` ) ); } }) .then(() => s3 .createBucket(createBuckerParams) .promise() .then(resolve) .catch(error => reject( new Error( `There was an error during the creation of the S3 Bucket ${chalk.bold( bucketName )} in region ${chalk.bold(region)}` ) ) ) ) ) ); }
javascript
{ "resource": "" }
q15791
uploadTemplate
train
function uploadTemplate(bucketName, filename, path) { return spinner( new Promise((resolve, reject) => fs.stat(path, (error, stats) => { if (!stats) { reject(new Error(`File ${chalk.bold(path)} not found`)); } const upload = s3.upload( { Bucket: bucketName, Key: filename, Body: fs.createReadStream(path) }, { partSize: Math.max(stats.size, S3_MIN_PART_SIZE), queueSize: 1 } ); let bar; upload.on('httpUploadProgress', evt => { if (!bar && evt.total) { const total = evt.total / 1000000; bar = new ProgressBar('uploading [:bar] :percent :etas', { complete: '=', incomplete: ' ', width: 20, total, clear: true }); } const curr = evt.loaded / 1000000; bar.tick(curr - bar.curr); }); return upload .promise() .then(resolve) .catch(reject); }) ) ); }
javascript
{ "resource": "" }
q15792
askForApplicationType
train
function askForApplicationType() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'deploymentApplicationType', message: 'Which *type* of application would you like to deploy?', choices: [ { value: 'monolith', name: 'Monolithic application' }, { value: 'microservice', name: 'Microservice application' } ], default: 'monolith' } ]; this.prompt(prompts).then(props => { this.deploymentApplicationType = props.deploymentApplicationType; done(); }); }
javascript
{ "resource": "" }
q15793
askForPath
train
function askForPath() { if (this.regenerate) return; const done = this.async(); const deploymentApplicationType = this.deploymentApplicationType; let messageAskForPath; if (deploymentApplicationType === 'monolith') { messageAskForPath = 'Enter the root directory where your applications are located'; } else { messageAskForPath = 'Enter the root directory where your gateway(s) and microservices are located'; } const prompts = [ { type: 'input', name: 'directoryPath', message: messageAskForPath, default: this.directoryPath || '../', validate: input => { const path = this.destinationPath(input); if (shelljs.test('-d', path)) { const appsFolders = getAppFolders.call(this, input, deploymentApplicationType); if (appsFolders.length === 0) { return deploymentApplicationType === 'monolith' ? `No monolith found in ${path}` : `No microservice or gateway found in ${path}`; } return true; } return `${path} is not a directory or doesn't exist`; } } ]; this.prompt(prompts).then(props => { this.directoryPath = props.directoryPath; // Patch the path if there is no trailing "/" if (!this.directoryPath.endsWith('/')) { this.log(chalk.yellow(`The path "${this.directoryPath}" does not end with a trailing "/", adding it anyway.`)); this.directoryPath += '/'; } this.appsFolders = getAppFolders.call(this, this.directoryPath, deploymentApplicationType); // Removing registry from appsFolders, using reverse for loop for (let i = this.appsFolders.length - 1; i >= 0; i--) { if (this.appsFolders[i] === 'jhipster-registry' || this.appsFolders[i] === 'registry') { this.appsFolders.splice(i, 1); } } this.log(chalk.green(`${this.appsFolders.length} applications found at ${this.destinationPath(this.directoryPath)}\n`)); done(); }); }
javascript
{ "resource": "" }
q15794
askForApps
train
function askForApps() { if (this.regenerate) return; const done = this.async(); const messageAskForApps = 'Which applications do you want to include in your configuration?'; const prompts = [ { type: 'checkbox', name: 'chosenApps', message: messageAskForApps, choices: this.appsFolders, default: this.defaultAppsFolders, validate: input => (input.length === 0 ? 'Please choose at least one application' : true) } ]; this.prompt(prompts).then(props => { this.appsFolders = props.chosenApps; loadConfigs.call(this); done(); }); }
javascript
{ "resource": "" }
q15795
askForClustersMode
train
function askForClustersMode() { if (this.regenerate) return; const clusteredDbApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.prodDatabaseType === 'mongodb' || appConfig.prodDatabaseType === 'couchbase') { clusteredDbApps.push(this.appsFolders[index]); } }); if (clusteredDbApps.length === 0) return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'clusteredDbApps', message: 'Which applications do you want to use with clustered databases (only available with MongoDB and Couchbase)?', choices: clusteredDbApps, default: this.clusteredDbApps } ]; this.prompt(prompts).then(props => { this.clusteredDbApps = props.clusteredDbApps; setClusteredApps.call(this); done(); }); }
javascript
{ "resource": "" }
q15796
askForMonitoring
train
function askForMonitoring() { if (this.regenerate) return; const done = this.async(); const prompts = [ { type: 'list', name: 'monitoring', message: 'Do you want to setup monitoring for your applications ?', choices: [ { value: 'no', name: 'No' }, { value: 'elk', name: this.deploymentApplicationType === 'monolith' ? 'Yes, for logs and metrics with the JHipster Console (based on ELK)' : 'Yes, for logs and metrics with the JHipster Console (based on ELK and Zipkin)' }, { value: 'prometheus', name: 'Yes, for metrics only with Prometheus' } ], default: this.monitoring ? this.monitoring : 'no' } ]; this.prompt(prompts).then(props => { this.monitoring = props.monitoring; done(); }); }
javascript
{ "resource": "" }
q15797
askForConsoleOptions
train
function askForConsoleOptions() { if (this.regenerate) return; if (this.monitoring !== 'elk') return; const done = this.async(); const prompts = [ { type: 'checkbox', name: 'consoleOptions', message: 'You have selected the JHipster Console which is based on the ELK stack and additional technologies, which one do you want to use ?', choices: [ { value: 'curator', name: 'Curator, to help you curate and manage your Elasticsearch indices' } ], default: this.monitoring } ]; if (this.deploymentApplicationType === 'microservice') { prompts[0].choices.push({ value: 'zipkin', name: 'Zipkin, for distributed tracing (only compatible with JHipster >= v4.2.0)' }); } this.prompt(prompts).then(props => { this.consoleOptions = props.consoleOptions; done(); }); }
javascript
{ "resource": "" }
q15798
askForServiceDiscovery
train
function askForServiceDiscovery() { if (this.regenerate) return; const done = this.async(); const serviceDiscoveryEnabledApps = []; this.appConfigs.forEach((appConfig, index) => { if (appConfig.serviceDiscoveryType) { serviceDiscoveryEnabledApps.push({ baseName: appConfig.baseName, serviceDiscoveryType: appConfig.serviceDiscoveryType }); } }); if (serviceDiscoveryEnabledApps.length === 0) { this.serviceDiscoveryType = false; done(); return; } if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'consul')) { this.serviceDiscoveryType = 'consul'; this.log(chalk.green('Consul detected as the service discovery and configuration provider used by your apps')); done(); } else if (serviceDiscoveryEnabledApps.every(app => app.serviceDiscoveryType === 'eureka')) { this.serviceDiscoveryType = 'eureka'; this.log(chalk.green('JHipster registry detected as the service discovery and configuration provider used by your apps')); done(); } else { this.log(chalk.yellow('Unable to determine the service discovery and configuration provider to use from your apps configuration.')); this.log('Your service discovery enabled apps:'); serviceDiscoveryEnabledApps.forEach(app => { this.log(` -${app.baseName} (${app.serviceDiscoveryType})`); }); const prompts = [ { type: 'list', name: 'serviceDiscoveryType', message: 'Which Service Discovery registry and Configuration server would you like to use ?', choices: [ { value: 'eureka', name: 'JHipster Registry' }, { value: 'consul', name: 'Consul' }, { value: false, name: 'No Service Discovery and Configuration' } ], default: 'eureka' } ]; this.prompt(prompts).then(props => { this.serviceDiscoveryType = props.serviceDiscoveryType; done(); }); } }
javascript
{ "resource": "" }
q15799
askForAdminPassword
train
function askForAdminPassword() { if (this.regenerate || this.serviceDiscoveryType !== 'eureka') return; const done = this.async(); const prompts = [ { type: 'input', name: 'adminPassword', message: 'Enter the admin password used to secure the JHipster Registry', default: 'admin', validate: input => (input.length < 5 ? 'The password must have at least 5 characters' : true) } ]; this.prompt(prompts).then(props => { this.adminPassword = props.adminPassword; this.adminPasswordBase64 = getBase64Secret(this.adminPassword); done(); }); }
javascript
{ "resource": "" }