UNPKG

@ohos/hpm-cli

Version:

CLI for HarmonyOS package manager

931 lines (928 loc) 55.7 kB
"use strict"; function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } Object.defineProperty(exports, "__esModule", { value: true }); exports.Bundle = void 0; exports.checkRiskManifests = checkRiskManifests; exports.execInstallHook = execInstallHook; exports.getNameToBundle = getNameToBundle; exports.installBinary = installBinary; exports.logOutInstallDetail = logOutInstallDetail; var _fs = _interopRequireDefault(require("fs")); var _glob = _interopRequireDefault(require("glob")); var _path2 = _interopRequireDefault(require("path")); var _manifest2 = require("./manifest"); var _dependency2 = require("./dependency"); var _variable = require("./variable"); var _dependencyGraph = require("./dependency-graph"); var _repository = require("./repository"); var _bundleLock2 = require("./bundle-lock"); var _helpers = require("../utils/helpers"); var _common = require("../utils/common"); var _constant = require("../constant/constant"); var _tar = _interopRequireDefault(require("tar")); var _i18n = _interopRequireWildcard(require("../i18n")); var _log = _interopRequireDefault(require("./log")); var _axios = _interopRequireDefault(require("../utils/axios")); var _config2 = require("../utils/config"); var _install2 = require("../commands/install"); var _bundleCache2 = require("./bundle-cache"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; } function asyncGeneratorStep(n, t, e, r, o, a, c) { try { var i = n[a](c), u = i.value; } catch (n) { return void e(n); } i.done ? t(u) : Promise.resolve(u).then(r, o); } function _asyncToGenerator(n) { return function () { var t = this, e = arguments; return new Promise(function (r, o) { var a = n.apply(t, e); function _next(n) { asyncGeneratorStep(a, r, o, _next, _throw, "next", n); } function _throw(n) { asyncGeneratorStep(a, r, o, _next, _throw, "throw", n); } _next(void 0); }); }; } function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; } function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } } function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; } function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); } function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } } function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } function _classPrivateFieldInitSpec(e, t, a) { _checkPrivateRedeclaration(e, t), t.set(e, a); } function _checkPrivateRedeclaration(e, t) { if (t.has(e)) throw new TypeError("Cannot initialize the same private elements twice on an object"); } function _classPrivateFieldGet(s, a) { return s.get(_assertClassBrand(s, a)); } function _classPrivateFieldSet(s, a, r) { return s.set(_assertClassBrand(s, a), r), r; } function _assertClassBrand(e, t, n) { if ("function" == typeof e ? e === t : e.has(t)) return arguments.length < 3 ? t : n; throw new TypeError("Private element is not present on this object"); } /* * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var _path = /*#__PURE__*/new WeakMap(); var _manifest = /*#__PURE__*/new WeakMap(); var _manifests = /*#__PURE__*/new WeakMap(); var _vars = /*#__PURE__*/new WeakMap(); var _bundleLock = /*#__PURE__*/new WeakMap(); var _bundleCache = /*#__PURE__*/new WeakMap(); var _bundleDescriptor = /*#__PURE__*/new WeakMap(); var Bundle = exports.Bundle = /*#__PURE__*/function () { function Bundle(bundlePath, manifest) { var bundleDescriptor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; _classCallCheck(this, Bundle); _classPrivateFieldInitSpec(this, _path, void 0); _classPrivateFieldInitSpec(this, _manifest, void 0); _classPrivateFieldInitSpec(this, _manifests, void 0); _classPrivateFieldInitSpec(this, _vars, void 0); _classPrivateFieldInitSpec(this, _bundleLock, void 0); _classPrivateFieldInitSpec(this, _bundleCache, void 0); _classPrivateFieldInitSpec(this, _bundleDescriptor, void 0); _classPrivateFieldSet(_path, this, bundlePath); _classPrivateFieldSet(_manifest, this, manifest); _classPrivateFieldSet(_bundleDescriptor, this, bundleDescriptor); var _tags = {}; var _config = {}; var _iterator = _createForOfIteratorHelper(this.dependencies), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var dependency = _step.value; if (dependency.tag) { _tags[dependency.tag] = (_tags[dependency.tag] ? _tags[dependency.tag] : []).concat([dependency.name]); } if (dependency.params) _config[dependency.name] = dependency.params; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } this.dependencies.tags = _tags; this.dependencies.config = _config; // 新增对pub_deps的处理 var _iterator2 = _createForOfIteratorHelper(this.pub_deps), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var _dependency = _step2.value; if (_dependency.tag) { _tags[_dependency.tag] = (_tags[_dependency.tag] ? _tags[_dependency.tag] : []).concat([_dependency.name]); } if (_dependency.params) _config[_dependency.name] = _dependency.params; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } this.pub_deps.tags = _tags; this.pub_deps.config = _config; _classPrivateFieldGet(_manifest, this).path = bundlePath; _classPrivateFieldSet(_vars, this, new _variable.Variable()); if (_fs["default"].existsSync(_path2["default"].join(_classPrivateFieldGet(_path, this), 'bundle-lock.json'))) { _classPrivateFieldSet(_bundleLock, this, _bundleLock2.BundleLock.fromUrl(_classPrivateFieldGet(_path, this))); } if (_bundleCache2.BundleCache.isExisted(bundlePath)) { _classPrivateFieldSet(_bundleCache, this, _bundleCache2.BundleCache.fromPath(bundlePath)); } } return _createClass(Bundle, [{ key: "vars", get: function get() { return _classPrivateFieldGet(_vars, this); } }, { key: "manifest", get: function get() { return _classPrivateFieldGet(_manifest, this); } }, { key: "name", get: function get() { return _classPrivateFieldGet(_manifest, this).name; } }, { key: "id", get: function get() { return this.manifest.id; } }, { key: "scripts", value: function scripts(name) { return _classPrivateFieldGet(_manifest, this).scripts(name); } }, { key: "dependencies", get: function get() { return _classPrivateFieldGet(_manifest, this).dependencies; } }, { key: "pub_deps", get: function get() { return _classPrivateFieldGet(_manifest, this).pub_deps; } }, { key: "path", get: function get() { return _classPrivateFieldGet(_path, this); } }, { key: "binary", get: function get() { return _classPrivateFieldGet(_path, this); } }, { key: "lock", get: function get() { return _classPrivateFieldGet(_bundleLock, this); } }, { key: "bundleDescriptor", get: function get() { return _classPrivateFieldGet(_bundleDescriptor, this); } }, { key: "copy", value: function copy() { var dirs = _classPrivateFieldGet(_manifest, this).dirs(); var result = {}; if (dirs) { Object.keys(dirs).forEach(function (key) { var pattern = dirs[key]; if (typeof pattern === 'string' && pattern.startsWith('@')) { result[key] = pattern.substr(1); } }); } return result; } }, { key: "link", value: function link() { var dirs = _classPrivateFieldGet(_manifest, this).dirs(); var result = []; if (dirs) { Object.keys(dirs).forEach(function (key) { var pattern = dirs[key]; if (typeof pattern === 'string' && pattern.startsWith('&')) { result.push({ source: pattern.substring(1), target: key }); } }); } return result; } }, { key: "files", value: function files(dir) { var _this = this; var patterns = _classPrivateFieldGet(_manifest, this).dirs(dir); if (patterns) { return (Array.isArray(patterns) ? patterns : [patterns]).flatMap(function (pattern) { return _glob["default"].sync(_path2["default"].normalize("".concat(_classPrivateFieldGet(_path, _this), "/").concat(pattern))); }); } return []; } }, { key: "copyReadme", value: function copyReadme() { var _this2 = this; var langToReadme = { en: 'README.md', cn: 'README_CN.md' }; if (_classPrivateFieldGet(_manifest, this).readmePath) { var _loop = function _loop() { var sourcePath = _path2["default"].join(_classPrivateFieldGet(_path, _this2), _classPrivateFieldGet(_manifest, _this2).readmePath[lang]); var destPath = _path2["default"].join(_classPrivateFieldGet(_path, _this2), langToReadme[lang] || 'README.md'); if (!_fs["default"].existsSync(destPath) && _fs["default"].existsSync(sourcePath)) { (0, _helpers.runShellCmd)(function (shell) { return shell.cp('-R', sourcePath, destPath); }); } }; for (var lang in _classPrivateFieldGet(_manifest, this).readmePath) { _loop(); } } } }, { key: "pack", value: function pack() { var _this3 = this; if (!_classPrivateFieldGet(_manifest, this).publishAs) { throw (0, _i18n.getI18nMessage)('bundle.missingPublishAs'); } if (!_classPrivateFieldGet(_manifest, this).license.trim()) { throw (0, _i18n.getI18nMessage)('bundle.missingLicense'); } var licensePath = _classPrivateFieldGet(_manifest, this).licensePath; var packConfig = getDefaultPackConfig(_classPrivateFieldGet(_path, this), licensePath); if (['source', 'distribution', 'binary', 'plugin', 'model', 'chip-definition'].some(this.isPublishAs.bind(this))) { var dirs = _classPrivateFieldGet(_manifest, this).dirs(); if (dirs) { Object.keys(dirs).forEach(function (key) { if (typeof dirs[key] === 'string' && (dirs[key].startsWith('@') || dirs[key].startsWith('&'))) { return; } packConfig[key] = (packConfig[key] || []).concat(_this3.files(key)); }); } return packConfig; } return null; // code-segment } }, { key: "build", value: function () { var _build = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(repo, startBundle, buildCustomizeArgs) { var osInfo, manifests, bundles, dirTemp, snapshotPath, snapshots, snapshotFile, _iterator3, _step3, manifest, bundle; return _regeneratorRuntime().wrap(function _callee$(_context) { while (1) switch (_context.prev = _context.next) { case 0: osInfo = null; if (startBundle.manifest.publishAs === 'binary') { osInfo = { branch: startBundle.manifest.branch, OS: startBundle.manifest.os, buildArch: startBundle.manifest.buildArch, variant: startBundle.manifest.variant, isBinary: true }; _i18n["default"].log('build.building', { name: "Resolve dependencies." }); } _context.next = 4; return this.install(repo, false, osInfo); case 4: manifests = _context.sent; _i18n["default"].log('build.building', { name: "Resolve finished." }); manifests = this.resolveSnapshotManifest(manifests, repo, false, false); bundles = []; dirTemp = buildCustomizeArgs ? _path2["default"].resolve(_path2["default"].join(_constant.DEFAULT_PROJECT_PACKS_DIR, _constant.DEP_FOLDER_NAME, _constant.DOWNLOAD_TEMP_FOLDER)) : _path2["default"].resolve(_path2["default"].join(process.cwd(), _constant.DEP_FOLDER_NAME, _constant.DOWNLOAD_TEMP_FOLDER)); (0, _repository.createDirIfNotExists)(dirTemp); _i18n["default"].log('build.building', { name: "Download dependencies based on ".concat(osInfo.branch, "-").concat(osInfo.OS, "-").concat(osInfo.buildArch, "-").concat(osInfo.variant, ".") }); snapshotPath = ''; snapshots = []; if (!_fs["default"].existsSync(_constant.DEFAULT_PROJECT_DIR)) { (0, _helpers.runShellCmd)(function (shell) { return shell.mkdir('-p', _constant.DEFAULT_PROJECT_DIR); }); } snapshotPath = _path2["default"].join(_constant.DEFAULT_PROJECT_DIR, 'buildcache.json'); if (!_fs["default"].existsSync(snapshotPath)) { _fs["default"].writeFileSync(snapshotPath, JSON.stringify({ snapshots: snapshots })); } else { snapshotFile = JSON.parse(_fs["default"].readFileSync(snapshotPath, 'utf-8')); snapshots = snapshotFile.snapshots; } _iterator3 = _createForOfIteratorHelper(manifests); _context.prev = 17; _iterator3.s(); case 19: if ((_step3 = _iterator3.n()).done) { _context.next = 27; break; } manifest = _step3.value; _context.next = 23; return Bundle.mapManifestToBundle(manifest, dirTemp, startBundle, snapshots); case 23: bundle = _context.sent; bundles.push(bundle); case 25: _context.next = 19; break; case 27: _context.next = 32; break; case 29: _context.prev = 29; _context.t0 = _context["catch"](17); _iterator3.e(_context.t0); case 32: _context.prev = 32; _iterator3.f(); return _context.finish(32); case 35: _fs["default"].writeFileSync(snapshotPath, JSON.stringify({ snapshots: snapshots }, null, 2)); this.updateCacheJson(manifests); return _context.abrupt("return", _variable.Variable.compute(bundles)); case 38: case "end": return _context.stop(); } }, _callee, this, [[17, 29, 32, 35]]); })); function build(_x, _x2, _x3) { return _build.apply(this, arguments); } return build; }() }, { key: "isPublishAs", value: function isPublishAs(publishAs) { return this.manifest.publishAs === publishAs; } }, { key: "install", value: function () { var _install = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(repo, isGlobal, osInfo) { var _yield$this$traverse, manifests, isFromBundleLock; return _regeneratorRuntime().wrap(function _callee2$(_context2) { while (1) switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.traverse(repo, osInfo); case 2: _yield$this$traverse = _context2.sent; manifests = _yield$this$traverse.manifests; isFromBundleLock = _yield$this$traverse.isFromBundleLock; if (!(!isFromBundleLock && !isGlobal)) { _context2.next = 8; break; } _context2.next = 8; return this.updateLockJsonForInstall(manifests); case 8: if ((0, _config2.ignoreLicenseCheck)()) { _context2.next = 11; break; } _context2.next = 11; return checkRiskManifests(manifests); case 11: _classPrivateFieldSet(_manifests, this, manifests); return _context2.abrupt("return", manifests); case 13: case "end": return _context2.stop(); } }, _callee2, this); })); function install(_x4, _x5, _x6) { return _install.apply(this, arguments); } return install; }() }, { key: "traverse", value: function () { var _traverse = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(repo, osInfo) { var manifests, isFromBundleLock, manifestGraph, _manifestGraph; return _regeneratorRuntime().wrap(function _callee3$(_context3) { while (1) switch (_context3.prev = _context3.next) { case 0: manifests = []; isFromBundleLock = false; if (!(_classPrivateFieldGet(_bundleLock, this) && _classPrivateFieldGet(_bundleLock, this).isCompatible(this.dependencies.concat(this.pub_deps), repo.globalManifests().map(function (m) { return m.name; })))) { _context3.next = 10; break; } _context3.next = 5; return _dependencyGraph.DependencyGraph.buildFromLock(this, _classPrivateFieldGet(_bundleLock, this), repo); case 5: manifestGraph = _context3.sent; manifests = manifestGraph.traverse(); isFromBundleLock = true; _context3.next = 14; break; case 10: _context3.next = 12; return _dependencyGraph.DependencyGraph.build(this, repo, false, osInfo); case 12: _manifestGraph = _context3.sent; manifests = _manifestGraph.traverse(); case 14: return _context3.abrupt("return", { manifests: manifests, isFromBundleLock: isFromBundleLock }); case 15: case "end": return _context3.stop(); } }, _callee3, this); })); function traverse(_x7, _x8) { return _traverse.apply(this, arguments); } return traverse; }() }, { key: "update", value: function () { var _update = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(repo, osInfo) { var _this4 = this; var isUpdate, localManifests, globalManifests, manifestGraph, remoteManifests, needUpdate; return _regeneratorRuntime().wrap(function _callee4$(_context4) { while (1) switch (_context4.prev = _context4.next) { case 0: isUpdate = true; localManifests = repo.manifests(); globalManifests = repo.globalManifests(); _context4.next = 5; return _dependencyGraph.DependencyGraph.build(this, repo.remoteRepo, isUpdate, osInfo); case 5: manifestGraph = _context4.sent; remoteManifests = manifestGraph.traverse(); needUpdate = []; remoteManifests.forEach(function (remote) { if (remote.name === _this4.manifest.name) { return; } var local = localManifests.find(function (localManifest) { return localManifest.name === remote.name; }); if (local) { if (local.version.version !== remote.version.version || local.isSnapshot()) { remote.local = local.version.version; remote.global = 'miss'; needUpdate.push(remote); } } else { var global = globalManifests.find(function (m) { return m.name === remote.name; }); if (global) { if (global.version.version !== remote.version.version) { remote.local = 'miss'; remote.global = global.version.version; needUpdate.push(remote); } } else { remote.local = 'miss'; remote.global = 'miss'; needUpdate.push(remote); } } }); return _context4.abrupt("return", needUpdate); case 10: case "end": return _context4.stop(); } }, _callee4, this); })); function update(_x9, _x10) { return _update.apply(this, arguments); } return update; }() }, { key: "resolveSnapshotManifest", value: function resolveSnapshotManifest(manifests, repo, isGlobal, isForce) { var _this5 = this; if (!_classPrivateFieldGet(_bundleCache, this)) { return manifests; } var snapShotManifests = []; var m = manifests.map(function (manifest) { if (!!manifest.url && manifest.isSnapshot()) { if (_classPrivateFieldGet(_bundleCache, _this5).isManifestTimeout(manifest) || isForce) { snapShotManifests.push(manifest); } else { manifest = _manifest2.Manifest.json(manifest.json()); } var info = (0, _helpers.parseScopeName)(manifest.name); var folder = _path2["default"].join(repo.path, info.scope, info.name); if (_fs["default"].existsSync(_path2["default"].join(folder, 'bundle.json'))) { manifest.path = folder; } } return manifest; }); repo.removeSnapshot(snapShotManifests, isGlobal); return m; } }, { key: "isDirectDep", value: function isDirectDep(depName) { return !!this.dependencies.find(function (dep) { return depName === dep.name; }); } }, { key: "addDependencies", value: function addDependencies(dependencies, type) { _classPrivateFieldGet(_manifest, this).addDependencies(dependencies, type); } }, { key: "removeDependencies", value: function removeDependencies(names, type) { var _this6 = this; var baseName = names.find(function (name) { var bName = _this6.manifest.base && _this6.manifest.base.name; return bName === name; }); if (baseName) { _classPrivateFieldGet(_manifest, this).removeBase({ name: baseName }); this.removeLocalBase(); } _classPrivateFieldGet(_manifest, this).removeDependencies(names, type); } }, { key: "removeLocalBase", value: function removeLocalBase() { var jsonPath = _path2["default"].join(_classPrivateFieldGet(_path, this), 'bundle.json'); if (_fs["default"].existsSync(jsonPath)) { var oldBundleJson = JSON.parse(_fs["default"].readFileSync(jsonPath)); delete oldBundleJson.base; _fs["default"].writeFileSync(jsonPath, JSON.stringify(oldBundleJson, null, 4)); } } }, { key: "updateDependencies", value: function updateDependencies(dependencies, type) { var _this7 = this; var newDependencies = []; var base = null; var _iterator4 = _createForOfIteratorHelper(dependencies), _step4; try { var _loop2 = function _loop2() { var dep = _step4.value; var manifest = _classPrivateFieldGet(_manifests, _this7).find(function (m) { return m.name === dep.name; }); if (manifest) { var versionRanges = dep.versionRanges && dep.versionRanges !== '*' ? dep.versionRanges : "~".concat(manifest.version.version); if (manifest.publishAs === 'distribution') { base = { name: dep.name, version: versionRanges }; } else { newDependencies.push(new _dependency2.Dependency(dep.name, versionRanges)); } } }; for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) { _loop2(); } } catch (err) { _iterator4.e(err); } finally { _iterator4.f(); } if (base) { _classPrivateFieldGet(_manifest, this).updateBase(base); } if (newDependencies.length > 0) { _classPrivateFieldGet(_manifest, this).updateDependencies(newDependencies, type); } } }, { key: "updateBundleJson", value: function updateBundleJson(dependencies) { var isBinary = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var json = this.manifest.json(); var jsonPath = _path2["default"].join(_classPrivateFieldGet(_path, this), 'bundle.json'); var oldBundleJson = {}; if (_fs["default"].existsSync(jsonPath)) { oldBundleJson = JSON.parse(_fs["default"].readFileSync(jsonPath)); } if (dependencies && dependencies.length > 0) { var oldDeps = oldBundleJson.dependencies; var oldPubDeps = oldBundleJson.pub_deps; var deps = (0, _common.concatAndRecordingDeps)(oldDeps, json.dependencies); var pub_deps = (0, _common.concatAndRecordingDeps)(oldPubDeps, json.pub_deps); var newBundleJson = _objectSpread(_objectSpread({}, oldBundleJson), json); for (var key in pub_deps) { if (deps[key]) { delete deps[key]; } } (0, _common.dealDepsBeforeUpdate)(newBundleJson); newBundleJson.dependencies = deps; newBundleJson.pub_deps = pub_deps; _fs["default"].writeFileSync(jsonPath, JSON.stringify(newBundleJson, null, 4)); } else { (0, _common.dealDepsBeforeUpdate)(json); _fs["default"].writeFileSync(jsonPath, JSON.stringify(_objectSpread(_objectSpread({}, oldBundleJson), json), null, 4)); } } }, { key: "updateLockJsonForInstall", value: function () { var _updateLockJsonForInstall = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee5(manifests) { var needUpdateManifests; return _regeneratorRuntime().wrap(function _callee5$(_context5) { while (1) switch (_context5.prev = _context5.next) { case 0: if (!_classPrivateFieldGet(_bundleLock, this)) { _context5.next = 5; break; } needUpdateManifests = manifests.filter(function (m) { return !!m.url && !m.isSnapshot(); }); _classPrivateFieldGet(_bundleLock, this).addOrUpdate(needUpdateManifests); _context5.next = 12; break; case 5: _context5.t0 = _classPrivateFieldSet; _context5.t1 = _bundleLock; _context5.t2 = this; _context5.next = 10; return _bundleLock2.BundleLock.fromManifests(manifests); case 10: _context5.t3 = _context5.sent; (0, _context5.t0)(_context5.t1, _context5.t2, _context5.t3); case 12: if (_classPrivateFieldGet(_bundleLock, this)) { _classPrivateFieldGet(_bundleLock, this).saveToFile(_classPrivateFieldGet(_path, this)); } case 13: case "end": return _context5.stop(); } }, _callee5, this); })); function updateLockJsonForInstall(_x11) { return _updateLockJsonForInstall.apply(this, arguments); } return updateLockJsonForInstall; }() }, { key: "updateLockJsonForUnInstall", value: function updateLockJsonForUnInstall(manifestNameList) { if (_classPrivateFieldGet(_bundleLock, this)) { _classPrivateFieldGet(_bundleLock, this).remove(manifestNameList); _classPrivateFieldGet(_bundleLock, this).saveToFile(_classPrivateFieldGet(_path, this)); } } }, { key: "updateCacheJson", value: function updateCacheJson(manifests) { var _this8 = this; var snapshotManifests = manifests.filter(function (manifest) { return manifest.isSnapshot() && manifest.name !== _this8.name; }); if (_classPrivateFieldGet(_bundleCache, this)) { _classPrivateFieldGet(_bundleCache, this).addOrUpdate(snapshotManifests); } else { _classPrivateFieldSet(_bundleCache, this, _bundleCache2.BundleCache.fromManifests(snapshotManifests)); } _classPrivateFieldGet(_bundleCache, this).saveToFile(_classPrivateFieldGet(_path, this)); } }, { key: "updateCacheJsonForUninstall", value: function updateCacheJsonForUninstall(manifestNameList) { if (_classPrivateFieldGet(_bundleCache, this)) { _classPrivateFieldGet(_bundleCache, this).removeCache(manifestNameList); _classPrivateFieldGet(_bundleCache, this).saveToFile(_classPrivateFieldGet(_path, this)); } } }]); }(); /** * 实例化Bundle类 * @param {String} dir 读取的bundlejson地址 * @param {String} bundleDescriptor 组件描述 * @param {Boolean} isBinary 是否是新二进制包 * @param {Object} bundleJson 解析出来的bundle内容,用于不是hpm生成的bundle.json的manifest实例化 * @returns {Bundle} 实例化的Bundle类 */ Bundle.from = function (dir) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var bundleDescriptor = options.bundleDescriptor, isBinary = options.isBinary, bundlePath = options.bundlePath; var manifest = _manifest2.Manifest.fromPath(dir, bundleDescriptor, isBinary); return new Bundle(bundlePath || dir, manifest, bundleDescriptor); }; Bundle.mapManifestToBundle = /*#__PURE__*/function () { var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee6(manifest, dirTemp, startBundle) { var snapshots, bundlePath, result, tarfile, name, obj, index, _args6 = arguments; return _regeneratorRuntime().wrap(function _callee6$(_context6) { while (1) switch (_context6.prev = _context6.next) { case 0: snapshots = _args6.length > 3 && _args6[3] !== undefined ? _args6[3] : []; bundlePath = manifest.path; if (!manifest.url) { _context6.next = 25; break; } result = snapshots.find(function (item) { return item.id === manifest.id; }); // 存在相同的包并且 sha256 相同,则不用下载。 if (!(result && result.sha256 === manifest.checksum)) { _context6.next = 11; break; } _i18n["default"].log('common.message', { message: "Bundle ".concat(result.id.split('-')[0] + '/' + result.id.split('-')[1], " already exists.") }); bundlePath = result.bundlePath; manifest.path = bundlePath; // execInstallHook(manifest, false, startBundle); return _context6.abrupt("return", Bundle.from(bundlePath)); case 11: if (result && result.bundlePath) { (0, _helpers.runShellCmd)(function (shell) { return shell.rm('-rf', result.bundlePath); }); } case 12: tarfile = _path2["default"].resolve(dirTemp, "".concat(manifest.id, ".tgz")); _context6.next = 15; return (0, _repository.bundleDownload)(manifest, false, startBundle, true); case 15: bundlePath = _context6.sent; manifest.path = bundlePath; // 记录带有 snapshot 的包 name = String.prototype.toUpperCase.call(manifest.id); if (name.includes('SNAPSHOT')) { obj = { id: manifest.id, bundlePath: bundlePath, sha256: manifest.checksum }; index = snapshots.findIndex(function (item) { return item.id === manifest.id; }); if (index > -1) { snapshots.splice(index, 1, obj); } else { snapshots.push(obj); } } manifest.path = bundlePath; _i18n["default"].log('install.extracting', { filePath: bundlePath.split('.hpmcache')[1] + " <<< ".concat(manifest.id, ".tgz"), prefix: '... ' }); _context6.next = 23; return (0, _common.extractTgz)(tarfile, bundlePath, function (progress) { process.stdout.write("\rExtracting... ".concat(progress.toFixed(2), "%")); }); case 23: (0, _helpers.runShellCmd)(function (shell) { return shell.rm(tarfile); }); execInstallHook(manifest, false, startBundle); case 25: return _context6.abrupt("return", Bundle.from(bundlePath)); case 26: case "end": return _context6.stop(); } }, _callee6); })); return function (_x12, _x13, _x14) { return _ref.apply(this, arguments); }; }(); function execInstallHook(manifest, isGlobal, startBundle) { var subsystem = startBundle.manifest.dependencies.some(function (item) { return item.name === manifest.name; }); var buildTools = startBundle.manifest.pub_deps.some(function (item) { return item.name === manifest.name; }); var installTarget = subsystem ? _constant.DEFAULT_PROJECT_BINARY_DIR : buildTools ? _constant.DEFAULT_PROJECT_BUILD_TOOLS_DIR : manifest.publishAs === 'binary' ? _constant.DEFAULT_PROJECT_BINARY_DIR : null; var installPath = isGlobal ? process.env.globalRepo : process.cwd(); var dirPath = manifest.path; var installCmd = manifest.scripts(_constant.Hooks.install) || manifest.scripts(_constant.Hooks.afterInstall); var insteadOfHook = false; var isCodeSeg = manifest.publishAs === 'code-segment'; var destPath = manifest.segment && manifest.segment.destPath; insteadOfHook = manifest.segment && manifest.segment.insteadOfHook; // 执行安装脚本 if (installCmd && !insteadOfHook) { (0, _helpers.runCmdWithSpawnSync)(function (spawnSync) { return spawnSync(installCmd, { shell: process.env.shellPath, env: _variable.Variable.basicEnv(installPath), cwd: dirPath, stdio: 'inherit' }); }); } // code-segment类型bundle根据destPath还原路径(根据配置项restoreCodeSegment决定是否立即还原) if (isCodeSeg && (0, _config2.restoreCodeSegment)() && destPath && !installTarget) { var targetPath = _path2["default"].join(process.cwd(), destPath); var sourcePaths = (0, _install2.getSourcePaths)(dirPath); _i18n["default"].log('install.restoring', { name: manifest.name, path: targetPath, prefix: '... ' }); (0, _helpers.runShellCmd)(function (shell) { return shell.mkdir('-p', targetPath); }); (0, _helpers.runShellCmd)(function (shell) { return shell.cp('-R', sourcePaths, targetPath); }); } // 独立编译的二进制包或工具集安装 if (installTarget) { var bundlePath = installBinary(manifest, installTarget, startBundle.name); return bundlePath; } } function installBinary(manifest, installTarget, root) { var _parseScopeName = (0, _helpers.parseScopeName)(manifest.name), name = _parseScopeName.name; var branch = manifest.branch; var os = manifest.os; var buildArch = manifest.buildArch; var variant = manifest.variant; // 下载依赖目录追加版本号 var version = manifest.version.version; var dirPath = manifest.path; var destPath = manifest.segment && manifest.segment.destPath; var targetPath = _path2["default"].join(installTarget, destPath || name, branch, os, buildArch, variant, version); var sourcePaths = (0, _install2.getSourcePaths)(dirPath); var rls = (0, _common.sysLinks)(dirPath, targetPath); if (!rls) { (0, _helpers.runShellCmd)(function (shell) { return shell.mkdir('-p', targetPath); }); _i18n["default"].log('install.restoring', { name: manifest.name, path: targetPath, prefix: '... ' }); (0, _helpers.runShellCmd)(function (shell) { return shell.cp('-R', sourcePaths, targetPath); }); } logOutInstallDetail(root, manifest); return targetPath; } /** * 输出二进制安装详情信息: name version installPath * @param {Object} manifest 当前install manifest类 * @param {File} outPath 输出位置 DEFAULT_PROJECT_DIR */ function logOutInstallDetail(root, manifest) { var outPath = arguments.length > 2 && ar