@wix/cli
Version:
CLI tool for building Wix sites and applications
1,676 lines (1,630 loc) • 89.6 kB
JavaScript
import { createRequire as _createRequire } from 'node:module';
const require = _createRequire(import.meta.url);
import {
BiProvider,
ErrorReporterProvider,
ErrorViewer,
useBiLogger,
useErrorReporter
} from "./chunk-EH3J5VW4.js";
import {
require_index_node,
wixCliLoginEnd,
wixCliLoginStart
} from "./chunk-CCOOZLEQ.js";
import {
I18nProvider,
Trans
} from "./chunk-75K4NCRA.js";
import {
Box_default,
Key,
Link,
Spinner,
Text,
render,
useAsync,
useAsyncCallback,
useExit,
use_input_default
} from "./chunk-OAVLQEAG.js";
import {
require_react
} from "./chunk-5A5B2WR4.js";
import {
getDataDirPath
} from "./chunk-62BYZXT7.js";
import {
getTestOverrides
} from "./chunk-WYHHEOWO.js";
import {
pathExists,
readJson,
writeJson
} from "./chunk-P4ZPHTFX.js";
import {
z
} from "./chunk-ZXYGJZOO.js";
import {
CliError,
CliErrorCode,
require_lib
} from "./chunk-D5VYILRO.js";
import {
__commonJS,
__toESM,
init_esm_shims
} from "./chunk-4EFJZ3GQ.js";
// ../../node_modules/p-retry/node_modules/retry/lib/retry_operation.js
var require_retry_operation = __commonJS({
"../../node_modules/p-retry/node_modules/retry/lib/retry_operation.js"(exports, module) {
"use strict";
init_esm_shims();
function RetryOperation(timeouts, options) {
if (typeof options === "boolean") {
options = { forever: options };
}
this._originalTimeouts = JSON.parse(JSON.stringify(timeouts));
this._timeouts = timeouts;
this._options = options || {};
this._maxRetryTime = options && options.maxRetryTime || Infinity;
this._fn = null;
this._errors = [];
this._attempts = 1;
this._operationTimeout = null;
this._operationTimeoutCb = null;
this._timeout = null;
this._operationStart = null;
this._timer = null;
if (this._options.forever) {
this._cachedTimeouts = this._timeouts.slice(0);
}
}
module.exports = RetryOperation;
RetryOperation.prototype.reset = function() {
this._attempts = 1;
this._timeouts = this._originalTimeouts.slice(0);
};
RetryOperation.prototype.stop = function() {
if (this._timeout) {
clearTimeout(this._timeout);
}
if (this._timer) {
clearTimeout(this._timer);
}
this._timeouts = [];
this._cachedTimeouts = null;
};
RetryOperation.prototype.retry = function(err) {
if (this._timeout) {
clearTimeout(this._timeout);
}
if (!err) {
return false;
}
var currentTime = (/* @__PURE__ */ new Date()).getTime();
if (err && currentTime - this._operationStart >= this._maxRetryTime) {
this._errors.push(err);
this._errors.unshift(new Error("RetryOperation timeout occurred"));
return false;
}
this._errors.push(err);
var timeout = this._timeouts.shift();
if (timeout === void 0) {
if (this._cachedTimeouts) {
this._errors.splice(0, this._errors.length - 1);
timeout = this._cachedTimeouts.slice(-1);
} else {
return false;
}
}
var self = this;
this._timer = setTimeout(function() {
self._attempts++;
if (self._operationTimeoutCb) {
self._timeout = setTimeout(function() {
self._operationTimeoutCb(self._attempts);
}, self._operationTimeout);
if (self._options.unref) {
self._timeout.unref();
}
}
self._fn(self._attempts);
}, timeout);
if (this._options.unref) {
this._timer.unref();
}
return true;
};
RetryOperation.prototype.attempt = function(fn, timeoutOps) {
this._fn = fn;
if (timeoutOps) {
if (timeoutOps.timeout) {
this._operationTimeout = timeoutOps.timeout;
}
if (timeoutOps.cb) {
this._operationTimeoutCb = timeoutOps.cb;
}
}
var self = this;
if (this._operationTimeoutCb) {
this._timeout = setTimeout(function() {
self._operationTimeoutCb();
}, self._operationTimeout);
}
this._operationStart = (/* @__PURE__ */ new Date()).getTime();
this._fn(this._attempts);
};
RetryOperation.prototype.try = function(fn) {
console.log("Using RetryOperation.try() is deprecated");
this.attempt(fn);
};
RetryOperation.prototype.start = function(fn) {
console.log("Using RetryOperation.start() is deprecated");
this.attempt(fn);
};
RetryOperation.prototype.start = RetryOperation.prototype.try;
RetryOperation.prototype.errors = function() {
return this._errors;
};
RetryOperation.prototype.attempts = function() {
return this._attempts;
};
RetryOperation.prototype.mainError = function() {
if (this._errors.length === 0) {
return null;
}
var counts = {};
var mainError = null;
var mainErrorCount = 0;
for (var i = 0; i < this._errors.length; i++) {
var error = this._errors[i];
var message = error.message;
var count = (counts[message] || 0) + 1;
counts[message] = count;
if (count >= mainErrorCount) {
mainError = error;
mainErrorCount = count;
}
}
return mainError;
};
}
});
// ../../node_modules/p-retry/node_modules/retry/lib/retry.js
var require_retry = __commonJS({
"../../node_modules/p-retry/node_modules/retry/lib/retry.js"(exports) {
"use strict";
init_esm_shims();
var RetryOperation = require_retry_operation();
exports.operation = function(options) {
var timeouts = exports.timeouts(options);
return new RetryOperation(timeouts, {
forever: options && (options.forever || options.retries === Infinity),
unref: options && options.unref,
maxRetryTime: options && options.maxRetryTime
});
};
exports.timeouts = function(options) {
if (options instanceof Array) {
return [].concat(options);
}
var opts = {
retries: 10,
factor: 2,
minTimeout: 1 * 1e3,
maxTimeout: Infinity,
randomize: false
};
for (var key in options) {
opts[key] = options[key];
}
if (opts.minTimeout > opts.maxTimeout) {
throw new Error("minTimeout is greater than maxTimeout");
}
var timeouts = [];
for (var i = 0; i < opts.retries; i++) {
timeouts.push(this.createTimeout(i, opts));
}
if (options && options.forever && !timeouts.length) {
timeouts.push(this.createTimeout(i, opts));
}
timeouts.sort(function(a, b) {
return a - b;
});
return timeouts;
};
exports.createTimeout = function(attempt, opts) {
var random = opts.randomize ? Math.random() + 1 : 1;
var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt));
timeout = Math.min(timeout, opts.maxTimeout);
return timeout;
};
exports.wrap = function(obj, options, methods) {
if (options instanceof Array) {
methods = options;
options = null;
}
if (!methods) {
methods = [];
for (var key in obj) {
if (typeof obj[key] === "function") {
methods.push(key);
}
}
}
for (var i = 0; i < methods.length; i++) {
var method = methods[i];
var original = obj[method];
obj[method] = function retryWrapper(original2) {
var op = exports.operation(options);
var args = Array.prototype.slice.call(arguments, 1);
var callback = args.pop();
args.push(function(err) {
if (op.retry(err)) {
return;
}
if (err) {
arguments[0] = op.mainError();
}
callback.apply(this, arguments);
});
op.attempt(function() {
original2.apply(obj, args);
});
}.bind(obj, original);
obj[method].options = options;
}
};
}
});
// ../../node_modules/p-retry/node_modules/retry/index.js
var require_retry2 = __commonJS({
"../../node_modules/p-retry/node_modules/retry/index.js"(exports, module) {
"use strict";
init_esm_shims();
module.exports = require_retry();
}
});
// ../cli-auth/src/index.ts
init_esm_shims();
// ../cli-auth/src/auth-strategies/index.ts
init_esm_shims();
// ../cli-auth/src/auth-strategies/api-key-auth-strategy.ts
init_esm_shims();
var import_variant3 = __toESM(require_lib(), 1);
// ../cli-auth/src/client.ts
init_esm_shims();
// ../../node_modules/p-retry/index.js
init_esm_shims();
var import_retry = __toESM(require_retry2(), 1);
// ../../node_modules/is-network-error/index.js
init_esm_shims();
var objectToString = Object.prototype.toString;
var isError = (value) => objectToString.call(value) === "[object Error]";
var errorMessages = /* @__PURE__ */ new Set([
"network error",
// Chrome
"Failed to fetch",
// Chrome
"NetworkError when attempting to fetch resource.",
// Firefox
"The Internet connection appears to be offline.",
// Safari 16
"Load failed",
// Safari 17+
"Network request failed",
// `cross-fetch`
"fetch failed",
// Undici (Node.js)
"terminated"
// Undici (Node.js)
]);
function isNetworkError(error) {
const isValid = error && isError(error) && error.name === "TypeError" && typeof error.message === "string";
if (!isValid) {
return false;
}
if (error.message === "Load failed") {
return error.stack === void 0;
}
return errorMessages.has(error.message);
}
// ../../node_modules/p-retry/index.js
var AbortError = class extends Error {
constructor(message) {
super();
if (message instanceof Error) {
this.originalError = message;
({ message } = message);
} else {
this.originalError = new Error(message);
this.originalError.stack = this.stack;
}
this.name = "AbortError";
this.message = message;
}
};
var decorateErrorWithCounts = (error, attemptNumber, options) => {
const retriesLeft = options.retries - (attemptNumber - 1);
error.attemptNumber = attemptNumber;
error.retriesLeft = retriesLeft;
return error;
};
async function pRetry(input, options) {
return new Promise((resolve2, reject) => {
options = { ...options };
options.onFailedAttempt ??= () => {
};
options.shouldRetry ??= () => true;
options.retries ??= 10;
const operation = import_retry.default.operation(options);
const abortHandler = () => {
operation.stop();
reject(options.signal?.reason);
};
if (options.signal && !options.signal.aborted) {
options.signal.addEventListener("abort", abortHandler, { once: true });
}
const cleanUp = () => {
options.signal?.removeEventListener("abort", abortHandler);
operation.stop();
};
operation.attempt(async (attemptNumber) => {
try {
const result = await input(attemptNumber);
cleanUp();
resolve2(result);
} catch (error) {
try {
if (!(error instanceof Error)) {
throw new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`);
}
if (error instanceof AbortError) {
throw error.originalError;
}
if (error instanceof TypeError && !isNetworkError(error)) {
throw error;
}
decorateErrorWithCounts(error, attemptNumber, options);
if (!await options.shouldRetry(error)) {
operation.stop();
reject(error);
}
await options.onFailedAttempt(error);
if (!operation.retry(error)) {
throw operation.mainError();
}
} catch (finalError) {
decorateErrorWithCounts(finalError, attemptNumber, options);
cleanUp();
reject(finalError);
}
}
});
});
}
// ../../node_modules/@wix/ambassador-identity-account-v2-account/build/es/http.impl.js
init_esm_shims();
// ../../node_modules/@wix/metro-runtime/dist/esm/index.js
init_esm_shims();
// ../../node_modules/@wix/metro-runtime/dist/esm/serialization/index.js
init_esm_shims();
// ../../node_modules/@wix/metro-runtime/dist/esm/serialization/utils.js
init_esm_shims();
function parseLeanSchemaRef(renderedSchemaName = "") {
const [typeOrName, schemaName] = getSchemaNameAndType(renderedSchemaName);
if (schemaName) {
return {
schemaName,
schemaType: typeOrName
};
}
return {
schemaName: typeOrName
};
}
var getSchemaNameAndType = (leanSchema) => leanSchema.split("#");
// ../../node_modules/@wix/metro-runtime/dist/esm/url-resolver.js
init_esm_shims();
// ../../node_modules/@wix/metro-runtime/dist/esm/utils.js
init_esm_shims();
function findByPath(obj, path2, defaultValue, suffix) {
let result = obj;
for (const field of path2.split(".")) {
if (!result) {
return defaultValue;
}
result = result[field];
}
return `${result}${suffix}`;
}
// ../../node_modules/@wix/metro-runtime/dist/esm/url-resolver.js
var USER_DOMAIN = "_";
var DOMAINS = ["wix.com", "editorx.com"];
var WIX_API_DOMAINS = ["42.wixprod.net", "uw2-edt-1.wixprod.net"];
var DEV_WIX_CODE_DOMAIN = "dev.wix-code.com";
var REGEX_CAPTURE_PROTO_FIELD = /{(.*)}/;
var REGEX_CAPTURE_DOMAINS = new RegExp(`\\.(${DOMAINS.join("|")})$`);
var REGEX_CAPTURE_API_DOMAINS = new RegExp(`\\.(${WIX_API_DOMAINS.join("|")})$`);
var REGEX_CAPTURE_DEV_WIX_CODE_DOMAIN = new RegExp(`.*\\.${DEV_WIX_CODE_DOMAIN}$`);
function resolveUrl(opts) {
const domain = resolveDomain(opts.host);
const mappings = resolveMappingsByDomain(domain, opts.domainToMappings);
const path2 = injectDataIntoProtoPath(opts.protoPath, opts.data || {});
return resolvePath(path2, mappings);
}
function injectDataIntoProtoPath(protoPath, data) {
return protoPath.split("/").map((path2) => maybeProtoPathToData(path2, data)).join("/");
}
function maybeProtoPathToData(protoPath, data) {
const protoRegExpMatch = protoPath.match(REGEX_CAPTURE_PROTO_FIELD) || [];
const field = protoRegExpMatch[1];
if (field) {
const suffix = protoPath.replace(protoRegExpMatch[0], "");
return findByPath(data, field, protoPath, suffix);
}
return protoPath;
}
function resolveDomain(host) {
const resolvedHost = fixHostExceptions(host);
return resolvedHost.replace(REGEX_CAPTURE_DOMAINS, "._base_domain_").replace(REGEX_CAPTURE_API_DOMAINS, "._api_base_domain_").replace(REGEX_CAPTURE_DEV_WIX_CODE_DOMAIN, "*.dev.wix-code.com");
}
function fixHostExceptions(host) {
return host.replace("create.editorx.com", "editor.editorx.com");
}
function resolveMappingsByDomain(domain, domainToMappings) {
const mappings = domainToMappings[domain] || domainToMappings[USER_DOMAIN];
if (!mappings) {
if (isBaseDomain(domain)) {
return domainToMappings[wwwBaseDomain];
}
}
return mappings;
}
function resolvePath(protoPath, mappings) {
const mapping = mappings?.find((m) => protoPath.startsWith(m.destPath));
if (!mapping) {
return protoPath;
}
return mapping.srcPath + protoPath.slice(mapping.destPath.length);
}
function isBaseDomain(domain) {
return !!domain.match(/\._base_domain_$/);
}
var wwwBaseDomain = "www._base_domain_";
// ../../node_modules/@wix/metro-runtime/dist/esm/flatten-params.js
init_esm_shims();
// ../../node_modules/js-base64/base64.mjs
init_esm_shims();
var _hasBuffer = typeof Buffer === "function";
var _TD = typeof TextDecoder === "function" ? new TextDecoder() : void 0;
var _TE = typeof TextEncoder === "function" ? new TextEncoder() : void 0;
var b64ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var b64chs = Array.prototype.slice.call(b64ch);
var b64tab = ((a) => {
let tab = {};
a.forEach((c, i) => tab[c] = i);
return tab;
})(b64chs);
var _fromCC = String.fromCharCode.bind(String);
var _U8Afrom = typeof Uint8Array.from === "function" ? Uint8Array.from.bind(Uint8Array) : (it) => new Uint8Array(Array.prototype.slice.call(it, 0));
var _mkUriSafe = (src) => src.replace(/=/g, "").replace(/[+\/]/g, (m0) => m0 == "+" ? "-" : "_");
var btoaPolyfill = (bin) => {
let u32, c0, c1, c2, asc = "";
const pad = bin.length % 3;
for (let i = 0; i < bin.length; ) {
if ((c0 = bin.charCodeAt(i++)) > 255 || (c1 = bin.charCodeAt(i++)) > 255 || (c2 = bin.charCodeAt(i++)) > 255)
throw new TypeError("invalid character found");
u32 = c0 << 16 | c1 << 8 | c2;
asc += b64chs[u32 >> 18 & 63] + b64chs[u32 >> 12 & 63] + b64chs[u32 >> 6 & 63] + b64chs[u32 & 63];
}
return pad ? asc.slice(0, pad - 3) + "===".substring(pad) : asc;
};
var _btoa = typeof btoa === "function" ? (bin) => btoa(bin) : _hasBuffer ? (bin) => Buffer.from(bin, "binary").toString("base64") : btoaPolyfill;
var _fromUint8Array = _hasBuffer ? (u8a) => Buffer.from(u8a).toString("base64") : (u8a) => {
const maxargs = 4096;
let strs = [];
for (let i = 0, l = u8a.length; i < l; i += maxargs) {
strs.push(_fromCC.apply(null, u8a.subarray(i, i + maxargs)));
}
return _btoa(strs.join(""));
};
var cb_utob = (c) => {
if (c.length < 2) {
var cc = c.charCodeAt(0);
return cc < 128 ? c : cc < 2048 ? _fromCC(192 | cc >>> 6) + _fromCC(128 | cc & 63) : _fromCC(224 | cc >>> 12 & 15) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
} else {
var cc = 65536 + (c.charCodeAt(0) - 55296) * 1024 + (c.charCodeAt(1) - 56320);
return _fromCC(240 | cc >>> 18 & 7) + _fromCC(128 | cc >>> 12 & 63) + _fromCC(128 | cc >>> 6 & 63) + _fromCC(128 | cc & 63);
}
};
var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
var utob = (u) => u.replace(re_utob, cb_utob);
var _encode = _hasBuffer ? (s) => Buffer.from(s, "utf8").toString("base64") : _TE ? (s) => _fromUint8Array(_TE.encode(s)) : (s) => _btoa(utob(s));
var encode = (src, urlsafe = false) => urlsafe ? _mkUriSafe(_encode(src)) : _encode(src);
// ../../node_modules/@wix/metro-runtime/dist/esm/flatten-params.js
function flattenParams(data, path2 = "") {
const params = {};
Object.entries(data).forEach(([key, value]) => {
const isObject = value !== null && typeof value === "object" && !Array.isArray(value);
const fieldPath = resolvePath2(path2, key);
if (isObject) {
const serializedObject = flattenParams(value, fieldPath);
Object.assign(params, serializedObject);
} else {
params[fieldPath] = value;
}
});
return params;
}
function resolvePath2(path2, key) {
return `${path2}${path2 ? "." : ""}${key}`;
}
function toURLSearchParams(params, isComplexRequest) {
const flatten = flattenParams(params);
const isPayloadNonSerializableAsUrlSearchParams = Object.entries(flatten).some(([key, value]) => key.includes(".") || Array.isArray(value) && value.some((v) => typeof v === "object"));
const shouldSerializeToRParam = isComplexRequest && isPayloadNonSerializableAsUrlSearchParams;
if (shouldSerializeToRParam) {
return new URLSearchParams({ ".r": encode(JSON.stringify(params), true) });
} else {
return Object.entries(flatten).reduce((urlSearchParams, [key, value]) => {
const keyParams = Array.isArray(value) ? value : [value];
keyParams.forEach((param) => {
if (param === void 0 || param === null || Array.isArray(value) && typeof param === "object") {
return;
}
urlSearchParams.append(key, param);
});
return urlSearchParams;
}, new URLSearchParams());
}
}
// ../../node_modules/@wix/metro-runtime/dist/esm/ambassador-index.js
init_esm_shims();
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/domain.js
init_esm_shims();
var ConverterType;
(function(ConverterType2) {
ConverterType2[ConverterType2["TO_JSON"] = 0] = "TO_JSON";
ConverterType2[ConverterType2["FROM_JSON"] = 1] = "FROM_JSON";
})(ConverterType || (ConverterType = {}));
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/serializer.js
init_esm_shims();
function schemaSerializer(rootSchema, depSchemas = {}, converterSets) {
return function serialize(json = {}, converterType) {
return typeof json === "string" ? json : transformSchema(rootSchema, json);
function transformSchema(schema, payload4) {
const result = {};
if ([null, void 0].includes(payload4)) {
return payload4;
}
Object.entries(payload4).forEach(([key, val]) => {
const renderedSchemaName = schema[key];
const { schemaName, schemaType } = parseLeanSchemaRef(renderedSchemaName);
const isMap = schemaType === "Map";
const isRepeatable = getConverter(schemaName)?.checkRepetable?.(val) ?? Array.isArray(val);
let parsedValue;
if (isRepeatable) {
parsedValue = val.map((v) => applyField(v, schemaName));
} else if (isMap) {
parsedValue = applyFieldOnMap(val, schemaName);
} else {
parsedValue = applyField(val, schemaName);
}
result[key] = parsedValue;
});
return result;
}
function applyField(val, schemaOrSerializer) {
if (!schemaOrSerializer) {
return val;
}
const maybeSchema = depSchemas[schemaOrSerializer];
const maybeConverter = getConverter(schemaOrSerializer);
if (maybeConverter) {
return getConverter(schemaOrSerializer).transform(val);
} else if (maybeSchema) {
return transformSchema(maybeSchema, val);
}
throw new Error(`${schemaOrSerializer} is neither schema nor serializable type`);
}
function getConverter(name) {
return converterSets[name]?.[converterType];
}
function applyFieldOnMap(val, sanitizedSchemaOrSerializer) {
return Object.entries(val).reduce((acc, [propertyName, value]) => {
acc[propertyName] = applyField(value, sanitizedSchemaOrSerializer);
return acc;
}, {});
}
};
}
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/protobuf-converters/converters.js
init_esm_shims();
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/protobuf-converters/timestamp.js
init_esm_shims();
var timestamp = {
types: ["google.protobuf.Timestamp"],
[ConverterType.TO_JSON]: {
transform: (val) => {
if (typeof val === "string" || !val) {
return val;
}
return val.toISOString();
}
},
[ConverterType.FROM_JSON]: {
transform: (val) => val ? new Date(val) : val
}
};
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/protobuf-converters/field-mask.js
init_esm_shims();
var fieldMask = {
types: ["google.protobuf.FieldMask"],
[ConverterType.TO_JSON]: {
transform: (val) => val.join(","),
/**
* This one handles cases where we have a repeated google.protobuf.FieldMask type,
* so it will look like: [['foo', 'bar'], ['qux']].
*
* The problem is that the serializer detects it as an array with actual fields (strings),
* while in practice it is an array of multiple google.protobuf.FieldMask.
*
* We should determine if the items are actual fields (so each item is a string),
* or arrays of google.protobuf.FieldMask (so each item is array that has items with fields).
*
* Another approach could be marking on the schama itseld each field if it's a repeatable or not,
* it's not a good appraoch, but as long as google.protobuf.FieldMask is our only issue, it's
* not _that_ bad solution.
*/
checkRepetable: (val) => {
return val.some((v) => Array.isArray(v));
}
},
[ConverterType.FROM_JSON]: {
transform: (val) => {
if (typeof val === "object") {
return val.paths;
}
return val.split(",");
}
}
};
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/protobuf-converters/bytes.js
init_esm_shims();
var bytes = {
types: ["google.protobuf.BytesValue", "BYTES"],
[ConverterType.TO_JSON]: {
transform: (val) => {
const chars = val.reduce((res, c) => res + String.fromCharCode(c), "");
return btoa(chars);
}
},
[ConverterType.FROM_JSON]: {
transform: (val) => {
return Uint8Array.from(atob(val), (c) => c.charCodeAt(0));
}
}
};
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/protobuf-converters/duration.js
init_esm_shims();
var duration = {
types: ["google.protobuf.Duration"],
[ConverterType.TO_JSON]: {
transform: ({ seconds: seconds2 = "0", nanos = 0 }) => {
let nanosPortion = "";
if (nanos !== 0) {
nanosPortion = `.${nanos.toString().padStart(9, "0")}`;
}
return `${seconds2}${nanosPortion}s`;
}
},
[ConverterType.FROM_JSON]: {
transform: (val) => {
const [seconds2, nanos] = val.substring(0, val.length - 1).split(".");
return {
seconds: seconds2,
nanos: nanosForString(nanos)
};
}
}
};
function nanosForString(nanos) {
let res = 0;
if (nanos !== void 0) {
const precision = 3 - nanos.length / 3;
res = parseInt(nanos, 10) * Math.pow(1e3, precision);
}
return res;
}
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/protobuf-converters/float.js
init_esm_shims();
var float = {
types: [
"FLOAT",
"DOUBLE",
"google.protobuf.FloatValue",
"google.protobuf.DoubleValue"
],
[ConverterType.TO_JSON]: {
transform: (val) => {
return isFinite(val) ? val : val.toString();
}
},
[ConverterType.FROM_JSON]: {
transform: (val) => {
if (val === "NaN") {
return NaN;
}
if (val === "Infinity") {
return Infinity;
}
if (val === "-Infinity") {
return -Infinity;
}
return val;
}
}
};
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/protobuf-converters/converters.js
var protobufConverters = [
timestamp,
fieldMask,
bytes,
duration,
float
];
// ../../node_modules/@wix/metro-runtime/dist/esm/serializer/utils.js
init_esm_shims();
function typeToConverterSet(converterSets) {
return converterSets.reduce((result, converterSet) => {
const types = converterSet.types.reduce((typeResult, type) => {
return {
...typeResult,
[type]: converterSet
};
}, {});
return {
...result,
...types
};
}, {});
}
// ../../node_modules/@wix/metro-runtime/dist/esm/ambassador-index.js
var ambassadorConverters = typeToConverterSet([...protobufConverters]);
function serializer(rootSchema, depSchemas = {}) {
const transform = schemaSerializer(rootSchema, depSchemas, ambassadorConverters);
return {
fromJSON(jsonOrString) {
const jsonOrText = safeJsonParse(jsonOrString) || jsonOrString;
return transform(jsonOrText, ConverterType.FROM_JSON);
},
toJSON(json) {
return transform(json, ConverterType.TO_JSON);
}
};
}
function safeJsonParse(someString) {
try {
return JSON.parse(someString);
} catch (error) {
}
}
// ../../node_modules/@wix/ambassador-identity-account-v2-account/build/es/http.impl.js
var _account = {
dateCreated: "google.protobuf.Timestamp",
dateUpdated: "google.protobuf.Timestamp"
};
var _accountResponse = { account: "_account" };
var _getMyAccountRequest = {};
function resolveComWixpressAccountApiAccountServiceUrl(opts) {
var domainToMappings = {
"api._api_base_domain_": [
{
srcPath: "/account-server",
destPath: ""
}
],
"www._base_domain_": [
{
srcPath: "/_api/account-server",
destPath: ""
}
],
"manage._base_domain_": [
{
srcPath: "/_api/account-server",
destPath: ""
},
{
srcPath: "/account-server",
destPath: ""
}
],
"premium._base_domain_": [
{
srcPath: "/_api/account-server",
destPath: ""
}
],
"editor._base_domain_": [
{
srcPath: "/_api/account-server",
destPath: ""
}
],
"blocks._base_domain_": [
{
srcPath: "/_api/account-server",
destPath: ""
}
],
"create.editorx": [
{
srcPath: "/_api/account-server",
destPath: ""
}
],
"bo._base_domain_": [
{
srcPath: "/account-server",
destPath: ""
}
],
"wixbo.ai": [
{
srcPath: "/account-server",
destPath: ""
}
],
"wix-bo.com": [
{
srcPath: "/account-server",
destPath: ""
}
],
"www.wixapis.com": [
{
srcPath: "/accounts",
destPath: ""
},
{
srcPath: "/accounts/v1/accounts",
destPath: "/v1/accounts"
},
{
srcPath: "/accounts/v1/account",
destPath: "/v1/account"
}
],
"users._base_domain_": [
{
srcPath: "/_api/account-server",
destPath: ""
}
],
"*.dev.wix-code.com": [
{
srcPath: "/_api/account-server",
destPath: ""
}
]
};
return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function getMyAccount(payload4) {
var _a = serializer(_getMyAccountRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
var fromRes = serializer(_accountResponse, { _account }).fromJSON;
function __getMyAccount(_a2) {
var host = _a2.host;
var serializedData = toReq(payload4);
var metadata = {
entityFqdn: "wix.identity.account.v2.account",
method: "GET",
methodFqn: "com.wixpress.account.api.AccountService.getMyAccount",
url: resolveComWixpressAccountApiAccountServiceUrl({
protoPath: "/v1/accounts/my_account",
data: serializedData,
host
}),
params: toURLSearchParams(serializedData),
transformResponse: fromRes
};
return metadata;
}
__getMyAccount.fromReq = fromReq;
__getMyAccount.__isAmbassador = true;
return __getMyAccount;
}
// ../../node_modules/@wix/ambassador-identity-oauth-v1-refresh-token/build/es/http.impl.js
init_esm_shims();
var _deviceCodeRequest = {};
var _deviceCodeResponse = {};
var _rawHttpRequest = { body: "BYTES" };
var _rawHttpResponse = { body: "BYTES" };
var _revokeRefreshTokenRequest = {};
var _revokeRefreshTokenResponse = {};
function resolveWixIdentityOauth2V1Oauth2NgUrl(opts) {
var domainToMappings = {
"manage._base_domain_": [
{
srcPath: "/oauth2",
destPath: "/v1/oauth"
}
],
"www.wixapis.com": [
{
srcPath: "/oauth2",
destPath: "/v1/oauth"
},
{
srcPath: "/oauth2/token_info",
destPath: "/v1/token_info"
}
],
"users._base_domain_": [
{
srcPath: "/v1/oauth/device/verify",
destPath: "/v1/oauth/device/verify"
},
{
srcPath: "/v1/oauth/manage/user-code",
destPath: "/v1/oauth/manage/user-code"
},
{
srcPath: "/v2/oauth/device/verify",
destPath: "/v2/oauth/device/verify"
},
{
srcPath: "/v1/oauth/authorize",
destPath: "/v1/oauth/authorize"
}
],
_: [
{
srcPath: "/_api/oauth2",
destPath: "/v1/oauth"
}
],
"platform.rise.ai": [
{
srcPath: "/oauth2",
destPath: "/v1/oauth"
}
],
"api._api_base_domain_": [
{
srcPath: "/oauth2-ng",
destPath: ""
}
]
};
return resolveUrl(Object.assign(opts, { domainToMappings }));
}
function token(payload4) {
var _a = serializer(_rawHttpRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
var fromRes = serializer(_rawHttpResponse, {}).fromJSON;
function __token(_a2) {
var host = _a2.host;
var serializedData = toReq(payload4);
var metadata = {
entityFqdn: "wix.identity.oauth.v1.refresh_token",
method: "POST",
methodFqn: "wix.identity.oauth2.v1.Oauth2Ng.Token",
url: resolveWixIdentityOauth2V1Oauth2NgUrl({
protoPath: "/v1/oauth/token",
data: serializedData,
host
}),
data: serializedData,
transformResponse: fromRes
};
return metadata;
}
__token.fromReq = fromReq;
__token.__isAmbassador = true;
return __token;
}
function deviceCode(payload4) {
var _a = serializer(_deviceCodeRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
var fromRes = serializer(_deviceCodeResponse, {}).fromJSON;
function __deviceCode(_a2) {
var host = _a2.host;
var serializedData = toReq(payload4);
var metadata = {
entityFqdn: "wix.identity.oauth.v1.refresh_token",
method: "GET",
methodFqn: "wix.identity.oauth2.v1.Oauth2Ng.DeviceCode",
url: resolveWixIdentityOauth2V1Oauth2NgUrl({
protoPath: "/v1/oauth/device/code",
data: serializedData,
host
}),
params: toURLSearchParams(serializedData),
transformResponse: fromRes
};
return metadata;
}
__deviceCode.fromReq = fromReq;
__deviceCode.__isAmbassador = true;
return __deviceCode;
}
function revokeRefreshToken(payload4) {
var _a = serializer(_revokeRefreshTokenRequest, {}), toReq = _a.toJSON, fromReq = _a.fromJSON;
var fromRes = serializer(_revokeRefreshTokenResponse, {}).fromJSON;
function __revokeRefreshToken(_a2) {
var host = _a2.host;
var serializedData = toReq(payload4);
var metadata = {
entityFqdn: "wix.identity.oauth.v1.refresh_token",
method: "POST",
methodFqn: "wix.identity.oauth2.v1.Oauth2Ng.RevokeRefreshToken",
url: resolveWixIdentityOauth2V1Oauth2NgUrl({
protoPath: "/v1/oauth/revoke",
data: serializedData,
host
}),
data: serializedData,
transformResponse: fromRes
};
return metadata;
}
__revokeRefreshToken.fromReq = fromReq;
__revokeRefreshToken.__isAmbassador = true;
return __revokeRefreshToken;
}
// ../cli-http-client/src/create-http-client.ts
init_esm_shims();
var import_http_client2 = __toESM(require_index_node(), 1);
// ../cli-http-client/src/is-http-error.ts
init_esm_shims();
var import_http_client = __toESM(require_index_node(), 1);
function isHttpError(error) {
return import_http_client.HttpClient.isHttpError(error);
}
// ../cli-http-client/src/create-http-client.ts
var baseUrls = {
backoffice: "https://manage.wix.com",
editor: "https://editor.wix.com",
code: "https://code.wix.com",
general: "https://www.wix.com",
api: "https://www.wixapis.com",
standalone: void 0
};
function interceptRequest(client2, fn) {
return (...args) => fn.apply(client2, args).catch((error) => {
if (isHttpError(error) && !client2.isCancel(error) && !error.response) {
throw new CliError({
code: CliErrorCode.NetworkError(),
cause: error,
info: { code: error.code }
});
}
throw error;
});
}
function createHttpClient({
getAppToken,
createHeaders,
type
}) {
const client2 = (0, import_http_client2.createHttpClient)({
baseURL: baseUrls[type],
...type !== "standalone" ? {
getAppToken
} : {},
createHeaders: () => ({
...createHeaders?.(),
// See https://wix.slack.com/archives/C0JLGMT28/p1667219337530909
"X-XSRF-TOKEN": "nocheck",
Cookie: "XSRF-TOKEN=nocheck",
"User-Agent": "wix-cli"
})
});
return {
...client2,
request: interceptRequest(client2, client2.request),
get: interceptRequest(client2, client2.get),
delete: interceptRequest(client2, client2.delete),
head: interceptRequest(client2, client2.head),
options: interceptRequest(client2, client2.options),
post: interceptRequest(client2, client2.post),
put: interceptRequest(client2, client2.put),
patch: interceptRequest(client2, client2.patch)
};
}
// ../cli-auth/src/client.ts
var import_variant = __toESM(require_lib(), 1);
// ../cli-auth/src/schemas.ts
init_esm_shims();
var deviceCodeSchema = z.object({
deviceCode: z.string(),
verificationUri: z.string().url(),
userCode: z.string(),
expiresIn: z.number()
});
var tokenSchema = z.object({
access_token: z.string(),
refresh_token: z.string(),
expires_in: z.number()
}).transform((token2) => ({
accessToken: token2.access_token,
refreshToken: token2.refresh_token,
expiresIn: token2.expires_in
}));
var userInfoSchema = z.object({
userId: z.string().uuid(),
email: z.string().email()
});
var getMyAccountSchema = z.object({
account: z.object({
slug: z.string(),
accountId: z.string().uuid(),
accountOwner: z.string().uuid()
})
});
var siteAuthSchema = z.object({
accessToken: z.string(),
refreshToken: z.string(),
expiresIn: z.number(),
issuedAt: z.number()
});
var accountAuthSchema = siteAuthSchema.extend({
userInfo: userInfoSchema
});
var apiKeyAuthSchema = z.object({
token: z.string(),
accountId: z.string().uuid(),
userInfo: z.object({
userId: z.string().uuid(),
email: z.string()
})
});
// ../cli-auth/src/client.ts
var {
InvalidResponseData,
FailedToGetAuthToken,
FailedToGetDeviceCode,
FailedToRenewAuthToken,
FailedToRenewAuthTokenSiteNotFound,
FailedToRevokeRefreshToken
} = CliErrorCode;
var clientId = "6f95cec8-3e98-48b9-b4e5-1fb92fcd9973";
var getCurrentTimestamp = () => Math.floor(Date.now() / 1e3);
var DeviceCodeNotYetVerifiedError = class extends Error {
};
var RenewTokenData = (0, import_variant.variant)({
TokenRenewed: (0, import_variant.payload)(),
RefreshTokenRevoked: (0, import_variant.fields)()
});
var AuthClient = class {
constructor(httpClient) {
this.httpClient = httpClient;
const { minRetryTimeout } = getTestOverrides();
this.retryOptions = {
retries: 3,
minTimeout: minRetryTimeout,
maxTimeout: 3 * 1e3
};
}
retryOptions;
async requestDeviceCode(req = {}) {
try {
const { data } = await pRetry(
() => this.httpClient.request(deviceCode({ ...req, clientId })),
this.retryOptions
);
return deviceCodeSchema.parse(data);
} catch (error) {
throw new CliError({
code: FailedToGetDeviceCode(),
cause: error
});
}
}
async createToken(req) {
try {
const payload4 = {
clientId,
grantType: "urn:ietf:params:oauth:grant-type:device_code",
scope: "offline_access",
...req
};
const tokenData = await pRetry(async () => {
const { data, requestId } = await this.httpClient.request(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
token(payload4)
);
const result = tokenSchema.safeParse(data);
if (result.success) {
return result.data;
}
throw new CliError({
code: InvalidResponseData(),
cause: result.error,
info: { requestId, data }
});
}, this.retryOptions);
return {
...tokenData,
issuedAt: getCurrentTimestamp()
};
} catch (error) {
if (isHttpError(error) && (error.response?.data?.message === "Device code is not yet verified" || // https://github.com/wix-private/wix-cli/pull/655#discussion_r1145992702
error.response?.data?.error === "authorization_pending")) {
throw new DeviceCodeNotYetVerifiedError(
"Device code is not yet verified."
);
}
throw new CliError({
code: FailedToGetAuthToken(),
cause: error
});
}
}
async renewToken(req) {
try {
const payload4 = {
clientId,
grantType: "refresh_token",
...req
};
const { data } = await pRetry(
() => this.httpClient.request(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
token(payload4)
),
this.retryOptions
);
const tokenData = tokenSchema.parse(data);
return RenewTokenData.TokenRenewed({
...tokenData,
issuedAt: getCurrentTimestamp()
});
} catch (error) {
if (isHttpError(error)) {
if (error.response?.status === 400 && error.response.data?.error === "invalid_grant") {
return RenewTokenData.RefreshTokenRevoked({ cause: error });
}
if (req.siteId && error.response?.status === 404 && error.response.data?.details?.applicationError?.code === "SITE_NOT_FOUND") {
throw new CliError({
code: FailedToRenewAuthTokenSiteNotFound({ siteId: req.siteId }),
cause: error
});
}
}
throw new CliError({
code: FailedToRenewAuthToken(),
cause: error
});
}
}
async revokeRefreshToken(req, { email }) {
try {
const { data } = await this.httpClient.request(revokeRefreshToken(req));
return data;
} catch (error) {
throw new CliError({
code: FailedToRevokeRefreshToken({
email
}),
info: {
email
},
cause: error
});
}
}
async userInfo({ accessToken }) {
try {
const httpClient = createHttpClient({
type: "backoffice",
getAppToken: async () => accessToken
});
const { data: userInfoData } = await httpClient.get(
"/_serverless/wix-cli-userinfo/userinfo"
);
return userInfoSchema.parse(userInfoData);
} catch (error) {
throw new CliError({
code: CliErrorCode.FailedToGetUserInfo(),
cause: error
});
}
}
async getMyAccount({ token: token2 }) {
try {
const httpClient = createHttpClient({
type: "backoffice",
getAppToken: async () => token2
});
const { data } = await httpClient.request(getMyAccount({}));
return getMyAccountSchema.parse(data).account;
} catch (error) {
if (isHttpError(error) && error.response?.status === 428 && error.response.data?.details?.applicationError?.code === "48876") {
throw new CliError({
code: CliErrorCode.InvalidApiKey(),
cause: error
});
}
throw new CliError({
code: CliErrorCode.FailedToGetMyAccount(),
cause: error
});
}
}
};
var client = new AuthClient(createHttpClient({ type: "backoffice" }));
// ../cli-auth/src/auth-data.ts
init_esm_shims();
import { unlink, rm } from "node:fs/promises";
import { resolve } from "node:path";
var import_variant2 = __toESM(require_lib(), 1);
function getLegacyAuthDataFilePath() {
return resolve(getDataDirPath(), "auth.json");
}
function getAuthDataFolder() {
return resolve(getDataDirPath(), "auth");
}
function getApiKeyAuthDataFilePath() {
return resolve(getAuthDataFolder(), "api-key.json");
}
function getAccountAuthDataFilePath() {
return resolve(getAuthDataFolder(), "account.json");
}
function getSiteAuthDataFilePath(siteId) {
return resolve(getAuthDataFolder(), `${siteId}.json`);
}
var ApiKeyAuthData = (0, import_variant2.variant)({
Authenticated: (0, import_variant2.payload)(),
Unauthenticated: {}
});
async function readApiKeyAuthData() {
const apiKeyAuthDataFilePath = getApiKeyAuthDataFilePath();
if (!await pathExists(apiKeyAuthDataFilePath)) {
return ApiKeyAuthData.Unauthenticated();
}
const apiKeyFileContents = await readJson(apiKeyAuthDataFilePath);
const savedApiKeyAuthData = apiKeyAuthSchema.parse(apiKeyFileContents);
return ApiKeyAuthData.Authenticated(savedApiKeyAuthData);
}
async function saveApiKeyAuthData(authData) {
try {
const targetFilePath = getApiKeyAuthDataFilePath();
await writeJson(targetFilePath, authData);
} catch (error) {
throw new CliError({
code: CliErrorCode.FailedToSaveApiKeyAuthData(),
cause: error
});
}
}
var AccountAuthData = (0, import_variant2.variant)({
Authenticated: (0, import_variant2.fields)(),
Unauthenticated: {},
Expired: (0, import_variant2.fields)()
});
async function readAccountAuthData() {
const accountAuthDataFilePath = getAccountAuthDataFilePath();
if (!await pathExists(accountAuthDataFilePath)) {
return AccountAuthData.Unauthenticated();
}
const authFileContents = await readJson(accountAuthDataFilePath);
const savedAccountAuthData = accountAuthSchema.parse(authFileContents);
if (!isValidToken(savedAccountAuthData)) {
return AccountAuthData.Expired(savedAccountAuthData);
}
return AccountAuthData.Authenticated(savedAccountAuthData);
}
var SiteAuthData = (0, import_variant2.variant)({
Authenticated: (0, import_variant2.fields)(),
Unauthenticated: {},
Expired: (0, import_variant2.fields)()
});
async function readSiteAuthData(siteId) {
const siteAuthDataFilePath = getSiteAuthDataFilePath(siteId);
if (!await pathExists(siteAuthDataFilePath)) {
return SiteAuthData.Unauthenticated();
}
const authFileContents = await readJson(siteAuthDataFilePath);
const savedSiteAuthData = siteAuthSchema.parse(authFileContents);
if (!isValidToken(savedSiteAuthData)) {
return SiteAuthData.Expired(savedSiteAuthData);
}
return SiteAuthData.Authenticated(savedSiteAuthData);
}
async function saveAuthData(authData, siteId) {
try {
const targetFilePath = siteId ? getSiteAuthDataFilePath(siteId) : getAccountAuthDataFilePath();
await writeJson(targetFilePath, authData);
} catch (error) {
throw new CliError({
code: CliErrorCode.FailedToSaveAuthData(),
cause: error
});
}
}
async function deleteAuthData() {
try {
await rm(getAuthDataFolder(), { recursive: true, force: true });
} catch (error) {
throw new CliError({
code: CliErrorCode.FailedToDeleteAuthData(),
cause: error
});
}
if (await hasLegacyAuthData()) {
await deleteLegacyAuthData();
}
}
async function deleteLegacyAuthData() {
try {
await unlink(getLegacyAuthDataFilePath());
} catch (error) {
throw new CliError({
code: CliErrorCode.FailedToDeleteLegacyAuthData(),
cause: error
});
}
}
async function hasLegacyAuthData() {
return pathExists(getLegacyAuthDataFilePath());
}
function isValidToken(authData) {
const currentTimestamp = Math.floor(Date.now() / 1e3);
const tokenOffset = 10 * 60;
const tokenLifetime = authData.expiresIn - tokenOffset;
const tokenGenerationTimestamp = authData.issuedAt;
return tokenGenerationTimestamp + tokenLifetime > currentTimestamp;
}
async function getUserInfo() {
const apiKeyAuthData = await readApiKeyAuthData();
if ((0, import_variant2.isType)(apiKeyAuthData, ApiKeyAuthData.Authenticated)) {
return apiKeyAuthData.payload.userInfo;
}
const accountAuthData = await readAccountAuthData();
return (0, import_variant2.match)(accountAuthData, {
Authenticated: ({ userInfo }) => userInfo,
Expired: ({ userInfo }) => userInfo,
Unauthenticated: () => null
});
}
// ../cli-auth/src/auth-strategies/api-key-auth-strategy.ts
function createApiKeyAuthState({
authData: { token: token2, accountId, userInfo },
siteId
}) {
return {
getAccessToken: async () => token2,
getRefreshToken: () => {
throw new Error("API key auth does not support refresh tokens");
},
getRequestHeaders: () => {
if (siteId) {
return { "wix-site-id": siteId };
}
return { "wix-account-id": accountId };
},
userInfo
};
}
var apiKeyAuthStrategy = {
async isLoggedIn({ siteId } = {}) {
const apiKeyAuth = await readApiKeyAuthData();
return (0, import_variant3.match)(apiKeyAuth, {
Authenticated: ({ payload: payload4 }) => {
return createApiKeyAuthState({ authData: payload4, siteId });
},
Unauthenticated: () => null
});
},
async login({ token: token2 }) {
const { accountId, accountOwner, slug } = await client.getMyAccount({
token: token2
});
const authData = {
token: token2,
accountId,
userInfo: {
userId: accountOwner,
// TODO: this should be the email of the account owner, not the slug
// https://jira.wixpress.com/browse/FEDINF-12201
email: slug
}
};
await deleteAuthData();
await saveApiKeyAuthData(authData);
return createApiKeyAuthState({ authData });
}
};
// ../cli-auth/src/auth-strategies/account-auth-strategy.ts
init_esm_shims();
// ../../node_modules/p-limit/index.js
init_esm_shims();
// ../../node_modules/p-limit/node_modules/yocto-queue/index.js
init_esm_shims();
var Node = class {
value;
next;
constructor(value) {
this.value = value;
}
};
var Queue = class {
#head;
#tail;
#size;
constructor() {
this.clear();
}
enqueue(value) {
const node = new Node(value);
if (this.#head) {
this.#tail.next = node;
this.#tail = node;
} else {
this.#head = node;
this.#tail = node;
}
this.#size++;
}
dequeue() {
const current = this.#head;
if (!current) {
return;
}
this.#head = this.#head.next;
this.#size--;
return current.value;
}
peek() {
if (!this.#head) {
return;
}
return this.#head.value;
}
clear() {
this.#head = void 0;
this.#tail = void 0;
this.#size = 0;
}
get size() {
return this.#size;
}
*[Symbol.iterator]() {
let current = this.#head;
while (current) {
yield current.value;
current = current.next;
}
}
};
// ../../node_modules/p-limit/index.js
function pLimit(concurrency) {
validateConcurrency(concurrency);
const queue = new Queue();
let activeCount = 0;
const resumeNext = () => {
if (activeCount < concurrency && queue.size > 0) {
queue.dequeue()();
activeCount++;
}
};
const next = () => {
activeCount--;
resumeNext();
};
const run = async (function_, resolve2, arguments_) => {
const result = (async () => function_(...arguments_))();
resolve2(result);
try {
await result;
} catch {
}
next();
};
const enqueue = (function_, resolve2, arguments_) => {
new Promise((internalResolve) => {
queue.enqueue(internalResolve);
}).th