lerna
Version:
Lerna is a fast, modern build system for managing and publishing multiple JavaScript/TypeScript packages from the same repository
6,778 lines • 210 kB
JavaScript
import {
__export
} from "./chunk-MLKGABMK.js";
// libs/child-process/src/colorize.ts
import { styleText } from "node:util";
var enabled = true;
function colorize(format, text) {
if (!enabled) {
return text;
}
return styleText(format, text);
}
colorize.disable = () => {
enabled = false;
};
colorize.enable = () => {
enabled = true;
};
// libs/child-process/src/index.ts
import execa from "execa";
import os from "node:os";
// libs/child-process/src/forked-strong-log-transformer.ts
import stream from "node:stream";
import { StringDecoder } from "node:string_decoder";
import util from "node:util";
var forked_strong_log_transformer_default = Logger;
Logger.DEFAULTS = {
format: "text",
tag: "",
mergeMultiline: false,
timeStamp: false
};
var formatters = {
text: textFormatter,
json: jsonFormatter
};
function Logger(options) {
var defaults2 = JSON.parse(JSON.stringify(Logger.DEFAULTS));
options = Object.assign(defaults2, options || {});
var catcher = deLiner();
var emitter = catcher;
var transforms = [objectifier()];
if (options.tag) {
transforms.push(staticTagger(options.tag));
}
if (options.mergeMultiline) {
transforms.push(lineMerger());
}
transforms.push(formatters[options.format](options));
transforms.push(reLiner());
for (var t in transforms) {
emitter = emitter.pipe(transforms[t]);
}
return createDuplex(catcher, emitter);
}
function deLiner() {
var decoder = new StringDecoder("utf8");
var last = "";
return new stream.Transform({
transform(chunk, _enc, callback) {
last += decoder.write(chunk);
var list3 = last.split(/\r\n|[\n\v\f\r\x85\u2028\u2029]/g);
last = list3.pop();
for (var i = 0; i < list3.length; i++) {
if (list3[i]) {
this.push(list3[i]);
}
}
callback();
},
flush(callback) {
last += decoder.end();
if (last) {
this.push(last);
}
callback();
}
});
}
function reLiner() {
return new stream.Transform({
objectMode: true,
transform(chunk, _encoding, callback) {
this.push(chunk + "\n");
callback();
}
});
}
function objectifier() {
return new stream.Transform({
objectMode: true,
autoDestroy: false,
transform(chunk, _encoding, callback) {
this.push({
msg: chunk,
time: Date.now()
});
callback();
}
});
}
function staticTagger(tag) {
return new stream.Transform({
objectMode: true,
transform(logEvent, _encoding, callback) {
logEvent.tag = tag;
this.push(logEvent);
callback();
}
});
}
function textFormatter(options) {
return new stream.Transform({
objectMode: true,
transform(logEvent, _encoding, callback) {
var line = util.format("%s%s", textifyTags(logEvent.tag), logEvent.msg.toString());
if (options.timeStamp) {
line = util.format("%s %s", new Date(logEvent.time).toISOString(), line);
}
this.push(line.replace(/\n/g, "\\n"));
callback();
}
});
function textifyTags(tags) {
var str = "";
if (typeof tags === "string") {
str = tags + " ";
} else if (typeof tags === "object") {
for (var t in tags) {
str += t + ":" + tags[t] + " ";
}
}
return str;
}
}
function jsonFormatter(options) {
return new stream.Transform({
objectMode: true,
transform(logEvent, _encoding, callback) {
if (options.timeStamp) {
logEvent.time = new Date(logEvent.time).toISOString();
} else {
delete logEvent.time;
}
logEvent.msg = logEvent.msg.toString();
this.push(JSON.stringify(logEvent));
callback();
}
});
}
function lineMerger() {
var previousLine = null;
var flushTimer = null;
var t = new stream.Transform({
objectMode: true,
transform(line, _encoding, callback) {
if (/^\s+/.test(line.msg)) {
if (previousLine) {
previousLine.msg += "\n" + line.msg;
} else {
previousLine = line;
}
} else {
flushPrevious.call(this);
previousLine = line;
}
clearTimeout(flushTimer);
flushTimer = setTimeout(flushPrevious.bind(this), 10);
callback();
},
flush(callback) {
flushPrevious.call(this);
callback();
}
});
return t;
function flushPrevious() {
if (previousLine) {
this.push(previousLine);
previousLine = null;
}
}
}
function createDuplex(input, output2) {
const duplex = new stream.Duplex({
objectMode: false,
allowHalfOpen: false
});
duplex._write = (chunk, encoding, cb) => {
input.write(chunk, encoding, cb);
};
duplex._read = () => {
};
duplex._final = (cb) => {
input.end(cb);
};
output2.on("data", (chunk) => {
duplex.push(chunk);
});
output2.on("end", () => {
duplex.push(null);
});
input.on("error", (err) => {
duplex.emit("error", err);
});
output2.on("error", (err) => {
duplex.emit("error", err);
});
return duplex;
}
// libs/child-process/src/set-exit-code.ts
function setExitCode(code) {
process.exitCode = code;
}
// libs/child-process/src/index.ts
var children = /* @__PURE__ */ new Set();
var colorWheel = ["cyan", "magenta", "blue", "yellow", "green", "blueBright"];
var NUM_COLORS = colorWheel.length;
var currentColor = 0;
function exec(command, args, opts) {
const options = Object.assign({ stdio: "pipe" }, opts);
const spawned = spawnProcess(command, args, options);
return wrapError(spawned);
}
function execSync(command, args, opts) {
return execa.sync(command, args, opts).stdout;
}
function spawn(command, args, opts) {
const options = Object.assign({}, opts, { stdio: "inherit" });
const spawned = spawnProcess(command, args, options);
return wrapError(spawned);
}
function spawnStreaming(command, args, opts, prefix2) {
const options = Object.assign({}, opts);
options.stdio = ["ignore", "pipe", "pipe"];
const spawned = spawnProcess(command, args, options);
const stdoutOpts = {};
const stderrOpts = {};
if (prefix2) {
const color2 = colorWheel[currentColor % NUM_COLORS];
currentColor += 1;
stdoutOpts.tag = `${colorize(["bold", color2], prefix2)}:`;
stderrOpts.tag = `${colorize(color2, prefix2)}:`;
}
if (children.size > process.stdout.listenerCount("close")) {
process.stdout.setMaxListeners(children.size);
process.stderr.setMaxListeners(children.size);
}
spawned.stdout?.pipe(forked_strong_log_transformer_default(stdoutOpts)).pipe(process.stdout);
spawned.stderr?.pipe(forked_strong_log_transformer_default(stderrOpts)).pipe(process.stderr);
return wrapError(spawned);
}
function getChildProcessCount() {
return children.size;
}
function getExitCode(result) {
if (result.exitCode) {
return result.exitCode;
}
if (typeof result.code === "number") {
return result.code;
}
if (typeof result.code === "string") {
return os.constants.errno[result.code];
}
return typeof process.exitCode === "number" ? process.exitCode : void 0;
}
function spawnProcess(command, args, opts) {
const child = execa(command, args, opts);
const drain = (exitCode, signal) => {
children.delete(child);
if (signal === void 0) {
child.removeListener("exit", drain);
}
if (exitCode) {
setExitCode(exitCode);
}
};
child.once("exit", drain);
child.once("error", drain);
if (opts?.pkg) {
child.pkg = opts.pkg;
}
children.add(child);
return child;
}
function wrapError(spawned) {
if (spawned.pkg) {
return spawned.catch((err) => {
err.exitCode = getExitCode(err);
err.pkg = spawned.pkg;
throw err;
});
}
return spawned;
}
// libs/core/src/lib/npmlog/index.ts
import { EventEmitter as EventEmitter2 } from "node:events";
import util4 from "node:util";
// libs/core/src/lib/npmlog/are-we-there-yet/tracker-base.ts
import EventEmitter from "node:events";
var trackerId = 0;
var TrackerBase = class extends EventEmitter {
id;
name;
constructor(name = "") {
super();
this.id = ++trackerId;
this.name = name;
}
};
// libs/core/src/lib/npmlog/are-we-there-yet/tracker.ts
var Tracker = class extends TrackerBase {
workDone;
workTodo;
constructor(name, todo) {
super(name);
this.workDone = 0;
this.workTodo = todo || 0;
}
completed() {
return this.workTodo === 0 ? 0 : this.workDone / this.workTodo;
}
addWork(work) {
this.workTodo += work;
this.emit("change", this.name, this.completed(), this);
}
completeWork(work) {
this.workDone += work;
if (this.workDone > this.workTodo) {
this.workDone = this.workTodo;
}
this.emit("change", this.name, this.completed(), this);
}
finish() {
this.workTodo = this.workDone = 1;
this.emit("change", this.name, 1, this);
}
};
// libs/core/src/lib/npmlog/are-we-there-yet/tracker-stream.ts
import stream2 from "node:stream";
var TrackerStream = class extends stream2.Transform {
tracker;
name;
id;
constructor(name, size = 0, options) {
super(options);
this.tracker = new Tracker(name, size);
this.name = name;
this.id = this.tracker.id;
this.tracker.on("change", this.trackerChange.bind(this));
}
trackerChange(name, completion) {
this.emit("change", name, completion, this);
}
_transform(data, encoding, cb) {
this.tracker.completeWork(data.length ? data.length : 1);
this.push(data);
cb();
}
_flush(cb) {
this.tracker.finish();
cb();
}
completed() {
return this.tracker.completed();
}
addWork(work) {
return this.tracker.addWork(work);
}
finish() {
return this.tracker.finish();
}
};
// libs/core/src/lib/npmlog/are-we-there-yet/tracker-group.ts
var TrackerGroup = class _TrackerGroup extends TrackerBase {
parentGroup = null;
trackers = [];
completion = {};
weight = {};
totalWeight = 0;
finished = false;
bubbleChange = bubbleChange(this);
nameInTree() {
const names = [];
let from = this;
while (from) {
names.unshift(from.name);
from = from.parentGroup;
}
return names.join("/");
}
addUnit(unit, weight = 0) {
if (unit.addUnit) {
let toTest = this;
while (toTest) {
if (unit === toTest) {
throw new Error(
"Attempted to add tracker group " + unit.name + " to tree that already includes it " + this.nameInTree()
);
}
toTest = toTest.parentGroup;
}
unit.parentGroup = this;
}
this.weight[unit.id] = weight || 1;
this.totalWeight += this.weight[unit.id];
this.trackers.push(unit);
this.completion[unit.id] = unit.completed();
unit.on("change", this.bubbleChange);
if (!this.finished) {
this.emit("change", unit.name, this.completion[unit.id], unit);
}
return unit;
}
completed() {
if (this.trackers.length === 0) {
return 0;
}
const valPerWeight = 1 / this.totalWeight;
let completed = 0;
for (let ii = 0; ii < this.trackers.length; ii++) {
const trackerId2 = this.trackers[ii].id;
completed += valPerWeight * this.weight[trackerId2] * this.completion[trackerId2];
}
return completed;
}
newGroup(name, weight = 0) {
return this.addUnit(new _TrackerGroup(name), weight);
}
newItem(name, todo, weight = 0) {
return this.addUnit(new Tracker(name, todo), weight);
}
newStream(name, todo, weight = 0) {
return this.addUnit(new TrackerStream(name, todo), weight);
}
finish() {
this.finished = true;
if (!this.trackers.length) {
this.addUnit(new Tracker(), 1);
}
for (let ii = 0; ii < this.trackers.length; ii++) {
const tracker = this.trackers[ii];
tracker.finish();
tracker.removeListener("change", this.bubbleChange);
}
this.emit("change", this.name, 1, this);
}
debug(depth = 0) {
const indent = " ".repeat(depth);
let output2 = `${indent}${this.name || "top"}: ${this.completed()}
`;
this.trackers.forEach(function(tracker) {
output2 += tracker instanceof _TrackerGroup ? tracker.debug(depth + 1) : `${indent} ${tracker.name}: ${tracker.completed()}
`;
});
return output2;
}
};
function bubbleChange(trackerGroup) {
return function(name, completed, tracker) {
trackerGroup.completion[tracker.id] = completed;
if (trackerGroup.finished) {
return;
}
trackerGroup.emit("change", name || trackerGroup.name, trackerGroup.completed(), trackerGroup);
};
}
// libs/core/src/lib/npmlog/gauge/index.ts
import onExit from "signal-exit";
// libs/core/src/lib/npmlog/gauge/has-unicode.ts
import os2 from "os";
function hasUnicode() {
if (os2.type() === "Windows_NT") return false;
const ctype = process.env.LC_ALL || process.env.LC_CTYPE || process.env.LANG;
return /UTF-?8$/i.test(ctype || "");
}
// libs/core/src/lib/npmlog/gauge/console-control-strings.ts
var prefix = "\x1B[";
function eraseLine() {
return prefix + "K";
}
function gotoSOL() {
return "\r";
}
function beep() {
return "\x07";
}
function hideCursor() {
return prefix + "?25l";
}
function showCursor() {
return prefix + "?25h";
}
var colors = {
reset: 0,
bold: 1,
italic: 3,
underline: 4,
inverse: 7,
stopBold: 22,
stopItalic: 23,
stopUnderline: 24,
stopInverse: 27,
white: 37,
black: 30,
blue: 34,
cyan: 36,
green: 32,
magenta: 35,
red: 31,
yellow: 33,
bgWhite: 47,
bgBlack: 40,
bgBlue: 44,
bgCyan: 46,
bgGreen: 42,
bgMagenta: 45,
bgRed: 41,
bgYellow: 43,
grey: 90,
brightBlack: 90,
brightRed: 91,
brightGreen: 92,
brightYellow: 93,
brightBlue: 94,
brightMagenta: 95,
brightCyan: 96,
brightWhite: 97,
bgGrey: 100,
bgBrightBlack: 100,
bgBrightRed: 101,
bgBrightGreen: 102,
bgBrightYellow: 103,
bgBrightBlue: 104,
bgBrightMagenta: 105,
bgBrightCyan: 106,
bgBrightWhite: 107
};
function colorNameToCode(name) {
if (colors[name] != null) return colors[name];
throw new Error("Unknown color or style name: " + name);
}
function color(...args) {
const colorWith = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;
return prefix + colorWith.map(colorNameToCode).join(";") + "m";
}
// libs/core/src/lib/npmlog/gauge/wide-align.ts
var wide_align_exports = {};
__export(wide_align_exports, {
center: () => center,
left: () => left,
right: () => right
});
import stringWidth from "string-width";
function alignLeft(str, width) {
var trimmed = str.trimEnd();
if (trimmed.length === 0 && str.length >= width) return str;
var strWidth = stringWidth(trimmed);
if (strWidth < width) {
return trimmed + " ".repeat(width - strWidth);
}
return trimmed;
}
function alignRight(str, width) {
var trimmed = str.trimStart();
if (trimmed.length === 0 && str.length >= width) return str;
var strWidth = stringWidth(trimmed);
if (strWidth < width) {
return " ".repeat(width - strWidth) + trimmed;
}
return trimmed;
}
function alignCenter(str, width) {
var trimmed = str.trim();
if (trimmed.length === 0 && str.length >= width) return str;
var strWidth = stringWidth(trimmed);
if (strWidth < width) {
var padLeftBy = Math.floor((width - strWidth) / 2);
var padRightBy = width - strWidth - padLeftBy;
return " ".repeat(padLeftBy) + trimmed + " ".repeat(padRightBy);
}
return trimmed;
}
var left = alignLeft;
var right = alignRight;
var center = alignCenter;
// libs/core/src/lib/npmlog/gauge/validate.ts
function isArguments(thingy) {
return thingy != null && typeof thingy === "object" && Object.prototype.hasOwnProperty.call(thingy, "callee");
}
var types = {
"*": { label: "any", check: () => true },
A: { label: "array", check: (_) => Array.isArray(_) || isArguments(_) },
S: { label: "string", check: (_) => typeof _ === "string" },
N: { label: "number", check: (_) => typeof _ === "number" },
F: { label: "function", check: (_) => typeof _ === "function" },
O: {
label: "object",
check: (_) => typeof _ === "object" && _ != null && !types["A"].check(_) && !types["E"].check(_)
},
B: { label: "boolean", check: (_) => typeof _ === "boolean" },
E: { label: "error", check: (_) => _ instanceof Error },
Z: { label: "null", check: (_) => _ == null }
};
function addSchema(schema, arity) {
const group = arity[schema.length] = arity[schema.length] || [];
if (group.indexOf(schema) === -1) group.push(schema);
}
function validate(rawSchemas, args) {
if (arguments.length !== 2) throw wrongNumberOfArgs(["SA"], arguments.length);
if (!rawSchemas) throw missingRequiredArg(0);
if (!args) throw missingRequiredArg(1);
if (!types["S"].check(rawSchemas)) throw invalidType(0, ["string"], rawSchemas);
if (!types["A"].check(args)) throw invalidType(1, ["array"], args);
const schemas = rawSchemas.split("|");
const arity = {};
schemas.forEach((schema) => {
for (let ii = 0; ii < schema.length; ++ii) {
const type = schema[ii];
if (!types[type]) throw unknownType(ii, type);
}
if (/E.*E/.test(schema)) throw moreThanOneError(schema);
addSchema(schema, arity);
if (/E/.test(schema)) {
addSchema(schema.replace(/E.*$/, "E"), arity);
addSchema(schema.replace(/E/, "Z"), arity);
if (schema.length === 1) addSchema("", arity);
}
});
let matching = arity[args.length];
if (!matching) {
throw wrongNumberOfArgs(Object.keys(arity).map(Number), args.length);
}
for (let ii = 0; ii < args.length; ++ii) {
const newMatching = matching.filter((schema) => {
const type = schema[ii];
const typeCheck = types[type].check;
return typeCheck(args[ii]);
});
if (!newMatching.length) {
const labels = matching.map((_) => types[_[ii]].label).filter((_) => _ != null);
throw invalidType(ii, labels, args[ii]);
}
matching = newMatching;
}
}
function missingRequiredArg(num) {
return newException("EMISSINGARG", "Missing required argument #" + (num + 1));
}
function unknownType(num, type) {
return newException("EUNKNOWNTYPE", "Unknown type " + type + " in argument #" + (num + 1));
}
function invalidType(num, expectedTypes, value) {
let valueType;
Object.keys(types).forEach((typeCode) => {
if (types[typeCode].check(value)) valueType = types[typeCode].label;
});
return newException(
"EINVALIDTYPE",
"Argument #" + (num + 1) + ": Expected " + englishList(expectedTypes) + " but got " + valueType
);
}
function englishList(list3) {
return list3.join(", ").replace(/, ([^,]+)$/, " or $1");
}
function wrongNumberOfArgs(expected, got) {
const english = englishList(expected);
const args = expected.every((ex) => String(ex).length === 1) ? "argument" : "arguments";
return newException("EWRONGARGCOUNT", "Expected " + english + " " + args + " but got " + got);
}
function moreThanOneError(schema) {
return newException(
"ETOOMANYERRORTYPES",
'Only one error type per argument signature is allowed, more than one found in "' + schema + '"'
);
}
function newException(code, msg) {
const err = new Error(msg);
err.code = code;
if (Error.captureStackTrace) Error.captureStackTrace(err, validate);
return err;
}
var validate_default = validate;
// libs/core/src/lib/npmlog/gauge/wide-truncate.ts
import stringWidth2 from "string-width";
import util2 from "node:util";
var wide_truncate_default = wideTruncate;
function wideTruncate(str, target) {
if (stringWidth2(str) === 0) {
return str;
}
if (target <= 0) {
return "";
}
if (stringWidth2(str) <= target) {
return str;
}
var noAnsi = util2.stripVTControlCharacters(str);
var ansiSize = str.length + noAnsi.length;
var truncated = str.slice(0, target + ansiSize);
while (stringWidth2(truncated) > target) {
truncated = truncated.slice(0, -1);
}
return truncated;
}
// libs/core/src/lib/npmlog/gauge/error.ts
import util3 from "util";
var User = function User2(msg) {
var err = new Error(msg);
Error.captureStackTrace(err, User2);
err.code = "EGAUGE";
return err;
};
var MissingTemplateValue = function MissingTemplateValue2(item, values) {
var err = new User(util3.format('Missing template value "%s"', item.type));
Error.captureStackTrace(err, MissingTemplateValue2);
err.template = item;
err.values = values;
return err;
};
var Internal = function Internal2(msg) {
var err = new Error(msg);
Error.captureStackTrace(err, Internal2);
err.code = "EGAUGEINTERNAL";
return err;
};
// libs/core/src/lib/npmlog/gauge/template-item.ts
import stringWidth3 from "string-width";
var template_item_default = TemplateItem;
function isPercent(num) {
if (typeof num !== "string") {
return false;
}
return num.slice(-1) === "%";
}
function percent(num) {
return Number(num.slice(0, -1)) / 100;
}
function TemplateItem(values, outputLength) {
this.overallOutputLength = outputLength;
this.finished = false;
this.type = null;
this.value = null;
this.length = null;
this.maxLength = null;
this.minLength = null;
this.kerning = null;
this.align = "left";
this.padLeft = 0;
this.padRight = 0;
this.index = null;
this.first = null;
this.last = null;
if (typeof values === "string") {
this.value = values;
} else {
for (var prop in values) {
this[prop] = values[prop];
}
}
if (isPercent(this.length)) {
this.length = Math.round(this.overallOutputLength * percent(this.length));
}
if (isPercent(this.minLength)) {
this.minLength = Math.round(this.overallOutputLength * percent(this.minLength));
}
if (isPercent(this.maxLength)) {
this.maxLength = Math.round(this.overallOutputLength * percent(this.maxLength));
}
return this;
}
TemplateItem.prototype = {};
TemplateItem.prototype.getBaseLength = function() {
var length = this.length;
if (length == null && typeof this.value === "string" && this.maxLength == null && this.minLength == null) {
length = stringWidth3(this.value);
}
return length;
};
TemplateItem.prototype.getLength = function() {
var length = this.getBaseLength();
if (length == null) {
return null;
}
return length + this.padLeft + this.padRight;
};
TemplateItem.prototype.getMaxLength = function() {
if (this.maxLength == null) {
return null;
}
return this.maxLength + this.padLeft + this.padRight;
};
TemplateItem.prototype.getMinLength = function() {
if (this.minLength == null) {
return null;
}
return this.minLength + this.padLeft + this.padRight;
};
// libs/core/src/lib/npmlog/gauge/render-template.ts
function renderValueWithValues(values) {
return function(item) {
return renderValue(item, values);
};
}
var renderTemplate = function(width, template, values) {
var items = prepareItems(width, template, values);
var rendered = items.map(renderValueWithValues(values)).join("");
return left(wide_truncate_default(rendered, width), width);
};
var render_template_default = renderTemplate;
function preType(item) {
var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1);
return "pre" + cappedTypeName;
}
function postType(item) {
var cappedTypeName = item.type[0].toUpperCase() + item.type.slice(1);
return "post" + cappedTypeName;
}
function hasPreOrPost(item, values) {
if (!item.type) {
return;
}
return values[preType(item)] || values[postType(item)];
}
function generatePreAndPost(baseItem, parentValues) {
var item = Object.assign({}, baseItem);
var values = Object.create(parentValues);
var template = [];
var pre = preType(item);
var post = postType(item);
if (values[pre]) {
template.push({ value: values[pre] });
values[pre] = null;
}
item.minLength = null;
item.length = null;
item.maxLength = null;
template.push(item);
values[item.type] = values[item.type];
if (values[post]) {
template.push({ value: values[post] });
values[post] = null;
}
return function($1, $2, length) {
return renderTemplate(length, template, values);
};
}
function prepareItems(width, template, values) {
function cloneAndObjectify(item, index, arr) {
var cloned = new template_item_default(item, width);
var type = cloned.type;
if (cloned.value == null) {
if (!(type in values)) {
if (cloned.default == null) {
throw new MissingTemplateValue(cloned, values);
} else {
cloned.value = cloned.default;
}
} else {
cloned.value = values[type];
}
}
if (cloned.value == null || cloned.value === "") {
return null;
}
cloned.index = index;
cloned.first = index === 0;
cloned.last = index === arr.length - 1;
if (hasPreOrPost(cloned, values)) {
cloned.value = generatePreAndPost(cloned, values);
}
return cloned;
}
var output2 = template.map(cloneAndObjectify).filter(function(item) {
return item != null;
});
var remainingSpace = width;
var variableCount = output2.length;
function consumeSpace(length) {
if (length > remainingSpace) {
length = remainingSpace;
}
remainingSpace -= length;
}
function finishSizing(item, length) {
if (item.finished) {
throw new Internal("Tried to finish template item that was already finished");
}
if (length === Infinity) {
throw new Internal("Length of template item cannot be infinity");
}
if (length != null) {
item.length = length;
}
item.minLength = null;
item.maxLength = null;
--variableCount;
item.finished = true;
if (item.length == null) {
item.length = item.getBaseLength();
}
if (item.length == null) {
throw new Internal("Finished template items must have a length");
}
consumeSpace(item.getLength());
}
output2.forEach(function(item) {
if (!item.kerning) {
return;
}
var prevPadRight = item.first ? 0 : output2[item.index - 1].padRight;
if (!item.first && prevPadRight < item.kerning) {
item.padLeft = item.kerning - prevPadRight;
}
if (!item.last) {
item.padRight = item.kerning;
}
});
output2.forEach(function(item) {
if (item.getBaseLength() == null) {
return;
}
finishSizing(item);
});
var resized = 0;
var resizing;
var hunkSize;
do {
resizing = false;
hunkSize = Math.round(remainingSpace / variableCount);
output2.forEach(function(item) {
if (item.finished) {
return;
}
if (!item.maxLength) {
return;
}
if (item.getMaxLength() < hunkSize) {
finishSizing(item, item.maxLength);
resizing = true;
}
});
} while (resizing && resized++ < output2.length);
if (resizing) {
throw new Internal("Resize loop iterated too many times while determining maxLength");
}
resized = 0;
do {
resizing = false;
hunkSize = Math.round(remainingSpace / variableCount);
output2.forEach(function(item) {
if (item.finished) {
return;
}
if (!item.minLength) {
return;
}
if (item.getMinLength() >= hunkSize) {
finishSizing(item, item.minLength);
resizing = true;
}
});
} while (resizing && resized++ < output2.length);
if (resizing) {
throw new Internal("Resize loop iterated too many times while determining minLength");
}
hunkSize = Math.round(remainingSpace / variableCount);
output2.forEach(function(item) {
if (item.finished) {
return;
}
finishSizing(item, hunkSize);
});
return output2;
}
function renderFunction(item, values, length) {
validate_default("OON", arguments);
if (item.type) {
return item.value(values, values[item.type + "Theme"] || {}, length);
} else {
return item.value(values, {}, length);
}
}
function renderValue(item, values) {
var length = item.getBaseLength();
var value = typeof item.value === "function" ? renderFunction(item, values, length) : item.value;
if (value == null || value === "") {
return "";
}
var alignWith = wide_align_exports[item.align] || left;
var leftPadding = item.padLeft ? left("", item.padLeft) : "";
var rightPadding = item.padRight ? right("", item.padRight) : "";
var truncated = wide_truncate_default(String(value), length);
var aligned = alignWith(truncated, length);
return leftPadding + aligned + rightPadding;
}
// libs/core/src/lib/npmlog/gauge/plumbing.ts
var Plumbing = function(theme, template, width) {
if (!width) {
width = 80;
}
validate_default("OAN", [theme, template, width]);
this.showing = false;
this.theme = theme;
this.width = width;
this.template = template;
};
Plumbing.prototype = {};
var plumbing_default = Plumbing;
Plumbing.prototype.setTheme = function(theme) {
validate_default("O", [theme]);
this.theme = theme;
};
Plumbing.prototype.setTemplate = function(template) {
validate_default("A", [template]);
this.template = template;
};
Plumbing.prototype.setWidth = function(width) {
validate_default("N", [width]);
this.width = width;
};
Plumbing.prototype.hide = function() {
return gotoSOL() + eraseLine();
};
Plumbing.prototype.hideCursor = hideCursor;
Plumbing.prototype.showCursor = showCursor;
Plumbing.prototype.show = function(status) {
var values = Object.create(this.theme);
for (var key in status) {
values[key] = status[key];
}
return render_template_default(this.width, this.template, values).trim() + color("reset") + eraseLine() + gotoSOL();
};
// libs/core/src/lib/npmlog/gauge/color-support.ts
import os3 from "os";
function hasNone() {
return { level: 0, hasBasic: false, has256: false, has16m: false };
}
function hasBasic() {
return { level: 1, hasBasic: true, has256: false, has16m: false };
}
function has256() {
return { level: 2, hasBasic: true, has256: true, has16m: false };
}
function has16m() {
return { level: 3, hasBasic: true, has256: true, has16m: true };
}
function colorSupport(stream3) {
const s = stream3 || process.stdout;
const env2 = process.env;
const term = env2.TERM || "";
const platform = os3.platform();
if (!s.isTTY) {
return hasNone();
}
if (term === "dumb" && !env2.COLORTERM) {
return hasNone();
}
if (platform === "win32") {
return hasBasic();
}
if (env2.TMUX) {
return has256();
}
if (env2.CI || env2.TEAMCITY_VERSION) {
if (env2.TRAVIS) {
return has256();
}
return hasNone();
}
switch (env2.TERM_PROGRAM) {
case "iTerm.app": {
const ver = env2.TERM_PROGRAM_VERSION || "0.";
return /^[0-2]\./.test(ver) ? has256() : has16m();
}
case "HyperTerm":
case "Hyper":
case "MacTerm":
return has16m();
case "Apple_Terminal":
return has256();
}
if (/^xterm-256/.test(term)) {
return has256();
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(term)) {
return hasBasic();
}
if (env2.COLORTERM) {
return hasBasic();
}
return hasNone();
}
// libs/core/src/lib/npmlog/gauge/has-color.ts
var has_color_default = colorSupport().hasBasic;
// libs/core/src/lib/npmlog/gauge/spin.ts
function spin(spinstr, spun) {
return spinstr[spun % spinstr.length];
}
// libs/core/src/lib/npmlog/gauge/progress-bar.ts
import stringWidth4 from "string-width";
function progress_bar_default(theme, width, completed) {
validate_default("ONN", [theme, width, completed]);
if (completed < 0) {
completed = 0;
}
if (completed > 1) {
completed = 1;
}
if (width <= 0) {
return "";
}
var sofar = Math.round(width * completed);
var rest = width - sofar;
var template = [
{ type: "complete", value: repeat(theme.complete, sofar), length: sofar },
{ type: "remaining", value: repeat(theme.remaining, rest), length: rest }
];
return render_template_default(width, template, theme);
}
function repeat(string, width) {
var result = "";
var n = width;
do {
if (n % 2) {
result += string;
}
n = Math.floor(n / 2);
string += string;
} while (n && stringWidth4(result) < width);
return wide_truncate_default(result, width);
}
// libs/core/src/lib/npmlog/gauge/base-theme.ts
var activityIndicator = function(values, theme) {
if (values.spun == null) {
return;
}
return spin(theme, values.spun);
};
var progressbar = function(values, theme, width) {
if (values.completed == null) {
return;
}
return progress_bar_default(theme, width, values.completed);
};
var base_theme_default = {
activityIndicator,
progressbar
};
// libs/core/src/lib/npmlog/gauge/theme-set.ts
function theme_set_default() {
return ThemeSetProto.newThemeSet();
}
var ThemeSetProto = {};
ThemeSetProto.baseTheme = base_theme_default;
ThemeSetProto.newTheme = function(parent, theme) {
if (!theme) {
theme = parent;
parent = this.baseTheme;
}
return Object.assign({}, parent, theme);
};
ThemeSetProto.getThemeNames = function() {
return Object.keys(this.themes);
};
ThemeSetProto.addTheme = function(name, parent, theme) {
this.themes[name] = this.newTheme(parent, theme);
};
ThemeSetProto.addToAllThemes = function(theme) {
var themes2 = this.themes;
Object.keys(themes2).forEach(function(name) {
Object.assign(themes2[name], theme);
});
Object.assign(this.baseTheme, theme);
};
ThemeSetProto.getTheme = function(name) {
if (!this.themes[name]) {
throw this.newMissingThemeError(name);
}
return this.themes[name];
};
ThemeSetProto.setDefault = function(opts, name) {
if (name == null) {
name = opts;
opts = {};
}
var platform = opts.platform == null ? "fallback" : opts.platform;
var hasUnicode4 = !!opts.hasUnicode;
var hasColor = !!opts.hasColor;
if (!this.defaults[platform]) {
this.defaults[platform] = { true: {}, false: {} };
}
this.defaults[platform][hasUnicode4][hasColor] = name;
};
ThemeSetProto.getDefault = function(opts) {
if (!opts) {
opts = {};
}
var platformName = opts.platform || process.platform;
var platform = this.defaults[platformName] || this.defaults.fallback;
var hasUnicode4 = !!opts.hasUnicode;
var hasColor = !!opts.hasColor;
if (!platform) {
throw this.newMissingDefaultThemeError(platformName, hasUnicode4, hasColor);
}
if (!platform[hasUnicode4][hasColor]) {
if (hasUnicode4 && hasColor && platform[!hasUnicode4][hasColor]) {
hasUnicode4 = false;
} else if (hasUnicode4 && hasColor && platform[hasUnicode4][!hasColor]) {
hasColor = false;
} else if (hasUnicode4 && hasColor && platform[!hasUnicode4][!hasColor]) {
hasUnicode4 = false;
hasColor = false;
} else if (hasUnicode4 && !hasColor && platform[!hasUnicode4][hasColor]) {
hasUnicode4 = false;
} else if (!hasUnicode4 && hasColor && platform[hasUnicode4][!hasColor]) {
hasColor = false;
} else if (platform === this.defaults.fallback) {
throw this.newMissingDefaultThemeError(platformName, hasUnicode4, hasColor);
}
}
if (platform[hasUnicode4][hasColor]) {
return this.getTheme(platform[hasUnicode4][hasColor]);
} else {
return this.getDefault(Object.assign({}, opts, { platform: "fallback" }));
}
};
ThemeSetProto.newMissingThemeError = function newMissingThemeError(name) {
var err = new Error('Could not find a gauge theme named "' + name + '"');
Error.captureStackTrace.call(err, newMissingThemeError);
err.theme = name;
err.code = "EMISSINGTHEME";
return err;
};
ThemeSetProto.newMissingDefaultThemeError = function newMissingDefaultThemeError(platformName, hasUnicode4, hasColor) {
var err = new Error(
"Could not find a gauge theme for your platform/unicode/color use combo:\n platform = " + platformName + "\n hasUnicode = " + hasUnicode4 + "\n hasColor = " + hasColor
);
Error.captureStackTrace.call(err, newMissingDefaultThemeError);
err.platform = platformName;
err.hasUnicode = hasUnicode4;
err.hasColor = hasColor;
err.code = "EMISSINGTHEME";
return err;
};
ThemeSetProto.newThemeSet = function() {
var themeset = function(opts) {
return themeset.getDefault(opts);
};
return Object.assign(themeset, ThemeSetProto, {
themes: Object.assign({}, this.themes),
baseTheme: Object.assign({}, this.baseTheme),
defaults: JSON.parse(JSON.stringify(this.defaults || {}))
});
};
// libs/core/src/lib/npmlog/gauge/themes.ts
var themes = new theme_set_default();
var themes_default = themes;
themes.addTheme("ASCII", {
preProgressbar: "[",
postProgressbar: "]",
progressbarTheme: {
complete: "#",
remaining: "."
},
activityIndicatorTheme: "-\\|/",
preSubsection: ">"
});
themes.addTheme("colorASCII", themes.getTheme("ASCII"), {
progressbarTheme: {
preComplete: color("bgBrightWhite", "brightWhite"),
complete: "#",
postComplete: color("reset"),
preRemaining: color("bgBrightBlack", "brightBlack"),
remaining: ".",
postRemaining: color("reset")
}
});
themes.addTheme("brailleSpinner", {
preProgressbar: "(",
postProgressbar: ")",
progressbarTheme: {
complete: "#",
remaining: "\u2802"
},
activityIndicatorTheme: "\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F",
preSubsection: ">"
});
themes.addTheme("colorBrailleSpinner", themes.getTheme("brailleSpinner"), {
progressbarTheme: {
preComplete: color("bgBrightWhite", "brightWhite"),
complete: "#",
postComplete: color("reset"),
preRemaining: color("bgBrightBlack", "brightBlack"),
remaining: "\u2802",
postRemaining: color("reset")
}
});
themes.setDefault({}, "ASCII");
themes.setDefault({ hasColor: true }, "colorASCII");
themes.setDefault({ platform: "darwin", hasUnicode: true }, "brailleSpinner");
themes.setDefault({ platform: "darwin", hasUnicode: true, hasColor: true }, "colorBrailleSpinner");
themes.setDefault({ platform: "linux", hasUnicode: true }, "brailleSpinner");
themes.setDefault({ platform: "linux", hasUnicode: true, hasColor: true }, "colorBrailleSpinner");
// libs/core/src/lib/npmlog/gauge/set-interval.ts
var set_interval_default = setInterval;
// libs/core/src/lib/npmlog/gauge/process.ts
var process_default = process;
// libs/core/src/lib/npmlog/gauge/set-immediate.ts
var exported;
try {
exported = setImmediate;
} catch (ex) {
exported = process_default.nextTick;
}
var set_immediate_default = exported;
// libs/core/src/lib/npmlog/gauge/index.ts
function callWith(obj, method) {
return function() {
return method.call(obj);
};
}
var Gauge = class {
_status;
_paused;
_disabled;
_showing;
_onScreen;
_needsRedraw;
_hideCursor;
_fixedFramerate;
_lastUpdateAt;
_updateInterval;
_themes;
_theme;
_gauge;
_tty;
_writeTo;
_$$doRedraw;
_$$handleSizeChange;
_cleanupOnExit;
_removeOnExit;
redrawTracker;
constructor(arg1, arg2) {
let options, writeTo;
if (arg1 && arg1.write) {
writeTo = arg1;
options = arg2 || {};
} else if (arg2 && arg2.write) {
writeTo = arg2;
options = arg1 || {};
} else {
writeTo = process_default.stderr;
options = arg1 || arg2 || {};
}
this._status = {
spun: 0,
section: "",
subsection: ""
};
this._paused = false;
this._disabled = true;
this._showing = false;
this._onScreen = false;
this._needsRedraw = false;
this._hideCursor = options.hideCursor == null ? true : options.hideCursor;
this._fixedFramerate = options.fixedFramerate == null ? !/^v0\.8\./.test(process_default.version) : options.fixedFramerate;
this._lastUpdateAt = null;
this._updateInterval = options.updateInterval == null ? 50 : options.updateInterval;
this._themes = options.themes || themes_default;
this._theme = options.theme;
const theme = this._computeTheme(options.theme);
const template = options.template || [
{ type: "progressbar", length: 20 },
{ type: "activityIndicator", kerning: 1, length: 1 },
{ type: "section", kerning: 1, default: "" },
{ type: "subsection", kerning: 1, default: "" }
];
this.setWriteTo(writeTo, options.tty);
const PlumbingClass = options.Plumbing || plumbing_default;
this._gauge = new PlumbingClass(theme, template, this.getWidth());
this._$$doRedraw = callWith(this, this._doRedraw);
this._$$handleSizeChange = callWith(this, this._handleSizeChange);
this._cleanupOnExit = options.cleanupOnExit == null || options.cleanupOnExit;
this._removeOnExit = null;
if (options.enabled || options.enabled == null && this._tty && this._tty.isTTY) {
this.enable();
} else {
this.disable();
}
}
isEnabled() {
return !this._disabled;
}
setTemplate(template) {
this._gauge.setTemplate(template);
if (this._showing) {
this._requestRedraw();
}
}
_computeTheme(theme) {
if (!theme) {
theme = {};
}
if (typeof theme === "string") {
theme = this._themes.getTheme(theme);
} else if (Object.keys(theme).length === 0 || theme.hasUnicode != null || theme.hasColor != null) {
const useUnicode = theme.hasUnicode == null ? hasUnicode() : theme.hasUnicode;
const useColor = theme.hasColor == null ? has_color_default : theme.hasColor;
theme = this._themes.getDefault({
hasUnicode: useUnicode,
hasColor: useColor,
platform: theme.platform
});
}
return theme;
}
setThemeset(themes2) {
this._themes = themes2;
this.setTheme(this._theme);
}
setTheme(theme) {
this._gauge.setTheme(this._computeTheme(theme));
if (this._showing) {
this._requestRedraw();
}
this._theme = theme;
}
_requestRedraw() {
this._needsRedraw = true;
if (!this._fixedFramerate) {
this._doRedraw();
}
}
getWidth() {
return (this._tty && this._tty.columns || 80) - 1;
}
setWriteTo(writeTo, tty) {
const enabled2 = !this._disabled;
if (enabled2) {
this.disable();
}
this._writeTo = writeTo;
this._tty = tty || writeTo === process_default.stderr && process_default.stdout.isTTY && process_default.stdout || writeTo.isTTY && writeTo || this._tty;
if (this._gauge) {
this._gauge.setWidth(this.getWidth());
}
if (enabled2) {
this.enable();
}
}
enable() {
if (!this._disabled) {
return;
}
this._disabled = false;
if (this._tty) {
this._enableEvents();
}
if (this._showing) {
this.show();
}
}
disable() {
if (this._disabled) {
return;
}
if (this._showing) {
this._lastUpdateAt = null;
this._showing = false;
this._doRedraw();
this._showing = true;
}
this._disabled = true;
if (this._tty) {
this._disableEvents();
}
}
_enableEvents() {
if (this._cleanupOnExit) {
this._removeOnExit = onExit(callWith(this, this.disable));
}
this._tty.on("resize", this._$$handleSizeChange);
if (this._fixedFramerate) {
this.redrawTracker = set_interval_default(this._$$doRedraw, this._updateInterval);
if (this.redrawTracker.unref) {
this.redrawTracker.unref();
}
}
}
_disableEvents() {
this._tty.removeListener("resize", this._$$handleSizeChange);
if (this._fixedFramerate) {
clearInterval(this.redrawTracker);
}
if (this._removeOnExit) {
this._removeOnExit();
}
}
hide(cb) {
if (this._disabled) {
return cb && process_default.nextTick(cb);
}
if (!this._showing) {
return cb && process_default.nextTick(cb);
}
this._showing = false;
this._doRedraw();
cb && set_immediate_default(cb);
}
show(section, completed) {
this._showing = true;
if (typeof section === "string") {
this._status.section = section;
} else if (typeof section === "object") {
const sectionKeys = Object.keys(section);
for (let ii = 0; ii < sectionKeys.length; ++ii) {
const key = sectionKeys[ii];
this._status[key] = section[key];
}
}
if (completed != null) {
this._status.completed = completed;
}
if (this._disabled) {
return;
}
this._requestRedraw();
}
pulse(subsection) {
this._status.subsection = subsection || "";
this._status.spun++;
if (this._disabled) {
return;
}
if (!this._showing) {
return;
}
this._requestRedraw();
}
_handleSizeChange() {
this._gauge.setWidth(this._tty.columns - 1);
this._requestRedraw();
}
_doRedraw() {
if (this._disabled || this._paused) {
return;
}
if (!this._fixedFramerate) {
const now = Date.now();
if (this._lastUpdateAt && now - this._lastUpdateAt < this._updateInterval) {
return;
}
this._lastUpdateAt = now;
}
if (!this._showing && this._onScreen) {
this._onScreen = false;
let result = this._gauge.hide();
if (this._hideCursor) {
result += this._gauge.showCursor();
}
return this._writeTo.write(result);
}
if (!this._showing && !this._onScreen) {
return;
}
if (this._showing && !this._onScreen) {
this._onScreen = true;
this._needsRedraw = true;
if (this._hideCursor) {
this._writeTo.write(this._gauge.hideCursor());
}
}
if (!this._needsRedraw) {
return;
}
if (!this._writeTo.write(this._gauge.show(this._status))) {
this._paused = true;
this._writeTo.on(
"drain",
callWith(this, function() {
this._paused = false;
this._doRedraw();
})
);
}
}
};
// libs/core/src/lib/npmlog/index.ts
[process.stdout, process.stderr].forEach((stream3) => {
const s = stream3;
if (s._handle && stream3.isTTY && typeof s._handle.setBlocking === "function") {
s._handle.setBlocking(true);
}
});
var Logger2 = class extends EventEmitter2 {
_stream;
_paused;
_buffer;
unicodeEnabled;
colorEnabled;
id;
record;
maxRecordSize;
gauge;
tracker;
progressEnabled;
level;
prefixStyle;
headingStyle;
style;
levels;
disp;
heading;
// Known log levels, assigned dynamically in the constructor
silly;
verbose;
info;
timing;
http;
notice;
warn;
error;
silent;
constructor() {
super();
this._stream = process.stderr;
this._paused = false;
this._buffer = [];
this.unicodeEnabled = false;
this.colorEnabled = void 0;
this.id = 0;
this.record = [];
this.maxRecordSize = 1e4;
this.level = "info";
this.prefixStyle = { fg: "magenta" };
this.headingStyle = { fg: "white", bg: "black" };
this.style = {};
this.levels = {};
this.disp = {};
this.gauge = new Gauge(this._stream, {
enabled: false,
theme: { hasColor: this.useColor() },
template: [
{ type: "progressbar", length: 20 },
{ type: "activityIndicator", kerning: 1, length: 1 },
{ type: "section", default: "" },
":",
{ type: "logline", kerning: 1, default: "" }
]
});
this.tracker = new TrackerGroup();
this.progressEnabled = this.gauge.isEnabled();
this.addLevel("silly", -Infinity, { inverse: true }, "sill");
this.addLevel("verbose", 1e3, { fg: "cyan", bg: "black" }, "verb");
this.addLevel("info", 2e3, { fg: "green" });
this.addLevel("timing", 2500, { fg: "green", bg: "black" });
this.addLevel("http", 3e3, { fg: "green", bg: "black" });
this.addLevel("notice", 3500, { fg: "cyan", bg: "black" });
this.addLevel("warn", 4e3, { fg: "black", bg: "yellow" }, "WARN");
this.addLevel("error", 5e3, { fg: "red", bg: "black" }, "ERR!");
this.addLevel("silent", Infinity);
this.on("error", () => {
});
}
get stream() {
return this._stream;
}
set stream(newStream) {
this._stream = newStream;
if (this.gauge) {
this.gauge.setWriteTo(this._stream, this._stream);
}
}
useColor() {
return this.colorEnabled != null ? this.colorEnabled : this._stream?.isTTY ?? false;
}
enableColor() {
this.colorEnabled = true;
this.gauge.setTheme({ hasColor: this.colorEnabled, hasUnicode: this.unicodeEnabled });
}
disableColor() {
this.colorEnabled = false;
this.gauge.setTheme({ hasColor: this.colorEnabled, hasUnicode: this.unicodeEnabled });
}
enableUnicode() {
this.unicodeEnabled = true;
this.gauge.setTheme({ hasColor: this.useColor(), hasUnicode: this.unicodeEnabled });
}
disableUnicode() {
this.unicodeEnabled = false;
this.gauge.setTheme({ hasColor: this.useColor(), hasUnicode: this.unicodeEnabled });
}
setGaugeThemeset(themes2) {
this.gauge.setThemeset(themes2);
}
setGaugeTemplate(template) {
this.gauge.setTemplate(template);
}
enableProgress() {
if (this.progressEnabled || this._paused) {
return;
}
this.progressEnabled = true;
this.tracker.on("change", this.showProgress.bind(this));
this.gauge.enable();
}
disableProgress() {
if (!this.progressEnabled) {
return;
}
this.progressEnabled = false;
this.tracker.removeListener("change", this.showProgress.bind(this));
this.gauge.disable();
}
clearProgress(cb) {
if (!this.progressEnabled) {
return cb && process.nextTick(cb);
}
this.gauge.hide(cb);
}
showProgress(name, completed) {
if (!this.progressEnabled) {
return;
}
const values = {};
if (name) {
values.section = name;
}
const last = this.record[this.record.length - 1];
if (last) {
values.subsection = last.prefix;
const disp = this.disp[last.level];
let logline = this._format(disp, this.style[last.level]);
if (last.prefix) {
logline += " " + this._format(last.prefix, this.prefixStyle);
}
logline += " " + last.message.split(/\r?\n/)[0];
values.logline = logline;
}
values.completed = completed || this.tracker.completed();
this.gauge.show(values);
}
pause() {
this._paused = true;
if (this.progressEnabled) {
this.gauge.disable();
}
}
resume() {
if (!this._paused) {
return;
}
this._paused = false;
const buffer = this._buffer;
this._buffer = [];
buffer.forEach((m) => this.emitLog(m));
if (this.progressEnabled) {
this.gauge.enable();
}
}
log(lvl, prefix2, ...messageArgs) {
const l = this.levels[lvl];
if (l === void 0) {
this.emit("error", new Error(util4.format("Undefined log level: %j", lvl)));
return;
}
let stack = null;
const a = messageArgs.map((arg) => {
if (arg instanceof Error && arg.stack) {
Object.defineProperty(arg, "stack", {
value: stack = arg.stack + "",
enumerable: true,
writable: true
});
}
return arg;
});
if (stack) {
a.unshift(stack + "\n");
}
const message = util4.format(...a);
const m = {
id: this.id++,
level: lvl,
prefix: String(prefix2 || ""),
message,
messageRaw: a
};
this.emit("log", m);
this.emit(`log.${lvl}`, m);
if (m.prefix) {
this.emit(m.prefix, m);
}
this.record.push(m);
const mrs = this.maxRecordSize;
if (this.record.length > mrs) {
this.record = this.record.slice(-Math.floor(mrs * 0.9));
}
this.emitLog(m);
}
emitLog(m) {
if (this._paused) {
this._buffer.push(m);
return;
}
if (this.progressEnabled) {
this.gauge.pulse(m.prefix);
}
const l = this.levels[m.level];
if (l === void 0 || l < this.levels[this.level] || l > 0 && !isFinite(l)) {
return;
}
const disp = this.disp[m.level];
this.clearProgress();
m.message?.split(/\r?\n/).forEach((line) => {
const heading = this.heading;
if (heading) {
this.write(heading, this.headingStyle);
this.write(" ");
}
this.write(disp, this.style[m.level]);
const p = m.prefix || "";
if (p) {
this.write(" ");
}
this.write(p, this.prefixStyle);
this.write(" " + line + "\n");
});
this.showProgress();
}
_format(msg, style) {
if (!this._stream) {
return;
}
let output2 = "";
if (this.useColor()) {
style = style || {};
const settings = [];
if (style.fg) settings.push(style.fg);
if (style.bg) settings.push("bg" + style.bg[0].toUpperCase() + style.bg.slice(1));
if (style.bold) settings.push("bold");
if (style.underline) settings.push("underline");
if (style.inverse) settings.push("inverse");
if (settings.length) output2 += color(settings);
if (style.beep) output2 += beep();
}
output2 += msg;
if (this.useColor()) output2 += color("reset");
return output2;
}
write(msg, style) {
if (!this._stream) {
return;
}
this._stream.write(this._format(msg, style));
}
addLevel(lvl, n, style, disp = null) {
if (disp == null) {
disp = lvl;
}
this.levels[lvl] = n;
this.style[lvl] = style;
if (!this[lvl]) {
this[lvl] = (...args) => {
const a = [lvl, ...args];
return this.log.apply(this, a);
};
}
this.disp[lvl] = disp;
}
};
var log = new Logger2();
var trackerConstructors = ["newGroup", "newItem", "newStream"];
var mixinLog = function(tracker) {
Array.from(
/* @__PURE__ */ new Set([...Object.keys(log), ...Object.getOwnPropertyNames(Object.getPrototypeOf(log))])
).forEach(function(P) {
if (P[0] === "_") {
return;
}
if (trackerConstructors.filter(function(C) {
return C === P;
}).length) {
return;
}
if (tracker[P]) {
return;
}
if (typeof log[P] !== "function") {
return;
}
const func = log[P];
tracker[P] = function() {
return func.apply(log, arguments);
};
});
if (tracker instanceof TrackerGroup) {
trackerConstructors.forEach(function(C) {
const func = tracker[C];
tracker[C] = function() {
return mixinLog(func.apply(tracker, arguments));
};
});
}
return tracker;
};
trackerConstructors.forEach(function(C) {
log[C] = function() {
return mixinLog(this.tracker[C].apply(this.tracker, arguments));
};
});
var npmlog_default = log;
// libs/core/src/lib/describe-ref.ts
function getArgs(options, includeMergedTags = false) {
let args = [
"describe",
// fallback to short sha if no tags located
"--always",
// always return full result, helps identify existing release
"--long",
// annotate if uncommitted changes present
"--dirty",
// prefer tags originating on upstream branch
"--first-parent"
];
if (options.match) {
args.push("--match", options.match);
}
if (includeMergedTags) {
args = args.filter((arg) => arg !== "--first-parent");
}
return args;
}
function describeRef(options = {}, includeMergedTags) {
const promise = exec("git", getArgs(options, includeMergedTags), options);
return promise.then(({ stdout }) => {
const result = parse(stdout, options.cwd, options.separator);
npmlog_default.verbose("git-describe", "%j => %j", options && options.match, stdout);
npmlog_default.silly("git-describe", "parsed => %j", result);
return result;
});
}
function describeRefSync(options = {}, includeMergedTags) {
const stdout = execSync("git", getArgs(options, includeMergedTags), options);
const result = parse(stdout, options.cwd, options.separator);
npmlog_default.silly("git-describe.sync", "%j => %j", stdout, result);
return result;
}
function parse(stdout, cwd, separator) {
separator = separator || "@";
const minimalShaRegex = /^([0-9a-f]{7,40})(-dirty)?$/;
if (minimalShaRegex.test(stdout)) {
const [, sha2, isDirty2] = minimalShaRegex.exec(stdout);
const refCount2 = execSync("git", ["rev-list", "--count", sha2], { cwd });
return { refCount: refCount2, sha: sha2, isDirty: Boolean(isDirty2) };
}
const escapedSeparator = separator.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const regexPattern = new RegExp(`^((?:.*${escapedSeparator})?(.*))-(\\d+)-g([0-9a-f]+)(-dirty)?$`);
const [, lastTagName, lastVersion, refCount, sha, isDirty] = regexPattern.exec(stdout) || [];
return { lastTagName, lastVersion, refCount, sha, isDirty: Boolean(isDirty) };
}
// libs/core/src/lib/validation-error.ts
var ValidationError = class extends Error {
prefix;
constructor(prefix2, message, ...rest) {
super(message);
this.name = "ValidationError";
this.prefix = prefix2;
npmlog_default.resume();
npmlog_default.error(prefix2, message, ...rest);
}
};
// libs/core/src/lib/collect-uncommitted.ts
var maybeColorize = (format) => (s) => s !== " " ? colorize(format, String(s)) : s;
var cRed = maybeColorize("red");
var cGreen = maybeColorize("green");
var replaceStatus = (_, maybeGreen, maybeRed) => `${cGreen(maybeGreen)}${cRed(maybeRed)}`;
var colorizeStats = (stats) => stats.replace(/^([^U]| )([A-Z]| )/gm, replaceStatus).replace(/^\?{2}|U{2}/gm, cRed("$&"));
var splitOnNewLine = (str) => str.split("\n");
var filterEmpty = (lines) => lines.filter((line) => line.length);
var o = (l, r) => (x) => l(r(x));
var transformOutput = o(filterEmpty, o(splitOnNewLine, colorizeStats));
function collectUncommitted({ cwd, log: log2 = npmlog_default }) {
log2.silly("collect-uncommitted", "git status --porcelain (async)");
return exec("git", ["status", "--porcelain"], { cwd }).then(({ stdout }) => transformOutput(stdout));
}
// libs/core/src/lib/check-working-tree.ts
function checkWorkingTree({ cwd } = {}) {
let chain = Promise.resolve();
chain = chain.then(() => describeRef({ cwd }));
const tests = [
// prevent duplicate versioning
chain.then(throwIfReleased),
// prevent publish of uncommitted changes
chain.then(mkThrowIfUncommitted({ cwd }))
];
return chain.then((result) => Promise.all(tests).then(() => result));
}
function throwIfReleased({ refCount }) {
if (refCount === "0") {
throw new ValidationError(
"ERELEASED",
"The current commit has already been released. Please make new commits before continuing."
);
}
}
var EUNCOMMIT_MSG = "Working tree has uncommitted changes, please commit or remove the following changes before continuing:\n";
function mkThrowIfUncommitted(options = {}) {
return function throwIfUncommitted2(opts) {
if (opts.isDirty) {
return collectUncommitted(options).then((uncommitted) => {
throw new ValidationError("EUNCOMMIT", `${EUNCOMMIT_MSG}${uncommitted.join("\n")}`);
});
}
};
}
var throwIfUncommitted = mkThrowIfUncommitted();
// libs/core/src/lib/cli.ts
import dedent from "dedent";
import os4 from "node:os";
import yargs from "yargs";
process.env["NX_ISOLATE_PLUGINS"] = "false";
process.env["NX_TUI"] = "false";
process.env["npm_config_legacy_peer_deps"] ??= "false";
function lernaCLI(argv, cwd) {
const cli = yargs(argv, cwd);
return globalOptions(cli).usage("Usage: $0 <command> [options]").demandCommand(1, "A command is required. Pass --help to see all available commands and options.").recommendCommands().strict().fail((msg, err) => {
const actual = err || new Error(msg);
if (actual.name !== "ValidationError" && !actual.pkg) {
if (/Did you mean/.test(actual.message)) {
npmlog_default.error("lerna", `Unknown command "${cli.parsed.argv._[0]}"`);
}
npmlog_default.error("lerna", actual.message);
}
cli.exit(actual.exitCode > 0 ? actual.exitCode : 1, actual);
}).alias("h", "help").alias("v", "version").wrap(cli.terminalWidth()).epilogue(dedent`
When a command fails, all logs are written to lerna-debug.log in the current working directory.
For more information, check out the docs at https://lerna.js.org/docs/introduction
`);
}
function globalOptions(argv) {
const opts = {
loglevel: {
defaultDescription: "info",
describe: "What level of logs to report.",
type: "string"
},
concurrency: {
defaultDescription: String(os4.cpus().length),
describe: "How many processes to use when lerna parallelizes tasks.",
type: "number",
requiresArg: true
},
"reject-cycles": {
describe: "Fail if a cycle is detected among dependencies.",
type: "boolean"
},
"no-progress": {
describe: "Disable progress bars. (Always off in CI)",
type: "boolean"
},
progress: {
// proxy for --no-progress
hidden: true,
type: "boolean"
},
"no-sort": {
describe: "Do not sort packages topologically (dependencies before dependents).",
type: "boolean"
},
sort: {
// proxy for --no-sort
hidden: true,
type: "boolean"
},
"max-buffer": {
describe: "Set max-buffer (in bytes) for subcommand execution",
type: "number",
requiresArg: true
}
};
const globalKeys = Object.keys(opts).concat(["help", "version"]);
return argv.options(opts).group(globalKeys, "Global Options:").option("ci", {
hidden: true,
type: "boolean"
});
}
// libs/core/src/lib/get-packages-for-option.ts
function getPackagesForOption(option) {
let inputs = null;
if (option === true) {
inputs = ["*"];
} else if (typeof option === "string") {
inputs = option.split(",");
} else if (Array.isArray(option)) {
inputs = [...option];
}
return new Set(inputs);
}
// libs/core/src/lib/prerelease-id-from-version.ts
import semver from "semver";
function prereleaseIdFromVersion(version) {
return (semver.prerelease(version) || []).shift();
}
// libs/core/src/lib/project-graph-with-packages.ts
var isExternalNpmDependency = (dep) => dep.startsWith("npm:");
function getPackage(project) {
if (!project.package) {
throw new Error(`Failed attempting to find package for project ${project.name}`);
}
return project.package;
}
// libs/core/src/lib/slash.ts
function slash(path23) {
const isExtendedLengthPath = path23.startsWith("\\\\?\\");
if (isExtendedLengthPath) {
return path23;
}
return path23.replace(/\\/g, "/");
}
// libs/core/src/lib/collect-updates/has-tags.ts
function hasTags(opts) {
npmlog_default.silly("hasTags");
let result = false;
try {
result = !!execSync("git", ["tag"], opts);
} catch (err) {
npmlog_default.warn("ENOTAGS", "No git tags were reachable from this branch!");
npmlog_default.verbose("hasTags error", err);
}
npmlog_default.verbose("hasTags", result);
return result;
}
// libs/core/src/lib/collect-updates/make-diff-predicate.ts
import minimatch from "minimatch";
import { relative } from "path";
function makeDiffPredicate(committish, execOpts, ignorePatterns = []) {
const ignoreFilters = new Set(
ignorePatterns.map(
(p) => minimatch.filter(`!${p}`, {
matchBase: true,
// dotfiles inside ignored directories should also match
dot: true
})
)
);
if (ignoreFilters.size) {
npmlog_default.info("ignoring diff in paths matching", ignorePatterns);
}
return function hasDiffSinceThatIsntIgnored(node) {
const diff = diffSinceIn(committish, getPackage(node).location, execOpts);
if (diff === "") {
npmlog_default.silly("", "no diff found in %s", node.name);
return false;
}
npmlog_default.silly("found diff in", diff);
let changedFiles = diff.split("\n");
if (ignoreFilters.size) {
for (const ignored of ignoreFilters) {
changedFiles = changedFiles.filter(ignored);
}
}
if (changedFiles.length) {
npmlog_default.verbose("filtered diff", changedFiles);
} else {
npmlog_default.verbose("", "no diff found in %s (after filtering)", node.name);
}
return changedFiles.length > 0;
};
}
function diffSinceIn(committish, location, opts) {
const args = ["diff", "--name-only", committish];
const formattedLocation = slash(relative(opts.cwd, location));
if (formattedLocation) {
args.push("--", formattedLocation);
}
npmlog_default.silly("checking diff", formattedLocation);
return execSync("git", args, opts);
}
// libs/core/src/lib/collect-updates/collect-project-updates.ts
function collectProjectUpdates(filteredProjects, projectGraph, execOpts, commandOptions) {
const {
forcePublish,
conventionalCommits,
forceConventionalGraduate,
conventionalGraduate,
excludeDependents,
tagVersionSeparator
} = commandOptions;
const useConventionalGraduate = conventionalCommits && (conventionalGraduate || forceConventionalGraduate);
const forced = getPackagesForOption(useConventionalGraduate ? conventionalGraduate : forcePublish);
let committish = commandOptions.since ?? "";
if (hasTags(execOpts)) {
const { sha, refCount, lastTagName } = describeRefSync(
{ ...execOpts, separator: tagVersionSeparator },
commandOptions.includeMergedTags
);
if (refCount === "0" && forced.size === 0 && !committish) {
npmlog_default.notice("", "Current HEAD is already released, skipping change detection.");
return [];
}
if (commandOptions.canary) {
committish = `${sha}^..${sha}`;
} else if (!committish) {
committish = lastTagName;
}
}
if (forced.size) {
npmlog_default.warn(
useConventionalGraduate ? "conventional-graduate" : "force-publish",
forced.has("*") ? "all packages" : Array.from(forced.values()).join("\n")
);
}
if (useConventionalGraduate) {
if (forced.has("*")) {
npmlog_default.info("", "Graduating all prereleased packages");
} else {
npmlog_default.info("", "Graduating prereleased packages");
}
} else if (!committish || forced.has("*")) {
npmlog_default.info("", "Assuming all packages changed");
return collectProjects(filteredProjects, projectGraph, {
onInclude: (name) => npmlog_default.verbose("updated", name),
excludeDependents
});
}
npmlog_default.info("", `Looking for changed packages since ${committish}`);
const hasDiff = makeDiffPredicate(committish, execOpts, commandOptions.ignoreChanges);
const needsBump = !commandOptions.bump || commandOptions.bump.startsWith("pre") ? () => false : (
/* skip packages that have not been previously prereleased */
(node) => !!prereleaseIdFromVersion(getPackage(node).version)
);
const isForced = (node, name) => !!((forced.has("*") || forced.has(name)) && ((useConventionalGraduate ? prereleaseIdFromVersion(getPackage(node).version) : true) || forceConventionalGraduate));
return collectProjects(filteredProjects, projectGraph, {
isCandidate: (node, name) => isForced(node, name) || needsBump(node) || hasDiff(node),
onInclude: (name) => npmlog_default.verbose("updated", name),
excludeDependents
});
}
function collectProjects(projects, projectGraph, { isCandidate = () => true, onInclude, excludeDependents } = {}) {
const candidates = {};
projects.forEach((node) => {
if (isCandidate(node, getPackage(node).name)) {
candidates[node.name] = node;
}
});
if (!excludeDependents) {
collectDependents(candidates, projectGraph).forEach((node) => candidates[node.name] = node);
}
const updates = [];
projects.forEach((node) => {
if (candidates[node.name]) {
if (onInclude) {
onInclude(getPackage(node).name);
}
updates.push(node);
}
});
return updates;
}
function collectDependents(nodes, projectGraph) {
const dependents = Object.values(projectGraph.localPackageDependencies).flat().reduce(
(prev, next) => ({
...prev,
[next.target]: [...prev[next.target] || [], next.source]
}),
{}
);
const collected = /* @__PURE__ */ new Set();
Object.values(nodes).forEach((currentNode) => {
if (dependents[currentNode.name] && dependents[currentNode.name].length === 0) {
return;
}
const queue2 = [currentNode];
const seen = /* @__PURE__ */ new Set();
while (queue2.length) {
const node = queue2.shift();
dependents[node.name]?.forEach((dep) => {
if (seen.has(dep)) {
return;
}
seen.add(dep);
if (dep === currentNode.name || nodes[dep]) {
return;
}
const dependentNode = projectGraph.nodes[dep];
collected.add(dependentNode);
queue2.push(dependentNode);
});
}
});
return collected;
}
// libs/core/src/lib/command/is-git-initialized.ts
import execa2 from "execa";
function isGitInitialized(cwd) {
const opts = {
cwd,
// don't throw, just want boolean
reject: false,
// only return code, no stdio needed
stdio: "ignore"
};
return execa2.sync("git", ["rev-parse"], opts).exitCode === 0;
}
// libs/core/src/lib/command/index.ts
import { isCI } from "ci-info";
import dedent3 from "dedent";
import { daemonClient } from "nx/src/daemon/client/client";
import os7 from "os";
// libs/core/src/lib/project/index.ts
import { parseJson, writeJsonFile } from "@nx/devkit";
import { cosmiconfigSync, defaultLoaders } from "cosmiconfig";
import dedent2 from "dedent";
import fs2 from "fs";
// libs/core/src/lib/glob-utils/glob-parent.ts
import os5 from "os";
import path from "path";
// libs/core/src/lib/glob-utils/is-extglob.ts
function isExtglob(str) {
if (str === "") return false;
const regex = /(\\).|([@?!+*]\(.*\))/g;
let match;
let remaining = str;
while (match = regex.exec(remaining)) {
if (match[2]) return true;
remaining = remaining.slice(match.index + match[0].length);
regex.lastIndex = 0;
}
return false;
}
// libs/core/src/lib/glob-utils/is-glob.ts
var strictRegex = /\\(.)|(^!|[*?]|[\].+)]\?|\[[^\\\]]+\]|\{[^\\}]+\}|\(\?[:!=][^\\)]+\))/;
function isGlob(str) {
if (str === "") return false;
if (isExtglob(str)) return true;
const match = strictRegex.exec(str);
if (match) {
return !match[1];
}
return false;
}
// libs/core/src/lib/glob-utils/glob-parent.ts
var slash2 = "/";
var backslash = /\\/g;
var enclosure = /[{[].*[}\]]$/;
var globby = /(^|[^\\])([{[]|\([^)]+$)/;
var escaped = /\\([!*?|[\](){}])/g;
function globParent(str) {
const isWin32 = os5.platform() === "win32";
if (isWin32 && !str.includes(slash2)) {
str = str.replace(backslash, slash2);
}
if (enclosure.test(str)) {
str += slash2;
}
str += "a";
do {
str = path.posix.dirname(str);
} while (isGlob(str) || globby.test(str));
return str.replace(escaped, "$1");
}
// libs/core/src/lib/project/index.ts
import { globSync as globSync2 } from "tinyglobby";
import { load } from "js-yaml";
import loadJsonFile2 from "load-json-file";
import pMap2 from "p-map";
import path6 from "path";
// libs/core/src/lib/package.ts
import { workspaceRoot } from "@nx/devkit";
import fs from "fs";
import loadJsonFile from "load-json-file";
import npa from "npm-package-arg";
import path3 from "path";
// libs/core/src/lib/write-package.ts
import { readFile, writeFile } from "node:fs/promises";
import path2 from "path";
var dependencyKeys = /* @__PURE__ */ new Set([
"dependencies",
"devDependencies",
"optionalDependencies",
"peerDependencies"
]);
function sortObjectKeys(obj) {
const sorted = {};
for (const key of Object.keys(obj).sort()) {
sorted[key] = obj[key];
}
return sorted;
}
function normalize(data) {
const result = {};
for (const key of Object.keys(data)) {
if (dependencyKeys.has(key) && data[key] && typeof data[key] === "object") {
result[key] = sortObjectKeys(data[key]);
} else {
result[key] = data[key];
}
}
return result;
}
function detectIndent(content) {
const match = content.match(/^[ \t]+/m);
return match ? match[0] : " ";
}
async function writePackage(filePath, data) {
const resolvedPath = path2.basename(filePath) === "package.json" ? filePath : path2.join(filePath, "package.json");
const normalized = normalize(data);
let indent = " ";
try {
const existing = await readFile(resolvedPath, "utf8");
indent = detectIndent(existing);
} catch {
}
const json2 = JSON.stringify(normalized, null, indent) + "\n";
await writeFile(resolvedPath, json2);
}
// libs/core/src/lib/package.ts
var PKG = /* @__PURE__ */ Symbol("pkg");
var _location = /* @__PURE__ */ Symbol("location");
var _resolved = /* @__PURE__ */ Symbol("resolved");
var _rootPath = /* @__PURE__ */ Symbol("rootPath");
var _scripts = /* @__PURE__ */ Symbol("scripts");
var _contents = /* @__PURE__ */ Symbol("contents");
function binSafeName({ name, scope }) {
return scope ? name.substring(scope.length + 1) : name;
}
function shallowCopy(json2) {
return Object.keys(json2).reduce((obj, key) => {
const val = json2[key];
if (Array.isArray(val)) {
obj[key] = val.slice();
} else if (val && typeof val === "object") {
obj[key] = Object.assign({}, val);
} else {
obj[key] = val;
}
return obj;
}, {});
}
var Package = class _Package {
name;
[PKG];
[_location];
[_resolved];
[_rootPath];
[_scripts];
[_contents];
licensePath;
packed;
/**
* Create a Package instance from parameters, possibly reusing existing instance.
* @param ref A path to a package.json file, Package instance, or JSON object
* @param [dir] If `ref` is a JSON object, this is the location of the manifest
*/
static lazy(ref, dir = ".") {
if (typeof ref === "string") {
const location = path3.resolve(path3.basename(ref) === "package.json" ? path3.dirname(ref) : ref);
const manifest = loadJsonFile.sync(path3.join(location, "package.json"));
return new _Package(manifest, location);
}
if ("__isLernaPackage" in ref) {
return ref;
}
return new _Package(ref, dir);
}
constructor(pkg, location, rootPath = location) {
const resolved = npa.resolve(pkg.name, `file:${path3.relative(rootPath, location)}`, rootPath);
this.name = pkg.name;
this[PKG] = pkg;
Object.defineProperty(this, PKG, { enumerable: false, writable: true });
this[_location] = location;
this[_resolved] = resolved;
this[_rootPath] = rootPath;
this[_scripts] = { ...pkg.scripts };
}
// readonly getters
get location() {
return this[_location];
}
get private() {
return Boolean(this[PKG].private);
}
set private(isPrivate) {
this[PKG].private = isPrivate;
}
get resolved() {
return this[_resolved];
}
get rootPath() {
return this[_rootPath];
}
get scripts() {
return this[_scripts];
}
get lernaConfig() {
return this[PKG].lerna;
}
set lernaConfig(config) {
this[PKG].lerna = config;
}
get bin() {
const pkg = this[PKG];
return typeof pkg.bin === "string" ? {
// See note on function implementation
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
[binSafeName(this.resolved)]: pkg.bin
} : Object.assign({}, pkg.bin);
}
get binLocation() {
return path3.join(this.location, "node_modules", ".bin");
}
get manifestLocation() {
return path3.join(this.location, "package.json");
}
get nodeModulesLocation() {
return path3.join(this.location, "node_modules");
}
get __isLernaPackage() {
return true;
}
// accessors
get version() {
return this[PKG].version;
}
set version(version) {
this[PKG].version = version;
}
get contents() {
if (this[_contents]) {
return this[_contents];
}
const publishConfig = this[PKG].publishConfig;
if (publishConfig && publishConfig.directory) {
return path3.join(this.location, publishConfig.directory);
}
return this.location;
}
set contents(subDirectory) {
const _workspaceRoot = process.env["NX_WORKSPACE_ROOT_PATH"] || workspaceRoot;
if (subDirectory.startsWith(_workspaceRoot)) {
this[_contents] = subDirectory;
return;
}
this[_contents] = path3.join(this.location, subDirectory);
}
// "live" collections
get dependencies() {
return this[PKG].dependencies;
}
get devDependencies() {
return this[PKG].devDependencies;
}
get optionalDependencies() {
return this[PKG].optionalDependencies;
}
get peerDependencies() {
return this[PKG].peerDependencies;
}
/**
* Map-like retrieval of arbitrary values
*/
get(key) {
return this[PKG][key];
}
/**
* Map-like storage of arbitrary values
*/
set(key, val) {
this[PKG][key] = val;
return this;
}
/**
* Provide shallow copy for munging elsewhere
*/
toJSON() {
return shallowCopy(this[PKG]);
}
/**
* Refresh internal state from disk (e.g., changed by external lifecycles)
*/
refresh() {
return loadJsonFile(this.manifestLocation).then((pkg) => {
this[PKG] = pkg;
return this;
});
}
/**
* Write manifest changes to disk
* @returns {Promise} resolves when write finished
*/
serialize() {
return writePackage(this.manifestLocation, this[PKG]).then(() => this);
}
/**
* Sync dist manifest version
*/
async syncDistVersion(doSync) {
if (doSync) {
const distPkg = path3.join(this.contents, "package.json");
if (distPkg !== this.manifestLocation && fs.existsSync(distPkg)) {
const pkg = await loadJsonFile(distPkg);
pkg.version = this[PKG].version;
await writePackage(distPkg, pkg);
}
}
return this;
}
getLocalDependency(depName) {
if (this.dependencies && this.dependencies[depName]) {
return {
collection: "dependencies",
spec: this.dependencies[depName]
};
}
if (this.devDependencies && this.devDependencies[depName]) {
return {
collection: "devDependencies",
spec: this.devDependencies[depName]
};
}
if (this.optionalDependencies && this.optionalDependencies[depName]) {
return {
collection: "optionalDependencies",
spec: this.optionalDependencies[depName]
};
}
if (this.peerDependencies && this.peerDependencies[depName]) {
const spec = this.peerDependencies[depName];
const collection = "peerDependencies";
const FILE_PROTOCOL = "file:";
const WORKSPACE_PROTOCOL = "workspace:";
if (spec.startsWith(WORKSPACE_PROTOCOL)) {
const token = spec.substring(WORKSPACE_PROTOCOL.length);
switch (token) {
case "*": {
return { collection, spec };
}
case "^": {
return { collection, spec };
}
case "~": {
return { collection, spec };
}
default: {
return { collection, spec };
}
}
}
if (spec.startsWith(FILE_PROTOCOL)) {
return null;
}
}
return null;
}
/**
* Mutate local dependency spec according to type
* @param resolved npa metadata
* @param depVersion semver
* @param savePrefix npm_config_save_prefix
* @param options
*/
updateLocalDependency(resolved, depVersion, savePrefix, options = { eraseWorkspacePrefix: false }) {
const depName = resolved.name;
let depCollection = this.dependencies;
if (!depCollection || !depCollection[depName]) {
depCollection = this.optionalDependencies;
}
if (!depCollection || !depCollection[depName]) {
depCollection = this.devDependencies;
}
if (!depCollection || !depCollection[depName]) {
depCollection = this.peerDependencies;
}
if (!depCollection) {
throw new Error(`${JSON.stringify(depName)} should exist in some dependency collection.`);
}
const workspaceSpec = resolved.workspaceSpec;
const workspaceAlias = resolved.workspaceAlias;
const gitCommittish = resolved.gitCommittish;
if (workspaceSpec) {
if (options.eraseWorkspacePrefix) {
if (workspaceAlias) {
const prefix2 = workspaceAlias === "*" ? "" : workspaceAlias;
depCollection[depName] = `${prefix2}${depVersion}`;
} else {
const semverRange = workspaceSpec.substring("workspace:".length);
depCollection[depName] = semverRange;
}
} else {
if (!workspaceAlias) {
const matches = workspaceSpec.match(/^(workspace:[*~^]?)/);
const workspacePrefix = matches[0];
depCollection[depName] = `${workspacePrefix}${depVersion}`;
}
}
} else if (resolved.registry || resolved.type === "directory") {
depCollection[depName] = `${savePrefix}${depVersion}`;
} else if (gitCommittish) {
const [tagPrefix] = /^\D*/.exec(gitCommittish);
const { hosted } = resolved;
hosted.committish = `${tagPrefix}${depVersion}`;
depCollection[depName] = hosted.toString({ noGitPlus: false, noCommittish: false });
} else if (resolved.gitRange) {
const { hosted } = resolved;
hosted.committish = `semver:${savePrefix}${depVersion}`;
depCollection[depName] = hosted.toString({ noGitPlus: false, noCommittish: false });
}
}
/**
* Remove the private property, effectively making the package public.
*/
removePrivate() {
delete this[PKG].private;
}
};
// libs/core/src/lib/project/apply-extends.ts
import { createRequire } from "node:module";
import path4 from "path";
// libs/core/src/lib/project/shallow-extend.ts
function shallowExtend(json2, defaults2 = {}) {
return Object.keys(json2).reduce((obj, key) => {
const val = json2[key];
if (Array.isArray(val)) {
obj[key] = val.slice();
} else if (val && typeof val === "object") {
obj[key] = shallowExtend(val, obj[key]);
} else {
obj[key] = val;
}
return obj;
}, defaults2);
}
// libs/core/src/lib/project/apply-extends.ts
var require2 = createRequire(import.meta.url);
function applyExtends(config, cwd, seen = /* @__PURE__ */ new Set()) {
let defaultConfig = {};
if ("extends" in config) {
let pathToDefault;
try {
pathToDefault = require2.resolve(config.extends, { paths: [cwd] });
} catch (err) {
throw new ValidationError("ERESOLVED", "Config .extends must be locally-resolvable", err);
}
if (seen.has(pathToDefault)) {
throw new ValidationError("ECIRCULAR", "Config .extends cannot be circular", seen);
}
seen.add(pathToDefault);
defaultConfig = require2(pathToDefault);
delete config.extends;
defaultConfig = applyExtends(defaultConfig, path4.dirname(pathToDefault), seen);
}
return shallowExtend(config, defaultConfig);
}
// libs/core/src/lib/project/make-file-finder.ts
import { glob, globSync } from "tinyglobby";
import pMap from "p-map";
import path5 from "path";
function normalize2(results) {
return results.map((fp) => path5.normalize(fp));
}
function getGlobOpts(rootPath, packageConfigs) {
const globOpts = {
cwd: rootPath,
absolute: true,
expandDirectories: false,
followSymbolicLinks: false
};
if (packageConfigs.some((cfg) => cfg.indexOf("**") > -1)) {
if (packageConfigs.some((cfg) => cfg.indexOf("node_modules") > -1)) {
throw new ValidationError(
"EPKGCONFIG",
"An explicit node_modules package path does not allow globstars (**)"
);
}
globOpts.ignore = [
// allow globs like "packages/**",
// but avoid picking up node_modules/**/package.json
"**/node_modules/**"
];
}
return globOpts;
}
function makeFileFinder(rootPath, packageConfigs) {
const globOpts = getGlobOpts(rootPath, packageConfigs);
return (fileName, fileMapper, customGlobOpts) => {
const options = Object.assign({}, customGlobOpts, globOpts);
const promise = pMap(
Array.from(packageConfigs).sort(),
(globPath) => {
let chain = glob(path5.posix.join(globPath, fileName), options);
chain = chain.then((results) => results.sort());
chain = chain.then(normalize2);
if (fileMapper) {
chain = chain.then(fileMapper);
}
return chain;
},
{ concurrency: 4 }
);
return promise.then((results) => results.reduce((acc, result) => acc.concat(result), []));
};
}
function makeSyncFileFinder(rootPath, packageConfigs) {
const globOpts = getGlobOpts(rootPath, packageConfigs);
return (fileName, fileMapper) => {
const patterns = packageConfigs.map((globPath) => path5.posix.join(globPath, fileName)).sort();
let results = globSync(patterns, globOpts);
results = normalize2(results);
return results.map((res) => fileMapper(res));
};
}
// libs/core/src/lib/project/index.ts
var LICENSE_GLOB = "LICEN{S,C}E{,.*}";
var Project = class _Project {
config;
configNotFound;
rootConfigLocation;
rootPath;
packageConfigs;
manifest;
/**
* @deprecated Only used in legacy core utilities
* TODO: remove in v8
*/
static getPackages(cwd) {
return new _Project(cwd).getPackages();
}
/**
* @deprecated Only used in legacy core utilities
* TODO: remove in v8
*/
static getPackagesSync(cwd) {
return new _Project(cwd).getPackagesSync();
}
constructor(cwd, options) {
const { config, configNotFound, filepath } = this.#resolveLernaConfig(cwd);
this.config = config;
this.configNotFound = configNotFound || false;
this.rootConfigLocation = filepath;
this.rootPath = path6.dirname(filepath);
this.manifest = this.#resolveRootPackageJson();
if (this.configNotFound) {
throw new ValidationError("ENOLERNA", "`lerna.json` does not exist, have you run `lerna init`?");
}
if (!options?.skipLernaConfigValidations) {
this.#validateLernaConfig(config);
}
this.packageConfigs = this.#resolvePackageConfigs();
npmlog_default.verbose("rootPath", this.rootPath);
}
get version() {
return this.config.version;
}
set version(val) {
this.config.version = val;
}
get packageParentDirs() {
return this.packageConfigs.map((packagePattern) => globParent(packagePattern)).map((parentDir) => path6.resolve(this.rootPath, parentDir));
}
get licensePath() {
let licensePath;
try {
const search = globSync2(LICENSE_GLOB, {
cwd: this.rootPath,
absolute: true,
caseSensitiveMatch: false,
// Project license is always a sibling of the root manifest
deep: 0
});
licensePath = search.shift();
if (licensePath) {
licensePath = path6.normalize(licensePath);
Object.defineProperty(this, "licensePath", {
value: licensePath
});
}
} catch (err) {
throw new ValidationError(err.name, err.message);
}
return licensePath;
}
get fileFinder() {
const finder = makeFileFinder(this.rootPath, this.packageConfigs);
Object.defineProperty(this, "fileFinder", {
value: finder
});
return finder;
}
/**
* A promise resolving to a list of Package instances
*/
getPackages() {
const mapper = (packageConfigPath) => loadJsonFile2(packageConfigPath).then(
(packageJson) => new Package(packageJson, path6.dirname(packageConfigPath), this.rootPath)
);
return this.fileFinder("package.json", (filePaths) => pMap2(filePaths, mapper, { concurrency: 50 }));
}
/**
* A list of Package instances
*/
getPackagesSync() {
const syncFileFinder = makeSyncFileFinder(this.rootPath, this.packageConfigs);
return syncFileFinder("package.json", (packageConfigPath) => {
return new Package(
loadJsonFile2.sync(packageConfigPath),
path6.dirname(packageConfigPath),
this.rootPath
);
});
}
getPackageLicensePaths() {
return this.fileFinder(LICENSE_GLOB, null, { caseSensitiveMatch: false });
}
isIndependent() {
return this.version === "independent";
}
serializeConfig() {
writeJsonFile(this.rootConfigLocation, this.config, { spaces: 2 });
return this.rootConfigLocation;
}
#resolveRootPackageJson() {
try {
const manifestLocation = path6.join(this.rootPath, "package.json");
const packageJson = loadJsonFile2.sync(manifestLocation);
if (!packageJson.name) {
packageJson.name = path6.basename(path6.dirname(manifestLocation));
}
return new Package(packageJson, this.rootPath);
} catch (err) {
if (err instanceof Error && err?.name === "JSONError") {
throw new ValidationError(err.name, err.message);
}
throw new ValidationError("ENOPKG", "`package.json` does not exist, have you run `lerna init`?");
}
}
#resolveLernaConfig(cwd) {
try {
const explorer = cosmiconfigSync("lerna", {
loaders: {
...defaultLoaders,
".json": (filepath, content) => {
if (!filepath.endsWith("lerna.json")) {
return defaultLoaders[".json"](filepath, content);
}
try {
return parseJson(content);
} catch (err) {
if (err instanceof Error) {
err.name = "JSONError";
err.message = `Error in: ${filepath}
${err.message}`;
}
throw err;
}
}
},
searchPlaces: ["lerna.json", "package.json"],
searchStrategy: "global",
// Fix breaking change behaviour in cosmiconfig@9.0.0
transform(obj) {
if (!obj) {
const configNotFoundResult = {
// No need to distinguish between missing and empty,
// saves a lot of noisy guards elsewhere
config: {},
configNotFound: true,
// path.resolve(".", ...) starts from process.cwd()
filepath: path6.resolve(cwd || ".", "lerna.json")
};
return configNotFoundResult;
}
obj.config = applyExtends(obj.config, path6.dirname(obj.filepath));
return obj;
}
});
return explorer.search(cwd);
} catch (err) {
if (err.name === "JSONError") {
throw new ValidationError(err.name, err.message);
}
throw err;
}
}
#validateLernaConfig(config) {
if (!this.version) {
throw new ValidationError("ENOVERSION", "Required property version does not exist in `lerna.json`");
}
if (config.useWorkspaces !== void 0) {
throw new ValidationError(
"ECONFIGWORKSPACES",
`The "useWorkspaces" option has been removed. By default lerna will resolve your packages using your package manager's workspaces configuration. Alternatively, you can manually provide a list of package globs to be used instead via the "packages" option in lerna.json.`
);
}
}
#resolvePnpmWorkspaceConfig() {
let config;
try {
const configLocation = path6.join(this.rootPath, "pnpm-workspace.yaml");
const configContent = fs2.readFileSync(configLocation, { encoding: "utf8" });
config = load(configContent);
} catch (err) {
if (err.message.includes("ENOENT: no such file or directory")) {
throw new ValidationError(
"ENOENT",
"No pnpm-workspace.yaml found. See https://pnpm.io/workspaces for help configuring workspaces in pnpm."
);
}
throw new ValidationError(err.name, err.message);
}
return config;
}
/**
* By default, the user's package manager workspaces configuration will be used to resolve packages.
* However, they can optionally specify an explicit set of package globs to be used instead.
*
* NOTE: This does not impact the project graph creation process, which will still ultimately use
* the package manager workspaces configuration to construct a full graph, it will only impact which
* of the packages in that graph will be considered when running commands.
*/
#resolvePackageConfigs() {
if (this.config.packages) {
npmlog_default.verbose(
"packageConfigs",
`Explicit "packages" configuration found in lerna.json. Resolving packages using the configured glob(s): ${JSON.stringify(
this.config.packages
)}`
);
return this.config.packages;
}
if (this.config.npmClient === "pnpm") {
npmlog_default.verbose(
"packageConfigs",
'Package manager "pnpm" detected. Resolving packages using `pnpm-workspace.yaml`.'
);
const workspaces2 = this.#resolvePnpmWorkspaceConfig().packages;
if (!workspaces2) {
throw new ValidationError(
"EWORKSPACES",
'No "packages" property found in `pnpm-workspace.yaml`. See https://pnpm.io/workspaces for help configuring workspaces in pnpm.'
);
}
return workspaces2;
}
const workspaces = this.manifest?.get("workspaces");
const isYarnClassicWorkspacesObjectConfig = Boolean(
workspaces && typeof workspaces === "object" && Array.isArray(workspaces.packages)
);
const isValidWorkspacesConfig = Array.isArray(workspaces) || isYarnClassicWorkspacesObjectConfig;
if (!workspaces || !isValidWorkspacesConfig) {
throw new ValidationError(
"EWORKSPACES",
dedent2`
Lerna is expecting to able to resolve the "workspaces" configuration from your package manager in order to determine what packages to work on, but no "workspaces" config was found.
(A) Did you mean to specify a "packages" config manually in lerna.json instead of using your workspaces config?
(B) Alternatively, if you are using pnpm as your package manager, make sure you set "npmClient": "pnpm" in your lerna.json so that lerna knows to read from the "pnpm-workspace.yaml" file instead of package.json.
See: https://lerna.js.org/docs/getting-started
`
);
}
npmlog_default.verbose("packageConfigs", `Resolving packages based on package.json "workspaces" configuration.`);
if (isYarnClassicWorkspacesObjectConfig) {
return workspaces.packages;
}
return workspaces;
}
};
var getPackages = Project.getPackages;
var getPackagesSync = Project.getPackagesSync;
// libs/core/src/lib/write-log-file.ts
import os6 from "os";
import path7 from "path";
import writeFileAtomic from "write-file-atomic";
function writeLogFile(cwd) {
let logOutput = "";
npmlog_default.record.forEach((m) => {
let pref = [m.id, m.level];
if (m.prefix) {
pref.push(m.prefix);
}
pref = pref.join(" ");
m.message.trim().split(/\r?\n/).map((line) => `${pref} ${line}`.trim()).forEach((line) => {
logOutput += line + os6.EOL;
});
});
writeFileAtomic.sync(path7.join(cwd, "lerna-debug.log"), logOutput);
npmlog_default.record.length = 0;
}
// libs/core/src/lib/command/clean-stack.ts
function cleanStack(err, className) {
const lines = isErrorWithStack(err) ? err.stack.split("\n") : String(err).split("\n");
const cutoff = new RegExp(`^ at ${className}.runCommand .*$`);
const relevantIndex = lines.findIndex((line) => cutoff.test(line));
if (relevantIndex) {
return lines.slice(0, relevantIndex).join("\n");
}
return err.toString();
}
function isErrorWithStack(err) {
return err.stack !== void 0;
}
// libs/core/src/lib/command/default-options.ts
function defaultOptions(...sources) {
const options = {};
for (const source of sources) {
if (source != null) {
for (const key of Object.keys(source)) {
if (options[key] === void 0) {
options[key] = source[key];
}
}
}
}
return options;
}
// libs/core/src/lib/command/detect-projects.ts
import { createProjectFileMapUsingProjectGraph, createProjectGraphAsync } from "@nx/devkit";
// libs/core/src/lib/command/create-project-graph-with-packages.ts
import { workspaceRoot as workspaceRoot2 } from "@nx/devkit";
import fs3 from "fs-extra";
import minimatch2 from "minimatch";
import { resolve as resolve2 } from "npm-package-arg";
import { join as join2 } from "path";
import { satisfies } from "semver";
// libs/core/src/lib/get-package-manifest-path.ts
import { join, resolve } from "path";
function getPackageManifestPath(node, files) {
const pkgJsonPath = resolve(join(node.data.root, "package.json"));
return files.find((f) => resolve(f.file) === pkgJsonPath)?.file;
}
// libs/core/src/lib/command/create-project-graph-with-packages.ts
async function createProjectGraphWithPackages(projectGraph, projectFileMap, packageConfigs) {
const _workspaceRoot = process.env["NX_WORKSPACE_ROOT_PATH"] || workspaceRoot2;
const normalizedPackageConfigs = packageConfigs.map((config) => config.replace(/^\.\//, ""));
const projectNodes = Object.values(projectGraph.nodes);
const projectNodesMatchingPackageConfigs = projectNodes.filter((node) => {
const matchesRootPath = (config) => minimatch2(node.data.root, config);
return normalizedPackageConfigs.some(matchesRootPath);
});
const tuples = await Promise.all(
projectNodesMatchingPackageConfigs.map(
(node) => new Promise((resolve3) => {
const manifestPath = getPackageManifestPath(node, projectFileMap[node.name] || []);
if (manifestPath) {
const fullManifestPath = join2(_workspaceRoot, manifestPath);
resolve3(fs3.readJson(fullManifestPath).then((manifest) => [node, manifest]));
} else {
resolve3([node, null]);
}
})
)
);
const projectGraphWithOrderedNodes = {
...projectGraph,
nodes: {},
localPackageDependencies: {}
};
const sortedTuples = [...tuples].sort((a, b) => a[0].data.root.localeCompare(b[0].data.root));
sortedTuples.forEach(([node, manifest]) => {
let pkg = null;
if (manifest) {
pkg = new Package(manifest, join2(_workspaceRoot, node.data.root), _workspaceRoot);
}
projectGraphWithOrderedNodes.nodes[node.name] = {
...node,
package: pkg
};
});
projectGraphWithOrderedNodes.dependencies = Object.keys(projectGraphWithOrderedNodes.dependencies).sort((a, b) => a.localeCompare(b)).reduce(
(prev, next) => ({
...prev,
[next]: projectGraphWithOrderedNodes.dependencies[next]
}),
{}
);
Object.values(projectGraphWithOrderedNodes.dependencies).forEach((projectDeps) => {
const workspaceDeps = projectDeps.filter(
(dep) => !isExternalNpmDependency(dep.target) && !isExternalNpmDependency(dep.source)
);
for (const dep of workspaceDeps) {
const source = projectGraphWithOrderedNodes.nodes[dep.source];
const target = projectGraphWithOrderedNodes.nodes[dep.target];
if (!source || !source.package || !target || !target.package) {
continue;
}
const sourcePkg = getPackage(source);
const targetPkg = getPackage(target);
const sourceNpmDependency = sourcePkg.getLocalDependency(targetPkg.name);
if (!sourceNpmDependency) {
continue;
}
const hasWorkspaceProtocol = sourceNpmDependency.spec.startsWith("workspace:");
const workspaceDep = dep;
const resolvedTarget = resolvePackage(
targetPkg.name,
targetPkg.version,
sourceNpmDependency.spec,
sourcePkg.location
);
const targetMatchesRequirement = hasWorkspaceProtocol || resolvedTarget.fetchSpec === targetPkg.location || satisfies(
targetPkg.version,
resolvedTarget.gitCommittish || resolvedTarget.gitRange || resolvedTarget.fetchSpec
);
workspaceDep.dependencyCollection = sourceNpmDependency.collection;
workspaceDep.targetResolvedNpaResult = resolvedTarget;
workspaceDep.targetVersionMatchesDependencyRequirement = targetMatchesRequirement;
if (workspaceDep.targetVersionMatchesDependencyRequirement) {
projectGraphWithOrderedNodes.localPackageDependencies[dep.source] = [
...projectGraphWithOrderedNodes.localPackageDependencies[dep.source] || [],
workspaceDep
];
}
}
});
return projectGraphWithOrderedNodes;
}
var resolvePackage = (name, version, spec, location) => {
spec = spec.replace(/^link:/, "file:");
const isWorkspaceSpec = /^workspace:/.test(spec);
let workspaceSpec;
let workspaceAlias;
if (isWorkspaceSpec) {
workspaceSpec = spec;
spec = spec.replace(/^workspace:/, "");
if (spec === "*" || spec === "^" || spec === "~") {
workspaceAlias = spec;
if (version) {
const prefix2 = spec === "*" ? "" : spec;
spec = `${prefix2}${version}`;
} else {
spec = "*";
}
}
}
const resolved = resolve2(name, spec, location);
resolved.workspaceSpec = workspaceSpec;
resolved.workspaceAlias = workspaceAlias;
return resolved;
};
// libs/core/src/lib/command/detect-projects.ts
async function detectProjects(packageConfigs) {
const _projectGraph = await createProjectGraphAsync();
const projectFileMap = await createProjectFileMapUsingProjectGraph(_projectGraph);
const projectGraph = await createProjectGraphWithPackages(_projectGraph, projectFileMap, packageConfigs);
return {
projectGraph,
projectFileMap
};
}
// libs/core/src/lib/command/log-package-error.ts
function logPackageError(err, stream3 = false) {
npmlog_default.error(err.command, `exited ${err.exitCode} in '${err.pkg.name}'`);
if (stream3) {
return;
}
if (err.stdout) {
npmlog_default.error(err.command, "stdout:");
directLog(err.stdout);
}
if (err.stderr) {
npmlog_default.error(err.command, "stderr:");
directLog(err.stderr);
}
npmlog_default.error(err.command, `exited ${err.exitCode} in '${err.pkg.name}'`);
}
function directLog(message) {
npmlog_default.pause();
console.error(message);
npmlog_default.resume();
}
// libs/core/src/lib/command/warn-if-hanging.ts
function warnIfHanging() {
const childProcessCount = getChildProcessCount();
if (childProcessCount > 0) {
npmlog_default.warn(
"complete",
`Waiting for ${childProcessCount} child process${childProcessCount === 1 ? "" : "es"} to exit. CTRL-C to exit immediately.`
);
}
}
// libs/core/src/lib/command/index.ts
var DEFAULT_CONCURRENCY = os7.cpus().length;
var Command = class _Command {
constructor(_argv, {
skipValidations,
preInitializedProjectData
} = { skipValidations: false }) {
this._argv = _argv;
npmlog_default.pause();
npmlog_default.heading = "lerna";
const argv = { ..._argv };
npmlog_default.silly("argv", argv);
this.name = this.constructor.name.replace(/Command$/, "").toLowerCase();
this.composed = typeof argv.composed === "string" && argv.composed !== this.name;
if (!this.composed) {
npmlog_default.notice("cli", `v${argv.lernaVersion}`);
}
let runner = new Promise((resolve3, reject) => {
let chain = Promise.resolve();
chain = chain.then(() => {
this.project = new Project(argv.cwd, { skipLernaConfigValidations: skipValidations });
});
chain = chain.then(() => this.configureEnvironment());
chain = chain.then(() => this.configureOptions());
chain = chain.then(() => this.configureProperties());
chain = chain.then(() => {
this.logger = _Command.createLogger(this.name, this.options.loglevel);
});
if (!skipValidations) {
chain = chain.then(() => this.runValidations());
}
chain = chain.then(() => {
if (preInitializedProjectData) {
this.projectFileMap = preInitializedProjectData.projectFileMap;
this.projectGraph = preInitializedProjectData.projectGraph;
return;
}
return this.detectProjects();
});
chain = chain.then(() => this.runPreparations());
chain = chain.then(() => this.runCommand());
chain.then(
(result) => {
warnIfHanging();
daemonClient.reset();
resolve3(result);
},
(err) => {
if (err.pkg) {
logPackageError(err, this.options.stream);
} else if (err.name !== "ValidationError") {
npmlog_default.error("", cleanStack(err, this.constructor.name));
}
if (err.name !== "ValidationError" && !err.pkg) {
writeLogFile(this.project.rootPath);
}
warnIfHanging();
daemonClient.reset();
reject(err);
}
);
});
if (argv.onResolved || argv.onRejected) {
runner = runner.then(argv.onResolved, argv.onRejected);
delete argv.onResolved;
delete argv.onRejected;
}
for (const key of ["cwd", "$0"]) {
Object.defineProperty(argv, key, { enumerable: false });
}
Object.defineProperty(this, "argv", {
value: Object.freeze(argv)
});
this.runner = runner;
}
_argv;
name;
composed;
options = {};
runner;
concurrency = 0;
toposort = false;
execOpts = {};
logger;
envDefaults;
argv = {};
projectGraph;
projectFileMap;
_project;
get project() {
if (this._project === void 0) {
throw new ValidationError("ENOPROJECT", "Lerna Project not initialized!");
}
return this._project;
}
set project(project) {
this._project = project;
}
static createLogger(name, loglevel) {
if (loglevel) {
npmlog_default.level = loglevel;
}
npmlog_default.addLevel("success", 3001, { fg: "green", bold: true });
npmlog_default.resume();
return npmlog_default["newGroup"](name);
}
// proxy "Promise" methods to "private" instance
then(onResolved, onRejected) {
return this.runner.then(onResolved, onRejected);
}
/* istanbul ignore next */
catch(onRejected) {
return this.runner.catch(onRejected);
}
get requiresGit() {
return true;
}
// Override this to inherit config from another command.
// For example `changed` inherits config from `publish`.
get otherCommandConfigs() {
return [];
}
async detectProjects() {
const { projectGraph, projectFileMap } = await detectProjects(this.project.packageConfigs);
this.projectGraph = projectGraph;
this.projectFileMap = projectFileMap;
}
configureEnvironment() {
const ci = isCI;
let loglevel;
let progress;
if (ci || !process.stderr.isTTY) {
npmlog_default.disableColor();
progress = false;
} else if (!process.stdout.isTTY) {
progress = false;
loglevel = "error";
} else if (process.stderr.isTTY) {
npmlog_default.enableColor();
npmlog_default.enableUnicode();
}
Object.defineProperty(this, "envDefaults", {
value: {
ci,
progress,
loglevel
}
});
}
configureOptions() {
const commandConfig = this.project.config.command || {};
const overrides = [this.name, ...this.otherCommandConfigs].map((key) => commandConfig[key]);
this.options = defaultOptions(
// CLI flags, which if defined overrule subsequent values
this.argv,
...overrides,
// Global options from `lerna.json`
this.project.config,
// Environmental defaults prepared in previous step
this.envDefaults
);
if (this.options.verbose && this.options.loglevel !== "silly") {
this.options.loglevel = "verbose";
}
}
configureProperties() {
const { concurrency = 0, sort, maxBuffer } = this.options;
this.concurrency = Math.max(1, +concurrency || DEFAULT_CONCURRENCY);
this.toposort = sort === void 0 || sort;
this.execOpts = {
cwd: this.project.rootPath,
maxBuffer
};
}
enableProgressBar() {
if (this.options.progress !== false) {
npmlog_default.enableProgress();
}
}
runValidations() {
if ((this.options.since !== void 0 || this.requiresGit) && !isGitInitialized(this.project.rootPath)) {
throw new ValidationError(
"ENOGIT",
"The git binary was not found, this is not a git repository, or you git doesn't have the right ownership. Run `git rev-parse` to get more details."
);
}
if (this.options.independent && !this.project.isIndependent()) {
throw new ValidationError(
"EVERSIONMODE",
dedent3`
You ran lerna with --independent or -i, but the repository is not set to independent mode.
To use independent mode you need to set lerna.json's "version" property to "independent".
Then you won't need to pass the --independent or -i flags.
`
);
}
}
runPreparations() {
if (!this.composed && this.project.isIndependent()) {
npmlog_default.info("versioning", "independent");
}
if (!this.composed && this.options.ci) {
npmlog_default.info("ci", "enabled");
}
}
async runCommand() {
const proceed = await this.initialize();
if (proceed !== false) {
return this.execute();
}
return void 0;
}
initialize() {
throw new ValidationError(this.name, "initialize() needs to be implemented.");
}
/**
* The execute() method can return a value in some cases (e.g. on the version command)
*/
execute() {
throw new ValidationError(this.name, "execute() needs to be implemented.");
}
};
// libs/core/src/lib/conventional-commits/apply-build-metadata.ts
var BUILD_METADATA_REGEX = /^[0-9a-zA-Z-]+(\.[0-9a-zA-Z-]+)*$/;
function applyBuildMetadata(version, buildMetadata) {
if (!buildMetadata) {
return version;
}
if (isValidBuildMetadata(buildMetadata)) {
return `${version}+${buildMetadata}`;
}
throw new ValidationError("EBUILDMETADATA", "Build metadata does not satisfy SemVer specification.");
}
function isValidBuildMetadata(buildMetadata) {
return BUILD_METADATA_REGEX.test(buildMetadata);
}
// libs/core/src/lib/conventional-commits/recommend-version.ts
import semver2 from "semver";
// libs/core/src/lib/conventional-commits/get-changelog-config.ts
import Handlebars from "handlebars";
import npa2 from "npm-package-arg";
import { createRequire as createRequire2 } from "node:module";
import { promisify } from "node:util";
var cfgCache = /* @__PURE__ */ new Map();
var require3 = createRequire2(import.meta.url);
function isFunction(config) {
return Object.prototype.toString.call(config) === "[object Function]" || Object.prototype.toString.call(config) === "[object AsyncFunction]";
}
function normalizeLegacyWriterOptions(writer) {
if (!writer || typeof writer !== "object") {
return writer;
}
const normalized = { ...writer };
const legacyMainTemplate = typeof writer.mainTemplate === "string" ? Handlebars.compile(writer.mainTemplate) : void 0;
const legacyHeaderPartial = typeof writer.headerPartial === "string" ? Handlebars.compile(writer.headerPartial) : void 0;
const legacyCommitPartial = typeof writer.commitPartial === "string" ? Handlebars.compile(writer.commitPartial) : void 0;
const legacyFooterPartial = typeof writer.footerPartial === "string" ? Handlebars.compile(writer.footerPartial) : void 0;
if (legacyMainTemplate) {
normalized.template = (context) => legacyMainTemplate(context, {
data: { root: context },
partials: {
header: legacyHeaderPartial || ((partialContext) => (writer.headerPartial || context.headerPartial)(partialContext)),
commit: legacyCommitPartial || ((commit, options) => (writer.commitPartial || context.commitPartial)(options.data.root, commit)),
footer: legacyFooterPartial || ((partialContext) => (writer.footerPartial || context.footerPartial)(partialContext))
}
});
delete normalized.mainTemplate;
delete normalized.headerPartial;
delete normalized.commitPartial;
delete normalized.footerPartial;
} else {
if (legacyHeaderPartial) {
normalized.headerPartial = (context) => legacyHeaderPartial(context);
}
if (legacyCommitPartial) {
normalized.commitPartial = (context, commit) => legacyCommitPartial(commit, { data: { root: context } });
}
if (legacyFooterPartial) {
normalized.footerPartial = (context) => legacyFooterPartial(context);
}
}
return normalized;
}
function normalizePresetConfig(config) {
if (config && (config.parser || config.writer || config.whatBump) && !config.parserOpts && !config.writerOpts && !config.conventionalChangelog) {
return {
...config,
writer: normalizeLegacyWriterOptions(config.writer)
};
}
if (config && (config.parserOpts || config.writerOpts || config.conventionalChangelog || config.recommendedBumpOpts || config.gitRawCommitsOpts)) {
npmlog_default.verbose("getChangelogConfig", "Normalizing legacy preset API to modern format");
const normalized = { ...config };
const cc2 = config.conventionalChangelog || config;
if (!normalized.parser) {
normalized.parser = cc2.parserOpts || config.parserOpts;
}
if (!normalized.writer) {
normalized.writer = cc2.writerOpts || config.writerOpts;
}
normalized.writer = normalizeLegacyWriterOptions(normalized.writer);
if (!normalized.commits) {
normalized.commits = cc2.gitRawCommitsOpts || config.gitRawCommitsOpts;
}
if (!normalized.whatBump) {
normalized.whatBump = config.recommendedBumpOpts?.whatBump || config.whatBump;
}
return normalized;
}
return config;
}
async function resolveConfigPromise(presetPackageName, presetConfig) {
npmlog_default.verbose("getChangelogConfig", "Attempting to resolve preset %j", presetPackageName);
let config;
try {
config = require3(presetPackageName);
} catch (requireError) {
if (requireError.code === "ERR_REQUIRE_ESM" || requireError.code === "ERR_PACKAGE_PATH_NOT_EXPORTED") {
npmlog_default.verbose("getChangelogConfig", "Preset is ESM, using dynamic import for %j", presetPackageName);
const imported = await import(presetPackageName);
config = imported.default || imported;
} else {
throw requireError;
}
}
if (config && config.__esModule && config.default) {
config = config.default;
}
npmlog_default.info("getChangelogConfig", "Successfully resolved preset %j", presetPackageName);
if (isFunction(config)) {
try {
config = config(presetConfig);
} catch (_) {
config = promisify(config)();
}
}
config = await Promise.resolve(config);
return normalizePresetConfig(config);
}
async function getChangelogConfig(changelogPreset = "conventional-changelog-angular", rootPath) {
const presetName = typeof changelogPreset === "string" ? changelogPreset : changelogPreset.name;
const presetConfig = typeof changelogPreset === "object" ? changelogPreset : {};
const cacheKey = `${presetName}${presetConfig ? JSON.stringify(presetConfig) : ""}`;
let config = cfgCache.get(cacheKey);
if (!config) {
let presetPackageName = presetName;
const parsed = npa2(presetPackageName, rootPath);
npmlog_default.verbose("getChangelogConfig", "using preset %j", presetPackageName);
npmlog_default.silly("npa", parsed);
if (parsed.type === "directory") {
if (parsed.raw[0] === "@") {
parsed.name = parsed.raw;
parsed.scope = parsed.raw.substring(0, parsed.raw.indexOf("/"));
} else {
presetPackageName = parsed.fetchSpec;
}
} else if (parsed.type === "git" && parsed.hosted && parsed.hosted.default === "shortcut") {
parsed.name = parsed.raw;
}
try {
config = await resolveConfigPromise(presetPackageName, presetConfig);
cfgCache.set(cacheKey, config);
return config;
} catch (err) {
npmlog_default.verbose("getChangelogConfig", err.message);
npmlog_default.info("getChangelogConfig", "Auto-prefixing conventional-changelog preset %j", presetName);
parsed.name = parsed.raw;
}
if (parsed.name.indexOf("conventional-changelog-") < 0) {
const parts = parsed.name.split("/");
const start = parsed.scope ? 1 : 0;
parts.splice(start, 1, `conventional-changelog-${parts[start]}`);
presetPackageName = parts.join("/");
}
try {
config = await resolveConfigPromise(presetPackageName, presetConfig);
cfgCache.set(cacheKey, config);
} catch (err) {
npmlog_default.warn("getChangelogConfig", err.message);
throw new ValidationError(
"EPRESET",
`Unable to load conventional-changelog preset '${presetName}'${presetName !== presetPackageName ? ` (${presetPackageName})` : ""}`
);
}
}
return config;
}
// libs/core/src/lib/conventional-commits/recommend-version.ts
async function recommendVersion(pkg, type, {
changelogPreset,
rootPath,
tagPrefix,
prereleaseId,
conventionalBumpPrerelease,
buildMetadata
}, premajorVersionBump) {
npmlog_default.silly(type, "for %s at %s", pkg.name, pkg.location);
const [config, { Bumper, packagePrefix }] = await Promise.all([
getChangelogConfig(changelogPreset, rootPath),
// @ts-expect-error ESM package with exports field not resolved by moduleResolution: "node"
import("conventional-recommended-bump")
]);
const bumper = new Bumper(pkg.location);
const bumpConfig = config.recommendedBumpOpts?.parserOpts ? { ...config, parser: { ...config.parser, ...config.recommendedBumpOpts.parserOpts } } : config;
bumper.config(bumpConfig);
bumper.commits({ path: pkg.location });
if (type === "independent") {
bumper.tag({ prefix: packagePrefix(pkg.name) });
} else {
bumper.tag({ prefix: tagPrefix ?? "v" });
}
const data = await bumper.bump(config.whatBump);
const shouldBumpPrerelease = (releaseType2, version) => {
if (!semver2.prerelease(version)) {
return true;
}
switch (releaseType2) {
case "major":
return semver2.minor(version) !== 0 || semver2.patch(version) !== 0;
case "minor":
return semver2.patch(version) !== 0;
default:
return false;
}
};
let releaseType = ("releaseType" in data ? data.releaseType : void 0) || "patch";
if (prereleaseId) {
const shouldBump = conventionalBumpPrerelease || shouldBumpPrerelease(releaseType, pkg.version);
const prereleaseType = shouldBump ? `pre${releaseType}` : "prerelease";
npmlog_default.verbose(type, "increment %s by %s", pkg.version, prereleaseType);
return applyBuildMetadata(
semver2.inc(pkg.version, prereleaseType, prereleaseId),
buildMetadata
);
} else {
if (semver2.major(pkg.version) === 0) {
if (releaseType === "major") {
releaseType = "minor";
} else if (premajorVersionBump === "force-patch") {
releaseType = "patch";
}
}
npmlog_default.verbose(type, "increment %s by %s", pkg.version, releaseType);
return applyBuildMetadata(
semver2.inc(pkg.version, releaseType),
buildMetadata
);
}
}
// libs/core/src/lib/conventional-commits/update-changelog.ts
import { execFileSync } from "node:child_process";
import fs5 from "fs-extra";
// libs/core/src/lib/conventional-commits/constants.ts
var EOL = "\n";
var BLANK_LINE = EOL + EOL;
var COMMIT_GUIDELINE = "See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.";
var CHANGELOG_HEADER = [
"# Change Log",
"",
"All notable changes to this project will be documented in this file.",
COMMIT_GUIDELINE
].join(EOL);
// libs/core/src/lib/conventional-commits/make-bump-only-filter.ts
function makeBumpOnlyFilter(pkg) {
return (newEntry) => {
if (!newEntry.split("\n").some((line) => line.startsWith("*"))) {
const message = `**Note:** Version bump only for package ${pkg.name}`;
return [newEntry.trim(), message, BLANK_LINE].join(BLANK_LINE);
}
return newEntry;
};
}
// libs/core/src/lib/conventional-commits/read-existing-changelog.ts
import fs4 from "fs-extra";
import path8 from "path";
function readExistingChangelog(pkg) {
const changelogFileLoc = path8.join(pkg.location, "CHANGELOG.md");
let chain = Promise.resolve();
chain = chain.then(() => fs4.readFile(changelogFileLoc, "utf8").catch(() => ""));
chain = chain.then((changelogContents) => {
const headerIndex = changelogContents.indexOf(COMMIT_GUIDELINE);
if (headerIndex !== -1) {
return changelogContents.substring(headerIndex + COMMIT_GUIDELINE.length + BLANK_LINE.length);
}
return changelogContents;
});
chain = chain.then((changelogContents) => [changelogFileLoc, changelogContents]);
return chain;
}
// libs/core/src/lib/conventional-commits/update-changelog.ts
function getGitRemoteUrl(cwd) {
try {
const url4 = execFileSync("git", ["config", "--get", "remote.origin.url"], { cwd, encoding: "utf8" }).trim() || null;
return url4 ? url4.replace(/\.git$/, "") : null;
} catch {
return null;
}
}
function parseRemoteUrl(remoteUrl) {
let pathname;
const scpMatch = remoteUrl.match(/^[\w-]+@([^:]+):(.+)$/);
if (scpMatch) {
pathname = "/" + scpMatch[2];
} else {
try {
const parsed = new URL(remoteUrl);
pathname = parsed.pathname;
} catch {
pathname = remoteUrl;
}
}
const match = pathname.match(/^\/?(.+)\/([^/]+)\/?$/);
if (match) {
return { owner: match[1], project: match[2] };
}
return null;
}
async function updateChangelog(pkg, type, {
changelogPreset,
changelogEntryAdditionalMarkdown,
rootPath,
tagPrefix = "v",
version
}) {
npmlog_default.silly(type, "for %s at %s", pkg.name, pkg.location);
const [config, { ConventionalChangelog, packagePrefix }] = await Promise.all([
getChangelogConfig(changelogPreset, rootPath),
// @ts-expect-error ESM package with exports field not resolved by moduleResolution: "node"
import("conventional-changelog")
]);
const generator = new ConventionalChangelog(pkg.location);
generator.config(config);
const remoteUrl = getGitRemoteUrl(pkg.location);
if (remoteUrl) {
const parsed = parseRemoteUrl(remoteUrl);
if (parsed) {
generator.repository(parsed);
}
}
generator.readPackage(pkg.manifestLocation);
if (type === "root") {
generator.context({ version, currentTag: `${tagPrefix}${version}` });
generator.tags({ prefix: tagPrefix });
} else {
generator.commits({ path: pkg.location });
if (type === "independent") {
generator.tags({ prefix: packagePrefix(pkg.name) });
} else {
generator.tags({ prefix: tagPrefix });
generator.context({ currentTag: `${tagPrefix}${pkg.version}` });
}
}
const changelogStream = generator.writeStream();
const [newEntryRaw, [changelogFileLoc, changelogContents]] = await Promise.all([
streamToString(changelogStream).then(makeBumpOnlyFilter(pkg)),
readExistingChangelog(pkg)
]);
let newEntry = newEntryRaw;
if (changelogEntryAdditionalMarkdown) {
const trailingWhitespace = newEntry.match(/\s*$/);
newEntry = newEntry.replace(/\s*$/, BLANK_LINE + changelogEntryAdditionalMarkdown + trailingWhitespace);
}
npmlog_default.silly(type, "writing new entry: %j", newEntry);
const content = [CHANGELOG_HEADER, newEntry, changelogContents].join(BLANK_LINE);
await fs5.writeFile(changelogFileLoc, content.trim() + EOL);
npmlog_default.verbose(type, "wrote", changelogFileLoc);
return {
logPath: changelogFileLoc,
newEntry
};
}
async function streamToString(stream3) {
const chunks = [];
for await (const chunk of stream3) {
chunks.push(String(chunk));
}
return chunks.join("");
}
// libs/core/src/lib/corepack/is-corepack-enabled.ts
function isCorepackEnabled() {
return process.env["COREPACK_ROOT"] !== void 0;
}
// libs/core/src/lib/corepack/exec-package-manager.ts
function createCommandAndArgs(npmClient, args) {
let command = npmClient;
const commandArgs = [...args];
if (isCorepackEnabled() && npmClient !== "bun") {
commandArgs.unshift(command);
command = "corepack";
}
return { command, commandArgs };
}
function execPackageManager(npmClient, args, opts) {
const { command, commandArgs } = createCommandAndArgs(npmClient, args);
return exec(command, commandArgs, opts);
}
function execPackageManagerSync(npmClient, args, opts) {
const { command, commandArgs } = createCommandAndArgs(npmClient, args);
return execSync(command, commandArgs, opts);
}
// libs/core/src/lib/filter-options.ts
import dedent4 from "dedent";
function filterOptions(yargs2) {
const opts = {
scope: {
describe: "Include only packages with names matching the given glob.",
type: "string",
requiresArg: true
},
ignore: {
describe: "Exclude packages with names matching the given glob.",
type: "string",
requiresArg: true
},
"no-private": {
describe: 'Exclude packages with { "private": true } in their package.json.',
type: "boolean"
},
private: {
// proxy for --no-private
hidden: true,
type: "boolean"
},
since: {
describe: dedent4`
Only include packages that have been changed since the specified [ref].
If no ref is passed, it defaults to the most-recent tag.
`,
type: "string"
},
"exclude-dependents": {
describe: dedent4`
Exclude all transitive dependents when running a command
with --since, overriding the default "changed" algorithm.
`,
conflicts: "include-dependents",
type: "boolean"
},
"include-dependents": {
describe: dedent4`
Include all transitive dependents when running a command
regardless of --scope, --ignore, or --since.
`,
conflicts: "exclude-dependents",
type: "boolean"
},
"include-dependencies": {
describe: dedent4`
Include all transitive dependencies when running a command
regardless of --scope, --ignore, or --since.
`,
type: "boolean"
},
"include-merged-tags": {
describe: "Include tags from merged branches when running a command with --since.",
type: "boolean"
},
"continue-if-no-match": {
describe: "Don't fail if no package is matched",
hidden: true,
type: "boolean"
}
};
return yargs2.options(opts).group(Object.keys(opts), "Filter Options:").option("include-filtered-dependents", {
// TODO: remove in next major release
hidden: true,
conflicts: ["exclude-dependents", "include-dependents"],
type: "boolean"
}).option("include-filtered-dependencies", {
// TODO: remove in next major release
hidden: true,
conflicts: "include-dependencies",
type: "boolean"
}).check((argv) => {
if (argv["includeFilteredDependents"]) {
argv["includeDependents"] = true;
argv["include-dependents"] = true;
delete argv["includeFilteredDependents"];
delete argv["include-filtered-dependents"];
npmlog_default.warn("deprecated", "--include-filtered-dependents has been renamed --include-dependents");
}
if (argv["includeFilteredDependencies"]) {
argv["includeDependencies"] = true;
argv["include-dependencies"] = true;
delete argv["includeFilteredDependencies"];
delete argv["include-filtered-dependencies"];
npmlog_default.warn("deprecated", "--include-filtered-dependencies has been renamed --include-dependencies");
}
return argv;
});
}
// libs/core/src/lib/multimatch.ts
import minimatch3 from "minimatch";
function multimatch(list3, patterns, options = {}) {
list3 = Array.isArray(list3) ? list3 : [list3];
patterns = Array.isArray(patterns) ? patterns : [patterns];
if (list3.length === 0 || patterns.length === 0) {
return [];
}
let result = [];
for (const item of list3) {
for (let pattern of patterns) {
let process2;
if (pattern[0] === "!") {
pattern = pattern.slice(1);
process2 = arrayDiffer;
} else {
process2 = arrayUnion;
}
result = process2(result, minimatch3.match([item], pattern, options));
}
}
return result;
}
function arrayUnion(a, b) {
const set = new Set(a);
for (const item of b) {
set.add(item);
}
return [...set];
}
function arrayDiffer(a, b) {
const set = new Set(b);
return a.filter((item) => !set.has(item));
}
// libs/core/src/lib/filter-projects.ts
import util5 from "util";
// libs/core/src/lib/add-dependencies.ts
function addDependencies(projects, projectGraph) {
const projectsLookup = new Set(projects.map((p) => p.name));
const dependencies = projectGraph.localPackageDependencies;
const collected = /* @__PURE__ */ new Set();
projects.forEach((currentNode) => {
if (dependencies[currentNode.name] && dependencies[currentNode.name].length === 0) {
return;
}
const queue2 = [currentNode];
const seen = /* @__PURE__ */ new Set();
while (queue2.length) {
const node = queue2.shift();
dependencies[node.name]?.forEach(({ target }) => {
if (seen.has(target)) {
return;
}
seen.add(target);
if (target === currentNode.name || projectsLookup.has(target)) {
return;
}
const dependencyNode = projectGraph.nodes[target];
collected.add(dependencyNode);
queue2.push(dependencyNode);
});
}
});
return Array.from(/* @__PURE__ */ new Set([...projects, ...collected]));
}
// libs/core/src/lib/add-dependents.ts
function addDependents(projects, projectGraph) {
const projectsLookup = new Set(projects.map((p) => p.name));
const dependents = Object.values(projectGraph.localPackageDependencies).flat().reduce(
(prev, next) => ({
...prev,
[next.target]: [...prev[next.target] || [], next.source]
}),
{}
);
const collected = /* @__PURE__ */ new Set();
projects.forEach((currentNode) => {
if (dependents[currentNode.name] && dependents[currentNode.name].length === 0) {
return;
}
const queue2 = [currentNode];
const seen = /* @__PURE__ */ new Set();
while (queue2.length) {
const node = queue2.shift();
dependents[node.name]?.forEach((dep) => {
if (seen.has(dep)) {
return;
}
seen.add(dep);
if (dep === currentNode.name || projectsLookup.has(dep)) {
return;
}
const dependentNode = projectGraph.nodes[dep];
collected.add(dependentNode);
queue2.push(dependentNode);
});
}
});
return Array.from(/* @__PURE__ */ new Set([...projects, ...collected]));
}
// libs/core/src/lib/filter-projects.ts
function filterProjects(projectGraph, execOpts = {}, opts = {}) {
const options = { log: npmlog_default, ...opts };
if (options.scope) {
options.log.notice("filter", "including %j", options.scope);
}
if (options.ignore) {
options.log.notice("filter", "excluding %j", options.ignore);
}
let projects = Object.values(projectGraph.nodes).filter((p) => !!p.package);
const patterns = [].concat(arrify(options.scope), negate(arrify(options.ignore)));
if (options.private === false) {
projects = projects.filter((p) => !p.package?.private);
}
const patternsToLog = [...patterns];
if (patterns.length) {
if (!options.scope?.length) {
patterns.unshift("**");
}
const packageNames = Array.from(projects).map((p) => p.package?.name).filter((p) => !!p);
const chosen = new Set(multimatch(packageNames, patterns));
projects = projects.filter((p) => p.package?.name && chosen.has(p.package.name));
if (!projects.length && !options.continueIfNoMatch) {
throw new ValidationError("EFILTER", util5.format("No packages remain after filtering", patterns));
}
}
if (options.since !== void 0) {
options.log.notice("filter", "changed since %j", options.since);
if (options.excludeDependents) {
options.log.notice("filter", "excluding dependents");
}
if (options.includeMergedTags) {
options.log.notice("filter", "including merged tags");
}
const updates = collectProjectUpdates(projects, projectGraph, execOpts, opts);
const updated = new Set(updates.map((node) => node.name));
projects = projects.filter((project) => updated.has(project.name));
}
if (options.includeDependents) {
options.log.notice("filter", "including dependents");
projects = addDependents(projects, projectGraph);
}
if (options.includeDependencies) {
options.log.notice("filter", "including dependencies");
projects = addDependencies(projects, projectGraph);
}
if (patternsToLog.length) {
npmlog_default.info("filter", patternsToLog);
}
return projects;
}
function arrify(thing) {
if (!thing) {
return [];
}
if (!Array.isArray(thing)) {
return [thing];
}
return thing;
}
function negate(patterns) {
return patterns.map((pattern) => `!${pattern}`);
}
// libs/core/src/lib/git-checkout.ts
function gitCheckout(stagedFiles, gitOpts, execOpts) {
const files = gitOpts.granularPathspec ? stagedFiles : ".";
npmlog_default.silly("gitCheckout", files);
return exec(
"git",
["checkout", "--"].concat(files),
execOpts
);
}
// libs/core/src/lib/listable-format-projects.ts
import columnify from "columnify";
import path9 from "path";
// libs/core/src/lib/cycles/get-cycles.ts
function getCycles(dependencies) {
const cycles = [];
const visited = /* @__PURE__ */ new Set();
function dfs(next, path23) {
visited.add(next);
path23.push(next);
for (const dep of dependencies[next] || []) {
if (path23.includes(dep)) {
const cycle = path23.slice(path23.indexOf(dep));
cycles.push(cycle);
} else if (!visited.has(dep)) {
dfs(dep, path23);
}
}
path23.pop();
}
for (const next of Object.keys(dependencies)) {
if (!visited.has(next)) {
dfs(next, []);
}
}
return cycles;
}
// libs/core/src/lib/cycles/merge-overlapping-cycles.ts
function intersection(arr1, arr2) {
return arr1.filter((item) => arr2.includes(item));
}
function difference(arr1, arr2) {
return arr1.filter((item) => !arr2.includes(item));
}
function mergeOverlappingCycles(cycles) {
const mergedCycles = [];
cycles.forEach((cycle) => {
let intersectionNodes = [];
const mergedCycle = mergedCycles.find((mergedCycle2) => {
intersectionNodes = intersection(mergedCycle2, cycle);
return intersectionNodes.length > 0;
});
if (mergedCycle) {
mergedCycle.push(...difference(cycle, intersectionNodes));
} else {
mergedCycles.push(cycle);
}
});
return mergedCycles;
}
// libs/core/src/lib/cycles/report-cycles.ts
function reportCycles(cycles, rejectCycles) {
const cyclesWithRepeatedNodes = cycles.map((cycle) => [...cycle, cycle[0]]);
const paths = Array.from(cyclesWithRepeatedNodes, (cycle) => cycle.join(" -> "), false);
if (!paths.length) {
return;
}
const cycleMessage = ["Dependency cycles detected, you should fix these!"].concat(paths).join("\n");
if (rejectCycles) {
throw new ValidationError("ECYCLE", cycleMessage);
}
npmlog_default.warn("ECYCLE", cycleMessage);
}
// libs/core/src/lib/toposort-projects.ts
function toposortProjects(projects, projectGraph, rejectCycles = false) {
const projectsMap = new Map(projects.map((p) => [p.name, p]));
const localDependencies = projectGraph.localPackageDependencies;
const flattenedLocalDependencies = Object.values(localDependencies).flat();
const getProject = (name) => {
const project = projectsMap.get(name);
if (!project) {
throw new Error(`Failed to find project ${name}. This is likely a bug in Lerna's toposort algorithm.`);
}
return project;
};
const dependenciesBySource = projects.reduce(
(prev, next) => ({
...prev,
[next.name]: /* @__PURE__ */ new Set()
}),
{}
);
flattenedLocalDependencies.forEach((dep) => {
if (dependenciesBySource[dep.source] && projectsMap.has(dep.target)) {
dependenciesBySource[dep.source].add(dep.target);
}
});
const unmergedCycles = getCycles(dependenciesBySource);
reportCycles(unmergedCycles, rejectCycles);
const cycles = new Set(mergeOverlappingCycles(unmergedCycles));
const seen = /* @__PURE__ */ new Set();
const queueNextPackages = () => {
if (seen.size === projects.length) {
return;
}
let batch = Object.keys(dependenciesBySource).filter((p) => dependenciesBySource[p].size === 0).filter((p) => !seen.has(p));
if (batch.length === 0) {
const cycle = Array.from(cycles.values()).find((cycle2) => {
const cycleHasExternalDependencies = cycle2.some((project) => {
const projectDeps = dependenciesBySource[project];
const depIsNotInCycle = (dep) => cycle2.indexOf(dep) === -1;
return !!projectDeps && Array.from(projectDeps).filter(depIsNotInCycle).length > 0;
});
return !cycleHasExternalDependencies;
});
if (cycle) {
cycles.delete(cycle);
batch = cycle.filter((p) => projectsMap.has(p));
}
}
batch.forEach((p) => {
seen.add(p);
delete dependenciesBySource[p];
Object.keys(dependenciesBySource).forEach((dep) => dependenciesBySource[dep].delete(p));
});
queueNextPackages();
};
queueNextPackages();
return Array.from(seen).map((p) => getProject(p));
}
// libs/core/src/lib/listable-format-projects.ts
function listableFormatProjects(projectsList, projectGraph, options) {
const viewOptions = parseViewOptions(options);
const resultList = filterResultList(projectsList, projectGraph, viewOptions);
const count = resultList.length;
let text;
if (viewOptions.showJSON) {
text = formatJSON(resultList);
} else if (viewOptions.showNDJSON) {
text = formatNDJSON(resultList);
} else if (viewOptions.showParseable) {
text = formatParseable(resultList, viewOptions);
} else if (viewOptions.showGraph) {
text = formatJSONGraph(resultList, viewOptions);
} else {
text = formatColumns(resultList, viewOptions);
}
return { text, count };
}
function parseViewOptions(options) {
const alias = options._[0];
return {
showAll: alias === "la" || options.all,
showLong: alias === "la" || alias === "ll" || options.long,
showJSON: options.json,
showNDJSON: options.ndjson,
showParseable: options.parseable,
isTopological: options.toposort,
showGraph: options.graph
};
}
function filterResultList(projectList, projectGraph, viewOptions) {
let result = viewOptions.showAll ? projectList : projectList.filter((project) => !getPackage(project).private);
if (viewOptions.isTopological) {
result = toposortProjects(result, projectGraph);
}
return result;
}
function toJSONList(resultList, addtionalProperties = () => ({})) {
return resultList.map((project) => {
const pkg = getPackage(project);
return {
name: pkg.name,
version: pkg.version,
private: pkg.private,
location: pkg.location,
...addtionalProperties(project)
};
});
}
function formatJSON(resultList, additionalProperties = () => ({})) {
return JSON.stringify(toJSONList(resultList, additionalProperties), null, 2);
}
function formatNDJSON(resultList) {
return toJSONList(resultList).map((data) => JSON.stringify(data)).join("\n");
}
function formatJSONGraph(resultList, viewOptions) {
const graph = {};
const getNeighbors = viewOptions.showAll ? (pkg) => Object.keys(
Object.assign(
{},
pkg.devDependencies,
pkg.peerDependencies,
pkg.optionalDependencies,
pkg.dependencies
)
).sort() : (pkg) => Object.keys(
Object.assign(
{},
// no devDependencies
// no peerDependencies
pkg.optionalDependencies,
pkg.dependencies
)
).sort();
for (const project of resultList) {
const pkg = getPackage(project);
graph[pkg.name] = getNeighbors(pkg);
}
return JSON.stringify(graph, null, 2);
}
function makeParseable(pkg) {
const result = [pkg.location, pkg.name];
if (pkg.version) {
result.push(pkg.version);
} else {
result.push("MISSING");
}
if (pkg.private) {
result.push("PRIVATE");
}
return result.join(":");
}
function formatParseable(resultList, viewOptions) {
return resultList.map((project) => {
const pkg = getPackage(project);
return viewOptions.showLong ? makeParseable(pkg) : pkg.location;
}).join("\n");
}
function getColumnOrder(viewOptions) {
const columns = ["name"];
if (viewOptions.showLong) {
columns.push("version", "location");
}
if (viewOptions.showAll) {
columns.push("private");
}
return columns;
}
function trimmedColumns(formattedResults, viewOptions) {
const str = columnify(formattedResults, {
showHeaders: false,
columns: getColumnOrder(viewOptions),
config: {
version: {
align: "right"
}
}
});
return str.split("\n").map((line) => line.trimRight()).join("\n");
}
function formatColumns(resultList, viewOptions) {
const formattedResults = resultList.map((project) => {
const pkg = getPackage(project);
const formatted = {
name: pkg.name
};
if (pkg.version) {
formatted.version = colorize("green", `v${pkg.version}`);
} else {
formatted.version = colorize("yellow", "MISSING");
}
if (pkg.private) {
formatted.private = `(${colorize("red", "PRIVATE")})`;
}
formatted.location = colorize("grey", path9.relative(".", pkg.location));
return formatted;
});
return trimmedColumns(formattedResults, viewOptions);
}
// libs/core/src/lib/byte-size.ts
var defaultOptions2 = {};
var referenceTables = {
metric: [
{ from: 0, to: 1e3, unit: "B", long: "bytes" },
{ from: 1e3, to: 1e6, unit: "kB", long: "kilobytes" },
{ from: 1e6, to: 1e9, unit: "MB", long: "megabytes" },
{ from: 1e9, to: 1e12, unit: "GB", long: "gigabytes" },
{ from: 1e12, to: 1e15, unit: "TB", long: "terabytes" },
{ from: 1e15, to: 1e18, unit: "PB", long: "petabytes" },
{ from: 1e18, to: 1e21, unit: "EB", long: "exabytes" },
{ from: 1e21, to: 1e24, unit: "ZB", long: "zettabytes" },
{ from: 1e24, to: 1e27, unit: "YB", long: "yottabytes" }
],
metric_octet: [
{ from: 0, to: 1e3, unit: "o", long: "octets" },
{ from: 1e3, to: 1e6, unit: "ko", long: "kilooctets" },
{ from: 1e6, to: 1e9, unit: "Mo", long: "megaoctets" },
{ from: 1e9, to: 1e12, unit: "Go", long: "gigaoctets" },
{ from: 1e12, to: 1e15, unit: "To", long: "teraoctets" },
{ from: 1e15, to: 1e18, unit: "Po", long: "petaoctets" },
{ from: 1e18, to: 1e21, unit: "Eo", long: "exaoctets" },
{ from: 1e21, to: 1e24, unit: "Zo", long: "zettaoctets" },
{ from: 1e24, to: 1e27, unit: "Yo", long: "yottaoctets" }
],
iec: [
{ from: 0, to: Math.pow(1024, 1), unit: "B", long: "bytes" },
{ from: Math.pow(1024, 1), to: Math.pow(1024, 2), unit: "KiB", long: "kibibytes" },
{ from: Math.pow(1024, 2), to: Math.pow(1024, 3), unit: "MiB", long: "mebibytes" },
{ from: Math.pow(1024, 3), to: Math.pow(1024, 4), unit: "GiB", long: "gibibytes" },
{ from: Math.pow(1024, 4), to: Math.pow(1024, 5), unit: "TiB", long: "tebibytes" },
{ from: Math.pow(1024, 5), to: Math.pow(1024, 6), unit: "PiB", long: "pebibytes" },
{ from: Math.pow(1024, 6), to: Math.pow(1024, 7), unit: "EiB", long: "exbibytes" },
{ from: Math.pow(1024, 7), to: Math.pow(1024, 8), unit: "ZiB", long: "zebibytes" },
{ from: Math.pow(1024, 8), to: Math.pow(1024, 9), unit: "YiB", long: "yobibytes" }
],
iec_octet: [
{ from: 0, to: Math.pow(1024, 1), unit: "o", long: "octets" },
{ from: Math.pow(1024, 1), to: Math.pow(1024, 2), unit: "Kio", long: "kibioctets" },
{ from: Math.pow(1024, 2), to: Math.pow(1024, 3), unit: "Mio", long: "mebioctets" },
{ from: Math.pow(1024, 3), to: Math.pow(1024, 4), unit: "Gio", long: "gibioctets" },
{ from: Math.pow(1024, 4), to: Math.pow(1024, 5), unit: "Tio", long: "tebioctets" },
{ from: Math.pow(1024, 5), to: Math.pow(1024, 6), unit: "Pio", long: "pebioctets" },
{ from: Math.pow(1024, 6), to: Math.pow(1024, 7), unit: "Eio", long: "exbioctets" },
{ from: Math.pow(1024, 7), to: Math.pow(1024, 8), unit: "Zio", long: "zebioctets" },
{ from: Math.pow(1024, 8), to: Math.pow(1024, 9), unit: "Yio", long: "yobioctets" }
]
};
var ByteSize = class {
value;
unit;
long;
#options;
constructor(bytes, options) {
const opts = {
units: "metric",
precision: 1,
locale: void 0,
...defaultOptions2,
...options
};
this.#options = opts;
if (opts.customUnits) {
Object.assign(referenceTables, opts.customUnits);
}
const prefix2 = bytes < 0 ? "-" : "";
bytes = Math.abs(bytes);
const table = referenceTables[opts.units];
if (table) {
const units = table.find((u) => bytes >= u.from && bytes < u.to);
if (units) {
const defaultFormat = new Intl.NumberFormat(opts.locale, {
style: "decimal",
maximumFractionDigits: opts.precision
});
const value = units.from === 0 ? prefix2 + defaultFormat.format(bytes) : prefix2 + defaultFormat.format(bytes / units.from);
this.value = value;
this.unit = units.unit;
this.long = units.long;
} else {
this.value = prefix2 + bytes;
this.unit = "";
this.long = "";
}
} else {
throw new Error(`Invalid units specified: ${opts.units}`);
}
}
toString() {
return this.#options.toStringFn ? this.#options.toStringFn.bind(this)() : `${this.value} ${this.unit}`;
}
};
function byteSize(bytes, options) {
return new ByteSize(bytes, options);
}
byteSize.defaultOptions = function(options) {
defaultOptions2 = options;
};
var byte_size_default = byteSize;
// libs/core/src/lib/log-packed.ts
import columnify2 from "columnify";
var hasUnicode2 = hasUnicode();
function logPacked(tarball) {
npmlog_default.notice("");
npmlog_default.notice("", `${hasUnicode2 ? "\u{1F4E6} " : "package:"} ${tarball.name}@${tarball.version}`);
if (tarball.files && tarball.files.length) {
npmlog_default.notice("=== Tarball Contents ===");
npmlog_default.notice(
"",
columnify2(
tarball.files.map((f) => {
const bytes = byte_size_default(f.size);
return {
path: f.path,
size: `${bytes.value}${bytes.unit}`
};
}),
{
// TODO: refactor based on TS feedback
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
include: ["size", "path"],
showHeaders: false
}
)
);
}
if (tarball.bundled && tarball.bundled.length) {
npmlog_default.notice("=== Bundled Dependencies ===");
tarball.bundled.forEach((name) => npmlog_default.notice("", name));
}
npmlog_default.notice("=== Tarball Details ===");
npmlog_default.notice(
"",
columnify2(
[
{ name: "name:", value: tarball.name },
{ name: "version:", value: tarball.version },
tarball.filename && { name: "filename:", value: tarball.filename },
tarball.size && { name: "package size:", value: byte_size_default(tarball.size) },
tarball.unpackedSize && { name: "unpacked size:", value: byte_size_default(tarball.unpackedSize) },
tarball.shasum && { name: "shasum:", value: tarball.shasum },
tarball.integrity && { name: "integrity:", value: elideIntegrity(tarball.integrity) },
tarball.bundled && tarball.bundled.length && {
name: "bundled deps:",
value: tarball.bundled.length
},
tarball.bundled && tarball.bundled.length && {
name: "bundled files:",
value: tarball.entryCount - tarball.files.length
},
tarball.bundled && tarball.bundled.length && {
name: "own files:",
value: tarball.files.length
},
tarball.entryCount && { name: "total files:", value: tarball.entryCount }
].filter((x) => x),
{
// TODO: refactor based on TS feedback
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
include: ["name", "value"],
showHeaders: false
}
)
);
npmlog_default.notice("", "");
}
function elideIntegrity(integrity) {
const str = integrity.toString();
return `${str.substr(0, 20)}[...]${str.substr(80)}`;
}
// libs/core/src/lib/prompt.ts
import inquirer from "inquirer";
function promptConfirmation(message) {
npmlog_default.pause();
return inquirer.prompt([
{
type: "expand",
name: "confirm",
message,
// We put any invalid default value here to help avoid accidentally clicking straight through
default: "2",
choices: [
{ key: "y", name: "Yes", value: true },
{ key: "n", name: "No", value: false }
]
}
]).then((answers) => {
npmlog_default.resume();
return answers["confirm"];
});
}
function promptSelectOne(message, {
choices,
filter,
validate: validate2
} = {}) {
npmlog_default.pause();
return inquirer.prompt([
{
type: "list",
name: "prompt",
message,
choices,
pageSize: choices?.length,
filter,
validate: validate2
}
]).then((answers) => {
npmlog_default.resume();
return answers["prompt"];
});
}
function promptTextInput(message, {
filter,
validate: validate2
} = {}) {
npmlog_default.pause();
return inquirer.prompt([
{
type: "input",
name: "input",
message,
filter,
validate: validate2
}
]).then((answers) => {
npmlog_default.resume();
return answers["input"];
});
}
// libs/core/src/lib/otplease.ts
var semaphore = {
_promise: void 0,
_resolve: void 0,
wait() {
return new Promise((resolve3) => {
if (!this._promise) {
this._promise = new Promise((release) => {
this._resolve = release;
});
resolve3(void 0);
} else {
resolve3(this._promise.then(() => this.wait()));
}
});
},
release() {
const resolve3 = this._resolve;
if (resolve3) {
this._resolve = void 0;
this._promise = void 0;
resolve3();
}
}
};
function otplease(fn, _opts, otpCache) {
const opts = { ...otpCache, ..._opts };
return attempt(fn, opts, otpCache);
}
function attempt(fn, opts, otpCache) {
return new Promise((resolve3) => {
resolve3(fn(opts));
}).catch((err) => {
if (err.code !== "EOTP" && !(err.code === "E401" && /one-time pass/.test(err.body))) {
throw err;
} else if (!process.stdin.isTTY || !process.stdout.isTTY) {
throw err;
} else {
if (otpCache != null && otpCache.otp != null && otpCache.otp !== opts["otp"]) {
return attempt(fn, { ...opts, ...otpCache }, otpCache);
}
return semaphore.wait().then(() => {
if (otpCache != null && otpCache.otp != null && otpCache.otp !== opts["otp"]) {
semaphore.release();
return attempt(fn, { ...opts, ...otpCache }, otpCache);
}
return getOneTimePassword().then(
(otp) => {
if (otpCache != null) {
otpCache.otp = otp;
}
semaphore.release();
return otp;
},
(promptError) => {
semaphore.release();
return Promise.reject(promptError);
}
).then((otp) => {
return fn({ ...opts, otp });
});
});
}
});
}
function getOneTimePassword(message = "This operation requires a one-time password:") {
return promptTextInput(message, {
filter: (otp) => otp.replace(/\s+/g, ""),
validate: (otp) => otp && /^[\d ]+$|^[A-Fa-f0-9]{64,64}$/.test(otp) || "Must be a valid one-time-password. See https://docs.npmjs.com/getting-started/using-two-factor-authentication"
});
}
// libs/core/src/lib/npm-conf/index.ts
import path16 from "path";
// libs/core/src/lib/npm-conf/conf.ts
import assert from "assert";
import fs8 from "fs";
import path14 from "path";
// libs/core/src/lib/npm-conf/env-replace.ts
function envReplace(str) {
if (typeof str !== "string" || !str) {
return str;
}
const regex = /(\\*)\$\{([^}]+)\}/g;
return str.replace(regex, (orig, esc, name) => {
esc = esc.length > 0 && esc.length % 2;
if (esc) {
return orig;
}
if (process.env[name] === void 0) {
throw new Error(`Failed to replace env in config: ${orig}`);
}
return process.env[name];
});
}
// libs/core/src/lib/npm-conf/find-prefix.ts
import fs6 from "fs";
import path10 from "path";
function findPrefix(start) {
let dir = path10.resolve(start);
let walkedUp = false;
while (path10.basename(dir) === "node_modules") {
dir = path10.dirname(dir);
walkedUp = true;
}
if (walkedUp) {
return dir;
}
return find(dir, dir);
}
function find(name, original) {
if (name === "/" || process.platform === "win32" && /^[a-zA-Z]:(\\|\/)?$/.test(name)) {
return original;
}
try {
const files = fs6.readdirSync(name);
if (files.indexOf("node_modules") !== -1 || files.indexOf("package.json") !== -1) {
return name;
}
const dirname = path10.dirname(name);
if (dirname === name) {
return original;
}
return find(dirname, original);
} catch (err) {
if (name === original) {
if (err.code === "ENOENT") {
return original;
}
throw err;
}
return original;
}
}
// libs/core/src/lib/npm-conf/parse-field.ts
import path12 from "path";
// libs/core/src/lib/npm-conf/types.ts
import path11 from "path";
import { Stream } from "stream";
import url from "url";
var Umask = () => {
};
var getLocalAddresses = () => [];
var semver3 = () => {
};
var types2 = {
access: [null, "restricted", "public"],
"allow-same-version": Boolean,
"always-auth": Boolean,
also: [null, "dev", "development"],
audit: Boolean,
"audit-level": ["low", "moderate", "high", "critical"],
"auth-type": ["legacy", "sso", "saml", "oauth"],
"bin-links": Boolean,
browser: [null, String],
ca: [null, String, Array],
cafile: path11,
cache: path11,
"cache-lock-stale": Number,
"cache-lock-retries": Number,
"cache-lock-wait": Number,
"cache-max": Number,
"cache-min": Number,
cert: [null, String],
cidr: [null, String, Array],
color: ["always", Boolean],
depth: Number,
description: Boolean,
dev: Boolean,
"dry-run": Boolean,
editor: String,
"engine-strict": Boolean,
force: Boolean,
"fetch-retries": Number,
"fetch-retry-factor": Number,
"fetch-retry-mintimeout": Number,
"fetch-retry-maxtimeout": Number,
git: String,
"git-tag-version": Boolean,
"commit-hooks": Boolean,
global: Boolean,
globalconfig: path11,
"global-style": Boolean,
group: [Number, String],
"https-proxy": [null, url],
"user-agent": String,
"ham-it-up": Boolean,
heading: String,
"if-present": Boolean,
"ignore-prepublish": Boolean,
"ignore-scripts": Boolean,
"init-module": path11,
"init-author-name": String,
"init-author-email": String,
"init-author-url": ["", url],
"init-license": String,
"init-version": semver3,
json: Boolean,
key: [null, String],
"legacy-bundling": Boolean,
link: Boolean,
"local-address": getLocalAddresses(),
loglevel: ["silent", "error", "warn", "notice", "http", "timing", "info", "verbose", "silly"],
logstream: Stream,
"logs-max": Number,
long: Boolean,
maxsockets: Number,
message: String,
"metrics-registry": [null, String],
"node-options": [null, String],
"node-version": [null, semver3],
noproxy: [null, String, Array],
offline: Boolean,
"onload-script": [null, String],
only: [null, "dev", "development", "prod", "production"],
optional: Boolean,
"package-lock": Boolean,
otp: [null, String],
"package-lock-only": Boolean,
parseable: Boolean,
"prefer-offline": Boolean,
"prefer-online": Boolean,
prefix: path11,
preid: String,
production: Boolean,
progress: Boolean,
// allow proxy to be disabled explicitly
proxy: [null, false, url],
"read-only": Boolean,
"rebuild-bundle": Boolean,
registry: [null, url],
rollback: Boolean,
save: Boolean,
"save-bundle": Boolean,
"save-dev": Boolean,
"save-exact": Boolean,
"save-optional": Boolean,
"save-prefix": String,
"save-prod": Boolean,
scope: String,
"script-shell": [null, String],
"scripts-prepend-node-path": [false, true, "auto", "warn-only"],
searchopts: String,
searchexclude: [null, String],
searchlimit: Number,
searchstaleness: Number,
"send-metrics": Boolean,
shell: String,
shrinkwrap: Boolean,
"sign-git-commit": Boolean,
"sign-git-tag": Boolean,
"sso-poll-frequency": Number,
"sso-type": [null, "oauth", "saml"],
"strict-ssl": Boolean,
tag: String,
timing: Boolean,
tmp: path11,
unicode: Boolean,
"unsafe-perm": Boolean,
"update-notifier": Boolean,
usage: Boolean,
user: [Number, String],
userconfig: path11,
umask: Umask,
version: Boolean,
"tag-version-prefix": String,
versions: Boolean,
viewer: String,
_exit: Boolean
};
// libs/core/src/lib/npm-conf/parse-field.ts
function parseField(input, key) {
if (typeof input !== "string") {
return input;
}
const typeList = [].concat(types2[key]);
const isPath = typeList.indexOf(path12) !== -1;
const isBool = typeList.indexOf(Boolean) !== -1;
const isString = typeList.indexOf(String) !== -1;
const isNumber = typeList.indexOf(Number) !== -1;
let field = `${input}`.trim();
if (/^".*"$/.test(field)) {
try {
field = JSON.parse(field);
} catch (err) {
throw new Error(`Failed parsing JSON config key ${key}: ${field}`);
}
}
if (isBool && !isString && field === "") {
return true;
}
switch (field) {
case "true": {
return true;
}
case "false": {
return false;
}
case "null": {
return null;
}
case "undefined": {
return void 0;
}
}
field = envReplace(field);
if (isPath) {
const regex = process.platform === "win32" ? /^~(\/|\\)/ : /^~\//;
if (regex.test(field) && process.env["HOME"]) {
field = path12.resolve(process.env["HOME"], field.substr(2));
}
field = path12.resolve(field);
}
if (isNumber && !Number.isNaN(field)) {
field = Number(field);
}
return field;
}
// libs/core/src/lib/npm-conf/nerf-dart.ts
import url2 from "url";
function toNerfDart(uri) {
const parsed = url2.parse(uri);
delete parsed.protocol;
delete parsed.auth;
delete parsed.query;
delete parsed.search;
delete parsed.hash;
return url2.resolve(url2.format(parsed), ".");
}
// libs/core/src/lib/npm-conf/config-chain/proto-list.ts
var proto_list_default = ProtoList;
function setProto(obj, proto) {
if (typeof Object.setPrototypeOf === "function") return Object.setPrototypeOf(obj, proto);
else obj.__proto__ = proto;
}
function ProtoList() {
this.list = [];
var root = null;
Object.defineProperty(this, "root", {
get: function() {
return root;
},
set: function(r) {
root = r;
if (this.list.length) {
setProto(this.list[this.list.length - 1], r);
}
},
enumerable: true,
configurable: true
});
}
ProtoList.prototype = {
get length() {
return this.list.length;
},
get keys() {
var k = [];
for (var i in this.list[0]) k.push(i);
return k;
},
get snapshot() {
var o2 = {};
this.keys.forEach(function(k) {
o2[k] = this.get(k);
}, this);
return o2;
},
get store() {
return this.list[0];
},
push: function(obj) {
if (typeof obj !== "object") obj = { valueOf: obj };
if (this.list.length >= 1) {
setProto(this.list[this.list.length - 1], obj);
}
setProto(obj, this.root);
return this.list.push(obj);
},
pop: function() {
if (this.list.length >= 2) {
setProto(this.list[this.list.length - 2], this.root);
}
return this.list.pop();
},
unshift: function(obj) {
setProto(obj, this.list[0] || this.root);
return this.list.unshift(obj);
},
shift: function() {
if (this.list.length === 1) {
setProto(this.list[0], this.root);
}
return this.list.shift();
},
get: function(key) {
return this.list[0][key];
},
set: function(key, val, save) {
if (!this.length) this.push({});
if (save && this.list[0].hasOwnProperty(key)) this.push({});
return this.list[0][key] = val;
},
forEach: function(fn, thisp) {
for (var key in this.list[0]) fn.call(thisp, key, this.list[0][key]);
},
slice: function() {
return this.list.slice.apply(this.list, arguments);
},
splice: function() {
var ret = this.list.splice.apply(this.list, arguments);
for (var i = 0, l = this.list.length; i < l; i++) {
setProto(this.list[i], this.list[i + 1] || this.root);
}
return ret;
}
};
// libs/core/src/lib/npm-conf/config-chain/index.ts
import path13 from "path";
import fs7 from "fs";
import ini from "ini";
import { EventEmitter as EE } from "events";
import url3 from "url";
import http from "http";
var cc = function() {
var args = [].slice.call(arguments), conf = new ConfigChain();
while (args.length) {
var a = args.shift();
if (a) conf.push("string" === typeof a ? json(a) : a);
}
return conf;
};
var find2 = cc.find = function() {
var rel = path13.join.apply(null, [].slice.call(arguments));
function find3(start, rel2) {
var file = path13.join(start, rel2);
try {
fs7.statSync(file);
return file;
} catch (err) {
if (path13.dirname(start) !== start)
return find3(path13.dirname(start), rel2);
}
}
return find3(import.meta.dirname, rel);
};
var parse2 = cc.parse = function(content, file, type) {
content = "" + content;
if (!type) {
try {
return JSON.parse(content);
} catch (er) {
return ini.parse(content);
}
} else if (type === "json") {
if (this.emit) {
try {
return JSON.parse(content);
} catch (er) {
this.emit("error", er);
}
} else {
return JSON.parse(content);
}
} else {
return ini.parse(content);
}
};
var json = cc.json = function() {
var args = [].slice.call(arguments).filter(function(arg) {
return arg != null;
});
var file = path13.join.apply(null, args);
var content;
try {
content = fs7.readFileSync(file, "utf-8");
} catch (err) {
return;
}
return parse2(content, file, "json");
};
var env = cc.env = function(prefix2, env2) {
env2 = env2 || process.env;
var obj = {};
var l = prefix2.length;
for (var k in env2) {
if (k.indexOf(prefix2) === 0) obj[k.substring(l)] = env2[k];
}
return obj;
};
cc.ConfigChain = ConfigChain;
function ConfigChain() {
EE.apply(this);
proto_list_default.apply(this, arguments);
this._awaiting = 0;
this._saving = 0;
this.sources = {};
}
var extras = {
constructor: { value: ConfigChain }
};
Object.keys(EE.prototype).forEach(function(k) {
extras[k] = Object.getOwnPropertyDescriptor(EE.prototype, k);
});
ConfigChain.prototype = Object.create(proto_list_default.prototype, extras);
ConfigChain.prototype.del = function(key, where) {
if (where) {
var target = this.sources[where];
target = target && target.data;
if (!target) {
return this.emit("error", new Error("not found " + where));
}
delete target[key];
} else {
for (var i = 0, l = this.list.length; i < l; i++) {
delete this.list[i][key];
}
}
return this;
};
ConfigChain.prototype.set = function(key, value, where) {
var target;
if (where) {
target = this.sources[where];
target = target && target.data;
if (!target) {
return this.emit("error", new Error("not found " + where));
}
} else {
target = this.list[0];
if (!target) {
return this.emit("error", new Error("cannot set, no confs!"));
}
}
target[key] = value;
return this;
};
ConfigChain.prototype.get = function(key, where) {
if (where) {
where = this.sources[where];
if (where) where = where.data;
if (where && Object.hasOwnProperty.call(where, key)) return where[key];
return void 0;
}
return this.list[0][key];
};
ConfigChain.prototype.save = function(where, type, cb) {
if (typeof type === "function") cb = type, type = null;
var target = this.sources[where];
if (!target || !(target.path || target.source) || !target.data) {
return this.emit("error", new Error("bad save target: " + where));
}
if (target.source) {
var pref = target.prefix || "";
Object.keys(target.data).forEach(function(k) {
target.source[pref + k] = target.data[k];
});
return this;
}
var type = type || target.type;
var data = target.data;
if (target.type === "json") {
data = JSON.stringify(data);
} else {
data = ini.stringify(data);
}
this._saving++;
fs7.writeFile(
target.path,
data,
"utf8",
function(er) {
this._saving--;
if (er) {
if (cb) return cb(er);
else return this.emit("error", er);
}
if (this._saving === 0) {
if (cb) cb();
this.emit("save");
}
}.bind(this)
);
return this;
};
ConfigChain.prototype.addFile = function(file, type, name) {
name = name || file;
var marker = { __source__: name };
this.sources[name] = { path: file, type };
this.push(marker);
this._await();
fs7.readFile(
file,
"utf8",
function(er, data) {
if (er) this.emit("error", er);
this.addString(data, file, type, marker);
}.bind(this)
);
return this;
};
ConfigChain.prototype.addEnv = function(prefix2, env2, name) {
name = name || "env";
var data = cc.env(prefix2, env2);
this.sources[name] = { data, source: env2, prefix: prefix2 };
return this.add(data, name);
};
ConfigChain.prototype.addUrl = function(req, type, name) {
this._await();
var href = url3.format(req);
name = name || href;
var marker = { __source__: name };
this.sources[name] = { href, type };
this.push(marker);
http.request(
req,
function(res) {
var c = [];
var ct = res.headers["content-type"];
if (!type) {
type = ct.indexOf("json") !== -1 ? "json" : ct.indexOf("ini") !== -1 ? "ini" : href.match(/\.json$/) ? "json" : href.match(/\.ini$/) ? "ini" : null;
marker.type = type;
}
res.on("data", c.push.bind(c)).on(
"end",
function() {
this.addString(Buffer.concat(c), href, type, marker);
}.bind(this)
).on("error", this.emit.bind(this, "error"));
}.bind(this)
).on("error", this.emit.bind(this, "error")).end();
return this;
};
ConfigChain.prototype.addString = function(data, file, type, marker) {
data = this.parse(data, file, type);
this.add(data, marker);
return this;
};
ConfigChain.prototype.add = function(data, marker) {
if (marker && typeof marker === "object") {
var i = this.list.indexOf(marker);
if (i === -1) {
return this.emit("error", new Error("bad marker"));
}
this.splice(i, 1, data);
marker = marker.__source__;
this.sources[marker] = this.sources[marker] || {};
this.sources[marker].data = data;
this._resolve();
} else {
if (typeof marker === "string") {
this.sources[marker] = this.sources[marker] || {};
this.sources[marker].data = data;
}
this._await();
this.push(data);
process.nextTick(this._resolve.bind(this));
}
return this;
};
ConfigChain.prototype.parse = cc.parse;
ConfigChain.prototype._await = function() {
this._awaiting++;
};
ConfigChain.prototype._resolve = function() {
this._awaiting--;
if (this._awaiting === 0) this.emit("load", this);
};
var _ConfigChain = ConfigChain;
// libs/core/src/lib/npm-conf/conf.ts
var Conf = class extends _ConfigChain {
root;
// https://github.com/npm/npm/blob/latest/lib/config/core.js#L208-L222
constructor(base) {
super(base);
this.root = base;
}
// https://github.com/npm/npm/blob/latest/lib/config/core.js#L332-L342
add(data, marker) {
try {
for (const x of Object.keys(data)) {
const newKey = envReplace(x);
const newField = parseField(data[x], newKey);
delete data[x];
data[newKey] = newField;
}
} catch (err) {
throw err;
}
return super.add(data, marker);
}
// https://github.com/npm/npm/blob/latest/lib/config/core.js#L312-L325
addFile(file, name = file) {
const marker = { __source__: name };
this["sources"][name] = { path: file, type: "ini" };
this["push"](marker);
this["_await"]();
try {
const contents = fs8.readFileSync(file, "utf8");
this["addString"](contents, file, "ini", marker);
} catch (err) {
this["add"]({}, marker);
}
return this;
}
// https://github.com/npm/npm/blob/latest/lib/config/core.js#L344-L360
addEnv(env2 = process.env) {
const conf = {};
Object.keys(env2).filter((x) => /^npm_config_/i.test(x)).forEach((x) => {
if (!env2[x]) {
return;
}
const p = x.toLowerCase().replace(/^npm_config_/, "").replace(/(?!^)_/g, "-");
conf[p] = env2[x];
});
return super.addEnv("", conf, "env");
}
// https://github.com/npm/npm/blob/latest/lib/config/load-prefix.js
loadPrefix() {
const cli = this["list"][0];
Object.defineProperty(this, "prefix", {
enumerable: true,
set: (prefix2) => {
const g = this["get"]("global");
this[g ? "globalPrefix" : "localPrefix"] = prefix2;
},
get: () => {
const g = this["get"]("global");
return g ? this["globalPrefix"] : this["localPrefix"];
}
});
Object.defineProperty(this, "globalPrefix", {
enumerable: true,
set: (prefix2) => {
this["set"]("prefix", prefix2);
},
get: () => path14.resolve(this["get"]("prefix"))
});
let p;
Object.defineProperty(this, "localPrefix", {
enumerable: true,
set: (prefix2) => {
p = prefix2;
},
get: () => p
});
if (Object.prototype.hasOwnProperty.call(cli, "prefix")) {
p = path14.resolve(cli.prefix);
} else {
try {
p = findPrefix(process.cwd());
} catch (err) {
throw err;
}
}
return p;
}
// https://github.com/npm/npm/blob/latest/lib/config/load-cafile.js
loadCAFile(file) {
if (!file) {
return;
}
try {
const contents = fs8.readFileSync(file, "utf8");
const delim = "-----END CERTIFICATE-----";
const output2 = contents.split(delim).filter((x) => Boolean(x.trim())).map((x) => x.trimLeft() + delim);
this["set"]("ca", output2);
} catch (err) {
if (err.code === "ENOENT") {
return;
}
throw err;
}
}
// https://github.com/npm/npm/blob/latest/lib/config/set-user.js
loadUser() {
const defConf = this.root;
if (this["get"]("global")) {
return;
}
if (process.env["SUDO_UID"]) {
defConf.user = Number(process.env["SUDO_UID"]);
return;
}
const prefix2 = path14.resolve(this["get"]("prefix"));
try {
const stats = fs8.statSync(prefix2);
defConf.user = stats.uid;
} catch (err) {
if (err.code === "ENOENT") {
return;
}
throw err;
}
}
// https://github.com/npm/npm/blob/24ec9f2/lib/config/get-credentials-by-uri.js
getCredentialsByURI(uri) {
assert(uri && typeof uri === "string", "registry URL is required");
const nerfed = toNerfDart(uri);
const defnerf = toNerfDart(this["get"]("registry"));
const c = {
scope: nerfed,
token: void 0,
password: void 0,
username: void 0,
email: void 0,
auth: void 0,
alwaysAuth: void 0
};
if (this["get"](`${nerfed}:always-auth`) !== void 0) {
const val = this["get"](`${nerfed}:always-auth`);
c.alwaysAuth = val === "false" ? false : !!val;
} else if (this["get"]("always-auth") !== void 0) {
c.alwaysAuth = this["get"]("always-auth");
}
if (this["get"](`${nerfed}:_authToken`)) {
c.token = this["get"](`${nerfed}:_authToken`);
return c;
}
let authDef = this["get"]("_auth");
let userDef = this["get"]("username");
let passDef = this["get"]("_password");
if (authDef && !(userDef && passDef)) {
authDef = Buffer.from(authDef, "base64").toString();
authDef = authDef.split(":");
userDef = authDef.shift();
passDef = authDef.join(":");
}
if (this["get"](`${nerfed}:_password`)) {
c.password = Buffer.from(this["get"](`${nerfed}:_password`), "base64").toString("utf8");
} else if (nerfed === defnerf && passDef) {
c.password = passDef;
}
if (this["get"](`${nerfed}:username`)) {
c.username = this["get"](`${nerfed}:username`);
} else if (nerfed === defnerf && userDef) {
c.username = userDef;
}
if (this["get"](`${nerfed}:email`)) {
c.email = this["get"](`${nerfed}:email`);
} else if (this["get"]("email")) {
c.email = this["get"]("email");
}
if (c.username && c.password) {
c.auth = Buffer.from(`${c.username}:${c.password}`).toString("base64");
}
return c;
}
// https://github.com/npm/npm/blob/24ec9f2/lib/config/set-credentials-by-uri.js
setCredentialsByURI(uri, c) {
assert(uri && typeof uri === "string", "registry URL is required");
assert(c && typeof c === "object", "credentials are required");
const nerfed = toNerfDart(uri);
if (c.token) {
this["set"](`${nerfed}:_authToken`, c.token, "user");
this["del"](`${nerfed}:_password`, "user");
this["del"](`${nerfed}:username`, "user");
this["del"](`${nerfed}:email`, "user");
this["del"](`${nerfed}:always-auth`, "user");
} else if (c.username || c.password || c.email) {
assert(c.username, "must include username");
assert(c.password, "must include password");
assert(c.email, "must include email address");
this["del"](`${nerfed}:_authToken`, "user");
const encoded = Buffer.from(c.password, "utf8").toString("base64");
this["set"](`${nerfed}:_password`, encoded, "user");
this["set"](`${nerfed}:username`, c.username, "user");
this["set"](`${nerfed}:email`, c.email, "user");
if (c.alwaysAuth !== void 0) {
this["set"](`${nerfed}:always-auth`, c.alwaysAuth, "user");
} else {
this["del"](`${nerfed}:always-auth`, "user");
}
} else {
throw new Error("No credentials to set.");
}
}
};
// libs/core/src/lib/npm-conf/defaults.ts
import os8 from "os";
import path15 from "path";
var temp = os8.tmpdir();
var uidOrPid = process.getuid ? process.getuid() : process.pid;
var hasUnicode3 = () => true;
var isWindows = process.platform === "win32";
var osenv = {
editor: () => process.env["EDITOR"] || process.env["VISUAL"] || (isWindows ? "notepad.exe" : "vi"),
shell: () => isWindows ? process.env["COMSPEC"] || "cmd.exe" : process.env["SHELL"] || "/bin/bash"
};
var umask = {
fromString: () => process.umask()
};
var home = os8.homedir();
if (home) {
process.env["HOME"] = home;
} else {
home = path15.resolve(temp, `npm-${uidOrPid}`);
}
var cacheExtra = process.platform === "win32" ? "npm-cache" : ".npm";
var cacheRoot = process.platform === "win32" && process.env["APPDATA"] || home;
var cache = path15.resolve(cacheRoot, cacheExtra);
function getGlobalPrefix() {
let globalPrefix2;
if (process.env["PREFIX"]) {
globalPrefix2 = process.env["PREFIX"];
} else if (process.platform === "win32") {
globalPrefix2 = path15.dirname(process.execPath);
} else {
globalPrefix2 = path15.dirname(path15.dirname(process.execPath));
if (process.env["DESTDIR"]) {
globalPrefix2 = path15.join(process.env["DESTDIR"], globalPrefix2);
}
}
return globalPrefix2;
}
var globalPrefix = getGlobalPrefix();
var defaults = {
access: null,
"allow-same-version": false,
"always-auth": false,
also: null,
audit: true,
"audit-level": "low",
"auth-type": "legacy",
"bin-links": true,
browser: null,
ca: null,
cafile: null,
cache,
"cache-lock-stale": 6e4,
"cache-lock-retries": 10,
"cache-lock-wait": 1e4,
"cache-max": Infinity,
"cache-min": 10,
cert: null,
cidr: null,
// color: true/false depending on NO_COLOR and FORCE_COLOR (NO_COLOR disables color, except NO_COLOR="false" means color enabled; FORCE_COLOR has priority if set)
color: typeof process.env["FORCE_COLOR"] !== "undefined" ? !!process.env["FORCE_COLOR"] && process.env["FORCE_COLOR"] !== "0" : typeof process.env["NO_COLOR"] !== "undefined" ? ["", "0"].includes(process.env["NO_COLOR"]) ? true : process.env["NO_COLOR"] === "false" ? true : false : true,
depth: Infinity,
description: true,
dev: false,
"dry-run": false,
editor: osenv.editor(),
"engine-strict": false,
force: false,
"fetch-retries": 2,
"fetch-retry-factor": 10,
"fetch-retry-mintimeout": 1e4,
"fetch-retry-maxtimeout": 6e4,
git: "git",
"git-tag-version": true,
"commit-hooks": true,
global: false,
globalconfig: path15.resolve(globalPrefix, "etc", "npmrc"),
"global-style": false,
group: process.platform === "win32" ? 0 : process.env["SUDO_GID"] || process.getgid && process.getgid(),
"ham-it-up": false,
heading: "npm",
"if-present": false,
"ignore-prepublish": false,
"ignore-scripts": false,
"init-module": path15.resolve(home, ".npm-init.js"),
"init-author-name": "",
"init-author-email": "",
"init-author-url": "",
"init-version": "1.0.0",
"init-license": "ISC",
json: false,
key: null,
"legacy-bundling": false,
link: false,
"local-address": void 0,
loglevel: "notice",
logstream: process.stderr,
"logs-max": 10,
long: false,
maxsockets: 50,
message: "%s",
"metrics-registry": null,
"node-options": null,
"node-version": process.version,
offline: false,
"onload-script": false,
only: null,
optional: true,
otp: void 0,
"package-lock": true,
"package-lock-only": false,
parseable: false,
"prefer-offline": false,
"prefer-online": false,
prefix: globalPrefix,
preid: "",
production: process.env["NODE_ENV"] === "production",
progress: !process.env["TRAVIS"] && !process.env["CI"],
proxy: null,
"https-proxy": null,
noproxy: null,
"user-agent": "npm/{npm-version} node/{node-version} {platform} {arch}",
"read-only": false,
"rebuild-bundle": true,
registry: "https://registry.npmjs.org/",
rollback: true,
save: true,
"save-bundle": false,
"save-dev": false,
"save-exact": false,
"save-optional": false,
"save-prefix": "^",
"save-prod": false,
scope: "",
"script-shell": void 0,
"scripts-prepend-node-path": "warn-only",
searchopts: "",
searchexclude: null,
searchlimit: 20,
searchstaleness: 15 * 60,
"send-metrics": false,
shell: osenv.shell(),
shrinkwrap: true,
"sign-git-commit": false,
"sign-git-tag": false,
"sso-poll-frequency": 500,
"sso-type": "oauth",
"strict-ssl": true,
tag: "latest",
"tag-version-prefix": "v",
timing: false,
tmp: temp,
unicode: hasUnicode3(),
"unsafe-perm": process.platform === "win32" || process.platform === "cygwin" || // TODO: refactor based on TS feedback
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
!(process.getuid && process.setuid && process.getgid && process.setgid) || process.getuid() !== 0,
"update-notifier": true,
usage: false,
user: process.platform === "win32" || os8.type() === "OS400" ? 0 : "nobody",
userconfig: path15.resolve(home, ".npmrc"),
// TODO: refactor based on TS feedback
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
umask: process.umask ? process.umask() : umask.fromString("022"),
version: false,
versions: false,
viewer: process.platform === "win32" ? "browser" : "man",
_exit: true
};
// libs/core/src/lib/npm-conf/index.ts
var defaultsCopy = Object.assign({}, defaults);
function npmConf(opts) {
const conf = new Conf(Object.assign({}, defaults));
const cleanOpts = opts ? Object.keys(opts).reduce((acc, key) => {
if (opts[key] !== void 0) {
acc[key] = opts[key];
}
return acc;
}, {}) : {};
conf.add(cleanOpts, "cli");
conf.addEnv();
conf.loadPrefix();
const projectConf = path16.resolve(conf["localPrefix"], ".npmrc");
const userConf = conf["get"]("userconfig");
if (!conf["get"]("global") && projectConf !== userConf) {
conf.addFile(projectConf, "project");
} else {
conf.add({}, "project");
}
conf.addFile(conf["get"]("userconfig"), "user");
if (conf["get"]("prefix")) {
const etc = path16.resolve(conf["get"]("prefix"), "etc");
conf.root.globalconfig = path16.resolve(etc, "npmrc");
conf.root.globalignorefile = path16.resolve(etc, "npmignore");
}
conf.addFile(conf["get"]("globalconfig"), "global");
conf.loadUser();
const caFile = conf["get"]("cafile");
if (caFile) {
conf.loadCAFile(caFile);
}
return conf;
}
// libs/core/src/lib/run-lifecycle.ts
import PQueueImport from "p-queue";
import runScript from "@npmcli/run-script";
var PQueue = PQueueImport.default ?? PQueueImport;
var queue = new PQueue({ concurrency: 1 });
function flattenOptions(obj) {
return {
ignorePrepublish: obj["ignore-prepublish"],
ignoreScripts: obj["ignore-scripts"],
nodeOptions: obj["node-options"],
scriptShell: obj["script-shell"],
scriptsPrependNodePath: obj["scripts-prepend-node-path"],
unsafePerm: obj["unsafe-perm"],
...obj
};
}
function printCommandBanner(id, event, cmd, path23) {
return console.log(`
> ${id ? `${id} ` : ""}${event} ${path23}
> ${cmd.trim().replace(/\n/g, "\n> ")}
`);
}
function runLifecycle(pkg, stage, options) {
if ("root" in options) {
options = options.snapshot;
}
const opts = {
log: npmlog_default,
unsafePerm: true,
...flattenOptions(options)
};
const dir = pkg.location;
const id = `${pkg.name}@${pkg.version}`;
const config = {};
if (opts.ignoreScripts) {
opts.log.verbose("lifecycle", "%j ignored in %j", stage, pkg.name);
return Promise.resolve();
}
if (!pkg.scripts || !pkg.scripts[stage]) {
opts.log.silly("lifecycle", "No script for %j in %j, continuing", stage, pkg.name);
return Promise.resolve();
}
if (stage === "prepublish" && opts.ignorePrepublish) {
opts.log.verbose("lifecycle", "%j ignored in %j", stage, pkg.name);
return Promise.resolve();
}
for (const [key, val] of Object.entries(opts)) {
if (val != null && key !== "log" && key !== "logstream") {
config[key] = val;
}
}
if (pkg.__isLernaPackage) {
pkg = pkg.toJSON();
}
pkg._id = id;
opts.log.silly("lifecycle", "%j starting in %j", stage, pkg.name);
opts.log.info("lifecycle", `${id}~${stage}: ${id}`);
const stdio = opts.stdio || "pipe";
if (npmlog_default.level !== "silent") {
printCommandBanner(id, stage, pkg.scripts[stage], dir);
}
return queue.add(
async () => runScript({
event: stage,
path: dir,
pkg,
args: [],
stdio,
banner: false,
// TODO: refactor based on TS feedback
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
scriptShell: config.scriptShell
}).then(
({ stdout }) => {
if (stdout) {
process.stdout.write(stdout.toString().trimEnd() + "\n");
}
opts.log.silly("lifecycle", "%j finished in %j", stage, pkg.name);
},
(err) => {
const exitCode = err.code || 1;
npmlog_default.error("lifecycle", "%j errored in %j, exiting %d", stage, pkg.name, exitCode);
err.name = "ValidationError";
err.exitCode = exitCode;
process.exitCode = exitCode;
throw err;
}
)
);
}
function createRunner(commandOptions) {
const cfg = npmConf(commandOptions)["snapshot"];
return (pkg, stage) => runLifecycle(pkg, stage, cfg);
}
// libs/core/src/lib/npm-publish.ts
import PackageJson from "@npmcli/package-json";
import fs9 from "fs-extra";
import { publish } from "libnpmpublish";
import npa4 from "npm-package-arg";
import path17 from "path";
// libs/core/src/lib/oidc.ts
import ciInfo from "ci-info";
import libaccess from "libnpmaccess";
import fetch from "make-fetch-happen";
import npa3 from "npm-package-arg";
import npmFetch from "npm-registry-fetch";
async function oidc({ packageName, registry, opts, config }) {
try {
if (!/** @see https://github.com/watson/ci-info/blob/v4.2.0/vendors.json#L152 */
(ciInfo.GITHUB_ACTIONS || /** @see https://github.com/watson/ci-info/blob/v4.2.0/vendors.json#L161C13-L161C22 */
ciInfo.GITLAB || /** @see https://github.com/watson/ci-info/blob/v4.2.0/vendors.json#L78 */
ciInfo.CIRCLE)) {
return void 0;
}
let idToken = process.env["NPM_ID_TOKEN"];
if (!idToken && ciInfo.GITHUB_ACTIONS) {
if (!(process.env["ACTIONS_ID_TOKEN_REQUEST_URL"] && process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"])) {
npmlog_default.silly("oidc", "Skipped because incorrect permissions for id-token within GitHub workflow");
return void 0;
}
const audience = `npm:${new URL(registry).hostname}`;
const url4 = new URL(process.env["ACTIONS_ID_TOKEN_REQUEST_URL"]);
url4.searchParams.append("audience", audience);
const startTime = Date.now();
const response2 = await fetch(url4.href, {
retry: opts.retry,
headers: {
Accept: "application/json",
Authorization: `Bearer ${process.env["ACTIONS_ID_TOKEN_REQUEST_TOKEN"]}`
}
});
const elapsedTime = Date.now() - startTime;
npmlog_default.http("fetch", `GET ${url4.href} ${response2.status} ${elapsedTime}ms`);
const json2 = await response2.json();
if (!response2.ok) {
npmlog_default.verbose("oidc", `Failed to fetch id_token from GitHub: received an invalid response`);
return void 0;
}
if (!json2.value) {
npmlog_default.verbose("oidc", `Failed to fetch id_token from GitHub: missing value`);
return void 0;
}
idToken = json2.value;
}
if (!idToken) {
npmlog_default.silly("oidc", "Skipped because no id_token available");
return void 0;
}
const parsedRegistry = new URL(registry);
const regKey = `//${parsedRegistry.host}${parsedRegistry.pathname}`;
const authTokenKey = `${regKey}:_authToken`;
const escapedPackageName = npa3(packageName).escapedName;
let response;
try {
response = await npmFetch.json(
// @ts-expect-error - Taken directly from npm codebase, the types for .json must be incomplete
new URL(`/-/npm/v1/oidc/token/exchange/package/${escapedPackageName}`, registry),
{
...opts,
[authTokenKey]: idToken,
// Use the idToken as the auth token for the request
method: "POST"
}
);
} catch (error) {
npmlog_default.verbose(
"oidc",
`Failed token exchange request with body message: ${error?.body?.message || "Unknown error"}`
);
return void 0;
}
if (!response?.["token"]) {
npmlog_default.verbose("oidc", "Failed because token exchange was missing the token in the response body");
return void 0;
}
opts[authTokenKey] = response["token"];
config["set"](authTokenKey, response["token"], "user");
npmlog_default.verbose("oidc", `Successfully retrieved and set token`);
try {
const [headerB64, payloadB64] = idToken.split(".");
if (headerB64 && payloadB64) {
const payloadJson = Buffer.from(payloadB64, "base64").toString("utf8");
const payload = JSON.parse(payloadJson);
if (ciInfo.GITHUB_ACTIONS && payload.repository_visibility === "public" || // only set provenance for gitlab if the repo is public and SIGSTORE_ID_TOKEN is available
ciInfo.GITLAB && payload.project_visibility === "public" && process.env["SIGSTORE_ID_TOKEN"]) {
const visibility = await libaccess.getVisibility(packageName, opts);
if (visibility?.public) {
npmlog_default.verbose("oidc", `Enabling provenance`);
opts.provenance = true;
config["set"]("provenance", true, "user");
}
}
}
} catch (error) {
npmlog_default.verbose("oidc", `Failed to set provenance with message: ${error?.message || "Unknown error"}`);
}
} catch (error) {
npmlog_default.verbose("oidc", `Failure with message: ${error?.message || "Unknown error"}`);
}
return void 0;
}
// libs/core/src/lib/npm-publish.ts
function flattenOptions2(obj) {
return {
defaultTag: obj["tag"] || "latest",
dryRun: obj["dry-run"],
// libnpmpublish / npm-registry-fetch check strictSSL rather than strict-ssl
strictSSL: obj["strict-ssl"],
...obj
};
}
async function npmPublish(pkg, tarFilePath, options, conf, otpCache) {
const { dryRun, ...remainingOptions } = flattenOptions2(options);
const { scope } = npa4(pkg.name);
const opts = {
log: npmlog_default,
...remainingOptions,
projectScope: scope
};
opts.log.verbose("publish", pkg.name);
let result;
if (!dryRun) {
let { manifestLocation } = pkg;
if (pkg.contents !== pkg.location) {
manifestLocation = path17.join(pkg.contents, "package.json");
}
const [tarData, npmCliPackageJson] = await Promise.all([
fs9.readFile(tarFilePath),
await PackageJson.prepare(path17.dirname(manifestLocation))
]);
const manifestContent = npmCliPackageJson.content;
if (opts.defaultTag !== "latest" && manifestContent.publishConfig && manifestContent.publishConfig.tag && manifestContent.publishConfig.tag !== opts.defaultTag) {
manifestContent.publishConfig.tag = opts.defaultTag;
}
if (manifestContent.publishConfig) {
Object.assign(opts, publishConfigToOpts(manifestContent.publishConfig));
}
await oidc({
packageName: pkg.name,
registry: opts.registry ?? "https://registry.npmjs.org/",
opts,
config: conf
});
result = await otplease((innerOpts) => publish(manifestContent, tarData, innerOpts), opts, otpCache);
}
opts.stdio = "inherit";
await runLifecycle(pkg, "publish", opts);
await runLifecycle(pkg, "postpublish", opts);
return result;
}
function publishConfigToOpts(publishConfig) {
const opts = { ...publishConfig };
if (publishConfig.tag) {
opts.defaultTag = publishConfig.tag;
delete opts.tag;
}
return opts;
}
// libs/core/src/lib/output.ts
function output(...args) {
npmlog_default["clearProgress"]();
console.log(...args);
npmlog_default["showProgress"]();
}
// libs/core/src/lib/pack-directory.ts
import Arborist from "@npmcli/arborist";
import packlist from "npm-packlist";
import path20 from "path";
import * as tar2 from "tar";
// libs/core/src/lib/get-packed.ts
import fs10 from "fs-extra";
import path18 from "path";
import ssri from "ssri";
import * as tar from "tar";
function getPacked(pkg, tarFilePath) {
const bundledWanted = new Set(pkg.bundleDependencies || pkg.bundledDependencies || []);
const bundled = /* @__PURE__ */ new Set();
const files = [];
let totalEntries = 0;
let totalEntrySize = 0;
return tar.list({
file: tarFilePath,
onentry(entry) {
totalEntries += 1;
totalEntrySize += entry.size;
const p = entry.path;
if (p.startsWith("package/node_modules/")) {
const name = p.match(/^package\/node_modules\/((?:@[^/]+\/)?[^/]+)/)[1];
if (bundledWanted.has(name)) {
bundled.add(name);
}
} else {
files.push({
path: entry.path.replace(/^package\//, ""),
size: entry.size,
mode: entry.mode
});
}
},
strip: 1
}).then(
() => Promise.all([
fs10.stat(tarFilePath),
ssri.fromStream(fs10.createReadStream(tarFilePath), {
algorithms: ["sha1", "sha512"]
})
])
).then(([{ size }, { sha1, sha512 }]) => {
const shasum = sha1[0].hexDigest();
return {
id: `${pkg.name}@${pkg.version}`,
name: pkg.name,
version: pkg.version,
size,
unpackedSize: totalEntrySize,
shasum,
integrity: ssri.parse(sha512[0]),
filename: path18.basename(tarFilePath),
files,
entryCount: totalEntries,
bundled: Array.from(bundled),
tarFilePath
};
});
}
// libs/core/src/lib/temp-write.ts
import { randomUUID } from "node:crypto";
import fs11 from "node:fs";
import os9 from "node:os";
import path19 from "path";
var tempDir = fs11.realpathSync(os9.tmpdir());
var tempfile = (filePath) => path19.join(tempDir, randomUUID(), filePath || "");
var writeStream = async (filePath, fileContent) => new Promise((resolve3, reject) => {
const writable = fs11.createWriteStream(filePath);
fileContent.on("error", (error) => {
reject(error);
fileContent.unpipe(writable);
writable.end();
}).pipe(writable).on("error", reject).on("finish", resolve3);
});
async function tempWrite(fileContent, filePath) {
const tempPath = tempfile(filePath);
const write = fileContent !== null && typeof fileContent === "object" && typeof fileContent.pipe === "function" ? writeStream : fs11.promises.writeFile;
await fs11.promises.mkdir(path19.dirname(tempPath), { recursive: true });
await write(tempPath, fileContent);
return tempPath;
}
tempWrite.sync = (fileContent, filePath) => {
const tempPath = tempfile(filePath);
fs11.mkdirSync(path19.dirname(tempPath), { recursive: true });
fs11.writeFileSync(tempPath, fileContent);
return tempPath;
};
var temp_write_default = tempWrite;
// libs/core/src/lib/pack-directory.ts
async function packDirectory(_pkg, dir, options) {
const pkg = Package.lazy(_pkg, dir);
const opts = {
log: npmlog_default,
...options
};
opts.log.verbose("pack-directory", path20.relative(".", pkg.contents));
if (opts.ignorePrepublish !== true) {
await runLifecycle(pkg, "prepublish", opts);
}
await runLifecycle(pkg, "prepare", opts);
if (opts.lernaCommand === "publish") {
opts.stdio = "inherit";
await pkg.refresh();
await runLifecycle(pkg, "prepublishOnly", opts);
await pkg.refresh();
}
await runLifecycle(pkg, "prepack", opts);
await pkg.refresh();
const arborist = new Arborist({
path: pkg.contents
});
const tree = await arborist.loadActual();
const files = await packlist(tree);
const stream3 = tar2.create(
{
cwd: pkg.contents,
prefix: "package/",
portable: true,
// Provide a specific date in the 1980s for the benefit of zip,
// which is confounded by files dated at the Unix epoch 0.
mtime: /* @__PURE__ */ new Date("1985-10-26T08:15:00.000Z"),
gzip: true
},
// NOTE: node-tar does some Magic Stuff depending on prefixes for files
// specifically with @ signs, so we just neutralize that one
// and any such future "features" by prepending `./`
files.map((f) => `./${f}`)
);
const tarFilePath = await temp_write_default(stream3, getTarballName(pkg));
const packed = await getPacked(pkg, tarFilePath);
await runLifecycle(pkg, "postpack", opts);
return packed;
}
function getTarballName(pkg) {
const name = pkg.name[0] === "@" ? (
// scoped packages get special treatment
pkg.name.substr(1).replace(/\//g, "-")
) : pkg.name;
return `${name}-${pkg.version}.tgz`;
}
// libs/core/src/lib/pulse-till-done.ts
var pulsers = 0;
var pulse;
function pulseStart(prefix2) {
pulsers += 1;
if (pulsers > 1) {
return;
}
pulse = setInterval(() => npmlog_default.gauge.pulse(prefix2), 150);
}
function pulseStop() {
pulsers -= 1;
if (pulsers > 0) {
return;
}
clearInterval(pulse);
}
function pulseTillDone(prefix2, promise) {
if (!promise) {
promise = prefix2;
prefix2 = "";
}
pulseStart(prefix2);
return Promise.resolve(promise).then(
(val) => {
pulseStop();
return val;
},
(err) => {
pulseStop();
throw err;
}
);
}
// libs/core/src/lib/rimraf-dir.ts
import { existsSync } from "node:fs";
import { rm } from "node:fs/promises";
async function rimrafDir(dirPath) {
npmlog_default.silly("rimrafDir", dirPath);
if (!existsSync(dirPath)) {
return;
}
await rm(dirPath, { recursive: true, force: true });
npmlog_default.verbose("rimrafDir", "removed", dirPath);
}
// libs/core/src/lib/run-projects-topologically.ts
import PQueueImport2 from "p-queue";
var PQueue2 = PQueueImport2.default ?? PQueueImport2;
async function runProjectsTopologically(projects, projectGraph, runner, { concurrency, rejectCycles } = {}) {
const queue2 = new PQueue2({ concurrency });
const returnValues = [];
const projectsMap = new Map(projects.map((p) => [p.name, p]));
const localDependencies = projectGraph.localPackageDependencies;
const flattenedLocalDependencies = Object.values(localDependencies).flat();
const getProject = (name) => {
const project = projectsMap.get(name);
if (!project) {
throw new Error(`Failed to find project ${name}. This is likely a bug in Lerna's toposort algorithm.`);
}
return project;
};
const dependenciesBySource = projects.reduce(
(prev, next) => ({
...prev,
[next.name]: /* @__PURE__ */ new Set()
}),
{}
);
flattenedLocalDependencies.forEach((dep) => {
if (dependenciesBySource[dep.source] && projectsMap.has(dep.target)) {
dependenciesBySource[dep.source].add(dep.target);
}
});
const unmergedCycles = getCycles(dependenciesBySource);
reportCycles(unmergedCycles, rejectCycles);
const cycles = new Set(mergeOverlappingCycles(unmergedCycles));
const seen = /* @__PURE__ */ new Set();
const errors = [];
const queueNextPackages = () => {
if (seen.size === projects.length) {
return;
}
let batch = Object.keys(dependenciesBySource).filter((p) => dependenciesBySource[p].size === 0).filter((p) => !seen.has(p));
if (batch.length === 0) {
const cycle = Array.from(cycles.values()).find((cycle2) => {
const cycleHasExternalDependencies = cycle2.some((project) => {
const projectDeps = dependenciesBySource[project];
const depIsNotInCycle = (dep) => cycle2.indexOf(dep) === -1;
return !!projectDeps && Array.from(projectDeps).filter(depIsNotInCycle).length > 0;
});
return !cycleHasExternalDependencies;
});
if (cycle) {
cycles.delete(cycle);
batch = cycle.filter((p) => projectsMap.has(p));
}
}
batch.forEach((p) => {
const project = getProject(p);
seen.add(p);
queue2.add(
() => runner(project).then((value) => {
returnValues.push(value);
delete dependenciesBySource[p];
Object.keys(dependenciesBySource).forEach((dep) => dependenciesBySource[dep].delete(p));
queueNextPackages();
})
).catch((err) => {
errors.push(err);
});
});
};
queueNextPackages();
await queue2.onIdle();
if (errors.length) {
throw errors[0];
}
if (seen.size !== projects.length) {
throw new ValidationError("ERROR", "Not all tasks were run. This is likely a bug in Lerna.");
}
return returnValues;
}
// libs/core/src/lib/npm-dist-tag.ts
var npm_dist_tag_exports = {};
__export(npm_dist_tag_exports, {
add: () => add,
list: () => list2,
remove: () => remove
});
import npa5 from "npm-package-arg";
import fetch2 from "npm-registry-fetch";
function add(spec, tag, options, otpCache) {
const opts = {
log: npmlog_default,
...options,
spec: npa5(spec)
};
const cleanTag = (tag || opts.defaultTag || opts.tag).trim();
const { name, rawSpec: version } = opts.spec;
opts.log.verbose("dist-tag", `adding "${cleanTag}" to ${name}@${version}`);
if (opts.dryRun) {
opts.log.silly("dist-tag", "dry-run configured, bailing now");
return Promise.resolve();
}
return fetchTags(opts).then((tags) => {
if (tags[cleanTag] === version) {
opts.log.warn("dist-tag", `${name}@${cleanTag} already set to ${version}`);
return tags;
}
const uri = `/-/package/${opts.spec.escapedName}/dist-tags/${encodeURIComponent(cleanTag)}`;
const payload = {
...opts,
method: "PUT",
body: JSON.stringify(version),
headers: {
// cannot use fetch.json() due to HTTP 204 response,
// so we manually set the required content-type
"content-type": "application/json"
},
spec: opts.spec
};
return otplease((wrappedPayload) => fetch2(uri, wrappedPayload), payload, otpCache).then(() => {
opts.log.verbose("dist-tag", `added "${cleanTag}" to ${name}@${version}`);
tags[cleanTag] = version;
return tags;
});
});
}
function remove(spec, tag, options, otpCache) {
const opts = {
log: npmlog_default,
...options,
spec: npa5(spec)
};
opts.log.verbose("dist-tag", `removing "${tag}" from ${opts.spec.name}`);
if (opts.dryRun) {
opts.log.silly("dist-tag", "dry-run configured, bailing now");
return Promise.resolve();
}
return fetchTags(opts).then((tags) => {
const version = tags[tag];
if (!version) {
opts.log.info("dist-tag", `"${tag}" is not a dist-tag on ${opts.spec.name}`);
return tags;
}
const uri = `/-/package/${opts.spec.escapedName}/dist-tags/${encodeURIComponent(tag)}`;
const payload = {
...opts,
method: "DELETE",
spec: opts.spec
};
return otplease((wrappedPayload) => fetch2(uri, wrappedPayload), payload, otpCache).then(() => {
opts.log.verbose("dist-tag", `removed "${tag}" from ${opts.spec.name}@${version}`);
delete tags[tag];
return tags;
});
});
}
function list2(spec, options) {
const opts = {
log: npmlog_default,
...options,
spec: npa5(spec)
};
if (opts.dryRun) {
opts.log.silly("dist-tag", "dry-run configured, bailing now");
return Promise.resolve();
}
return fetchTags(opts);
}
function fetchTags(opts) {
return fetch2.json(`/-/package/${opts.spec.escapedName}/dist-tags`, {
...opts,
preferOnline: true,
spec: opts.spec
}).then((data) => {
if (data && typeof data === "object") {
delete data["_etag"];
}
return data || {};
});
}
// libs/core/src/lib/has-npm-version.ts
import semver4 from "semver";
// libs/core/src/lib/listable-options.ts
function listableOptions(yargs2, group = "Command Options:") {
return yargs2.options({
json: {
group,
describe: "Show information as a JSON array",
type: "boolean"
},
ndjson: {
group,
describe: "Show information as newline-delimited JSON",
type: "boolean"
},
a: {
group,
describe: "Show private packages that are normally hidden",
type: "boolean",
alias: "all"
},
l: {
group,
describe: "Show extended information",
type: "boolean",
alias: "long"
},
p: {
group,
describe: "Show parseable output instead of columnified view",
type: "boolean",
alias: "parseable"
},
toposort: {
group,
describe: "Sort packages in topological order instead of lexical by directory",
type: "boolean"
},
graph: {
group,
describe: "Show dependency graph as a JSON-formatted adjacency list",
type: "boolean"
}
});
}
// libs/core/src/lib/npm-install.ts
import fs12 from "fs-extra";
import npa6 from "npm-package-arg";
import onExit2 from "signal-exit";
// libs/core/src/lib/get-npm-exec-opts.ts
function getNpmExecOpts(pkg, registry, npmClient) {
const env2 = {
LERNA_PACKAGE_NAME: pkg.name
};
if (registry) {
env2.npm_config_registry = registry;
if (npmClient === "bun") {
env2.BUN_CONFIG_REGISTRY = registry;
}
}
npmlog_default.silly("getNpmExecOpts", pkg.location, registry);
return {
cwd: pkg.location,
env: env2,
pkg
};
}
// libs/core/src/lib/npm-run-script.ts
function npmRunScript(script, { args, npmClient, pkg, reject = true }) {
npmlog_default.silly("npmRunScript", script, args, pkg.name);
const argv = ["run", script, ...args];
const opts = makeOpts(pkg, reject);
return exec(npmClient, argv, opts);
}
function npmRunScriptStreaming(script, { args, npmClient, pkg, prefix: prefix2, reject = true }) {
npmlog_default.silly("npmRunScriptStreaming", [script, args, pkg.name]);
const argv = ["run", script, ...args];
const opts = makeOpts(pkg, reject);
return spawnStreaming(npmClient, argv, opts, prefix2 && pkg.name);
}
function makeOpts(pkg, reject) {
return Object.assign(getNpmExecOpts(pkg), {
windowsHide: false,
reject
});
}
// libs/core/src/lib/profiler.ts
import fs13 from "fs-extra";
import path21 from "path";
var hrtimeToMicroseconds = (hrtime) => {
return (hrtime[0] * 1e9 + hrtime[1]) / 1e3;
};
var range = (len) => {
return Array(len).fill().map((_, idx) => idx);
};
var getTimeBasedFilename = () => {
const now = /* @__PURE__ */ new Date();
const datetime = now.toISOString().split(".")[0];
const datetimeNormalized = datetime.replace(/-|:/g, "");
return `Lerna-Profile-${datetimeNormalized}.json`;
};
function generateProfileOutputPath(outputDirectory) {
return path21.join(path21.resolve(outputDirectory || "."), getTimeBasedFilename());
}
var Profiler = class {
events;
logger;
outputPath;
threads;
constructor({ concurrency, log: log2 = npmlog_default, outputDirectory }) {
this.events = [];
this.logger = log2;
this.outputPath = generateProfileOutputPath(outputDirectory);
this.threads = range(concurrency);
}
run(fn, name) {
let startTime;
let threadId;
return Promise.resolve().then(() => {
startTime = process.hrtime();
threadId = this.threads.shift();
}).then(() => fn()).then((value) => {
const duration = process.hrtime(startTime);
const event = {
name,
ph: "X",
ts: hrtimeToMicroseconds(startTime),
pid: 1,
tid: threadId,
dur: hrtimeToMicroseconds(duration)
};
this.events.push(event);
this.threads.unshift(threadId);
this.threads.sort();
return value;
});
}
output() {
return fs13.outputJson(this.outputPath, this.events).then(() => this.logger.info("profiler", `Performance profile saved to ${this.outputPath}`));
}
};
// libs/core/src/lib/scm-clients/github/create-github-client.ts
import { Octokit } from "@octokit/rest";
import parseGitUrl from "git-url-parse";
import { createRequire as createRequire3 } from "node:module";
var require4 = createRequire3(import.meta.url);
function createGitHubClient() {
npmlog_default.silly("createGitHubClient");
const { GH_TOKEN, GHE_API_URL, GHE_VERSION } = process.env;
if (!GH_TOKEN) {
throw new ValidationError(
"",
`A GH_TOKEN environment variable is required when "createRelease" is set to "github"`
);
}
if (GHE_VERSION) {
Octokit.plugin(require4(`@octokit/plugin-enterprise-rest/ghe-${GHE_VERSION}`));
}
const options = {
auth: `token ${GH_TOKEN}`
};
if (GHE_API_URL) {
options.baseUrl = GHE_API_URL;
}
return new Octokit(options);
}
function parseGitRepo(remote = "origin", opts) {
npmlog_default.silly("parseGitRepo");
const args = ["config", "--get", `remote.${remote}.url`];
npmlog_default.verbose("git", args);
const url4 = execSync("git", args, opts);
if (!url4) {
throw new ValidationError("", `Git remote URL could not be found using "${remote}".`);
}
return parseGitUrl(url4);
}
// libs/core/src/lib/scm-clients/gitlab/gitlab-client.ts
import fetch3 from "make-fetch-happen";
import path22 from "path";
var GitLabClient = class {
constructor(token, baseUrl = "https://gitlab.com/api/v4") {
this.token = token;
this.baseUrl = baseUrl;
}
token;
baseUrl;
// TODO: refactor based on TS feedback
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
createRelease({ owner, repo, name, tag_name: tagName, body }) {
const releasesUrl = this.releasesUrl(owner, repo, "releases");
npmlog_default.silly("Requesting GitLab releases", releasesUrl);
return fetch3(releasesUrl, {
method: "post",
body: JSON.stringify({ name, tag_name: tagName, description: body }),
headers: {
"PRIVATE-TOKEN": this.token,
"Content-Type": "application/json"
}
}).then(({ ok, status, statusText }) => {
if (!ok) {
npmlog_default.error("gitlab", `Failed to create release
Request returned ${status} ${statusText}`);
} else {
npmlog_default.silly("gitlab", "Created release successfully.");
}
});
}
releasesUrl(namespace, project) {
return new URL(
`${this.baseUrl}/${path22.join("projects", encodeURIComponent(`${namespace}/${project}`), "releases")}`
).toString();
}
};
// libs/core/src/lib/scm-clients/gitlab/create-gitlab-client.ts
function OcktokitAdapter(client) {
return { repos: { createRelease: client.createRelease.bind(client) } };
}
function createGitLabClient() {
const { GL_API_URL, GL_TOKEN } = process.env;
npmlog_default.silly("Creating a GitLab client...");
if (!GL_TOKEN) {
throw new Error("A GL_TOKEN environment variable is required.");
}
const client = new GitLabClient(GL_TOKEN, GL_API_URL);
return OcktokitAdapter(client);
}
// libs/core/src/lib/timer.ts
function timer() {
if (process.env["LERNA_INTEGRATION"]) {
return () => 0;
}
const startMillis = Date.now();
return () => Date.now() - startMillis;
}
export {
colorize,
exec,
execSync,
spawn,
spawnStreaming,
npmlog_default,
describeRef,
ValidationError,
checkWorkingTree,
throwIfUncommitted,
lernaCLI,
getPackagesForOption,
prereleaseIdFromVersion,
getPackage,
slash,
collectProjectUpdates,
collectProjects,
Project,
detectProjects,
isGitInitialized,
Command,
applyBuildMetadata,
recommendVersion,
updateChangelog,
execPackageManager,
execPackageManagerSync,
filterOptions,
filterProjects,
gitCheckout,
listableFormatProjects,
formatJSON,
listableOptions,
logPacked,
promptConfirmation,
promptSelectOne,
promptTextInput,
getOneTimePassword,
npmConf,
createRunner,
npmPublish,
npmRunScript,
npmRunScriptStreaming,
output,
temp_write_default,
packDirectory,
generateProfileOutputPath,
Profiler,
pulseTillDone,
rimrafDir,
runProjectsTopologically,
createGitHubClient,
parseGitRepo,
createGitLabClient,
timer,
npm_dist_tag_exports
};