UNPKG

121 kBSource Map (JSON)View Raw
1{"version":3,"sources":["ng://@ibm-wch-sdk/schematics-utils/utility/find-module.ts","node_modules/tslib/tslib.es6.js","ng://@ibm-wch-sdk/schematics-utils/utility/change.ts","ng://@ibm-wch-sdk/schematics-utils/utility/ast-utils.ts","ng://@ibm-wch-sdk/schematics-utils/utility/config.ts","ng://@ibm-wch-sdk/schematics-utils/utility/ng-ast-utils.ts","ng://@ibm-wch-sdk/schematics-utils/utility/validation.ts","ng://@ibm-wch-sdk/schematics-utils/wch/url.utils.ts","ng://@ibm-wch-sdk/schematics-utils/wch/assert.ts","ng://@ibm-wch-sdk/schematics-utils/wch/tenant.ts","ng://@ibm-wch-sdk/schematics-utils/wch/rx.request.ts","ng://@ibm-wch-sdk/schematics-utils/wch/rx.file.ts","ng://@ibm-wch-sdk/schematics-utils/wch/wchtools.ts","ng://@ibm-wch-sdk/schematics-utils/package/package.ts","ng://@ibm-wch-sdk/schematics-utils/wch/wch.utils.ts","ng://@ibm-wch-sdk/schematics-utils/wch/json.ts","ng://@ibm-wch-sdk/schematics-utils/text/lines.ts","ng://@ibm-wch-sdk/schematics-utils/wch/rx.tree.ts","ng://@ibm-wch-sdk/schematics-utils/wch/rx.zip.ts","ng://@ibm-wch-sdk/schematics-utils/wch/rx.html.ts","ng://@ibm-wch-sdk/schematics-utils/typescript/source.ts","ng://@ibm-wch-sdk/schematics-utils/typescript/changes.ts","ng://@ibm-wch-sdk/schematics-utils/typescript/finders.ts","ng://@ibm-wch-sdk/schematics-utils/utility/parse-name.ts"],"names":["findModule","host","generateDir","dir","getDir","moduleRe","routingModuleRe","matches","subfiles","filter","p","test","length","join","path","Error","parent","extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","hasOwnProperty","__assign","assign","t","s","i","n","arguments","prototype","call","apply","this","__values","o","m","Symbol","iterator","next","value","done","__read","r","e","ar","push","error","__spread","concat","__makeTemplateObject","cooked","raw","defineProperty","NoopChange","Infinity","Promise","resolve","InsertChange","pos","toAdd","description","order","_this","read","then","content","prefix","substring","suffix","write","RemoveChange","toRemove","ReplaceChange","oldText","newText","text","reject","insertImport","source","fileToEdit","symbolName","fileName","isDefault","rootNode","allImports","findNodes","ts.SyntaxKind","ImportDeclaration","relevantImports","node","getChildren","child","kind","StringLiteral","map","file","importsAsterisk_1","imports_1","forEach","Identifier","AsteriskToken","fallbackPos_1","CloseBraceToken","getStart","FromKeyword","insertAfterLastOccurrence","useStrict","fallbackPos","end","open","close","insertAtBeginning","max","arr","_b","tslib_1.__values","_c","getSourceNodes","sourceFile","nodes","result","shift","getChildCount","unshift","findNode","getText","foundNode","ts.forEachChild","childNode","nodesByPosition","first","second","toInsert","syntaxKind","lastItem","tslib_1.__spread","sort","pop","undefined","lastItemPosition","getEnd","getDecoratorMetadata","identifier","module","angularImports","_angularImportsFromNode","_sourceFile","modulePath","ms","moduleSpecifier","startsWith","importClause","name","namedBindings","nb","NamespaceImport","_a","elements","is","propertyName","reduce","acc","curr","current","keys","key","Decorator","expression","CallExpression","expr","id","getFullText","PropertyAccessExpression","paExpr","moduleId","ObjectLiteralExpression","addSymbolToNgModuleMetadata","ngModulePath","metadataField","importPath","matchingProperties","properties","prop","PropertyAssignment","position_1","toInsert_1","match","replace","assignment","initializer","ArrayLiteralExpression","arrLiteral","console","log","isArray","indexOf","position","addImportToModule","classifiedName","getWorkspacePath","exists","configPath","findBootstrapModuleCall","mainPath","mainBuffer","SchematicsException","mainText","toString","allNodes","ts.createSourceFile","ts.ScriptTarget","Latest","bootstrapCall","allNodes_1","allNodes_1_1","bootstrapCallNode","findBootstrapModulePath","bootstrapModule","imp","htmlSelectorRe","_ensureTrailingSlash","aUrl","endsWith","_hasTrailingSlash","isString","isValidUrl","aValue","isWebUri","isValidEmail","validateEmail","isValidUserName","assertHasTrailingSlash","Assert.ok","hasTrailingSlash","TENANT_BASED_URL_REGEXP","RegExp","createXHR","require","ajaxRequest","req","ajax","responseType","pipe","resp","rxGet","aUri","url","rxGetJson","data","JSON","parse","rxFormPost","aData","method","body","rxReadFile","aPath","Observable","create","observer","readFile","err","complete","_getCredentialsFromEnvironment","username","env","password","PADDING_MODE","RSA_PKCS1_PADDING","ENCRYPTED_ENCODING","DECTYPTED_ENCODING","_loadCredentials","aApiBase","filename","homedir","_loadPrivateKey","padding","mergeMap","cred","k","_decryptPassword","aHash","aKey","privateDecrypt","Buffer","from","catchError","of","_getStoredCredentials","aApiUrl","ensureTrailingSlash","platform","_getWindowsCredentials","cmd","normalize","__dirname","process","arch","exec","encoding","stdout","stderr","_isValidCredential","aCred","wchToolsGetCredentials","_mergeCredentials","aBase","aOverride","cloneDeep","PEER","RUNTIME","DEVELOPMENT","getFolderForType","aType","DEP_TYPE","bindNodeCallback","findPackageJson","aDir","_getCurrentUser","REL_PATH_CURRENT_USER","_throwInvalidUrl","aError","throwError","VError","_throwInvalidCredentials","validateCredentials","aCredentials","_isValidPassword","aPassword","loginUrl","REL_PATH_BASICAUTH_LOGIN","KEY_BASICAUTH_LOGIN_USERNAME","KEY_BASICAUTH_LOGIN_PASSWORD","mapTo","_validateUser","aFeed","externalId","PACKAGE_JSON","FALLBACK","WCHTOOLS_DEPENDENCIES","_findBuildVersion","pluck","findDataDir","buf","isNil","config","_keys","KEY_WEIGHTS","classification","_getKey","aName","Number","MAX_SAFE_INTEGER","_compareName","aLeft","aRight","c","_compareNumber","localeCompare","_canonicalize","copy_1","v","isPlainObject","copy_2","serializeJson","stringify","serializeLines","aSource","parseLines","split","rxTransformTextFile","aOp","aTree","buffer","isNotNil","overwrite","delete","StreamOnBuffer","_super","__extends","__","constructor","tslib_1.__extends","_write","chunk","callback","buffers","_final","emit","Writable","_serializeHtml","aHtml","html","getSourceFile","createSourceFile","ScriptTarget","insertChanges","aChanges","aRecorder","change","insertLeft","anyChange","remove","changeSourceFile","aFile","aHost","recorder","beginUpdate","commitUpdate","byTypeAndName","findModuleFromOptions","options","skipImport","moduleBaseName","pathToCheck","flat","strings","dasherize","buildRelativePath","to","fromParts","toParts","toFileName","relativePath","relative","pathPrefix","getContentOfKeyLiteral","_source","getFirstNgModuleName","ngModulesMetadata","moduleClass","findClassDeclarationParent","ts.isClassDeclaration","addDeclarationToModule","addProviderToModule","addExportToModule","addBootstrapToModule","addEntryComponentToModule","isImported","ImportSpecifier","getWorkspace","configBuffer","parseJson","JsonParseMode","Loose","addProjectToWorkspace","workspace","project","context","projects","defaultProject","getConfig","getAppFromConfig","appIndexOrName","apps","parseInt","app","getAppModulePath","moduleRelativePath","mainDir","dirname","parseName","nameWithoutPath","basename","namePath","validateName","tags","oneLine","templateObject_1","validateHtmlSelector","selector","templateObject_2","validateProjectName","projectName","errorIndex","getRegExpFailPosition","str","parts","matched","projectNameRegexp","part","compare","firstMessage","templateObject_3","msg","stripIndent","templateObject_4","assertNotNull","assertParameter","aParameterName","assertIsUrl","assertIsEmail","assertIsValidUserName","validateApiUrl","bValidateWithCredentials","isUri","normUrl","onCredentials","switchMap","switchMapTo","findSdkVersion","pkg","deps","dependencies","devDeps","devDependencies","fromPkg","_fromDependency","aVersion","parsed","coerce","version","findWchToolsOptions","addToWchToolsDependencies","aDeps","aPkg","assertArray","dep","rxTransformJsonFile","op","textContent","canonicalizeJSON","rxTransformLinesFile","updateField","aGenerator","aObj","oldValue","rxUnzipFromUrl","aSrcUrl","aDstDir","aSkip","defer","stream","get","Parse","onEntry","fromEvent","onClose","takeUntil","entry","_rxExtractEntry","aEntry","_skipPrefix","aCount","idx","nextIdx","tap","autodrain","type","stream_1","rxTransformHtmlFile","_parseHtml","aString","load","addImportsToModule","aModules","byType","byText","aText","byName","byIdentifier","SyntaxKind","insertLines","aInsert","existing_1","Set","line","has","updateMinVersion","aMinVersion","folder","assertObject","oldDep","satisfies"],"mappings":"66CAuDA,SAAAA,EAA2BC,EAAYC,GAMrC,IALA,IAAIC,EAAuBF,EAAKG,OAAO,IAAMF,GAEvCG,EAAW,gBACXC,EAAkB,uBAEjBH,GAAK,CACV,IAAMI,EAAUJ,EAAIK,SAASC,OAAO,S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EnM,EACAoM,GAEA,GAAIpM,EAAS,CAEX,IAAMqM,EAAW,IAAIC,IAAYtM,GAEjC,OAAAhU,EAAWgU,EAAYoM,EAAQ7iB,OAAO,SAAAgjB,GAAQ,OAACF,EAASG,IAAID,MAG5D,OAAAvgB,EAAWogB,6CHSf,SAAAK,GACE1N,EACA2N,EACAtD,EACA1M,GAGA,IAAMiQ,EAASlQ,GAAiBC,GAE1B6L,EAAOqE,EAAAA,aAAaD,EAAQvD,GAC5ByD,EAAStE,EAAKxJ,GAMpB,OALIN,EAAAA,MAAMoO,IAAYC,EAAAA,UAAUJ,EAAaG,KAE3CtE,EAAKxJ,GAAS,IAAI2N,GAGbtD","sourcesContent":["/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nimport { Path, join, normalize, relative, strings } from '@angular-devkit/core';\nimport { DirEntry, Tree } from '@angular-devkit/schematics';\n\n\nexport interface ModuleOptions {\n module?: string;\n name: string;\n flat?: boolean;\n path?: string;\n skipImport?: boolean;\n}\n\n\n/**\n * Find the module referred by a set of options passed to the schematics.\n */\nexport function findModuleFromOptions(host: Tree, options: ModuleOptions): Path | undefined {\n if (options.hasOwnProperty('skipImport') && options.skipImport) {\n return undefined;\n }\n\n if (!options.module) {\n const pathToCheck = (options.path || '')\n + (options.flat ? '' : '/' + strings.dasherize(options.name));\n\n return normalize(findModule(host, pathToCheck));\n } else {\n const modulePath = normalize(\n '/' + (options.path) + '/' + options.module);\n const moduleBaseName = normalize(modulePath).split('/').pop();\n\n if (host.exists(modulePath)) {\n return normalize(modulePath);\n } else if (host.exists(modulePath + '.ts')) {\n return normalize(modulePath + '.ts');\n } else if (host.exists(modulePath + '.module.ts')) {\n return normalize(modulePath + '.module.ts');\n } else if (host.exists(modulePath + '/' + moduleBaseName + '.module.ts')) {\n return normalize(modulePath + '/' + moduleBaseName + '.module.ts');\n } else {\n throw new Error('Specified module does not exist');\n }\n }\n}\n\n/**\n * Function to find the \"closest\" module to a generated file's path.\n */\nexport function findModule(host: Tree, generateDir: string): Path {\n let dir: DirEntry | null = host.getDir('/' + generateDir);\n\n const moduleRe = /\\.module\\.ts$/;\n const routingModuleRe = /-routing\\.module\\.ts/;\n\n while (dir) {\n const matches = dir.subfiles.filter(p => moduleRe.test(p) && !routingModuleRe.test(p));\n\n if (matches.length == 1) {\n return join(dir.path, matches[0]);\n } else if (matches.length > 1) {\n throw new Error('More than one module matches. Use skip-import option to skip importing '\n + 'the component into the closest module.');\n }\n\n dir = dir.parent;\n }\n\n throw new Error('Could not find an NgModule. Use the skip-import '\n + 'option to skip importing in NgModule.');\n}\n\n/**\n * Build a relative path from one file path to another file path.\n */\nexport function buildRelativePath(from: string, to: string): string {\n from = normalize(from);\n to = normalize(to);\n\n // Convert to arrays.\n const fromParts = from.split('/');\n const toParts = to.split('/');\n\n // Remove file names (preserving destination)\n fromParts.pop();\n const toFileName = toParts.pop();\n\n const relativePath = relative(normalize(fromParts.join('/')), normalize(toParts.join('/')));\n let pathPrefix = '';\n\n // Set the path prefix for same dir or child dir, parent dir starts with `..`\n if (!relativePath) {\n pathPrefix = '.';\n } else if (!relativePath.startsWith('.')) {\n pathPrefix = `./`;\n }\n if (pathPrefix && !pathPrefix.endsWith('/')) {\n pathPrefix += '/';\n }\n\n return pathPrefix + (relativePath ? relativePath + '/' : '') + toFileName;\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation. All rights reserved.\r\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\r\nthis file except in compliance with the License. You may obtain a copy of the\r\nLicense at http://www.apache.org/licenses/LICENSE-2.0\r\n\r\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\r\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\r\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\r\nMERCHANTABLITY OR NON-INFRINGEMENT.\r\n\r\nSee the Apache Version 2.0 License for specific language governing permissions\r\nand limitations under the License.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)\r\n t[p[i]] = s[p[i]];\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator], i = 0;\r\n if (m) return m.call(o);\r\n return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n","/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nexport interface Host {\n write(path: string, content: string): Promise<void>;\n read(path: string): Promise<string>;\n}\n\n\nexport interface Change {\n apply(host: Host): Promise<void>;\n\n // The file this change should be applied to. Some changes might not apply to\n // a file (maybe the config).\n readonly path: string | null;\n\n // The order this change should be applied. Normally the position inside the file.\n // Changes are applied from the bottom of a file to the top.\n readonly order: number;\n\n // The description of this change. This will be outputted in a dry or verbose run.\n readonly description: string;\n}\n\n\n/**\n * An operation that does nothing.\n */\nexport class NoopChange implements Change {\n description = 'No operation.';\n order = Infinity;\n path = null;\n apply() { return Promise.resolve(); }\n}\n\n\n/**\n * Will add text to the source code.\n */\nexport class InsertChange implements Change {\n\n order: number;\n description: string;\n\n constructor(public path: string, public pos: number, public toAdd: string) {\n if (pos < 0) {\n throw new Error('Negative positions are invalid');\n }\n this.description = `Inserted ${toAdd} into position ${pos} of ${path}`;\n this.order = pos;\n }\n\n /**\n * This method does not insert spaces if there is none in the original string.\n */\n apply(host: Host) {\n return host.read(this.path).then(content => {\n const prefix = content.substring(0, this.pos);\n const suffix = content.substring(this.pos);\n\n return host.write(this.path, `${prefix}${this.toAdd}${suffix}`);\n });\n }\n}\n\n/**\n * Will remove text from the source code.\n */\nexport class RemoveChange implements Change {\n\n order: number;\n description: string;\n\n constructor(public path: string, private pos: number, private toRemove: string) {\n if (pos < 0) {\n throw new Error('Negative positions are invalid');\n }\n this.description = `Removed ${toRemove} into position ${pos} of ${path}`;\n this.order = pos;\n }\n\n apply(host: Host): Promise<void> {\n return host.read(this.path).then(content => {\n const prefix = content.substring(0, this.pos);\n const suffix = content.substring(this.pos + this.toRemove.length);\n\n // TODO: throw error if toRemove doesn't match removed string.\n return host.write(this.path, `${prefix}${suffix}`);\n });\n }\n}\n\n/**\n * Will replace text from the source code.\n */\nexport class ReplaceChange implements Change {\n order: number;\n description: string;\n\n constructor(public path: string, private pos: number, private oldText: string,\n private newText: string) {\n if (pos < 0) {\n throw new Error('Negative positions are invalid');\n }\n this.description = `Replaced ${oldText} into position ${pos} of ${path} with ${newText}`;\n this.order = pos;\n }\n\n apply(host: Host): Promise<void> {\n return host.read(this.path).then(content => {\n const prefix = content.substring(0, this.pos);\n const suffix = content.substring(this.pos + this.oldText.length);\n const text = content.substring(this.pos, this.pos + this.oldText.length);\n\n if (text !== this.oldText) {\n return Promise.reject(new Error(`Invalid replace: \"${text}\" != \"${this.oldText}\".`));\n }\n\n // TODO: throw error if oldText doesn't match removed string.\n return host.write(this.path, `${prefix}${this.newText}${suffix}`);\n });\n }\n}\n","/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nimport * as ts from 'typescript';\nimport { Change, InsertChange, NoopChange } from './change';\n\n/**\n * Add Import `import { symbolName } from fileName` if the import doesn't exit\n * already. Assumes fileToEdit can be resolved and accessed.\n * @param fileToEdit (file we want to add import to)\n * @param symbolName (item to import)\n * @param fileName (path to the file)\n * @param isDefault (if true, import follows style for importing default exports)\n * @return Change\n */\nexport function insertImport(\n source: ts.SourceFile,\n fileToEdit: string,\n symbolName: string,\n fileName: string,\n isDefault = false\n): Change {\n const rootNode = source;\n const allImports = findNodes(rootNode, ts.SyntaxKind.ImportDeclaration);\n\n // get nodes that map to import statements from the file fileName\n const relevantImports = allImports.filter(node => {\n // StringLiteral of the ImportDeclaration is the import file (fileName in this case).\n const importFiles = node\n .getChildren()\n .filter(child => child.kind === ts.SyntaxKind.StringLiteral)\n .map(n => (n as ts.StringLiteral).text);\n\n return importFiles.filter(file => file === fileName).length === 1;\n });\n\n if (relevantImports.length > 0) {\n let importsAsterisk = false;\n // imports from import file\n const imports: ts.Node[] = [];\n relevantImports.forEach(n => {\n Array.prototype.push.apply(\n imports,\n findNodes(n, ts.SyntaxKind.Identifier)\n );\n if (findNodes(n, ts.SyntaxKind.AsteriskToken).length > 0) {\n importsAsterisk = true;\n }\n });\n\n // if imports * from fileName, don't add symbolName\n if (importsAsterisk) {\n return new NoopChange();\n }\n\n const importTextNodes = imports.filter(\n n => (n as ts.Identifier).text === symbolName\n );\n\n // insert import if it's not there\n if (importTextNodes.length === 0) {\n const fallbackPos =\n findNodes(\n relevantImports[0],\n ts.SyntaxKind.CloseBraceToken\n )[0].getStart() ||\n findNodes(relevantImports[0], ts.SyntaxKind.FromKeyword)[0].getStart();\n\n return insertAfterLastOccurrence(\n imports,\n `, ${symbolName}`,\n fileToEdit,\n fallbackPos\n );\n }\n\n return new NoopChange();\n }\n\n // no such import declaration exists\n const useStrict = findNodes(rootNode, ts.SyntaxKind.StringLiteral).filter(\n (n: ts.StringLiteral) => n.text === 'use strict'\n );\n let fallbackPos = 0;\n if (useStrict.length > 0) {\n fallbackPos = useStrict[0].end;\n }\n const open = isDefault ? '' : '{ ';\n const close = isDefault ? '' : ' }';\n // if there are no imports or 'use strict' statement, insert import at beginning of file\n const insertAtBeginning = allImports.length === 0 && useStrict.length === 0;\n const separator = insertAtBeginning ? '' : ';\\n';\n const toInsert =\n `${separator}import ${open}${symbolName}${close}` +\n ` from '${fileName}'${insertAtBeginning ? ';\\n' : ''}`;\n\n return insertAfterLastOccurrence(\n allImports,\n toInsert,\n fileToEdit,\n fallbackPos,\n ts.SyntaxKind.StringLiteral\n );\n}\n\n/**\n * Find all nodes from the AST in the subtree of node of SyntaxKind kind.\n * @param node\n * @param kind\n * @param max The maximum number of items to return.\n * @return all nodes of kind, or [] if none is found\n */\nexport function findNodes(\n node: ts.Node,\n kind: ts.SyntaxKind,\n max = Infinity\n): ts.Node[] {\n if (!node || max == 0) {\n return [];\n }\n\n const arr: ts.Node[] = [];\n if (node.kind === kind) {\n arr.push(node);\n max--;\n }\n if (max > 0) {\n for (const child of node.getChildren()) {\n findNodes(child, kind, max).forEach(node => {\n if (max > 0) {\n arr.push(node);\n }\n max--;\n });\n\n if (max <= 0) {\n break;\n }\n }\n }\n\n return arr;\n}\n\n/**\n * Get all the nodes from a source.\n * @param sourceFile The source file object.\n * @returns An observable of all the nodes in the source.\n */\nexport function getSourceNodes(sourceFile: ts.SourceFile): ts.Node[] {\n const nodes: ts.Node[] = [sourceFile];\n const result = [];\n\n while (nodes.length > 0) {\n const node = nodes.shift();\n\n if (node) {\n result.push(node);\n if (node.getChildCount(sourceFile) >= 0) {\n nodes.unshift(...node.getChildren());\n }\n }\n }\n\n return result;\n}\n\nexport function findNode(\n node: ts.Node,\n kind: ts.SyntaxKind,\n text: string\n): ts.Node | null {\n if (node.kind === kind && node.getText() === text) {\n // throw new Error(node.getText());\n return node;\n }\n\n let foundNode: ts.Node | null = null;\n ts.forEachChild(node, childNode => {\n foundNode = foundNode || findNode(childNode, kind, text);\n });\n\n return foundNode;\n}\n\n/**\n * Helper for sorting nodes.\n * @return function to sort nodes in increasing order of position in sourceFile\n */\nfunction nodesByPosition(first: ts.Node, second: ts.Node): number {\n return first.getStart() - second.getStart();\n}\n\n/**\n * Insert `toInsert` after the last occurence of `ts.SyntaxKind[nodes[i].kind]`\n * or after the last of occurence of `syntaxKind` if the last occurence is a sub child\n * of ts.SyntaxKind[nodes[i].kind] and save the changes in file.\n *\n * @param nodes insert after the last occurence of nodes\n * @param toInsert string to insert\n * @param file file to insert changes into\n * @param fallbackPos position to insert if toInsert happens to be the first occurence\n * @param syntaxKind the ts.SyntaxKind of the subchildren to insert after\n * @return Change instance\n * @throw Error if toInsert is first occurence but fall back is not set\n */\nexport function insertAfterLastOccurrence(\n nodes: ts.Node[],\n toInsert: string,\n file: string,\n fallbackPos: number,\n syntaxKind?: ts.SyntaxKind\n): Change {\n // sort() has a side effect, so make a copy so that we won't overwrite the parent's object.\n let lastItem = [...nodes].sort(nodesByPosition).pop();\n if (!lastItem) {\n throw new Error();\n }\n if (syntaxKind) {\n lastItem = findNodes(lastItem, syntaxKind)\n .sort(nodesByPosition)\n .pop();\n }\n if (!lastItem && fallbackPos == undefined) {\n throw new Error(\n `tried to insert ${toInsert} as first occurence with no fallback position`\n );\n }\n const lastItemPosition: number = lastItem ? lastItem.getEnd() : fallbackPos;\n\n return new InsertChange(file, lastItemPosition, toInsert);\n}\n\nexport function getContentOfKeyLiteral(\n _source: ts.SourceFile,\n node: ts.Node\n): string | null {\n if (node.kind == ts.SyntaxKind.Identifier) {\n return (node as ts.Identifier).text;\n } else if (node.kind == ts.SyntaxKind.StringLiteral) {\n return (node as ts.StringLiteral).text;\n } else {\n return null;\n }\n}\n\nfunction _angularImportsFromNode(\n node: ts.ImportDeclaration,\n _sourceFile: ts.SourceFile\n): { [name: string]: string } {\n const ms = node.moduleSpecifier;\n let modulePath: string;\n switch (ms.kind) {\n case ts.SyntaxKind.StringLiteral:\n modulePath = (ms as ts.StringLiteral).text;\n break;\n default:\n return {};\n }\n\n if (!modulePath.startsWith('@angular/')) {\n return {};\n }\n\n if (node.importClause) {\n if (node.importClause.name) {\n // This is of the form `import Name from 'path'`. Ignore.\n return {};\n } else if (node.importClause.namedBindings) {\n const nb = node.importClause.namedBindings;\n if (nb.kind == ts.SyntaxKind.NamespaceImport) {\n // This is of the form `import * as name from 'path'`. Return `name.`.\n return {\n [(nb as ts.NamespaceImport).name.text + '.']: modulePath\n };\n } else {\n // This is of the form `import {a,b,c} from 'path'`\n const namedImports = nb as ts.NamedImports;\n\n return namedImports.elements\n .map(\n (is: ts.ImportSpecifier) =>\n is.propertyName ? is.propertyName.text : is.name.text\n )\n .reduce((acc: { [name: string]: string }, curr: string) => {\n acc[curr] = modulePath;\n\n return acc;\n }, {});\n }\n }\n\n return {};\n } else {\n // This is of the form `import 'path';`. Nothing to do.\n return {};\n }\n}\n\nexport function getDecoratorMetadata(\n source: ts.SourceFile,\n identifier: string,\n module: string\n): ts.Node[] {\n const angularImports: { [name: string]: string } = findNodes(\n source,\n ts.SyntaxKind.ImportDeclaration\n )\n .map((node: ts.ImportDeclaration) => _angularImportsFromNode(node, source))\n .reduce(\n (\n acc: { [name: string]: string },\n current: { [name: string]: string }\n ) => {\n for (const key of Object.keys(current)) {\n acc[key] = current[key];\n }\n\n return acc;\n },\n {}\n );\n\n return getSourceNodes(source)\n .filter(node => {\n return (\n node.kind == ts.SyntaxKind.Decorator &&\n (node as ts.Decorator).expression.kind == ts.SyntaxKind.CallExpression\n );\n })\n .map(node => (node as ts.Decorator).expression as ts.CallExpression)\n .filter(expr => {\n if (expr.expression.kind == ts.SyntaxKind.Identifier) {\n const id = expr.expression as ts.Identifier;\n\n return (\n id.getFullText(source) == identifier &&\n angularImports[id.getFullText(source)] === module\n );\n } else if (\n expr.expression.kind == ts.SyntaxKind.PropertyAccessExpression\n ) {\n // This covers foo.NgModule when importing * as foo.\n const paExpr = expr.expression as ts.PropertyAccessExpression;\n // If the left expression is not an identifier, just give up at that point.\n if (paExpr.expression.kind !== ts.SyntaxKind.Identifier) {\n return false;\n }\n\n const id = paExpr.name.text;\n const moduleId = (paExpr.expression as ts.Identifier).getText(source);\n\n return id === identifier && angularImports[moduleId + '.'] === module;\n }\n\n return false;\n })\n .filter(\n expr =>\n expr.arguments[0] &&\n expr.arguments[0].kind == ts.SyntaxKind.ObjectLiteralExpression\n )\n .map(expr => expr.arguments[0] as ts.ObjectLiteralExpression);\n}\n\nfunction findClassDeclarationParent(\n node: ts.Node\n): ts.ClassDeclaration | undefined {\n if (ts.isClassDeclaration(node)) {\n return node;\n }\n\n return node.parent && findClassDeclarationParent(node.parent);\n}\n\n/**\n * Given a source file with @NgModule class(es), find the name of the first @NgModule class.\n *\n * @param source source file containing one or more @NgModule\n * @returns the name of the first @NgModule, or `undefined` if none is found\n */\nexport function getFirstNgModuleName(\n source: ts.SourceFile\n): string | undefined {\n // First, find the @NgModule decorators.\n const ngModulesMetadata = getDecoratorMetadata(\n source,\n 'NgModule',\n '@angular/core'\n );\n if (ngModulesMetadata.length === 0) {\n return undefined;\n }\n\n // Then walk parent pointers up the AST, looking for the ClassDeclaration parent of the NgModule\n // metadata.\n const moduleClass = findClassDeclarationParent(ngModulesMetadata[0]);\n if (!moduleClass || !moduleClass.name) {\n return undefined;\n }\n\n // Get the class name of the module ClassDeclaration.\n return moduleClass.name.text;\n}\n\nexport function addSymbolToNgModuleMetadata(\n source: ts.SourceFile,\n ngModulePath: string,\n metadataField: string,\n symbolName: string,\n importPath: string | null = null\n): Change[] {\n const nodes = getDecoratorMetadata(source, 'NgModule', '@angular/core');\n let node: any = nodes[0]; // tslint:disable-line:no-any\n\n // Find the decorator declaration.\n if (!node) {\n return [];\n }\n\n // Get all the children property assignment of object literals.\n const matchingProperties: ts.ObjectLiteralElement[] = (node as ts.ObjectLiteralExpression).properties\n .filter(prop => prop.kind == ts.SyntaxKind.PropertyAssignment)\n // Filter out every fields that's not \"metadataField\". Also handles string literals\n // (but not expressions).\n .filter((prop: ts.PropertyAssignment) => {\n const name = prop.name;\n switch (name.kind) {\n case ts.SyntaxKind.Identifier:\n return (name as ts.Identifier).getText(source) == metadataField;\n case ts.SyntaxKind.StringLiteral:\n return (name as ts.StringLiteral).text == metadataField;\n }\n\n return false;\n });\n\n // Get the last node of the array literal.\n if (!matchingProperties) {\n return [];\n }\n if (matchingProperties.length == 0) {\n // We haven't found the field in the metadata declaration. Insert a new field.\n const expr = node as ts.ObjectLiteralExpression;\n let position: number;\n let toInsert: string;\n if (expr.properties.length == 0) {\n position = expr.getEnd() - 1;\n toInsert = ` ${metadataField}: [${symbolName}]\\n`;\n } else {\n node = expr.properties[expr.properties.length - 1];\n position = node.getEnd();\n // Get the indentation of the last element, if any.\n const text = node.getFullText(source);\n const matches = text.match(/^\\r?\\n\\s*/);\n if (matches.length > 0) {\n toInsert = `,${matches[0]}${metadataField}: [${symbolName}]`;\n } else {\n toInsert = `, ${metadataField}: [${symbolName}]`;\n }\n }\n if (importPath !== null) {\n return [\n new InsertChange(ngModulePath, position, toInsert),\n insertImport(\n source,\n ngModulePath,\n symbolName.replace(/\\..*$/, ''),\n importPath\n )\n ];\n } else {\n return [new InsertChange(ngModulePath, position, toInsert)];\n }\n }\n const assignment = matchingProperties[0] as ts.PropertyAssignment;\n\n // If it's not an array, nothing we can do really.\n if (assignment.initializer.kind !== ts.SyntaxKind.ArrayLiteralExpression) {\n return [];\n }\n\n const arrLiteral = assignment.initializer as ts.ArrayLiteralExpression;\n if (arrLiteral.elements.length == 0) {\n // Forward the property.\n node = arrLiteral;\n } else {\n node = arrLiteral.elements;\n }\n\n if (!node) {\n console.log(\n 'No app module found. Please add your new class to your component.'\n );\n\n return [];\n }\n\n if (Array.isArray(node)) {\n const nodeArray = (node as {}) as Array<ts.Node>;\n const symbolsArray = nodeArray.map(node => node.getText());\n if (symbolsArray.indexOf(symbolName) >= 0) {\n return [];\n }\n\n node = node[node.length - 1];\n }\n\n let toInsert: string;\n let position = node.getEnd();\n if (node.kind == ts.SyntaxKind.ObjectLiteralExpression) {\n // We haven't found the field in the metadata declaration. Insert a new\n // field.\n const expr = node as ts.ObjectLiteralExpression;\n if (expr.properties.length == 0) {\n position = expr.getEnd() - 1;\n toInsert = ` ${metadataField}: [${symbolName}]\\n`;\n } else {\n node = expr.properties[expr.properties.length - 1];\n position = node.getEnd();\n // Get the indentation of the last element, if any.\n const text = node.getFullText(source);\n if (text.match('^\\r?\\r?\\n')) {\n toInsert = `,${\n text.match(/^\\r?\\n\\s+/)[0]\n }${metadataField}: [${symbolName}]`;\n } else {\n toInsert = `, ${metadataField}: [${symbolName}]`;\n }\n }\n } else if (node.kind == ts.SyntaxKind.ArrayLiteralExpression) {\n // We found the field but it's empty. Insert it just before the `]`.\n position--;\n toInsert = `${symbolName}`;\n } else {\n // Get the indentation of the last element, if any.\n const text = node.getFullText(source);\n if (text.match(/^\\r?\\n/)) {\n toInsert = `,${text.match(/^\\r?\\n(\\r?)\\s+/)[0]}${symbolName}`;\n } else {\n toInsert = `, ${symbolName}`;\n }\n }\n if (importPath !== null) {\n return [\n new InsertChange(ngModulePath, position, toInsert),\n insertImport(\n source,\n ngModulePath,\n symbolName.replace(/\\..*$/, ''),\n importPath\n )\n ];\n }\n\n return [new InsertChange(ngModulePath, position, toInsert)];\n}\n\n/**\n * Custom function to insert a declaration (component, pipe, directive)\n * into NgModule declarations. It also imports the component.\n */\nexport function addDeclarationToModule(\n source: ts.SourceFile,\n modulePath: string,\n classifiedName: string,\n importPath: string\n): Change[] {\n return addSymbolToNgModuleMetadata(\n source,\n modulePath,\n 'declarations',\n classifiedName,\n importPath\n );\n}\n\n/**\n * Custom function to insert an NgModule into NgModule imports. It also imports the module.\n */\nexport function addImportToModule(\n source: ts.SourceFile,\n modulePath: string,\n classifiedName: string,\n importPath: string\n): Change[] {\n return addSymbolToNgModuleMetadata(\n source,\n modulePath,\n 'imports',\n classifiedName,\n importPath\n );\n}\n\n/**\n * Custom function to insert a provider into NgModule. It also imports it.\n */\nexport function addProviderToModule(\n source: ts.SourceFile,\n modulePath: string,\n classifiedName: string,\n importPath: string\n): Change[] {\n return addSymbolToNgModuleMetadata(\n source,\n modulePath,\n 'providers',\n classifiedName,\n importPath\n );\n}\n\n/**\n * Custom function to insert an export into NgModule. It also imports it.\n */\nexport function addExportToModule(\n source: ts.SourceFile,\n modulePath: string,\n classifiedName: string,\n importPath: string\n): Change[] {\n return addSymbolToNgModuleMetadata(\n source,\n modulePath,\n 'exports',\n classifiedName,\n importPath\n );\n}\n\n/**\n * Custom function to insert an export into NgModule. It also imports it.\n */\nexport function addBootstrapToModule(\n source: ts.SourceFile,\n modulePath: string,\n classifiedName: string,\n importPath: string\n): Change[] {\n return addSymbolToNgModuleMetadata(\n source,\n modulePath,\n 'bootstrap',\n classifiedName,\n importPath\n );\n}\n\n/**\n * Custom function to insert an entryComponent into NgModule. It also imports it.\n */\nexport function addEntryComponentToModule(\n source: ts.SourceFile,\n modulePath: string,\n classifiedName: string,\n importPath: string\n): Change[] {\n return addSymbolToNgModuleMetadata(\n source,\n modulePath,\n 'entryComponents',\n classifiedName,\n importPath\n );\n}\n\n/**\n * Determine if an import already exists.\n */\nexport function isImported(\n source: ts.SourceFile,\n classifiedName: string,\n importPath: string\n): boolean {\n const allNodes = getSourceNodes(source);\n const matchingNodes = allNodes\n .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration)\n .filter(\n (imp: ts.ImportDeclaration) =>\n imp.moduleSpecifier.kind === ts.SyntaxKind.StringLiteral\n )\n .filter((imp: ts.ImportDeclaration) => {\n return (<ts.StringLiteral>imp.moduleSpecifier).text === importPath;\n })\n .filter((imp: ts.ImportDeclaration) => {\n if (!imp.importClause) {\n return false;\n }\n const nodes = findNodes(\n imp.importClause,\n ts.SyntaxKind.ImportSpecifier\n ).filter(n => n.getText() === classifiedName);\n\n return nodes.length > 0;\n });\n\n return matchingNodes.length > 0;\n}\n","/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nimport { JsonParseMode, experimental, parseJson } from '@angular-devkit/core';\nimport { Rule, SchematicContext, SchematicsException, Tree } from '@angular-devkit/schematics';\n\n\n// The interfaces below are generated from the Angular CLI configuration schema\n// https://github.com/angular/angular-cli/blob/master/packages/@angular/cli/lib/config/schema.json\nexport interface AppConfig {\n /**\n * Name of the app.\n */\n name?: string;\n /**\n * Directory where app files are placed.\n */\n appRoot?: string;\n /**\n * The root directory of the app.\n */\n root?: string;\n /**\n * The output directory for build results.\n */\n outDir?: string;\n /**\n * List of application assets.\n */\n assets?: (string | {\n /**\n * The pattern to match.\n */\n glob?: string;\n /**\n * The dir to search within.\n */\n input?: string;\n /**\n * The output path (relative to the outDir).\n */\n output?: string;\n })[];\n /**\n * URL where files will be deployed.\n */\n deployUrl?: string;\n /**\n * Base url for the application being built.\n */\n baseHref?: string;\n /**\n * The runtime platform of the app.\n */\n platform?: ('browser' | 'server');\n /**\n * The name of the start HTML file.\n */\n index?: string;\n /**\n * The name of the main entry-point file.\n */\n main?: string;\n /**\n * The name of the polyfills file.\n */\n polyfills?: string;\n /**\n * The name of the test entry-point file.\n */\n test?: string;\n /**\n * The name of the TypeScript configuration file.\n */\n tsconfig?: string;\n /**\n * The name of the TypeScript configuration file for unit tests.\n */\n testTsconfig?: string;\n /**\n * The prefix to apply to generated selectors.\n */\n prefix?: string;\n /**\n * Experimental support for a service worker from @angular/service-worker.\n */\n serviceWorker?: boolean;\n /**\n * Global styles to be included in the build.\n */\n styles?: (string | {\n input?: string;\n [name: string]: any; // tslint:disable-line:no-any\n })[];\n /**\n * Options to pass to style preprocessors\n */\n stylePreprocessorOptions?: {\n /**\n * Paths to include. Paths will be resolved to project root.\n */\n includePaths?: string[];\n };\n /**\n * Global scripts to be included in the build.\n */\n scripts?: (string | {\n input: string;\n [name: string]: any; // tslint:disable-line:no-any\n })[];\n /**\n * Source file for environment config.\n */\n environmentSource?: string;\n /**\n * Name and corresponding file for environment config.\n */\n environments?: {\n [name: string]: any; // tslint:disable-line:no-any\n };\n appShell?: {\n app: string;\n route: string;\n };\n budgets?: {\n /**\n * The type of budget\n */\n type?: ('bundle' | 'initial' | 'allScript' | 'all' | 'anyScript' | 'any');\n /**\n * The name of the bundle\n */\n name?: string;\n /**\n * The baseline size for comparison.\n */\n baseline?: string;\n /**\n * The maximum threshold for warning relative to the baseline.\n */\n maximumWarning?: string;\n /**\n * The maximum threshold for error relative to the baseline.\n */\n maximumError?: string;\n /**\n * The minimum threshold for warning relative to the baseline.\n */\n minimumWarning?: string;\n /**\n * The minimum threshold for error relative to the baseline.\n */\n minimumError?: string;\n /**\n * The threshold for warning relative to the baseline (min & max).\n */\n warning?: string;\n /**\n * The threshold for error relative to the baseline (min & max).\n */\n error?: string;\n }[];\n}\n\nexport interface CliConfig {\n $schema?: string;\n /**\n * The global configuration of the project.\n */\n project?: {\n /**\n * The name of the project.\n */\n name?: string;\n /**\n * Whether or not this project was ejected.\n */\n ejected?: boolean;\n };\n /**\n * Properties of the different applications in this project.\n */\n apps?: AppConfig[];\n /**\n * Configuration for end-to-end tests.\n */\n e2e?: {\n protractor?: {\n /**\n * Path to the config file.\n */\n config?: string;\n };\n };\n /**\n * Properties to be passed to TSLint.\n */\n lint?: {\n /**\n * File glob(s) to lint.\n */\n files?: (string | string[]);\n /**\n * Location of the tsconfig.json project file.\n * Will also use as files to lint if 'files' property not present.\n */\n project: string;\n /**\n * Location of the tslint.json configuration.\n */\n tslintConfig?: string;\n /**\n * File glob(s) to ignore.\n */\n exclude?: (string | string[]);\n }[];\n /**\n * Configuration for unit tests.\n */\n test?: {\n karma?: {\n /**\n * Path to the karma config file.\n */\n config?: string;\n };\n codeCoverage?: {\n /**\n * Globs to exclude from code coverage.\n */\n exclude?: string[];\n };\n };\n /**\n * Specify the default values for generating.\n */\n defaults?: {\n /**\n * The file extension to be used for style files.\n */\n styleExt?: string;\n /**\n * How often to check for file updates.\n */\n poll?: number;\n /**\n * Use lint to fix files after generation\n */\n lintFix?: boolean;\n /**\n * Options for generating a class.\n */\n class?: {\n /**\n * Specifies if a spec file is generated.\n */\n spec?: boolean;\n };\n /**\n * Options for generating a component.\n */\n component?: {\n /**\n * Flag to indicate if a dir is created.\n */\n flat?: boolean;\n /**\n * Specifies if a spec file is generated.\n */\n spec?: boolean;\n /**\n * Specifies if the style will be in the ts file.\n */\n inlineStyle?: boolean;\n /**\n * Specifies if the template will be in the ts file.\n */\n inlineTemplate?: boolean;\n /**\n * Specifies the view encapsulation strategy.\n */\n viewEncapsulation?: ('Emulated' | 'Native' | 'None');\n /**\n * Specifies the change detection strategy.\n */\n changeDetection?: ('Default' | 'OnPush');\n };\n /**\n * Options for generating a directive.\n */\n directive?: {\n /**\n * Flag to indicate if a dir is created.\n */\n flat?: boolean;\n /**\n * Specifies if a spec file is generated.\n */\n spec?: boolean;\n };\n /**\n * Options for generating a guard.\n */\n guard?: {\n /**\n * Flag to indicate if a dir is created.\n */\n flat?: boolean;\n /**\n * Specifies if a spec file is generated.\n */\n spec?: boolean;\n };\n /**\n * Options for generating an interface.\n */\n interface?: {\n /**\n * Prefix to apply to interface names. (i.e. I)\n */\n prefix?: string;\n };\n /**\n * Options for generating a module.\n */\n module?: {\n /**\n * Flag to indicate if a dir is created.\n */\n flat?: boolean;\n /**\n * Specifies if a spec file is generated.\n */\n spec?: boolean;\n };\n /**\n * Options for generating a pipe.\n */\n pipe?: {\n /**\n * Flag to indicate if a dir is created.\n */\n flat?: boolean;\n /**\n * Specifies if a spec file is generated.\n */\n spec?: boolean;\n };\n /**\n * Options for generating a service.\n */\n service?: {\n /**\n * Flag to indicate if a dir is created.\n */\n flat?: boolean;\n /**\n * Specifies if a spec file is generated.\n */\n spec?: boolean;\n };\n /**\n * Properties to be passed to the build command.\n */\n build?: {\n /**\n * Output sourcemaps.\n */\n sourcemaps?: boolean;\n /**\n * Base url for the application being built.\n */\n baseHref?: string;\n /**\n * The ssl key used by the server.\n */\n progress?: boolean;\n /**\n * Enable and define the file watching poll time period (milliseconds).\n */\n poll?: number;\n /**\n * Delete output path before build.\n */\n deleteOutputPath?: boolean;\n /**\n * Do not use the real path when resolving modules.\n */\n preserveSymlinks?: boolean;\n /**\n * Show circular dependency warnings on builds.\n */\n showCircularDependencies?: boolean;\n /**\n * Use a separate bundle containing code used across multiple bundles.\n */\n commonChunk?: boolean;\n /**\n * Use file name for lazy loaded chunks.\n */\n namedChunks?: boolean;\n };\n /**\n * Properties to be passed to the serve command.\n */\n serve?: {\n /**\n * The port the application will be served on.\n */\n port?: number;\n /**\n * The host the application will be served on.\n */\n host?: string;\n /**\n * Enables ssl for the application.\n */\n ssl?: boolean;\n /**\n * The ssl key used by the server.\n */\n sslKey?: string;\n /**\n * The ssl certificate used by the server.\n */\n sslCert?: string;\n /**\n * Proxy configuration file.\n */\n proxyConfig?: string;\n };\n /**\n * Properties about schematics.\n */\n schematics?: {\n /**\n * The schematics collection to use.\n */\n collection?: string;\n /**\n * The new app schematic.\n */\n newApp?: string;\n };\n };\n /**\n * Specify which package manager tool to use.\n */\n packageManager?: ('npm' | 'cnpm' | 'yarn' | 'default');\n /**\n * Allow people to disable console warnings.\n */\n warnings?: {\n /**\n * Show a warning when the user enabled the --hmr option.\n */\n hmrWarning?: boolean;\n /**\n * Show a warning when the node version is incompatible.\n */\n nodeDeprecation?: boolean;\n /**\n * Show a warning when the user installed angular-cli.\n */\n packageDeprecation?: boolean;\n /**\n * Show a warning when the global version is newer than the local one.\n */\n versionMismatch?: boolean;\n /**\n * Show a warning when the TypeScript version is incompatible\n */\n typescriptMismatch?: boolean;\n };\n}\n\nexport type WorkspaceSchema = experimental.workspace.WorkspaceSchema;\nexport type WorkspaceProject = experimental.workspace.WorkspaceProject;\n\n\nexport function getWorkspacePath(host: Tree): string {\n const possibleFiles = [ '/angular.json', '/.angular.json' ];\n const path = possibleFiles.filter(path => host.exists(path))[0];\n\n return path;\n}\n\nexport function getWorkspace(host: Tree): WorkspaceSchema {\n const path = getWorkspacePath(host);\n const configBuffer = host.read(path);\n if (configBuffer === null) {\n throw new SchematicsException(`Could not find (${path})`);\n }\n const content = configBuffer.toString();\n\n return parseJson(content, JsonParseMode.Loose) as {} as WorkspaceSchema;\n}\n\nexport function addProjectToWorkspace(\n workspace: WorkspaceSchema,\n name: string,\n project: WorkspaceProject,\n): Rule {\n return (host: Tree, context: SchematicContext) => {\n\n if (workspace.projects[name]) {\n throw new Error(`Project '${name}' already exists in workspace.`);\n }\n\n // Add project to workspace.\n workspace.projects[name] = project;\n\n if (!workspace.defaultProject && Object.keys(workspace.projects).length === 1) {\n // Make the new project the default one.\n workspace.defaultProject = name;\n }\n\n host.overwrite(getWorkspacePath(host), JSON.stringify(workspace, null, 2));\n };\n}\n\nexport const configPath = '/.angular-cli.json';\n\nexport function getConfig(host: Tree): CliConfig {\n const configBuffer = host.read(configPath);\n if (configBuffer === null) {\n throw new SchematicsException('Could not find .angular-cli.json');\n }\n\n const config = parseJson(configBuffer.toString(), JsonParseMode.Loose) as {} as CliConfig;\n\n return config;\n}\n\nexport function getAppFromConfig(config: CliConfig, appIndexOrName: string): AppConfig | null {\n if (!config.apps) {\n return null;\n }\n\n if (parseInt(appIndexOrName) >= 0) {\n return config.apps[parseInt(appIndexOrName)];\n }\n\n return config.apps.filter((app) => app.name === appIndexOrName)[0];\n}\n","/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nimport { normalize } from '@angular-devkit/core';\nimport { SchematicsException, Tree } from '@angular-devkit/schematics';\nimport { dirname } from 'path';\nimport * as ts from 'typescript';\nimport { findNode, getSourceNodes } from '../utility/ast-utils';\n\nexport function findBootstrapModuleCall(host: Tree, mainPath: string): ts.CallExpression | null {\n const mainBuffer = host.read(mainPath);\n if (!mainBuffer) {\n throw new SchematicsException(`Main file (${mainPath}) not found`);\n }\n const mainText = mainBuffer.toString('utf-8');\n const source = ts.createSourceFile(mainPath, mainText, ts.ScriptTarget.Latest, true);\n\n const allNodes = getSourceNodes(source);\n\n let bootstrapCall: ts.CallExpression | null = null;\n\n for (const node of allNodes) {\n\n let bootstrapCallNode: ts.Node | null = null;\n bootstrapCallNode = findNode(node, ts.SyntaxKind.Identifier, 'bootstrapModule');\n\n // Walk up the parent until CallExpression is found.\n while (bootstrapCallNode && bootstrapCallNode.parent\n && bootstrapCallNode.parent.kind !== ts.SyntaxKind.CallExpression) {\n\n bootstrapCallNode = bootstrapCallNode.parent;\n }\n\n if (bootstrapCallNode !== null &&\n bootstrapCallNode.parent !== undefined &&\n bootstrapCallNode.parent.kind === ts.SyntaxKind.CallExpression) {\n bootstrapCall = bootstrapCallNode.parent as ts.CallExpression;\n break;\n }\n }\n\n return bootstrapCall;\n}\n\nexport function findBootstrapModulePath(host: Tree, mainPath: string): string {\n const bootstrapCall = findBootstrapModuleCall(host, mainPath);\n if (!bootstrapCall) {\n throw new SchematicsException('Bootstrap call not found');\n }\n\n const bootstrapModule = bootstrapCall.arguments[0];\n\n const mainBuffer = host.read(mainPath);\n if (!mainBuffer) {\n throw new SchematicsException(`Client app main file (${mainPath}) not found`);\n }\n const mainText = mainBuffer.toString('utf-8');\n const source = ts.createSourceFile(mainPath, mainText, ts.ScriptTarget.Latest, true);\n const allNodes = getSourceNodes(source);\n const bootstrapModuleRelativePath = allNodes\n .filter(node => node.kind === ts.SyntaxKind.ImportDeclaration)\n .filter(imp => {\n return findNode(imp, ts.SyntaxKind.Identifier, bootstrapModule.getText());\n })\n .map((imp: ts.ImportDeclaration) => {\n const modulePathStringLiteral = <ts.StringLiteral> imp.moduleSpecifier;\n\n return modulePathStringLiteral.text;\n })[0];\n\n return bootstrapModuleRelativePath;\n}\n\nexport function getAppModulePath(host: Tree, mainPath: string): string {\n const moduleRelativePath = findBootstrapModulePath(host, mainPath);\n const mainDir = dirname(mainPath);\n const modulePath = normalize(`/${mainDir}/${moduleRelativePath}.ts`);\n\n return modulePath;\n}\n","/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\nimport { tags } from '@angular-devkit/core';\nimport { SchematicsException } from '@angular-devkit/schematics';\n\nexport function validateName(name: string): void {\n if (name && /^\\d/.test(name)) {\n throw new SchematicsException(tags.oneLine`name (${name})\n can not start with a digit.`);\n }\n}\n\n// Must start with a letter, and must contain only alphanumeric characters or dashes.\n// When adding a dash the segment after the dash must also start with a letter.\nexport const htmlSelectorRe = /^[a-zA-Z][.0-9a-zA-Z]*(:?-[a-zA-Z][.0-9a-zA-Z]*)*$/;\n\nexport function validateHtmlSelector(selector: string): void {\n if (selector && !htmlSelectorRe.test(selector)) {\n throw new SchematicsException(tags.oneLine`Selector (${selector})\n is invalid.`);\n }\n}\n\n\nexport function validateProjectName(projectName: string) {\n const errorIndex = getRegExpFailPosition(projectName);\n const unsupportedProjectNames = ['test', 'ember', 'ember-cli', 'vendor', 'app'];\n const packageNameRegex = /^(?:@[a-zA-Z0-9_-]+\\/)?[a-zA-Z0-9_-]+$/;\n if (errorIndex !== null) {\n const firstMessage = tags.oneLine`\n Project name \"${projectName}\" is not valid. New project names must\n start with a letter, and must contain only alphanumeric characters or dashes.\n When adding a dash the segment after the dash must also start with a letter.\n `;\n const msg = tags.stripIndent`\n ${firstMessage}\n ${projectName}\n ${Array(errorIndex + 1).join(' ') + '^'}\n `;\n throw new SchematicsException(msg);\n } else if (unsupportedProjectNames.indexOf(projectName) !== -1) {\n throw new SchematicsException(\n `Project name ${JSON.stringify(projectName)} is not a supported name.`);\n } else if (!packageNameRegex.test(projectName)) {\n throw new SchematicsException(`Project name ${JSON.stringify(projectName)} is invalid.`);\n }\n}\n\nfunction getRegExpFailPosition(str: string): number | null {\n const isScope = /^@.*\\/.*/.test(str);\n if (isScope) {\n // Remove starting @\n str = str.replace(/^@/, '');\n // Change / to - for validation\n str = str.replace(/\\//g, '-');\n }\n\n const parts = str.indexOf('-') >= 0 ? str.split('-') : [str];\n const matched: string[] = [];\n\n const projectNameRegexp = /^[a-zA-Z][.0-9a-zA-Z]*(-[.0-9a-zA-Z]*)*$/;\n\n parts.forEach(part => {\n if (part.match(projectNameRegexp)) {\n matched.push(part);\n }\n });\n\n const compare = matched.join('-');\n\n return (str !== compare) ? compare.length : null;\n}\n","/* Copyright IBM Corp. 2017 */\nimport { isString } from 'lodash';\n\n/*\n * Makes sure our path ends with a proper trailing slash\n */\nfunction _ensureTrailingSlash(aUrl: string): string {\n return aUrl.endsWith('/') ? aUrl : aUrl + '/';\n}\n\nfunction _hasTrailingSlash(aUrl: string): boolean {\n return !!(aUrl && isString(aUrl) && aUrl.endsWith('/'));\n}\n\nexport {\n _ensureTrailingSlash as ensureTrailingSlash,\n _hasTrailingSlash as hasTrailingSlash\n};\n","import { isString } from '@ibm-wch-sdk/utils';\nimport * as Assert from 'assert';\nimport { validate as validateEmail } from 'email-validator';\nimport { isWebUri } from 'valid-url';\n\nimport { hasTrailingSlash } from './url.utils';\n\nexport function assertNotNull(aValue: any, aName?: string) {\n Assert.ok(\n aValue != null,\n aName\n ? `Value [${aName}] must not be null or undefined.`\n : 'Value must not be null or undefined.'\n );\n}\n\nexport function assertParameter(aValue: any, aParameterName: string) {\n Assert.ok(!!aValue, `Please specify the '--${aParameterName}' parameter.`);\n}\n\nexport function isValidUrl(aValue: any): aValue is string {\n return isString(aValue) && !!isWebUri(aValue);\n}\n\nexport function assertIsUrl(aValue: any, aName?: string): string {\n Assert.ok(\n isValidUrl(aValue),\n aName\n ? `Value [${aName}] must be a valid URL.`\n : 'Value must be a valid URL.'\n );\n return aValue;\n}\n\nexport function isValidEmail(aValue: any): aValue is string {\n return isString(aValue) && !!validateEmail(aValue);\n}\n\nexport function isValidUserName(aValue: any): aValue is string {\n return isString(aValue) && (!!validateEmail(aValue) || aValue === 'apikey');\n}\n\nexport function assertIsEmail(aValue: any, aName?: string): string {\n Assert.ok(\n isValidEmail(aValue),\n aName\n ? `Value [${aName}] must be a valid e-mail address.`\n : 'Value must be a valid e-mail address.'\n );\n return aValue;\n}\n\nexport function assertIsValidUserName(aValue: any, aName?: string): string {\n Assert.ok(\n isValidUserName(aValue),\n aName\n ? `Value [${aName}] must be a valid e-mail address or the term 'apikey'.`\n : \"Value must be a valid e-mail address or the term 'apikey'.\"\n );\n return aValue;\n}\n\nexport function assertHasTrailingSlash(aValue: any): string {\n Assert.ok(\n isValidUrl(aValue) && hasTrailingSlash(aValue),\n 'URL [${aValue}] must end with a slash.'\n );\n return aValue;\n}\n","/* Copyright IBM Corp. 2018 */\n\n// regular expression to detect uuid.v4 strings\nconst HEX_REGEXP_STRING = '[0-9a-fA-F]';\nconst HOST_REGEXP_STRING = '[^\\\\.\\\\:]';\nconst UUID_V4_REGEXP_STRING =\n `${HEX_REGEXP_STRING}{8}-${HEX_REGEXP_STRING}{4}-4${HEX_REGEXP_STRING}{3}-[89abAB]${HEX_REGEXP_STRING}{3}-${HEX_REGEXP_STRING}{12}`;\nconst TENANT_BASED_URL = `^(?:\\\\/api)?\\\\/(${UUID_V4_REGEXP_STRING})(?:\\\\/)?(?:.*)$`;\nexport const TENANT_BASED_URL_REGEXP = new RegExp(TENANT_BASED_URL);\n","/* Copyright IBM Corp. 2017 */\nimport { Observable, defer, from } from 'rxjs';\nimport { ajax, AjaxRequest } from 'rxjs/ajax';\nimport { pluck, map, tap } from 'rxjs/operators';\n\nconst createXHR = () => {\n const XMLHttpRequest = require('xhr2');\n return new XMLHttpRequest();\n};\n\nconst ajaxRequest = (req: AjaxRequest) =>\n ajax({ ...req, responseType: 'text', createXHR }).pipe(\n map(resp => resp.response as string)\n );\n\nexport function rxGet(aUri: string): Observable<string> {\n // setup the request\n return ajaxRequest({\n url: aUri\n });\n}\n\nexport function rxGetJson(aUri: string): Observable<any> {\n return rxGet(aUri).pipe(map(data => JSON.parse(data)));\n}\n\nexport function rxFormPost(aUri: string, aData: any): Observable<string> {\n // setup the request\n return ajaxRequest({\n method: 'POST',\n url: aUri,\n body: aData\n });\n}\n","import { Observable, Observer } from 'rxjs';\nimport { readFile } from 'fs';\n\nexport function rxReadFile(aPath: string): Observable<string> {\n return Observable.create((observer: Observer<string>) => {\n readFile(aPath, 'utf-8', (err, data) => {\n if (err) {\n observer.error(err);\n } else {\n observer.next(data);\n observer.complete();\n }\n });\n });\n}\n","import { exec } from 'child_process';\nimport { RSA_PKCS1_PADDING } from 'constants';\nimport {\n privateDecrypt,\n publicEncrypt,\n RsaPrivateKey,\n RsaPublicKey\n} from 'crypto';\nimport { cloneDeep, isString } from 'lodash';\nimport { homedir, platform } from 'os';\nimport { join, normalize } from 'path';\nimport { env } from 'process';\nimport { Observable, Observer, of } from 'rxjs';\nimport { catchError, map, mergeMap } from 'rxjs/operators';\nimport { parseKey } from 'sshpk';\n\nimport { assertHasTrailingSlash, isValidUserName } from './assert';\nimport { rxReadFile } from './rx.file';\nimport { ensureTrailingSlash } from './url.utils';\n\nexport { wchGetDeliveryUrlFromApiURL } from '@ibm-wch-sdk/utils';\n\nexport interface Credentials {\n username: string;\n password: string;\n}\n\nfunction _isValidCredential(aCred?: Credentials): boolean {\n return !!(\n aCred &&\n isValidUserName(aCred.username) &&\n isString(aCred.password)\n );\n}\n\nfunction _emptyCredentials(): Credentials {\n return {\n username: '',\n password: ''\n };\n}\n\nfunction _createCredentials(aUserName: string, aPassword: string): Credentials {\n return {\n username: aUserName,\n password: aPassword\n };\n}\n\nfunction _getCredentialsFromEnvironment(): Credentials {\n // access the credentials from the environment\n const username = env['ibm_wch_sdk_cli_username'] || '';\n const password = env['ibm_wch_sdk_cli_password'] || '';\n // construct\n return { username, password };\n}\n\n/**\n * Merge different credentials layers\n *\n * @param aBase base layer\n * @param aOverride override layer\n *\n * @return the merged credentials\n */\nfunction _mergeCredentials(\n aBase: Credentials,\n aOverride?: Credentials\n): Credentials {\n // target\n if (!aOverride) {\n return aBase;\n }\n // clone\n const cred = cloneDeep(aBase);\n // override\n if (!!aOverride.username) {\n cred.username = aOverride.username;\n }\n if (!!aOverride.password) {\n cred.password = aOverride.password;\n }\n // ok\n return cred;\n}\n\nconst PADDING_MODE = RSA_PKCS1_PADDING;\n\nfunction _loadPrivateKey(): Observable<RsaPrivateKey> {\n // filename\n const name = join(homedir(), '.ssh', 'id_rsa');\n return rxReadFile(name).pipe(map(key => ({ key, padding: PADDING_MODE })));\n}\n\nfunction _loadPublicKey(): Observable<RsaPublicKey> {\n // filename\n const name = join(homedir(), '.ssh', 'id_rsa.pub');\n return rxReadFile(name).pipe(\n map(key => parseKey(key, 'auto').toString('pkcs1')),\n map(key => ({ key, padding: PADDING_MODE }))\n );\n}\n\nconst ENCRYPTED_ENCODING = 'base64';\nconst DECTYPTED_ENCODING = 'utf8';\n\nfunction _encryptPassword(aPassword: string, aKey: RsaPublicKey): string {\n // encrypt\n return publicEncrypt(\n aKey,\n Buffer.from(aPassword, DECTYPTED_ENCODING)\n ).toString(ENCRYPTED_ENCODING);\n}\n\nfunction _decryptPassword(aHash: string, aKey: RsaPrivateKey): string {\n return privateDecrypt(aKey, Buffer.from(aHash, ENCRYPTED_ENCODING)).toString(\n DECTYPTED_ENCODING\n );\n}\n\nfunction _loadCredentials(aApiBase: string): Observable<Credentials> {\n // validate the URL\n assertHasTrailingSlash(aApiBase);\n // credential file name\n const filename = join(homedir(), '.ibm-wch-sdk-cli', '.credentials');\n // read the credential\n const key = _loadPrivateKey();\n // load the file\n return rxReadFile(filename).pipe(\n map(data => JSON.parse(data)),\n map(data => data[aApiBase]),\n mergeMap(cred =>\n key.pipe(\n map(k => _decryptPassword(cred.password, k)),\n map(p => {\n cred.password = p;\n return cred;\n })\n )\n ),\n catchError(() => of(_emptyCredentials()))\n );\n}\n\nfunction _getWindowsCredentials(aApiUrl: string): Observable<Credentials> {\n // validate the URL\n assertHasTrailingSlash(aApiUrl);\n // the executable\n const path = normalize(\n join(\n __dirname,\n '..',\n '..',\n '..',\n 'assets',\n 'credman',\n process.arch,\n 'WchCredMan.exe'\n )\n );\n // execute\n const cmd = `\\\"${path}\\\" \\\"${aApiUrl}\\\"`;\n // construct the observable\n return Observable.create((observer: Observer<Credentials>) => {\n // execute the command\n exec(\n cmd,\n {\n encoding: 'utf8'\n },\n (error, stdout, stderr) => {\n if (error) {\n observer.error(error);\n } else {\n try {\n // parse\n observer.next(JSON.parse(stdout));\n observer.complete();\n } catch (e) {\n observer.error(e);\n }\n }\n }\n );\n });\n}\n\nfunction _getStoredCredentials(aApiUrl: string): Observable<Credentials> {\n // the key\n const key = ensureTrailingSlash(aApiUrl);\n // normalize the URL\n if (platform() === 'win32') {\n // load the credentials module\n return _getWindowsCredentials(key).pipe(\n mergeMap(\n (cred: Credentials) =>\n _isValidCredential(cred) ? of(cred) : _loadCredentials(key)\n ),\n catchError(() => _loadCredentials(key))\n );\n }\n // linux like fallback\n return _loadCredentials(key);\n}\n\nexport function wchToolsGetCredentials(\n aApiUrl: string\n): Observable<Credentials> {\n // return\n return _getStoredCredentials(aApiUrl).pipe(\n map(cred => _mergeCredentials(_getCredentialsFromEnvironment(), cred)),\n catchError(err => of(_getCredentialsFromEnvironment()))\n );\n}\n","import { assertObject, isNil } from '@ibm-wch-sdk/utils';\nimport { readFile } from 'fs';\nimport { join, parse } from 'path';\nimport { bindNodeCallback, Observable } from 'rxjs';\nimport { catchError, map } from 'rxjs/operators';\nimport { satisfies } from 'semver';\n\nexport enum DEP_TYPE {\n PEER,\n RUNTIME,\n DEVELOPMENT\n}\n\nexport function getFolderForType(aType?: DEP_TYPE): string {\n return aType === DEP_TYPE.PEER\n ? 'peerDependencies'\n : aType === DEP_TYPE.DEVELOPMENT\n ? 'devDependencies'\n : 'dependencies';\n}\n\n/**\n * Updates the package JSON to use at least the given version\n *\n * @param aName name\n * @param aMinVersion min version\n * @param aPkg package\n */\nexport function updateMinVersion(\n aName: string,\n aMinVersion: string,\n aPkg: any,\n aType?: DEP_TYPE\n): any {\n // check if we have a version identifier\n const folder = getFolderForType(aType);\n // access\n const deps = assertObject(folder, aPkg) as any;\n const oldDep = deps[aName];\n if (isNil(oldDep) || !satisfies(aMinVersion, oldDep)) {\n // just update\n deps[aName] = `^${aMinVersion}`;\n }\n // ok\n return aPkg;\n}\n\nconst rxReadFile = bindNodeCallback<string, string, string>(readFile);\n\nexport function findPackageJson(aDir: string): Observable<any> {\n // read\n return rxReadFile(join(aDir, 'package.json'), 'utf-8').pipe(\n map(data => JSON.parse(data)),\n catchError(err => findPackageJson(parse(aDir).dir))\n );\n}\n","import { Path, resolve } from '@angular-devkit/core';\nimport { Tree } from '@angular-devkit/schematics';\nimport { coerce } from 'semver';\nimport {\n KEY_BASICAUTH_LOGIN_PASSWORD,\n KEY_BASICAUTH_LOGIN_USERNAME,\n REL_PATH_BASICAUTH_LOGIN,\n REL_PATH_CURRENT_USER\n} from '@ibm-wch-sdk/api';\nimport { isNil, isNotNil, assertArray } from '@ibm-wch-sdk/utils';\nimport { Observable, of, throwError } from 'rxjs';\nimport {\n catchError,\n map,\n mapTo,\n pluck,\n switchMap,\n switchMapTo\n} from 'rxjs/operators';\nimport { isUri } from 'valid-url';\nimport { VError } from 'verror';\n\nimport { findPackageJson } from './../package';\nimport { isValidUserName } from './assert';\nimport { rxFormPost, rxGetJson } from './rx.request';\nimport { ensureTrailingSlash } from './url.utils';\nimport { Credentials, wchToolsGetCredentials } from './wchtools';\n\nfunction _isApiKey(aName: string): boolean {\n return aName === 'apikey';\n}\n\nfunction _isValidPassword(aPassword: string): boolean {\n return aPassword && aPassword.length > 0;\n}\n\nfunction _throwInvalidUrl(aApiUrl: string, aError: Error): Observable<never> {\n return throwError(\n new VError(aError, 'The API URL [%s] is not a valid WCH API URL.', aApiUrl)\n );\n}\n\nfunction _getCurrentUser(aApiUrl: string): Observable<any> {\n // the URL\n const currentUserUrl = `${aApiUrl}${REL_PATH_CURRENT_USER}`;\n return rxGetJson(currentUserUrl).pipe(\n catchError(error => _throwInvalidUrl(aApiUrl, error))\n );\n}\n\nfunction _throwInvalidCredentials(aApiUrl: string): Observable<never> {\n return throwError(\n new VError(\n 'Unable to access credentials for the API URL [%s]. Please follow the directions on https://www.npmjs.com/package/ibm-wch-sdk-cli#credential-management to register credentials.',\n aApiUrl\n )\n );\n}\n\nexport function validateCredentials(\n aApiUrl: string,\n aCredentials: Credentials\n): Observable<string> {\n // check the credentials object\n if (\n !aCredentials ||\n !isValidUserName(aCredentials.username) ||\n !_isValidPassword(aCredentials.password)\n ) {\n return _throwInvalidCredentials(aApiUrl);\n }\n // test if we can login\n const loginUrl = `${aApiUrl}${REL_PATH_BASICAUTH_LOGIN}`;\n const body = {\n [KEY_BASICAUTH_LOGIN_USERNAME]: aCredentials.username,\n [KEY_BASICAUTH_LOGIN_PASSWORD]: aCredentials.password\n };\n // execute\n return rxFormPost(loginUrl, body).pipe(\n map(data => JSON.parse(data)),\n catchError(error =>\n throwError(\n new VError(\n error,\n 'Unable to login to [%s] with user [%s]. Please check your registered password.',\n loginUrl,\n aCredentials.username\n )\n )\n ),\n mapTo(aApiUrl)\n );\n}\n\nfunction _validateUser(aFeed: any): Observable<any> {\n // test the feed result\n if (!aFeed || !aFeed.externalId) {\n return throwError(new VError('Invalid currentuser response'));\n }\n return of(aFeed);\n}\n\n/**\n * Tests if the API URL is valid and if we have sufficient credentials to access the API\n *\n * @param aUrl the API URL\n * @return the url\n */\nexport function validateApiUrl(\n aUrl: string,\n bValidateWithCredentials: boolean\n): Observable<string> {\n // check if the URL is valud\n if (!isUri(aUrl)) {\n return throwError(\n new VError(\n 'Please enter a valid API URL. Copy this URL from the \"Hub Information\" section of your WCH tenant.'\n )\n );\n }\n // check if the URL is valid\n const normUrl = ensureTrailingSlash(aUrl);\n\n if (bValidateWithCredentials) {\n // load the credentials\n const onCredentials = wchToolsGetCredentials(normUrl).pipe(\n catchError(error => _throwInvalidCredentials(normUrl))\n );\n\n // check if the URL exists\n const onValidUrl: Observable<string> = _getCurrentUser(normUrl).pipe(\n switchMap(_validateUser),\n switchMapTo(onCredentials),\n switchMap(cred => validateCredentials(normUrl, cred))\n );\n // ok\n return onValidUrl;\n } else {\n // check if the URL exists\n const onValidUrl: Observable<string> = _getCurrentUser(normUrl).pipe(\n switchMap(_validateUser),\n mapTo(normUrl)\n );\n // ok\n return onValidUrl;\n }\n}\n\nconst PACKAGE_JSON = '/package.json' as Path;\nconst FALLBACK = '/data' as Path;\n\nconst OPTIONS = '.wchtoolsoptions.json' as Path;\n\nconst SDK_IMPORT = '@ibm-wch-sdk/ng';\nconst CLI_IMPORT = '@ibm-wch-sdk/cli';\n\nexport const WCHTOOLS_DEPENDENCIES = 'wchtools-dependencies';\n\nfunction _findBuildVersion(): Observable<string> {\n // find the package\n return findPackageJson(__dirname).pipe(pluck<any, string>('version'));\n}\n\n/**\n * Decode the version from the dependency\n *\n * @param aVersion the version\n *\n * @return observable of the version\n */\nfunction _fromDependency(aVersion: string): Observable<string> {\n const parsed = coerce(aVersion);\n return !!parsed ? of(parsed.version) : _findBuildVersion();\n}\n\nexport function findSdkVersion(host: Tree): Observable<string> {\n // try to locate the package json\n const buf = host.read(PACKAGE_JSON);\n if (isNil(buf)) {\n return _findBuildVersion();\n }\n // source package\n const pkg = JSON.parse(buf.toString());\n // check if we have imports\n const deps = pkg.dependencies || {};\n const devDeps = pkg.devDependencies || {};\n\n const fromPkg = deps[SDK_IMPORT] || devDeps[CLI_IMPORT];\n\n return isNotNil(fromPkg) ? _fromDependency(fromPkg) : _findBuildVersion();\n}\n\nexport function findDataDir(host: Tree): Path {\n const buf = host.read(PACKAGE_JSON);\n if (isNil(buf)) {\n return FALLBACK;\n }\n\n const pkg = JSON.parse(buf.toString());\n const cfg = pkg.config || {};\n\n const data = cfg.data || FALLBACK;\n\n return resolve('/' as Path, data);\n}\n\nexport function findWchToolsOptions(host: Tree): Path {\n return resolve(findDataDir(host), OPTIONS);\n}\n\nexport function addToWchToolsDependencies(aDeps: string[], aPkg: any) {\n // add the key\n const deps = assertArray<string>(WCHTOOLS_DEPENDENCIES, aPkg);\n // filter\n deps.push(...aDeps.filter(dep => deps.indexOf(dep) < 0));\n}\n","import { Generator, isArray, isNil, isPlainObject } from '@ibm-wch-sdk/utils';\n\nconst _keys = Object.keys;\n\nconst KEY_WEIGHTS: { [key: string]: number } = {\n name: 1,\n description: 2,\n id: 3,\n classification: 4\n};\n\nfunction _compareNumber(aLeft: number, aRight: number): number {\n return aLeft < aRight ? -1 : aLeft > aRight ? +1 : 0;\n}\n\nfunction _getKey(aName: string): number {\n return KEY_WEIGHTS[aName] || Number.MAX_SAFE_INTEGER;\n}\n\nfunction _compareName(aLeft: string, aRight: string): number {\n // first by key\n let c = _compareNumber(_getKey(aLeft), _getKey(aRight));\n if (c === 0) {\n c = aLeft.localeCompare(aRight);\n }\n // ok\n return c;\n}\n\nfunction _canonicalize(aData: any): any {\n // handle\n if (isArray(aData)) {\n const copy: any[] = [];\n aData.forEach(v => copy.push(_canonicalize(v)));\n return copy;\n }\n if (isPlainObject(aData)) {\n // sort the keys\n const copy: any = {};\n _keys(aData)\n .sort(_compareName)\n .forEach(k => (copy[k] = _canonicalize(aData[k])));\n return copy;\n }\n // nothing to do\n return aData;\n}\n\nexport function serializeJson(aData: any): string | undefined {\n return aData ? JSON.stringify(aData, undefined, 2) : undefined;\n}\n\nexport function updateField(\n aName: string,\n aGenerator: Generator<string>,\n aObj: any\n): any {\n const oldValue = aObj[aName];\n if (isNil(oldValue)) {\n // update with the generated value\n aObj[aName] = aGenerator();\n }\n return aObj;\n}\n\nexport { _canonicalize as canonicalizeJSON };\n","export function serializeLines(aSource?: string[]): string | undefined {\n return aSource ? aSource.join('\\n') : undefined;\n}\n\nexport function parseLines(aSource?: string): string[] {\n return aSource ? aSource.split('\\n') : [];\n}\n\nexport function insertLines(\n aSource: string[] | undefined,\n aInsert: string[]\n): string[] {\n if (aSource) {\n // build the set\n const existing = new Set<string>(aSource);\n\n return [...aSource, ...aInsert.filter(line => !existing.has(line))];\n } else {\n // just insert into the empty file\n return [...aInsert];\n }\n}\n","import { Tree } from '@angular-devkit/schematics';\nimport { isNotNil } from '@ibm-wch-sdk/utils';\nimport { Observable, UnaryFunction } from 'rxjs';\nimport { first, map, mapTo } from 'rxjs/operators';\n\nimport { canonicalizeJSON, serializeJson } from './json';\nimport { parseLines, serializeLines } from './../text/lines';\n\nexport interface TransformWithPath<T> {\n (aSource: T | undefined, aPath: string): Observable<T | undefined>;\n}\n\nexport interface TransformWithoutPath<T> {\n (aSource: T | undefined): Observable<T | undefined>;\n}\n\nexport type TransformCallback<T> =\n | TransformWithPath<T>\n | TransformWithoutPath<T>;\n\n/**\n * Reads a text file from the tree and then transforms it using the given function. If the result\n * is null or undefined, the file will be deleted, else replaced or created.\n *\n * @param aName name of the file\n * @param aOp the operator\n * @param aTree the tree to work in\n */\nexport function rxTransformTextFile(\n aName: string,\n aOp: TransformCallback<string>,\n aTree: Tree\n): Observable<string> {\n // load the file if it exists\n const buffer = aTree.read(aName);\n const value = isNotNil(buffer) ? buffer.toString() : null;\n const op: TransformWithPath<string> = aOp as any;\n // replace\n return op(value, aName).pipe(\n first(),\n map(\n result =>\n isNotNil(result)\n ? isNotNil(buffer)\n ? aTree.overwrite(aName, result)\n : aTree.create(aName, result)\n : isNotNil(buffer)\n ? aTree.delete(aName)\n : undefined\n ),\n mapTo(aName)\n );\n}\n\n/**\n * Reads a JSON file from the tree and then transforms it using the given function. If the result\n * is null or undefined, the file will be deleted, else replaced or created.\n *\n * @param aName name of the file\n * @param aOp the operator\n * @param aTree the tree to work in\n */\nexport function rxTransformJsonFile(\n aName: string,\n aOp: TransformCallback<any>,\n aTree: Tree\n): Observable<string> {\n // cast\n const op: TransformWithPath<any> = aOp as any;\n // dispatch\n return rxTransformTextFile(\n aName,\n (textContent, path) =>\n op(textContent ? JSON.parse(textContent) : undefined, path).pipe(\n map(canonicalizeJSON),\n map(serializeJson)\n ),\n aTree\n );\n}\n\n/**\n * Reads a line based file from the tree and then transforms it using the given function. If the result\n * is null or undefined, the file will be deleted, else replaced or created.\n *\n * @param aName name of the file\n * @param aOp the operator\n * @param aTree the tree to work in\n */\nexport function rxTransformLinesFile(\n aName: string,\n aOp: TransformCallback<string[]>,\n aTree: Tree\n): Observable<string> {\n // cast\n const op: TransformWithPath<string[]> = aOp as any;\n // dispatch\n return rxTransformTextFile(\n aName,\n (textContent, path) =>\n op(textContent ? parseLines(textContent) : undefined, path).pipe(\n map(serializeLines)\n ),\n aTree\n );\n}\n","/* Copyright IBM Corp. 2018 */\nimport { Tree } from '@angular-devkit/schematics';\nimport { join, normalize } from 'path';\nimport { get } from 'request';\nimport { defer, fromEvent, Observable, of } from 'rxjs';\nimport {\n filter,\n first,\n map,\n mapTo,\n mergeMap,\n takeUntil,\n tap\n} from 'rxjs/operators';\nimport { Writable } from 'stream';\nimport { Entry, Parse } from 'unzip';\n\nfunction _skipPrefix(aName: string, aCount: number): string | null {\n // current name\n let idx = 0;\n for (let i = 0; i < aCount; ++i) {\n // find the next separator\n const nextIdx = aName.indexOf('/', idx);\n if (nextIdx >= idx) {\n idx = nextIdx + 1;\n } else {\n return null;\n }\n }\n // split\n return aName.substring(idx);\n}\n\nclass StreamOnBuffer extends Writable {\n buffers: Buffer[] = [];\n\n _write(chunk: any, encoding: string, callback: (err?: Error) => void) {\n this.buffers.push(chunk);\n callback();\n }\n\n _final(callback: Function) {\n callback();\n this.emit('close');\n }\n}\n\nfunction _rxExtractEntry(\n aTree: Tree,\n aEntry: Entry,\n aDstDir: string,\n aSkip: number\n): Observable<string> {\n // skip the prefix\n const path = _skipPrefix(aEntry.path, aSkip);\n if (!path) {\n // nothing\n return of('').pipe(\n tap(() => aEntry.autodrain()),\n filter(() => false)\n );\n }\n // create filename\n const fileName = normalize(join(aDstDir, path));\n // handle directories\n if (aEntry.type === 'Directory') {\n // create the directory\n return of('').pipe(\n tap(() => aEntry.autodrain()),\n filter(() => false)\n );\n } else {\n // construct the stream\n const stream = aEntry.pipe(new StreamOnBuffer());\n // attach\n return fromEvent(stream, 'close').pipe(\n // just take one\n first(),\n // copy into the tree\n map(() => aTree.create(fileName, Buffer.concat(stream.buffers))),\n // map to the target name\n mapTo(fileName)\n );\n }\n}\n\nexport function rxUnzipFromUrl(\n aTree: Tree,\n aSrcUrl: string,\n aDstDir: string,\n aSkip: number = 0\n): Observable<string> {\n // defer\n return defer(() => {\n // construct the stream\n const stream = get(aSrcUrl).pipe(Parse());\n // handle\n const onEntry = fromEvent<Entry>(stream, 'entry');\n const onClose = fromEvent(stream, 'close');\n // return the full stream\n return onEntry.pipe(\n takeUntil(onClose),\n mergeMap(entry => _rxExtractEntry(aTree, entry, aDstDir, aSkip))\n );\n });\n}\n","import { Tree } from '@angular-devkit/schematics/src/tree/interface';\nimport { isNotNil } from '@ibm-wch-sdk/utils';\nimport { load } from 'cheerio';\nimport { Observable, of } from 'rxjs';\nimport { switchMap } from 'rxjs/operators';\n\nimport { rxTransformTextFile, TransformCallback, TransformWithPath } from './rx.tree';\n\nfunction _parseHtml(aString?: string): Observable<CheerioStatic> {\n return of(load(isNotNil(aString) ? aString! : ''));\n}\n\nfunction _serializeHtml(aHtml: CheerioStatic): Observable<string> {\n return of(aHtml!.html());\n}\n\n/**\n * Reads an HMTL from the tree and then transforms it using the given function. If the result\n * is null or undefined, the file will be deleted, else replaced or created.\n *\n * @param aName name of the file\n * @param aOp the operator\n * @param aTree the tree to work in\n */\nexport function rxTransformHtmlFile(\n aName: string,\n aOp: TransformCallback<CheerioStatic>,\n aTree: Tree\n): Observable<string> {\n // cast\n const op: TransformWithPath<CheerioStatic> = aOp as any;\n // dispatch\n return rxTransformTextFile(\n aName,\n (textContent, path) =>\n _parseHtml(textContent).pipe(\n switchMap(html => op(html, path)),\n switchMap(_serializeHtml)\n ),\n aTree\n );\n}\n","import { SchematicsException, Tree } from '@angular-devkit/schematics';\nimport { createSourceFile, ScriptTarget, SourceFile } from 'typescript';\n\nexport function getSourceFile(host: Tree, path: string): SourceFile {\n const buffer = host.read(path);\n if (!buffer) {\n throw new SchematicsException(`Could not find ${path}.`);\n }\n const content = buffer.toString();\n const source = createSourceFile(path, content, ScriptTarget.Latest, true);\n\n return source;\n}\n","import { Tree, UpdateRecorder } from '@angular-devkit/schematics';\nimport { SourceFile } from 'typescript';\n\nimport {\n addImportToModule,\n Change,\n InsertChange,\n RemoveChange,\n ReplaceChange\n} from './../utility';\nimport { getSourceFile } from './source';\n\nexport function insertChanges(aChanges: Change[], aRecorder: UpdateRecorder) {\n aChanges.forEach((change: Change) => {\n // delete\n if (change instanceof InsertChange) {\n aRecorder.insertLeft(change.pos, change.toAdd);\n } else if (change instanceof RemoveChange) {\n } else if (change instanceof ReplaceChange) {\n // remove old chunk\n const anyChange = change as any;\n aRecorder.remove(anyChange.pos, anyChange.oldText.length);\n aRecorder.insertLeft(anyChange.pos, anyChange.newText);\n }\n });\n}\n\nexport function changeSourceFile(\n aFile: string,\n aOp: (aFile: string, aContent: SourceFile) => Change[],\n aHost: Tree\n) {\n // make sure at least an empty file exists\n if (!aHost.exists(aFile)) {\n aHost.create(aFile, '');\n }\n\n // update\n const recorder = aHost.beginUpdate(aFile);\n insertChanges(aOp(aFile, getSourceFile(aHost, aFile)), recorder);\n\n aHost.commitUpdate(recorder);\n}\n\n/**\n * Changes the identified module by adding a couple of imports\n *\n * @param aFile the filename\n * @param aModules the modules to be added\n * @param aHost the tree\n */\nexport function addImportsToModule(\n aFile: string,\n aModules: { [identifier: string]: string },\n aHost: Tree\n) {\n // iterate\n Object.keys(aModules).forEach(name =>\n changeSourceFile(\n aFile,\n (file, content) => addImportToModule(content, file, name, aModules[name]),\n aHost\n )\n );\n}\n","import { Predicate } from '@ibm-wch-sdk/utils';\nimport { NamedDeclaration, Node, SyntaxKind } from 'typescript';\n\nexport function byType(aType: SyntaxKind): Predicate<Node> {\n return node => node && node.kind === aType;\n}\n\nexport function byText(aText: string): Predicate<Node> {\n return node => node && node.getText() === aText;\n}\n\nexport function byName(aText: string): Predicate<NamedDeclaration> {\n return node => !!(node && node.name && node.name.getText() === aText);\n}\n\nexport function byTypeAndName(\n aType: SyntaxKind,\n aName: string\n): Predicate<Node> {\n return node => node && node.kind === aType && node.getText() === aName;\n}\n\nexport function byIdentifier(aName: string): Predicate<Node> {\n return byTypeAndName(SyntaxKind.Identifier, aName);\n}\n","\n/**\n * @license\n * Copyright Google Inc. All Rights Reserved.\n *\n * Use of this source code is governed by an MIT-style license that can be\n * found in the LICENSE file at https://angular.io/license\n */\n// import { relative, Path } from \"../../../angular_devkit/core/src/virtual-fs\";\nimport { Path, basename, dirname, normalize } from '@angular-devkit/core';\n\nexport interface Location {\n name: string;\n path: Path;\n}\n\nexport function parseName(path: string, name: string): Location {\n const nameWithoutPath = basename(name as Path);\n const namePath = dirname((path + '/' + name) as Path);\n\n return {\n name: nameWithoutPath,\n path: normalize('/' + namePath),\n };\n}\n"]}
\No newline at end of file