brickcharts
Version:
A comprehensive library for managing Billboard and Last.FM charts with visualizations and data management
4,369 lines • 128 kB
JavaScript
var b = /* @__PURE__ */ ((n) => (n.BILLBOARD = "billboard", n.LASTFM = "lastfm", n.CUSTOM = "custom", n))(b || {});
class nt extends Error {
constructor(e, t, r) {
super(e), this.code = t, this.source = r, this.name = "BrickChartsError";
}
}
class D extends nt {
constructor(e, t, r) {
super(e, "API_ERROR", r), this.statusCode = t, this.name = "APIError";
}
}
class xe extends nt {
constructor(e) {
super(e, "CACHE_ERROR"), this.name = "CacheError";
}
}
const { getChart: $e, listCharts: Nt } = require("@aribradshaw/billboard-top-100");
class _t {
constructor() {
this.name = "Billboard", this.source = b.BILLBOARD, this.chartMap = /* @__PURE__ */ new Map([
["hot-100", "hot-100"],
["billboard-200", "billboard-200"],
["artist-100", "artist-100"],
["pop-songs", "pop-songs"],
["country-songs", "country-songs"],
["rock-songs", "rock-songs"],
["r-b-songs", "r-b-songs"],
["rap-songs", "rap-songs"],
["dance-songs", "dance-songs"],
["latin-songs", "latin-songs"]
]);
}
/**
* Get available Billboard chart types
*/
async getAvailableCharts() {
return new Promise((e, t) => {
Nt((r, a) => {
if (r)
t(new D(
`Failed to fetch available charts: ${r}`,
500,
b.BILLBOARD
));
else {
const s = a.map((i) => typeof i == "string" ? i : i && i.chart ? i.chart : i && i.name ? i.name : String(i));
e(s);
}
});
});
}
/**
* Fetch a specific Billboard chart
*/
async getChart(e, t = {}) {
return new Promise((r, a) => {
const s = this.chartMap.get(e) || e, i = t.date ? this.formatDateForAPI(t.date) : void 0;
i ? $e(s, i, (o, c) => {
o ? a(new D(
`Failed to fetch Billboard chart ${e}: ${o}`,
500,
b.BILLBOARD
)) : r(this.normalizeBillboardData(c, e, t.date || /* @__PURE__ */ new Date()));
}) : $e(s, (o, c) => {
o ? a(new D(
`Failed to fetch Billboard chart ${e}: ${o}`,
500,
b.BILLBOARD
)) : r(this.normalizeBillboardData(c, e, /* @__PURE__ */ new Date()));
});
});
}
/**
* Get historical data for a chart over a date range
*/
async getHistoricalData(e, t) {
const r = [], a = new Date(t.start), s = new Date(t.end), i = this.generateWeeklyDates(a, s);
try {
for (const o of i)
try {
const c = await this.getChart(e, { date: o });
r.push(c), await this.delay(100);
} catch (c) {
console.warn(`Failed to fetch chart for ${o}: ${c}`);
}
return {
chartType: e,
dateRange: t,
data: r,
source: b.BILLBOARD
};
} catch (o) {
throw new D(
`Failed to fetch historical data for ${e}: ${o}`,
500,
b.BILLBOARD
);
}
}
/**
* Normalize Billboard API response to our standard format
*/
normalizeBillboardData(e, t, r) {
const a = [];
return (e.songs || e.albums || []).forEach((i, o) => {
var c, l, d;
a.push({
rank: i.rank || o + 1,
title: i.title,
artist: i.artist,
lastWeek: ((c = i.position) == null ? void 0 : c.positionLastWeek) > 0 ? i.position.positionLastWeek : void 0,
peakPosition: (l = i.position) == null ? void 0 : l.peakPosition,
weeksOnChart: (d = i.position) == null ? void 0 : d.weeksOnChart,
chartDate: r,
source: b.BILLBOARD,
metadata: {
originalData: i,
cover: i.cover
}
});
}), {
chartType: t,
date: r,
entries: a,
source: b.BILLBOARD,
totalEntries: a.length,
metadata: {
week: e.week,
previousWeek: e.previousWeek,
nextWeek: e.nextWeek
}
};
}
/**
* Format date for Billboard API (YYYY-MM-DD)
*/
formatDateForAPI(e) {
return e.toISOString().split("T")[0];
}
/**
* Generate weekly dates between start and end date
*/
generateWeeklyDates(e, t) {
const r = [], a = new Date(e);
for (; a <= t; )
r.push(new Date(a)), a.setDate(a.getDate() + 7);
return r;
}
/**
* Simple delay utility for rate limiting
*/
delay(e) {
return new Promise((t) => setTimeout(t, e));
}
/**
* Get chart metadata and information
*/
async getChartInfo(e) {
try {
return (await this.getAvailableCharts()).find((r) => r === e) ? { name: e, available: !0 } : null;
} catch (t) {
throw new D(
`Failed to get chart info for ${e}: ${t}`,
500,
b.BILLBOARD
);
}
}
}
function at(n, e) {
return function() {
return n.apply(e, arguments);
};
}
const { toString: $t } = Object.prototype, { getPrototypeOf: Ue } = Object, { iterator: me, toStringTag: st } = Symbol, pe = /* @__PURE__ */ ((n) => (e) => {
const t = $t.call(e);
return n[t] || (n[t] = t.slice(8, -1).toLowerCase());
})(/* @__PURE__ */ Object.create(null)), U = (n) => (n = n.toLowerCase(), (e) => pe(e) === n), ge = (n) => (e) => typeof e === n, { isArray: V } = Array, ee = ge("undefined");
function Bt(n) {
return n !== null && !ee(n) && n.constructor !== null && !ee(n.constructor) && R(n.constructor.isBuffer) && n.constructor.isBuffer(n);
}
const it = U("ArrayBuffer");
function It(n) {
let e;
return typeof ArrayBuffer < "u" && ArrayBuffer.isView ? e = ArrayBuffer.isView(n) : e = n && n.buffer && it(n.buffer), e;
}
const Wt = ge("string"), R = ge("function"), ot = ge("number"), we = (n) => n !== null && typeof n == "object", jt = (n) => n === !0 || n === !1, ie = (n) => {
if (pe(n) !== "object")
return !1;
const e = Ue(n);
return (e === null || e === Object.prototype || Object.getPrototypeOf(e) === null) && !(st in n) && !(me in n);
}, zt = U("Date"), Ht = U("File"), Yt = U("Blob"), qt = U("FileList"), Vt = (n) => we(n) && R(n.pipe), Jt = (n) => {
let e;
return n && (typeof FormData == "function" && n instanceof FormData || R(n.append) && ((e = pe(n)) === "formdata" || // detect form-data instance
e === "object" && R(n.toString) && n.toString() === "[object FormData]"));
}, Kt = U("URLSearchParams"), [Xt, Qt, Gt, Zt] = ["ReadableStream", "Request", "Response", "Headers"].map(U), er = (n) => n.trim ? n.trim() : n.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
function te(n, e, { allOwnKeys: t = !1 } = {}) {
if (n === null || typeof n > "u")
return;
let r, a;
if (typeof n != "object" && (n = [n]), V(n))
for (r = 0, a = n.length; r < a; r++)
e.call(null, n[r], r, n);
else {
const s = t ? Object.getOwnPropertyNames(n) : Object.keys(n), i = s.length;
let o;
for (r = 0; r < i; r++)
o = s[r], e.call(null, n[o], o, n);
}
}
function ct(n, e) {
e = e.toLowerCase();
const t = Object.keys(n);
let r = t.length, a;
for (; r-- > 0; )
if (a = t[r], e === a.toLowerCase())
return a;
return null;
}
const j = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : typeof window < "u" ? window : global, lt = (n) => !ee(n) && n !== j;
function De() {
const { caseless: n } = lt(this) && this || {}, e = {}, t = (r, a) => {
const s = n && ct(e, a) || a;
ie(e[s]) && ie(r) ? e[s] = De(e[s], r) : ie(r) ? e[s] = De({}, r) : V(r) ? e[s] = r.slice() : e[s] = r;
};
for (let r = 0, a = arguments.length; r < a; r++)
arguments[r] && te(arguments[r], t);
return e;
}
const tr = (n, e, t, { allOwnKeys: r } = {}) => (te(e, (a, s) => {
t && R(a) ? n[s] = at(a, t) : n[s] = a;
}, { allOwnKeys: r }), n), rr = (n) => (n.charCodeAt(0) === 65279 && (n = n.slice(1)), n), nr = (n, e, t, r) => {
n.prototype = Object.create(e.prototype, r), n.prototype.constructor = n, Object.defineProperty(n, "super", {
value: e.prototype
}), t && Object.assign(n.prototype, t);
}, ar = (n, e, t, r) => {
let a, s, i;
const o = {};
if (e = e || {}, n == null) return e;
do {
for (a = Object.getOwnPropertyNames(n), s = a.length; s-- > 0; )
i = a[s], (!r || r(i, n, e)) && !o[i] && (e[i] = n[i], o[i] = !0);
n = t !== !1 && Ue(n);
} while (n && (!t || t(n, e)) && n !== Object.prototype);
return e;
}, sr = (n, e, t) => {
n = String(n), (t === void 0 || t > n.length) && (t = n.length), t -= e.length;
const r = n.indexOf(e, t);
return r !== -1 && r === t;
}, ir = (n) => {
if (!n) return null;
if (V(n)) return n;
let e = n.length;
if (!ot(e)) return null;
const t = new Array(e);
for (; e-- > 0; )
t[e] = n[e];
return t;
}, or = /* @__PURE__ */ ((n) => (e) => n && e instanceof n)(typeof Uint8Array < "u" && Ue(Uint8Array)), cr = (n, e) => {
const r = (n && n[me]).call(n);
let a;
for (; (a = r.next()) && !a.done; ) {
const s = a.value;
e.call(n, s[0], s[1]);
}
}, lr = (n, e) => {
let t;
const r = [];
for (; (t = n.exec(e)) !== null; )
r.push(t);
return r;
}, ur = U("HTMLFormElement"), dr = (n) => n.toLowerCase().replace(
/[-_\s]([a-z\d])(\w*)/g,
function(t, r, a) {
return r.toUpperCase() + a;
}
), Be = (({ hasOwnProperty: n }) => (e, t) => n.call(e, t))(Object.prototype), fr = U("RegExp"), ut = (n, e) => {
const t = Object.getOwnPropertyDescriptors(n), r = {};
te(t, (a, s) => {
let i;
(i = e(a, s, n)) !== !1 && (r[s] = i || a);
}), Object.defineProperties(n, r);
}, hr = (n) => {
ut(n, (e, t) => {
if (R(n) && ["arguments", "caller", "callee"].indexOf(t) !== -1)
return !1;
const r = n[t];
if (R(r)) {
if (e.enumerable = !1, "writable" in e) {
e.writable = !1;
return;
}
e.set || (e.set = () => {
throw Error("Can not rewrite read-only method '" + t + "'");
});
}
});
}, mr = (n, e) => {
const t = {}, r = (a) => {
a.forEach((s) => {
t[s] = !0;
});
};
return V(n) ? r(n) : r(String(n).split(e)), t;
}, pr = () => {
}, gr = (n, e) => n != null && Number.isFinite(n = +n) ? n : e;
function wr(n) {
return !!(n && R(n.append) && n[st] === "FormData" && n[me]);
}
const yr = (n) => {
const e = new Array(10), t = (r, a) => {
if (we(r)) {
if (e.indexOf(r) >= 0)
return;
if (!("toJSON" in r)) {
e[a] = r;
const s = V(r) ? [] : {};
return te(r, (i, o) => {
const c = t(i, a + 1);
!ee(c) && (s[o] = c);
}), e[a] = void 0, s;
}
}
return r;
};
return t(n, 0);
}, vr = U("AsyncFunction"), br = (n) => n && (we(n) || R(n)) && R(n.then) && R(n.catch), dt = ((n, e) => n ? setImmediate : e ? ((t, r) => (j.addEventListener("message", ({ source: a, data: s }) => {
a === j && s === t && r.length && r.shift()();
}, !1), (a) => {
r.push(a), j.postMessage(t, "*");
}))(`axios@${Math.random()}`, []) : (t) => setTimeout(t))(
typeof setImmediate == "function",
R(j.postMessage)
), Tr = typeof queueMicrotask < "u" ? queueMicrotask.bind(j) : typeof process < "u" && process.nextTick || dt, Cr = (n) => n != null && R(n[me]), u = {
isArray: V,
isArrayBuffer: it,
isBuffer: Bt,
isFormData: Jt,
isArrayBufferView: It,
isString: Wt,
isNumber: ot,
isBoolean: jt,
isObject: we,
isPlainObject: ie,
isReadableStream: Xt,
isRequest: Qt,
isResponse: Gt,
isHeaders: Zt,
isUndefined: ee,
isDate: zt,
isFile: Ht,
isBlob: Yt,
isRegExp: fr,
isFunction: R,
isStream: Vt,
isURLSearchParams: Kt,
isTypedArray: or,
isFileList: qt,
forEach: te,
merge: De,
extend: tr,
trim: er,
stripBOM: rr,
inherits: nr,
toFlatObject: ar,
kindOf: pe,
kindOfTest: U,
endsWith: sr,
toArray: ir,
forEachEntry: cr,
matchAll: lr,
isHTMLForm: ur,
hasOwnProperty: Be,
hasOwnProp: Be,
// an alias to avoid ESLint no-prototype-builtins detection
reduceDescriptors: ut,
freezeMethods: hr,
toObjectSet: mr,
toCamelCase: dr,
noop: pr,
toFiniteNumber: gr,
findKey: ct,
global: j,
isContextDefined: lt,
isSpecCompliantForm: wr,
toJSONObject: yr,
isAsyncFn: vr,
isThenable: br,
setImmediate: dt,
asap: Tr,
isIterable: Cr
};
function y(n, e, t, r, a) {
Error.call(this), Error.captureStackTrace ? Error.captureStackTrace(this, this.constructor) : this.stack = new Error().stack, this.message = n, this.name = "AxiosError", e && (this.code = e), t && (this.config = t), r && (this.request = r), a && (this.response = a, this.status = a.status ? a.status : null);
}
u.inherits(y, Error, {
toJSON: function() {
return {
// Standard
message: this.message,
name: this.name,
// Microsoft
description: this.description,
number: this.number,
// Mozilla
fileName: this.fileName,
lineNumber: this.lineNumber,
columnNumber: this.columnNumber,
stack: this.stack,
// Axios
config: u.toJSONObject(this.config),
code: this.code,
status: this.status
};
}
});
const ft = y.prototype, ht = {};
[
"ERR_BAD_OPTION_VALUE",
"ERR_BAD_OPTION",
"ECONNABORTED",
"ETIMEDOUT",
"ERR_NETWORK",
"ERR_FR_TOO_MANY_REDIRECTS",
"ERR_DEPRECATED",
"ERR_BAD_RESPONSE",
"ERR_BAD_REQUEST",
"ERR_CANCELED",
"ERR_NOT_SUPPORT",
"ERR_INVALID_URL"
// eslint-disable-next-line func-names
].forEach((n) => {
ht[n] = { value: n };
});
Object.defineProperties(y, ht);
Object.defineProperty(ft, "isAxiosError", { value: !0 });
y.from = (n, e, t, r, a, s) => {
const i = Object.create(ft);
return u.toFlatObject(n, i, function(c) {
return c !== Error.prototype;
}, (o) => o !== "isAxiosError"), y.call(i, n.message, e, t, r, a), i.cause = n, i.name = n.name, s && Object.assign(i, s), i;
};
const Sr = null;
function Re(n) {
return u.isPlainObject(n) || u.isArray(n);
}
function mt(n) {
return u.endsWith(n, "[]") ? n.slice(0, -2) : n;
}
function Ie(n, e, t) {
return n ? n.concat(e).map(function(a, s) {
return a = mt(a), !t && s ? "[" + a + "]" : a;
}).join(t ? "." : "") : e;
}
function Or(n) {
return u.isArray(n) && !n.some(Re);
}
const kr = u.toFlatObject(u, {}, null, function(e) {
return /^is[A-Z]/.test(e);
});
function ye(n, e, t) {
if (!u.isObject(n))
throw new TypeError("target must be an object");
e = e || new FormData(), t = u.toFlatObject(t, {
metaTokens: !0,
dots: !1,
indexes: !1
}, !1, function(g, p) {
return !u.isUndefined(p[g]);
});
const r = t.metaTokens, a = t.visitor || d, s = t.dots, i = t.indexes, c = (t.Blob || typeof Blob < "u" && Blob) && u.isSpecCompliantForm(e);
if (!u.isFunction(a))
throw new TypeError("visitor must be a function");
function l(h) {
if (h === null) return "";
if (u.isDate(h))
return h.toISOString();
if (u.isBoolean(h))
return h.toString();
if (!c && u.isBlob(h))
throw new y("Blob is not supported. Use a Buffer instead.");
return u.isArrayBuffer(h) || u.isTypedArray(h) ? c && typeof Blob == "function" ? new Blob([h]) : Buffer.from(h) : h;
}
function d(h, g, p) {
let C = h;
if (h && !p && typeof h == "object") {
if (u.endsWith(g, "{}"))
g = r ? g : g.slice(0, -2), h = JSON.stringify(h);
else if (u.isArray(h) && Or(h) || (u.isFileList(h) || u.endsWith(g, "[]")) && (C = u.toArray(h)))
return g = mt(g), C.forEach(function(O, P) {
!(u.isUndefined(O) || O === null) && e.append(
// eslint-disable-next-line no-nested-ternary
i === !0 ? Ie([g], P, s) : i === null ? g : g + "[]",
l(O)
);
}), !1;
}
return Re(h) ? !0 : (e.append(Ie(p, g, s), l(h)), !1);
}
const f = [], m = Object.assign(kr, {
defaultVisitor: d,
convertValue: l,
isVisitable: Re
});
function w(h, g) {
if (!u.isUndefined(h)) {
if (f.indexOf(h) !== -1)
throw Error("Circular reference detected in " + g.join("."));
f.push(h), u.forEach(h, function(C, v) {
(!(u.isUndefined(C) || C === null) && a.call(
e,
C,
u.isString(v) ? v.trim() : v,
g,
m
)) === !0 && w(C, g ? g.concat(v) : [v]);
}), f.pop();
}
}
if (!u.isObject(n))
throw new TypeError("data must be an object");
return w(n), e;
}
function We(n) {
const e = {
"!": "%21",
"'": "%27",
"(": "%28",
")": "%29",
"~": "%7E",
"%20": "+",
"%00": "\0"
};
return encodeURIComponent(n).replace(/[!'()~]|%20|%00/g, function(r) {
return e[r];
});
}
function Ne(n, e) {
this._pairs = [], n && ye(n, this, e);
}
const pt = Ne.prototype;
pt.append = function(e, t) {
this._pairs.push([e, t]);
};
pt.toString = function(e) {
const t = e ? function(r) {
return e.call(this, r, We);
} : We;
return this._pairs.map(function(a) {
return t(a[0]) + "=" + t(a[1]);
}, "").join("&");
};
function Er(n) {
return encodeURIComponent(n).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]");
}
function gt(n, e, t) {
if (!e)
return n;
const r = t && t.encode || Er;
u.isFunction(t) && (t = {
serialize: t
});
const a = t && t.serialize;
let s;
if (a ? s = a(e, t) : s = u.isURLSearchParams(e) ? e.toString() : new Ne(e, t).toString(r), s) {
const i = n.indexOf("#");
i !== -1 && (n = n.slice(0, i)), n += (n.indexOf("?") === -1 ? "?" : "&") + s;
}
return n;
}
class je {
constructor() {
this.handlers = [];
}
/**
* Add a new interceptor to the stack
*
* @param {Function} fulfilled The function to handle `then` for a `Promise`
* @param {Function} rejected The function to handle `reject` for a `Promise`
*
* @return {Number} An ID used to remove interceptor later
*/
use(e, t, r) {
return this.handlers.push({
fulfilled: e,
rejected: t,
synchronous: r ? r.synchronous : !1,
runWhen: r ? r.runWhen : null
}), this.handlers.length - 1;
}
/**
* Remove an interceptor from the stack
*
* @param {Number} id The ID that was returned by `use`
*
* @returns {Boolean} `true` if the interceptor was removed, `false` otherwise
*/
eject(e) {
this.handlers[e] && (this.handlers[e] = null);
}
/**
* Clear all interceptors from the stack
*
* @returns {void}
*/
clear() {
this.handlers && (this.handlers = []);
}
/**
* Iterate over all the registered interceptors
*
* This method is particularly useful for skipping over any
* interceptors that may have become `null` calling `eject`.
*
* @param {Function} fn The function to call for each interceptor
*
* @returns {void}
*/
forEach(e) {
u.forEach(this.handlers, function(r) {
r !== null && e(r);
});
}
}
const wt = {
silentJSONParsing: !0,
forcedJSONParsing: !0,
clarifyTimeoutError: !1
}, xr = typeof URLSearchParams < "u" ? URLSearchParams : Ne, Dr = typeof FormData < "u" ? FormData : null, Rr = typeof Blob < "u" ? Blob : null, Ar = {
isBrowser: !0,
classes: {
URLSearchParams: xr,
FormData: Dr,
Blob: Rr
},
protocols: ["http", "https", "file", "blob", "url", "data"]
}, _e = typeof window < "u" && typeof document < "u", Ae = typeof navigator == "object" && navigator || void 0, Pr = _e && (!Ae || ["ReactNative", "NativeScript", "NS"].indexOf(Ae.product) < 0), Mr = typeof WorkerGlobalScope < "u" && // eslint-disable-next-line no-undef
self instanceof WorkerGlobalScope && typeof self.importScripts == "function", Lr = _e && window.location.href || "http://localhost", Fr = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
__proto__: null,
hasBrowserEnv: _e,
hasStandardBrowserEnv: Pr,
hasStandardBrowserWebWorkerEnv: Mr,
navigator: Ae,
origin: Lr
}, Symbol.toStringTag, { value: "Module" })), x = {
...Fr,
...Ar
};
function Ur(n, e) {
return ye(n, new x.classes.URLSearchParams(), Object.assign({
visitor: function(t, r, a, s) {
return x.isNode && u.isBuffer(t) ? (this.append(r, t.toString("base64")), !1) : s.defaultVisitor.apply(this, arguments);
}
}, e));
}
function Nr(n) {
return u.matchAll(/\w+|\[(\w*)]/g, n).map((e) => e[0] === "[]" ? "" : e[1] || e[0]);
}
function _r(n) {
const e = {}, t = Object.keys(n);
let r;
const a = t.length;
let s;
for (r = 0; r < a; r++)
s = t[r], e[s] = n[s];
return e;
}
function yt(n) {
function e(t, r, a, s) {
let i = t[s++];
if (i === "__proto__") return !0;
const o = Number.isFinite(+i), c = s >= t.length;
return i = !i && u.isArray(a) ? a.length : i, c ? (u.hasOwnProp(a, i) ? a[i] = [a[i], r] : a[i] = r, !o) : ((!a[i] || !u.isObject(a[i])) && (a[i] = []), e(t, r, a[i], s) && u.isArray(a[i]) && (a[i] = _r(a[i])), !o);
}
if (u.isFormData(n) && u.isFunction(n.entries)) {
const t = {};
return u.forEachEntry(n, (r, a) => {
e(Nr(r), a, t, 0);
}), t;
}
return null;
}
function $r(n, e, t) {
if (u.isString(n))
try {
return (e || JSON.parse)(n), u.trim(n);
} catch (r) {
if (r.name !== "SyntaxError")
throw r;
}
return (t || JSON.stringify)(n);
}
const re = {
transitional: wt,
adapter: ["xhr", "http", "fetch"],
transformRequest: [function(e, t) {
const r = t.getContentType() || "", a = r.indexOf("application/json") > -1, s = u.isObject(e);
if (s && u.isHTMLForm(e) && (e = new FormData(e)), u.isFormData(e))
return a ? JSON.stringify(yt(e)) : e;
if (u.isArrayBuffer(e) || u.isBuffer(e) || u.isStream(e) || u.isFile(e) || u.isBlob(e) || u.isReadableStream(e))
return e;
if (u.isArrayBufferView(e))
return e.buffer;
if (u.isURLSearchParams(e))
return t.setContentType("application/x-www-form-urlencoded;charset=utf-8", !1), e.toString();
let o;
if (s) {
if (r.indexOf("application/x-www-form-urlencoded") > -1)
return Ur(e, this.formSerializer).toString();
if ((o = u.isFileList(e)) || r.indexOf("multipart/form-data") > -1) {
const c = this.env && this.env.FormData;
return ye(
o ? { "files[]": e } : e,
c && new c(),
this.formSerializer
);
}
}
return s || a ? (t.setContentType("application/json", !1), $r(e)) : e;
}],
transformResponse: [function(e) {
const t = this.transitional || re.transitional, r = t && t.forcedJSONParsing, a = this.responseType === "json";
if (u.isResponse(e) || u.isReadableStream(e))
return e;
if (e && u.isString(e) && (r && !this.responseType || a)) {
const i = !(t && t.silentJSONParsing) && a;
try {
return JSON.parse(e);
} catch (o) {
if (i)
throw o.name === "SyntaxError" ? y.from(o, y.ERR_BAD_RESPONSE, this, null, this.response) : o;
}
}
return e;
}],
/**
* A timeout in milliseconds to abort a request. If set to 0 (default) a
* timeout is not created.
*/
timeout: 0,
xsrfCookieName: "XSRF-TOKEN",
xsrfHeaderName: "X-XSRF-TOKEN",
maxContentLength: -1,
maxBodyLength: -1,
env: {
FormData: x.classes.FormData,
Blob: x.classes.Blob
},
validateStatus: function(e) {
return e >= 200 && e < 300;
},
headers: {
common: {
Accept: "application/json, text/plain, */*",
"Content-Type": void 0
}
}
};
u.forEach(["delete", "get", "head", "post", "put", "patch"], (n) => {
re.headers[n] = {};
});
const Br = u.toObjectSet([
"age",
"authorization",
"content-length",
"content-type",
"etag",
"expires",
"from",
"host",
"if-modified-since",
"if-unmodified-since",
"last-modified",
"location",
"max-forwards",
"proxy-authorization",
"referer",
"retry-after",
"user-agent"
]), Ir = (n) => {
const e = {};
let t, r, a;
return n && n.split(`
`).forEach(function(i) {
a = i.indexOf(":"), t = i.substring(0, a).trim().toLowerCase(), r = i.substring(a + 1).trim(), !(!t || e[t] && Br[t]) && (t === "set-cookie" ? e[t] ? e[t].push(r) : e[t] = [r] : e[t] = e[t] ? e[t] + ", " + r : r);
}), e;
}, ze = Symbol("internals");
function X(n) {
return n && String(n).trim().toLowerCase();
}
function oe(n) {
return n === !1 || n == null ? n : u.isArray(n) ? n.map(oe) : String(n);
}
function Wr(n) {
const e = /* @__PURE__ */ Object.create(null), t = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;
let r;
for (; r = t.exec(n); )
e[r[1]] = r[2];
return e;
}
const jr = (n) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(n.trim());
function Te(n, e, t, r, a) {
if (u.isFunction(r))
return r.call(this, e, t);
if (a && (e = t), !!u.isString(e)) {
if (u.isString(r))
return e.indexOf(r) !== -1;
if (u.isRegExp(r))
return r.test(e);
}
}
function zr(n) {
return n.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (e, t, r) => t.toUpperCase() + r);
}
function Hr(n, e) {
const t = u.toCamelCase(" " + e);
["get", "set", "has"].forEach((r) => {
Object.defineProperty(n, r + t, {
value: function(a, s, i) {
return this[r].call(this, e, a, s, i);
},
configurable: !0
});
});
}
let A = class {
constructor(e) {
e && this.set(e);
}
set(e, t, r) {
const a = this;
function s(o, c, l) {
const d = X(c);
if (!d)
throw new Error("header name must be a non-empty string");
const f = u.findKey(a, d);
(!f || a[f] === void 0 || l === !0 || l === void 0 && a[f] !== !1) && (a[f || c] = oe(o));
}
const i = (o, c) => u.forEach(o, (l, d) => s(l, d, c));
if (u.isPlainObject(e) || e instanceof this.constructor)
i(e, t);
else if (u.isString(e) && (e = e.trim()) && !jr(e))
i(Ir(e), t);
else if (u.isObject(e) && u.isIterable(e)) {
let o = {}, c, l;
for (const d of e) {
if (!u.isArray(d))
throw TypeError("Object iterator must return a key-value pair");
o[l = d[0]] = (c = o[l]) ? u.isArray(c) ? [...c, d[1]] : [c, d[1]] : d[1];
}
i(o, t);
} else
e != null && s(t, e, r);
return this;
}
get(e, t) {
if (e = X(e), e) {
const r = u.findKey(this, e);
if (r) {
const a = this[r];
if (!t)
return a;
if (t === !0)
return Wr(a);
if (u.isFunction(t))
return t.call(this, a, r);
if (u.isRegExp(t))
return t.exec(a);
throw new TypeError("parser must be boolean|regexp|function");
}
}
}
has(e, t) {
if (e = X(e), e) {
const r = u.findKey(this, e);
return !!(r && this[r] !== void 0 && (!t || Te(this, this[r], r, t)));
}
return !1;
}
delete(e, t) {
const r = this;
let a = !1;
function s(i) {
if (i = X(i), i) {
const o = u.findKey(r, i);
o && (!t || Te(r, r[o], o, t)) && (delete r[o], a = !0);
}
}
return u.isArray(e) ? e.forEach(s) : s(e), a;
}
clear(e) {
const t = Object.keys(this);
let r = t.length, a = !1;
for (; r--; ) {
const s = t[r];
(!e || Te(this, this[s], s, e, !0)) && (delete this[s], a = !0);
}
return a;
}
normalize(e) {
const t = this, r = {};
return u.forEach(this, (a, s) => {
const i = u.findKey(r, s);
if (i) {
t[i] = oe(a), delete t[s];
return;
}
const o = e ? zr(s) : String(s).trim();
o !== s && delete t[s], t[o] = oe(a), r[o] = !0;
}), this;
}
concat(...e) {
return this.constructor.concat(this, ...e);
}
toJSON(e) {
const t = /* @__PURE__ */ Object.create(null);
return u.forEach(this, (r, a) => {
r != null && r !== !1 && (t[a] = e && u.isArray(r) ? r.join(", ") : r);
}), t;
}
[Symbol.iterator]() {
return Object.entries(this.toJSON())[Symbol.iterator]();
}
toString() {
return Object.entries(this.toJSON()).map(([e, t]) => e + ": " + t).join(`
`);
}
getSetCookie() {
return this.get("set-cookie") || [];
}
get [Symbol.toStringTag]() {
return "AxiosHeaders";
}
static from(e) {
return e instanceof this ? e : new this(e);
}
static concat(e, ...t) {
const r = new this(e);
return t.forEach((a) => r.set(a)), r;
}
static accessor(e) {
const r = (this[ze] = this[ze] = {
accessors: {}
}).accessors, a = this.prototype;
function s(i) {
const o = X(i);
r[o] || (Hr(a, i), r[o] = !0);
}
return u.isArray(e) ? e.forEach(s) : s(e), this;
}
};
A.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]);
u.reduceDescriptors(A.prototype, ({ value: n }, e) => {
let t = e[0].toUpperCase() + e.slice(1);
return {
get: () => n,
set(r) {
this[t] = r;
}
};
});
u.freezeMethods(A);
function Ce(n, e) {
const t = this || re, r = e || t, a = A.from(r.headers);
let s = r.data;
return u.forEach(n, function(o) {
s = o.call(t, s, a.normalize(), e ? e.status : void 0);
}), a.normalize(), s;
}
function vt(n) {
return !!(n && n.__CANCEL__);
}
function J(n, e, t) {
y.call(this, n ?? "canceled", y.ERR_CANCELED, e, t), this.name = "CanceledError";
}
u.inherits(J, y, {
__CANCEL__: !0
});
function bt(n, e, t) {
const r = t.config.validateStatus;
!t.status || !r || r(t.status) ? n(t) : e(new y(
"Request failed with status code " + t.status,
[y.ERR_BAD_REQUEST, y.ERR_BAD_RESPONSE][Math.floor(t.status / 100) - 4],
t.config,
t.request,
t
));
}
function Yr(n) {
const e = /^([-+\w]{1,25})(:?\/\/|:)/.exec(n);
return e && e[1] || "";
}
function qr(n, e) {
n = n || 10;
const t = new Array(n), r = new Array(n);
let a = 0, s = 0, i;
return e = e !== void 0 ? e : 1e3, function(c) {
const l = Date.now(), d = r[s];
i || (i = l), t[a] = c, r[a] = l;
let f = s, m = 0;
for (; f !== a; )
m += t[f++], f = f % n;
if (a = (a + 1) % n, a === s && (s = (s + 1) % n), l - i < e)
return;
const w = d && l - d;
return w ? Math.round(m * 1e3 / w) : void 0;
};
}
function Vr(n, e) {
let t = 0, r = 1e3 / e, a, s;
const i = (l, d = Date.now()) => {
t = d, a = null, s && (clearTimeout(s), s = null), n.apply(null, l);
};
return [(...l) => {
const d = Date.now(), f = d - t;
f >= r ? i(l, d) : (a = l, s || (s = setTimeout(() => {
s = null, i(a);
}, r - f)));
}, () => a && i(a)];
}
const le = (n, e, t = 3) => {
let r = 0;
const a = qr(50, 250);
return Vr((s) => {
const i = s.loaded, o = s.lengthComputable ? s.total : void 0, c = i - r, l = a(c), d = i <= o;
r = i;
const f = {
loaded: i,
total: o,
progress: o ? i / o : void 0,
bytes: c,
rate: l || void 0,
estimated: l && o && d ? (o - i) / l : void 0,
event: s,
lengthComputable: o != null,
[e ? "download" : "upload"]: !0
};
n(f);
}, t);
}, He = (n, e) => {
const t = n != null;
return [(r) => e[0]({
lengthComputable: t,
total: n,
loaded: r
}), e[1]];
}, Ye = (n) => (...e) => u.asap(() => n(...e)), Jr = x.hasStandardBrowserEnv ? /* @__PURE__ */ ((n, e) => (t) => (t = new URL(t, x.origin), n.protocol === t.protocol && n.host === t.host && (e || n.port === t.port)))(
new URL(x.origin),
x.navigator && /(msie|trident)/i.test(x.navigator.userAgent)
) : () => !0, Kr = x.hasStandardBrowserEnv ? (
// Standard browser envs support document.cookie
{
write(n, e, t, r, a, s) {
const i = [n + "=" + encodeURIComponent(e)];
u.isNumber(t) && i.push("expires=" + new Date(t).toGMTString()), u.isString(r) && i.push("path=" + r), u.isString(a) && i.push("domain=" + a), s === !0 && i.push("secure"), document.cookie = i.join("; ");
},
read(n) {
const e = document.cookie.match(new RegExp("(^|;\\s*)(" + n + ")=([^;]*)"));
return e ? decodeURIComponent(e[3]) : null;
},
remove(n) {
this.write(n, "", Date.now() - 864e5);
}
}
) : (
// Non-standard browser env (web workers, react-native) lack needed support.
{
write() {
},
read() {
return null;
},
remove() {
}
}
);
function Xr(n) {
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(n);
}
function Qr(n, e) {
return e ? n.replace(/\/?\/$/, "") + "/" + e.replace(/^\/+/, "") : n;
}
function Tt(n, e, t) {
let r = !Xr(e);
return n && (r || t == !1) ? Qr(n, e) : e;
}
const qe = (n) => n instanceof A ? { ...n } : n;
function H(n, e) {
e = e || {};
const t = {};
function r(l, d, f, m) {
return u.isPlainObject(l) && u.isPlainObject(d) ? u.merge.call({ caseless: m }, l, d) : u.isPlainObject(d) ? u.merge({}, d) : u.isArray(d) ? d.slice() : d;
}
function a(l, d, f, m) {
if (u.isUndefined(d)) {
if (!u.isUndefined(l))
return r(void 0, l, f, m);
} else return r(l, d, f, m);
}
function s(l, d) {
if (!u.isUndefined(d))
return r(void 0, d);
}
function i(l, d) {
if (u.isUndefined(d)) {
if (!u.isUndefined(l))
return r(void 0, l);
} else return r(void 0, d);
}
function o(l, d, f) {
if (f in e)
return r(l, d);
if (f in n)
return r(void 0, l);
}
const c = {
url: s,
method: s,
data: s,
baseURL: i,
transformRequest: i,
transformResponse: i,
paramsSerializer: i,
timeout: i,
timeoutMessage: i,
withCredentials: i,
withXSRFToken: i,
adapter: i,
responseType: i,
xsrfCookieName: i,
xsrfHeaderName: i,
onUploadProgress: i,
onDownloadProgress: i,
decompress: i,
maxContentLength: i,
maxBodyLength: i,
beforeRedirect: i,
transport: i,
httpAgent: i,
httpsAgent: i,
cancelToken: i,
socketPath: i,
responseEncoding: i,
validateStatus: o,
headers: (l, d, f) => a(qe(l), qe(d), f, !0)
};
return u.forEach(Object.keys(Object.assign({}, n, e)), function(d) {
const f = c[d] || a, m = f(n[d], e[d], d);
u.isUndefined(m) && f !== o || (t[d] = m);
}), t;
}
const Ct = (n) => {
const e = H({}, n);
let { data: t, withXSRFToken: r, xsrfHeaderName: a, xsrfCookieName: s, headers: i, auth: o } = e;
e.headers = i = A.from(i), e.url = gt(Tt(e.baseURL, e.url, e.allowAbsoluteUrls), n.params, n.paramsSerializer), o && i.set(
"Authorization",
"Basic " + btoa((o.username || "") + ":" + (o.password ? unescape(encodeURIComponent(o.password)) : ""))
);
let c;
if (u.isFormData(t)) {
if (x.hasStandardBrowserEnv || x.hasStandardBrowserWebWorkerEnv)
i.setContentType(void 0);
else if ((c = i.getContentType()) !== !1) {
const [l, ...d] = c ? c.split(";").map((f) => f.trim()).filter(Boolean) : [];
i.setContentType([l || "multipart/form-data", ...d].join("; "));
}
}
if (x.hasStandardBrowserEnv && (r && u.isFunction(r) && (r = r(e)), r || r !== !1 && Jr(e.url))) {
const l = a && s && Kr.read(s);
l && i.set(a, l);
}
return e;
}, Gr = typeof XMLHttpRequest < "u", Zr = Gr && function(n) {
return new Promise(function(t, r) {
const a = Ct(n);
let s = a.data;
const i = A.from(a.headers).normalize();
let { responseType: o, onUploadProgress: c, onDownloadProgress: l } = a, d, f, m, w, h;
function g() {
w && w(), h && h(), a.cancelToken && a.cancelToken.unsubscribe(d), a.signal && a.signal.removeEventListener("abort", d);
}
let p = new XMLHttpRequest();
p.open(a.method.toUpperCase(), a.url, !0), p.timeout = a.timeout;
function C() {
if (!p)
return;
const O = A.from(
"getAllResponseHeaders" in p && p.getAllResponseHeaders()
), k = {
data: !o || o === "text" || o === "json" ? p.responseText : p.response,
status: p.status,
statusText: p.statusText,
headers: O,
config: n,
request: p
};
bt(function($) {
t($), g();
}, function($) {
r($), g();
}, k), p = null;
}
"onloadend" in p ? p.onloadend = C : p.onreadystatechange = function() {
!p || p.readyState !== 4 || p.status === 0 && !(p.responseURL && p.responseURL.indexOf("file:") === 0) || setTimeout(C);
}, p.onabort = function() {
p && (r(new y("Request aborted", y.ECONNABORTED, n, p)), p = null);
}, p.onerror = function() {
r(new y("Network Error", y.ERR_NETWORK, n, p)), p = null;
}, p.ontimeout = function() {
let P = a.timeout ? "timeout of " + a.timeout + "ms exceeded" : "timeout exceeded";
const k = a.transitional || wt;
a.timeoutErrorMessage && (P = a.timeoutErrorMessage), r(new y(
P,
k.clarifyTimeoutError ? y.ETIMEDOUT : y.ECONNABORTED,
n,
p
)), p = null;
}, s === void 0 && i.setContentType(null), "setRequestHeader" in p && u.forEach(i.toJSON(), function(P, k) {
p.setRequestHeader(k, P);
}), u.isUndefined(a.withCredentials) || (p.withCredentials = !!a.withCredentials), o && o !== "json" && (p.responseType = a.responseType), l && ([m, h] = le(l, !0), p.addEventListener("progress", m)), c && p.upload && ([f, w] = le(c), p.upload.addEventListener("progress", f), p.upload.addEventListener("loadend", w)), (a.cancelToken || a.signal) && (d = (O) => {
p && (r(!O || O.type ? new J(null, n, p) : O), p.abort(), p = null);
}, a.cancelToken && a.cancelToken.subscribe(d), a.signal && (a.signal.aborted ? d() : a.signal.addEventListener("abort", d)));
const v = Yr(a.url);
if (v && x.protocols.indexOf(v) === -1) {
r(new y("Unsupported protocol " + v + ":", y.ERR_BAD_REQUEST, n));
return;
}
p.send(s || null);
});
}, en = (n, e) => {
const { length: t } = n = n ? n.filter(Boolean) : [];
if (e || t) {
let r = new AbortController(), a;
const s = function(l) {
if (!a) {
a = !0, o();
const d = l instanceof Error ? l : this.reason;
r.abort(d instanceof y ? d : new J(d instanceof Error ? d.message : d));
}
};
let i = e && setTimeout(() => {
i = null, s(new y(`timeout ${e} of ms exceeded`, y.ETIMEDOUT));
}, e);
const o = () => {
n && (i && clearTimeout(i), i = null, n.forEach((l) => {
l.unsubscribe ? l.unsubscribe(s) : l.removeEventListener("abort", s);
}), n = null);
};
n.forEach((l) => l.addEventListener("abort", s));
const { signal: c } = r;
return c.unsubscribe = () => u.asap(o), c;
}
}, tn = function* (n, e) {
let t = n.byteLength;
if (t < e) {
yield n;
return;
}
let r = 0, a;
for (; r < t; )
a = r + e, yield n.slice(r, a), r = a;
}, rn = async function* (n, e) {
for await (const t of nn(n))
yield* tn(t, e);
}, nn = async function* (n) {
if (n[Symbol.asyncIterator]) {
yield* n;
return;
}
const e = n.getReader();
try {
for (; ; ) {
const { done: t, value: r } = await e.read();
if (t)
break;
yield r;
}
} finally {
await e.cancel();
}
}, Ve = (n, e, t, r) => {
const a = rn(n, e);
let s = 0, i, o = (c) => {
i || (i = !0, r && r(c));
};
return new ReadableStream({
async pull(c) {
try {
const { done: l, value: d } = await a.next();
if (l) {
o(), c.close();
return;
}
let f = d.byteLength;
if (t) {
let m = s += f;
t(m);
}
c.enqueue(new Uint8Array(d));
} catch (l) {
throw o(l), l;
}
},
cancel(c) {
return o(c), a.return();
}
}, {
highWaterMark: 2
});
}, ve = typeof fetch == "function" && typeof Request == "function" && typeof Response == "function", St = ve && typeof ReadableStream == "function", an = ve && (typeof TextEncoder == "function" ? /* @__PURE__ */ ((n) => (e) => n.encode(e))(new TextEncoder()) : async (n) => new Uint8Array(await new Response(n).arrayBuffer())), Ot = (n, ...e) => {
try {
return !!n(...e);
} catch {
return !1;
}
}, sn = St && Ot(() => {
let n = !1;
const e = new Request(x.origin, {
body: new ReadableStream(),
method: "POST",
get duplex() {
return n = !0, "half";
}
}).headers.has("Content-Type");
return n && !e;
}), Je = 64 * 1024, Pe = St && Ot(() => u.isReadableStream(new Response("").body)), ue = {
stream: Pe && ((n) => n.body)
};
ve && ((n) => {
["text", "arrayBuffer", "blob", "formData", "stream"].forEach((e) => {
!ue[e] && (ue[e] = u.isFunction(n[e]) ? (t) => t[e]() : (t, r) => {
throw new y(`Response type '${e}' is not supported`, y.ERR_NOT_SUPPORT, r);
});
});
})(new Response());
const on = async (n) => {
if (n == null)
return 0;
if (u.isBlob(n))
return n.size;
if (u.isSpecCompliantForm(n))
return (await new Request(x.origin, {
method: "POST",
body: n
}).arrayBuffer()).byteLength;
if (u.isArrayBufferView(n) || u.isArrayBuffer(n))
return n.byteLength;
if (u.isURLSearchParams(n) && (n = n + ""), u.isString(n))
return (await an(n)).byteLength;
}, cn = async (n, e) => {
const t = u.toFiniteNumber(n.getContentLength());
return t ?? on(e);
}, ln = ve && (async (n) => {
let {
url: e,
method: t,
data: r,
signal: a,
cancelToken: s,
timeout: i,
onDownloadProgress: o,
onUploadProgress: c,
responseType: l,
headers: d,
withCredentials: f = "same-origin",
fetchOptions: m
} = Ct(n);
l = l ? (l + "").toLowerCase() : "text";
let w = en([a, s && s.toAbortSignal()], i), h;
const g = w && w.unsubscribe && (() => {
w.unsubscribe();
});
let p;
try {
if (c && sn && t !== "get" && t !== "head" && (p = await cn(d, r)) !== 0) {
let k = new Request(e, {
method: "POST",
body: r,
duplex: "half"
}), M;
if (u.isFormData(r) && (M = k.headers.get("content-type")) && d.setContentType(M), k.body) {
const [$, Y] = He(
p,
le(Ye(c))
);
r = Ve(k.body, Je, $, Y);
}
}
u.isString(f) || (f = f ? "include" : "omit");
const C = "credentials" in Request.prototype;
h = new Request(e, {
...m,
signal: w,
method: t.toUpperCase(),
headers: d.normalize().toJSON(),
body: r,
duplex: "half",
credentials: C ? f : void 0
});
let v = await fetch(h, m);
const O = Pe && (l === "stream" || l === "response");
if (Pe && (o || O && g)) {
const k = {};
["status", "statusText", "headers"].forEach((ne) => {
k[ne] = v[ne];
});
const M = u.toFiniteNumber(v.headers.get("content-length")), [$, Y] = o && He(
M,
le(Ye(o), !0)
) || [];
v = new Response(
Ve(v.body, Je, $, () => {
Y && Y(), g && g();
}),
k
);
}
l = l || "text";
let P = await ue[u.findKey(ue, l) || "text"](v, n);
return !O && g && g(), await new Promise((k, M) => {
bt(k, M, {
data: P,
headers: A.from(v.headers),
status: v.status,
statusText: v.statusText,
config: n,
request: h
});
});
} catch (C) {
throw g && g(), C && C.name === "TypeError" && /Load failed|fetch/i.test(C.message) ? Object.assign(
new y("Network Error", y.ERR_NETWORK, n, h),
{
cause: C.cause || C
}
) : y.from(C, C && C.code, n, h);
}
}), Me = {
http: Sr,
xhr: Zr,
fetch: ln
};
u.forEach(Me, (n, e) => {
if (n) {
try {
Object.defineProperty(n, "name", { value: e });
} catch {
}
Object.defineProperty(n, "adapterName", { value: e });
}
});
const Ke = (n) => `- ${n}`, un = (n) => u.isFunction(n) || n === null || n === !1, kt = {
getAdapter: (n) => {
n = u.isArray(n) ? n : [n];
const { length: e } = n;
let t, r;
const a = {};
for (let s = 0; s < e; s++) {
t = n[s];
let i;
if (r = t, !un(t) && (r = Me[(i = String(t)).toLowerCase()], r === void 0))
throw new y(`Unknown adapter '${i}'`);
if (r)
break;
a[i || "#" + s] = r;
}
if (!r) {
const s = Object.entries(a).map(
([o, c]) => `adapter ${o} ` + (c === !1 ? "is not supported by the environment" : "is not available in the build")
);
let i = e ? s.length > 1 ? `since :
` + s.map(Ke).join(`
`) : " " + Ke(s[0]) : "as no adapter specified";
throw new y(
"There is no suitable adapter to dispatch the request " + i,
"ERR_NOT_SUPPORT"
);
}
return r;
},
adapters: Me
};
function Se(n) {
if (n.cancelToken && n.cancelToken.throwIfRequested(), n.signal && n.signal.aborted)
throw new J(null, n);
}
function Xe(n) {
return Se(n), n.headers = A.from(n.headers), n.data = Ce.call(
n,
n.transformRequest
), ["post", "put", "patch"].indexOf(n.method) !== -1 && n.headers.setContentType("application/x-www-form-urlencoded", !1), kt.getAdapter(n.adapter || re.adapter)(n).then(function(r) {
return Se(n), r.data = Ce.call(
n,
n.transformResponse,
r
), r.headers = A.from(r.headers), r;
}, function(r) {
return vt(r) || (Se(n), r && r.response && (r.response.data = Ce.call(
n,
n.transformResponse,
r.response
), r.response.headers = A.from(r.response.headers))), Promise.reject(r);
});
}
const Et = "1.10.0", be = {};
["object", "boolean", "number", "function", "string", "symbol"].forEach((n, e) => {
be[n] = function(r) {
return typeof r === n || "a" + (e < 1 ? "n " : " ") + n;
};
});
const Qe = {};
be.transitional = function(e, t, r) {
function a(s, i) {
return "[Axios v" + Et + "] Transitional option '" + s + "'" + i + (r ? ". " + r : "");
}
return (s, i, o) => {
if (e === !1)
throw new y(
a(i, " has been removed" + (t ? " in " + t : "")),
y.ERR_DEPRECATED
);
return t && !Qe[i] && (Qe[i] = !0, console.warn(
a(
i,
" has been deprecated since v" + t + " and will be removed in the near future"
)
)), e ? e(s, i, o) : !0;
};
};
be.spelling = function(e) {
return (t, r) => (console.warn(`${r} is likely a misspelling of ${e}`), !0);
};
function dn(n, e, t) {
if (typeof n != "object")
throw new y("options must be an object", y.ERR_BAD_OPTION_VALUE);
const r = Object.keys(n);
let a = r.length;
for (; a-- > 0; ) {
const s = r[a], i = e[s];
if (i) {
const o = n[s], c = o === void 0 || i(o, s, n);
if (c !== !0)
throw new y("option " + s + " must be " + c, y.ERR_BAD_OPTION_VALUE);
continue;
}
if (t !== !0)
throw new y("Unknown option " + s, y.ERR_BAD_OPTION);
}
}
const ce = {
assertOptions: dn,
validators: be
}, N = ce.validators;
let z = class {
constructor(e) {
this.defaults = e || {}, this.interceptors = {
request: new je(),
response: new je()
};
}
/**
* Dispatch a request
*
* @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults)
* @param {?Object} config
*
* @returns {Promise} The Promise to be fulfilled
*/
async request(e, t) {
try {
return await this._request(e, t);
} catch (r) {
if (r instanceof Error) {
let a = {};
Error.captureStackTrace ? Error.captureStackTrace(a) : a = new Error();
const s = a.stack ? a.stack.replace(/^.+\n/, "") : "";
try {
r.stack ? s && !String(r.stack).endsWith(s.replace(/^.+\n.+\n/, "")) && (r.stack += `
` + s) : r.stack = s;
} catch {
}
}
throw r;
}
}
_request(e, t) {
typeof e == "string" ? (t = t || {}, t.url = e) : t = e || {}, t = H(this.defaults, t);
const { transitional: r, paramsSerializer: a, headers: s } = t;
r !== void 0 && ce.assertOptions(r, {
silentJSONParsing: N.transitional(N.boolean),
forcedJSONParsing: N.transitional(N.boolean),
clarifyTimeoutError: N.transitional(N.boolean)
}, !1), a != null && (u.isFunction(a) ? t.paramsSerializer = {
serialize: a
} : ce.assertOptions(a, {
encode: N.function,
serialize: N.function
}, !0)), t.allowAbsoluteUrls !== void 0 || (this.defaults.allowAbsoluteUrls !== void 0 ? t.allowAbsoluteUrls = this.defaults.allowAbsoluteUrls : t.allowAbsoluteUrls = !0), ce.assertOptions(t, {
baseUrl: N.spelling("baseURL"),
withXsrfToken: N.spelling("withXSRFToken")
}, !0), t.method = (t.method || this.defaults.method || "get").toLowerCase();
let i = s && u.merge(
s.common,
s[t.method]
);
s && u.forEach(
["delete", "get", "head", "post", "put", "patch", "common"],
(h) => {
delete s[h];
}
), t.headers = A.concat(i, s);
const o = [];
let c = !0;
this.interceptors.request.forEach(function(g) {
typeof g.runWhen == "function" && g.runWhen(t) === !1 || (c = c && g.synchronous, o.unshift(g.fulfilled, g.rejected));
});
const l = [];
this.interceptors.response.forEach(function(g) {
l.push(g.fulfilled, g.rejected);
});
let d, f = 0, m;
if (!c) {
const h = [Xe.bind(this), void 0];
for (h.unshift.apply(h, o), h.push.apply(h, l), m = h.length, d = Promise.resolve(t); f < m; )
d = d.then(h[f++], h[f++]);
return d;
}
m = o.length;
let w = t;
for (f = 0; f < m; ) {
const h = o[f++], g = o[f++];
try {
w = h(w);
} catch (p) {
g.call(this, p);
break;
}
}
try {
d = Xe.call(this, w);
} catch (h) {
return Promise.reject(h);
}
for (f = 0, m = l.length; f < m; )
d = d.then(l[f++], l[f++]);
return d;
}
getUri(e) {
e = H(this.defaults, e);
const t = Tt(e.baseURL, e.url, e.allowAbsoluteUrls);
return gt(t, e.params, e.paramsSerializer);
}
};
u.forEach(["delete", "get", "head", "options"], function(e) {
z.prototype[e] = function(t, r) {
return this.request(H(r || {}, {
method: e,
url: t,
data: (r || {}).data
}));
};
});
u.forEach(["post", "put", "patch"], function(e) {
function t(r) {
return function(s, i, o) {
return this.request(H(o || {}, {
method: e,
headers: r ? {
"Content-Type": "multipart/form-data"
} : {},
url: s,
data: i
}));
};
}
z.prototype[e] = t(), z.prototype[e + "Form"] = t(!0);
});
let fn = class xt {
constructor(e) {
if (typeof e != "function")
throw new TypeError("executor must be a function.");
let t;
this.promise = new Promise(function(s) {
t = s;
});
const r = this;
this.promise.then((a) => {
if (!r._listeners) return;
let s = r._listeners.length;
for (; s-- > 0; )
r._listeners[s](a);
r._listeners = null;
}), this.promise.then = (a) => {
let s;
const i = new Promise((o) => {
r.subscribe(o), s = o;
}).then(a);
return i.cancel = function() {
r.unsubscribe(s);
}, i;
}, e(function(s, i, o) {
r.reason || (r.reason = new J(s, i, o), t(r.reason));
});
}
/**
* Throws a `CanceledError` if cancellation has been requested.
*/
throwIfRequested() {
if (this.reason)
throw this.reason;
}
/**
* Subscribe to the cancel signal
*/
subscribe(e) {
if (this.reason) {
e(this.reason);
return;
}
this._listeners ? this._listeners.push(e) : this._listeners = [e];
}
/**
* Unsubscribe from the cancel signal
*/
unsubscribe(e) {
if (!this._listeners)
return;
const t = this._listeners.indexOf(e);
t !== -1 && this._listeners.splice(t, 1);
}
toAbortSignal() {
const e = new AbortController(), t = (r) => {
e.abort(r);
};
return this.subscribe(t), e.signal.unsubscribe = () => this.unsubscribe(t), e.signal;
}
/**
* Returns an object that contains a new `CancelToken` and a function that, when called,
* cancels the `CancelToken`.
*/
static source() {
let e;
return {
token: new xt(function(a) {
e = a;
}),
cancel: e
};
}
};
function hn(n) {
return function(t) {
return n.apply(null, t);
};
}
function mn(n) {
return u.isObject(n) && n.isAxiosError === !0;
}
const Le = {
Continue: 100,
SwitchingProtocols: 101,
Processing: 102,
EarlyHints: 103,
Ok: 200,
Created: 201,
Accepted: 202,
NonAuthoritativeInformation: 203,
NoContent: 204,
ResetContent: 205,
PartialContent: 206,
MultiStatus: 207,
AlreadyReported: 208,
ImUsed: 226,
MultipleChoices: 300,
MovedPermanently: 301,
Found: 302,
SeeOther: 303,
NotModified: 304,
UseProxy: 305,
Unused: 306,
TemporaryRedirect: 307,
PermanentRedirect: 308,
BadRequest: 400,
Unauthorized: 401,
PaymentRequired: 402,
Forbidden: 403,
NotFound: 404,
MethodNotAllowed: 405,
NotAcceptable: 406,
ProxyAuthenticationRequired: 407,
RequestTimeout: 408,
Conflict: 409,
Gone: 410,
LengthRequired: 411,
PreconditionFailed: 412,
PayloadTooLarge: 413,
UriTooLong: 414,
UnsupportedMediaType: 415,
RangeNotSatisfiable: 416,
ExpectationFailed: 417,
ImATeapot: 418,
MisdirectedRequest: 421,
UnprocessableEntity: 422,
Locked: 423,
FailedDependency: 424,
TooEarly: 425,
UpgradeRequired: 426,
PreconditionRequired: 428,
TooManyRequests: 429,
RequestHeaderFieldsTooLarge: 431,
UnavailableForLegalReasons: 451,
InternalServerError: 500,
NotImplemented: 501,
BadGateway: 502,
ServiceUnavailable: 503,
GatewayTimeout: 504,
HttpVersionNotSupported: 505,
VariantAlsoNegotiates: 506,
InsufficientStorage: 507,
LoopDetected: 508,
NotExtended: 510,
NetworkAuthenticationRequired: 511
};
Object.entries(Le).forEach(([n, e]) => {
Le[e] = n;
});
function Dt(n) {
const e = new z(n), t = at(z.prototype.request, e);
return u.extend(t, z.prototype, e, { allOwnKeys: !0 }), u.extend(t, e, null, { allOwnKeys: !0 }), t.create = function(a) {
return Dt(H(n, a));
}, t;
}
const S = Dt(re);
S.Axios = z;
S.CanceledError = J;
S.CancelToken = fn;
S.isCancel = vt;
S.VERSION = Et;
S.toFormData = ye;
S.AxiosError = y;
S.Cancel = S.CanceledError;
S.all = function(e) {
return Promise.all(e);
};
S.spread = hn;
S.isAxiosError = mn;
S.mergeConfig = H;
S.AxiosHeaders = A;
S.formToJSON = (n) => yt(u.isHTMLForm(n) ? new FormData(n) : n);
S.getAdapter = kt.getAdapter;
S.HttpStatusCode = Le;
S.default = S;
const {
Axios: qa,
AxiosError: Va,
CanceledError: Ja,
isCancel: Ka,
CancelToken: Xa,
VERSION: Qa,
all: Ga,
Cancel: Za,
isAxiosError: es,
spread: ts,
toFormData: rs,
AxiosHeaders: ns,
HttpStatusCode: as,
formToJSON: ss,
getAdapter: is,
mergeConfig: os
} = S;
class pn {
constructor(e) {
this.apiKey = e, this.name = "Last.FM", this.source = b.LASTFM, this.baseUrl = "https://ws.audioscrobbler.com/2.0/", this.chartMap = /* @__PURE__ */ new Map([
["top-tracks", { method: "chart.gettoptracks" }],
["top-albums", { method: "chart.gettopalbums" }],
["top-artists", { method: "chart.gettopartists" }],
["top-tracks-weekly", { method: "chart.gettoptracks", period: "7day" }],
["top-tracks-monthly", { method: "chart.gettoptracks", period: "1month" }],
["top-tracks-yearly", { method: "chart.gettoptracks", period: "12month" }],
["top-albums-weekly", { method: "chart.gettopalbums", period: "7day" }],
["top-albums-monthly", { method: "chart.gettopalbums", period: "1month" }],
["top-albums-yearly", { method: "chart.gettopalbums", period: "12month" }],
["top-artists-weekly", { method: "chart.gettopartists", period: "7day" }],
["top-artists-monthly", { method: "chart.gettopartists", period: "1month" }],
["top-artists-yearly", { method: "chart.gettopartists", period: "12month" }]
]), this.apiKey || console.warn("LastFM API key not provided - Last.FM features will be unavailable");
}
async getAvailableCharts() {
return Array.from(this.chartMap.keys());
}
async getChart(e, t = {}) {
var a, s, i;
if (!this.apiKey)
throw new D(
"Last.FM API key is required",
401,
b.LASTFM
);
const r = this.chartMap.get(e);
if (!r)
throw new D(
`Unknown chart type: ${e}`,
400,
b.LASTFM
);
try {
const o = {
method: r.method,
api_key: this.apiKey,
format: "json",
limit: (t.limit || 50).toString(),
page: "1"
}, c = await S.get(this.baseUrl, { params: o });
return this.transformToChartData(c.data, e, t.date || /* @__PURE__ */ new Date());
} catch (o) {
if (S.isAxiosError(o)) {
const c = ((a = o.response) == null ? void 0 : a.status) || 500, l = ((i = (s = o.response) == null ? void 0 : s.data) == null ? void 0 : i.message) || o.message;
throw new D(
`Last.FM API error: ${l}`,
c,
b.LASTFM
);
}
throw new D(
`Failed to fetch Last.FM chart: ${o}`,
500,
b.LASTFM
);
}
}
async getHistoricalData(e, t) {
const r = await this.getChart(e, { date: t.end });
return {
chartType: e,
dateRange: t,
data: [r],
source: b.LASTFM
};
}
/**
* Search for tracks by artist or title
*/
async searchTracks(e, t = 50) {
var r, a, s, i, o;
if (!this.apiKey)
throw new D(
"Last.FM API key is required",
401,
b.LASTFM
);
try {
const c = {
method: "track.search",
api_key: this.apiKey,
format: "json",
track: e,
limit: t.toString()
};
return (((a = (r = (await S.get(this.baseUrl, { params: c })).data.results) == null ? void 0 : r.trackmatches) == null ? void 0 : a.track) || []).map((f, m) => ({
rank: m + 1,
title: f.name,
artist: f.artist,
chartDate: /* @__PURE__ */ new Date(),
source: b.LASTFM,
metadata: {
listeners: f.listeners,
url: f.url,
mbid: f.mbid
}
}));
} catch (c) {
if (S.isAxiosError(c)) {
const l = ((s = c.response) == null ? void 0 : s.status) || 500, d = ((o = (i = c.response) == null ? void 0 : i.data) == null ? void 0 : o.message) || c.message;
throw new D(
`Last.FM search error: ${d}`,
l,
b.LASTFM
);
}
throw new D(
`Failed to search Last.FM: ${c}`,
500,
b.LASTFM
);
}
}
/**
* Get track info including play count and tags
*/
async getTrackInfo(e, t) {
var r, a, s;
if (!this.apiKey)
throw new D(
"Last.FM API key is required",
401,
b.LASTFM
);
try {
const i = {
method: "track.getInfo",
api_key: this.apiKey,
format: "json",
artist: e,
track: t
};
return (await S.get(this.baseUrl, { params: i })).data.track;
} catch (i) {
if (S.isAxiosError(i)) {
const o = ((r = i.response) == null ? void 0 : r.status) || 500, c = ((s = (a = i.response) == null ? void 0 : a.data) == null ? void 0 : s.message) || i.message;
throw new D(
`Last.FM track info error: ${c}`,
o,
b.LASTFM
);
}
throw new D(
`Failed to get track info from Last.FM: ${i}`,
500,
b.LASTFM
);
}
}
transformToChartData(e, t, r) {
var o, c, l;
const a = Object.keys(e)[0], s = e[a];
let i = [];
return s.track ? i = this.transformTracks(s.track, r) : s.album ? i = this.transformAlbums(s.album, r) : s.artist && (i = this.transformArtists(s.artist, r)), {
chartType: t,
date: r,
entries: i,
source: b.LASTFM,
totalEntries: i.length,
metadata: {
period: ((o = this.chartMap.get(t)) == null ? void 0 : o.period) || "overall",
total: (c = s["@attr"]) == null ? void 0 : c.total,
page: (l = s["@attr"]) == null ? void 0 : l.page
}
};
}
transformTracks(e, t) {
return e.map((r, a) => {
var s;
return {
rank: parseInt(((s = r["@attr"]) == null ? void 0 : s.rank) || r.rank || (a + 1).toString()),
title: r.name,
artist: r.artist.name,
chartDate: t,
source: b.LASTFM,
metadata: {
playcount: parseInt(r.playcount || "0"),
listeners: parseInt(r.listeners || "0"),
mbid: r.artist.mbid
}
};
});
}
transformAlbums(e, t) {
return e.map((r, a) => {
var s;
return {
rank: parseInt(((s = r["@attr"]) == null ? void 0 : s.rank) || r.rank || (a + 1).toString()),
title: r.name,
artist: r.artist.name,
album: r.name,
chartDate: t,
source: b.LASTFM,
metadata: {
playcount: parseInt(r.playcount || "0"),
mbid: r.artist.mbid
}
};
});
}
transformArtists(e, t) {
return e.map((r, a) => {
var s;
return {
rank: parseInt(((s = r["@attr"]) == null ? void 0 : s.rank) || r.rank || (a + 1).toString()),
title: r.name,
// For artists, we use name as title
artist: r.name,
chartDate: t,
source: b.LASTFM,
metadata: {
playcount: parseInt(r.playcount || "0"),
listeners: parseInt(r.listeners || "0")
}
};
});
}
}
class gn {
constructor(e) {
this.memoryCache = /* @__PURE__ */ new Map(), this.options = {
ttl: 1e3 * 60 * 60,
// 1 hour default
maxSize: 100,
persistent: !0,
...e
}, this.options.persistent && this.loadFromStorage();
}
/**
* Set cache item
*/
async set(e, t) {
try {
const r = {
data: t,
timestamp: Date.now(),
ttl: this.options.ttl
};
this.memoryCache.size >= this.options.maxSize && this.evictOldest(), this.memoryCache.set(e, r), this.options.persistent && await this.saveToStorage(e, r);
} catch (r) {
throw new xe(`Failed to set cache item: ${r}`);
}
}
/**
* Get cache item
*/
async get(e) {
try {
let t = this.memoryCache.get(e);
if (!t && this.options.persistent) {
const r = await this.loadFromStorage(e);
r && (this.memoryCache.set(e, r), t = r);
}
return t ? this.isExpired(t) ? (await this.delete(e), null) : t.data : null;
} catch (t) {
return console.warn(`Failed to get cache item: ${t}`), null;
}
}
/**
* Delete cache item
*/
async delete(e) {
this.memoryCache.delete(e), this.options.persistent && typeof localStorage < "u" && localStorage.removeItem(`brickcharts-${e}`);
}
/**
* Clear cache by pattern
*/
async clearByPattern(e) {
const t = [];
for (const r of this.memoryCache.keys())
r.includes(e) && t.push(r);
for (const r of t)
await this.delete(r);
}
/**
* Clear all cache
*/
async clear() {
if (this.memoryCache.clear(), this.options.persistent && typeof localStorage < "u") {
const e = Object.keys(localStorage).filter(
(t) => t.startsWith("brickcharts-")
);
for (const t of e)
localStorage.removeItem(t);
}
}
/**
* Get cache statistics
*/
async getStats() {
let e = 0, t = 0;
for (const r of this.memoryCache.values())
this.isExpired(r) ? e++ : t++;
return {
totalItems: this.memoryCache.size,
validItems: t,
expiredItems: e,
maxSize: this.options.maxSize,
persistent: this.options.persistent,
ttl: this.options.ttl
};
}
/**
* Check if cache item is expired
*/
isExpired(e) {
return Date.now() - e.timestamp > e.ttl;
}
/**
* Evict oldest cache item
*/
evictOldest() {
let e = null, t = Date.now();
for (const [r, a] of this.memoryCache)
a.timestamp < t && (t = a.timestamp, e = r);
e && this.memoryCache.delete(e);
}
/**
* Save to localStorage
*/
async saveToStorage(e, t) {
if (!(typeof localStorage > "u"))
try {
localStorage.setItem(`brickcharts-${e}`, JSON.stringify({
...t,
data: {
...t.data,
date: t.data.date.toISOString()
// Serialize date
}
}));
} catch (r) {
console.warn(`Failed to save to localStorage: ${r}`);
}
}
/**
* Load from localStorage
*/
async loadFromStorage(e) {
if (typeof localStorage > "u") return null;
try {
if (e) {
const t = localStorage.getItem(`brickcharts-${e}`);
if (t) {
const r = JSON.parse(t);
return {
...r,
data: {
...r.data,
date: new Date(r.data.date)
// Deserialize date
}
};
}
return null;
} else {
const t = Object.keys(localStorage).filter((r) => r.startsWith("brickcharts-"));
for (const r of t) {
const a = r.replace("brickcharts-", ""), s = await this.loadFromStorage(a);
s && !this.isExpired(s) && this.memoryCache.set(a, s);
}
}
} catch (t) {
console.warn(`Failed to load from localStorage: ${t}`);
}
return null;
}
}
class wn {
constructor(e) {
this.cache = new gn(e);
}
/**
* Cache chart data
*/
async cacheChart(e) {
try {
await this.cache.set(this.generateCacheKey(e), e);
} catch (t) {
throw new xe(`Failed to cache chart data: ${t}`);
}
}
/**
* Get cached chart data
*/
async getCachedChart(e, t, r) {
try {
const a = this.generateCacheKey({
chartType: e,
source: t,
date: r || /* @__PURE__ */ new Date()
});
return await this.cache.get(a);
} catch (a) {
return console.warn(`Failed to get cached chart: ${a}`), null;
}
}
/**
* Clear cache
*/
async clearCache(e, t) {
try {
if (e && t) {
const r = `${t}-${e}-`;
await this.cache.clearByPattern(r);
} else
await this.cache.clear();
} catch (r) {
throw new xe(`Failed to clear cache: ${r}`);
}
}
/**
* Get cache statistics
*/
async getCacheStats() {
return await this.cache.getStats();
}
/**
* Generate cache key for chart data
*/
generateCacheKey(e) {
const t = e.date.toISOString().split("T")[0];
return `${e.source}-${e.chartType}-${t}`;
}
}
function de(n) {
"@babel/helpers - typeof";
return de = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) {
return typeof e;
} : function(e) {
return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
}, de(n);
}
function _(n) {
if (n === null || n === !0 || n === !1)
return NaN;
var e = Number(n);
return isNaN(e) ? e : e < 0 ? Math.ceil(e) : Math.floor(e);
}
function E(n, e) {
if (e.length < n)
throw new TypeError(n + " argument" + (n > 1 ? "s" : "") + " required, but only " + e.length + " present");
}
function F(n) {
E(1, arguments);
var e = Object.prototype.toString.call(n);
return n instanceof Date || de(n) === "object" && e === "[object Date]" ? new Date(n.getTime()) : typeof n == "number" || e === "[object Number]" ? new Date(n) : ((typeof n == "string" || e === "[object String]") && typeof console < "u" && (console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"), console.warn(new Error().stack)), /* @__PURE__ */ new Date(NaN));
}
function yn(n, e) {
E(2, arguments);
var t = F(n).getTime(), r = _(e);
return new Date(t + r);
}
var vn = {};
function K() {
return vn;
}
function bn(n, e) {
var t, r, a, s, i, o, c, l;
E(1, arguments);
var d = K(), f = _((t = (r = (a = (s = e == null ? void 0 : e.weekStartsOn) !== null && s !== void 0 ? s : e == null || (i = e.locale) === null || i === void 0 || (o = i.options) === null || o === void 0 ? void 0 : o.weekStartsOn) !== null && a !== void 0 ? a : d.weekStartsOn) !== null && r !== void 0 ? r : (c = d.locale) === null || c === void 0 || (l = c.options) === null || l === void 0 ? void 0 : l.weekStartsOn) !== null && t !== void 0 ? t : 0);
if (!(f >= 0 && f <= 6))
throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
var m = F(n), w = m.getDay(), h = (w < f ? 7 : 0) + w - f;
return m.setDate(m.getDate() - h), m.setHours(0, 0, 0, 0), m;
}
function Tn(n) {
var e = new Date(Date.UTC(n.getFullYear(), n.getMonth(), n.getDate(), n.getHours(), n.getMinutes(), n.getSeconds(), n.getMilliseconds()));
return e.setUTCFullYear(n.getFullYear()), n.getTime() - e.getTime();
}
var Rt = 6e4, At = 36e5;
function Cn(n) {
return E(1, arguments), n instanceof Date || de(n) === "object" && Object.prototype.toString.call(n) === "[object Date]";
}
function Fe(n) {
if (E(1, arguments), !Cn(n) && typeof n != "number")
return !1;
var e = F(n);
return !isNaN(Number(e));
}
function Sn(n, e) {
var t, r, a, s, i, o, c, l;
E(1, arguments);
var d = K(), f = _((t = (r = (a = (s = e == null ? void 0 : e.weekStartsOn) !== null && s !== void 0 ? s : e == null || (i = e.locale) === null || i === void 0 || (o = i.options) === null || o === void 0 ? void 0 : o.weekStartsOn) !== null && a !== void 0 ? a : d.weekStartsOn) !== null && r !== void 0 ? r : (c = d.locale) === null || c === void 0 || (l = c.options) === null || l === void 0 ? void 0 : l.weekStartsOn) !== null && t !== void 0 ? t : 0);
if (!(f >= 0 && f <= 6))
throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
var m = F(n), w = m.getDay(), h = (w < f ? -7 : 0) + 6 - (w - f);
return m.setDate(m.getDate() + h), m.setHours(23, 59, 59, 999), m;
}
function On(n, e) {
E(2, arguments);
var t = _(e);
return yn(n, -t);
}
var kn = 864e5;
function En(n) {
E(1, arguments);
var e = F(n), t = e.getTime();
e.setUTCMonth(0, 1), e.setUTCHours(0, 0, 0, 0);
var r = e.getTime(), a = t - r;
return Math.floor(a / kn) + 1;
}
function fe(n) {
E(1, arguments);
var e = 1, t = F(n), r = t.getUTCDay(), a = (r < e ? 7 : 0) + r - e;
return t.setUTCDate(t.getUTCDate() - a), t.setUTCHours(0, 0, 0, 0), t;
}
function Pt(n) {
E(1, arguments);
var e = F(n), t = e.getUTCFullYear(), r = /* @__PURE__ */ new Date(0);
r.setUTCFullYear(t + 1, 0, 4), r.setUTCHours(0, 0, 0, 0);
var a = fe(r), s = /* @__PURE__ */ new Date(0);
s.setUTCFullYear(t, 0, 4), s.setUTCHours(0, 0, 0, 0);
var i = fe(s);
return e.getTime() >= a.getTime() ? t + 1 : e.getTime() >= i.getTime() ? t : t - 1;
}
function xn(n) {
E(1, arguments);
var e = Pt(n), t = /* @__PURE__ */ new Date(0);
t.setUTCFullYear(e, 0, 4), t.setUTCHours(0, 0, 0, 0);
var r = fe(t);
return r;
}
var Dn = 6048e5;
function Rn(n) {
E(1, arguments);
var e = F(n), t = fe(e).getTime() - xn(e).getTime();
return Math.round(t / Dn) + 1;
}
function he(n, e) {
var t, r, a, s, i, o, c, l;
E(1, arguments);
var d = K(), f = _((t = (r = (a = (s = e == null ? void 0 : e.weekStartsOn) !== null && s !== void 0 ? s : e == null || (i = e.locale) === null || i === void 0 || (o = i.options) === null || o === void 0 ? void 0 : o.weekStartsOn) !== null && a !== void 0 ? a : d.weekStartsOn) !== null && r !== void 0 ? r : (c = d.locale) === null || c === void 0 || (l = c.options) === null || l === void 0 ? void 0 : l.weekStartsOn) !== null && t !== void 0 ? t : 0);
if (!(f >= 0 && f <= 6))
throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
var m = F(n), w = m.getUTCDay(), h = (w < f ? 7 : 0) + w - f;
return m.setUTCDate(m.getUTCDate() - h), m.setUTCHours(0, 0, 0, 0), m;
}
function Mt(n, e) {
var t, r, a, s, i, o, c, l;
E(1, arguments);
var d = F(n), f = d.getUTCFullYear(), m = K(), w = _((t = (r = (a = (s = e == null ? void 0 : e.firstWeekContainsDate) !== null && s !== void 0 ? s : e == null || (i = e.locale) === null || i === void 0 || (o = i.options) === null || o === void 0 ? void 0 : o.firstWeekContainsDate) !== null && a !== void 0 ? a : m.firstWeekContainsDate) !== null && r !== void 0 ? r : (c = m.locale) === null || c === void 0 || (l = c.options) === null || l === void 0 ? void 0 : l.firstWeekContainsDate) !== null && t !== void 0 ? t : 1);
if (!(w >= 1 && w <= 7))
throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
var h = /* @__PURE__ */ new Date(0);
h.setUTCFullYear(f + 1, 0, w), h.setUTCHours(0, 0, 0, 0);
var g = he(h, e), p = /* @__PURE__ */ new Date(0);
p.setUTCFullYear(f, 0, w), p.setUTCHours(0, 0, 0, 0);
var C = he(p, e);
return d.getTime() >= g.getTime() ? f + 1 : d.getTime() >= C.getTime() ? f : f - 1;
}
function An(n, e) {
var t, r, a, s, i, o, c, l;
E(1, arguments);
var d = K(), f = _((t = (r = (a = (s = e == null ? void 0 : e.firstWeekContainsDate) !== null && s !== void 0 ? s : e == null || (i = e.locale) === null || i === void 0 || (o = i.options) === null || o === void 0 ? void 0 : o.firstWeekContainsDate) !== null && a !== void 0 ? a : d.firstWeekContainsDate) !== null && r !== void 0 ? r : (c = d.locale) === null || c === void 0 || (l = c.options) === null || l === void 0 ? void 0 : l.firstWeekContainsDate) !== null && t !== void 0 ? t : 1), m = Mt(n, e), w = /* @__PURE__ */ new Date(0);
w.setUTCFullYear(m, 0, f), w.setUTCHours(0, 0, 0, 0);
var h = he(w, e);
return h;
}
var Pn = 6048e5;
function Mn(n, e) {
E(1, arguments);
var t = F(n), r = he(t, e).getTime() - An(t, e).getTime();
return Math.round(r / Pn) + 1;
}
function T(n, e) {
for (var t = n < 0 ? "-" : "", r = Math.abs(n).toString(); r.length < e; )
r = "0" + r;
return t + r;
}
var I = {
// Year
y: function(e, t) {
var r = e.getUTCFullYear(), a = r > 0 ? r : 1 - r;
return T(t === "yy" ? a % 100 : a, t.length);
},
// Month
M: function(e, t) {
var r = e.getUTCMonth();
return t === "M" ? String(r + 1) : T(r + 1, 2);
},
// Day of the month
d: function(e, t) {
return T(e.getUTCDate(), t.length);
},
// AM or PM
a: function(e, t) {
var r = e.getUTCHours() / 12 >= 1 ? "pm" : "am";
switch (t) {
case "a":
case "aa":
return r.toUpperCase();
case "aaa":
return r;
case "aaaaa":
return r[0];
case "aaaa":
default:
return r === "am" ? "a.m." : "p.m.";
}
},
// Hour [1-12]
h: function(e, t) {
return T(e.getUTCHours() % 12 || 12, t.length);
},
// Hour [0-23]
H: function(e, t) {
return T(e.getUTCHours(), t.length);
},
// Minute
m: function(e, t) {
return T(e.getUTCMinutes(), t.length);
},
// Second
s: function(e, t) {
return T(e.getUTCSeconds(), t.length);
},
// Fraction of second
S: function(e, t) {
var r = t.length, a = e.getUTCMilliseconds(), s = Math.floor(a * Math.pow(10, r - 3));
return T(s, t.length);
}
}, q = {
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
}, Ln = {
// Era
G: function(e, t, r) {
var a = e.getUTCFullYear() > 0 ? 1 : 0;
switch (t) {
case "G":
case "GG":
case "GGG":
return r.era(a, {
width: "abbreviated"
});
case "GGGGG":
return r.era(a, {
width: "narrow"
});
case "GGGG":
default:
return r.era(a, {
width: "wide"
});
}
},
// Year
y: function(e, t, r) {
if (t === "yo") {
var a = e.getUTCFullYear(), s = a > 0 ? a : 1 - a;
return r.ordinalNumber(s, {
unit: "year"
});
}
return I.y(e, t);
},
// Local week-numbering year
Y: function(e, t, r, a) {
var s = Mt(e, a), i = s > 0 ? s : 1 - s;
if (t === "YY") {
var o = i % 100;
return T(o, 2);
}
return t === "Yo" ? r.ordinalNumber(i, {
unit: "year"
}) : T(i, t.length);
},
// ISO week-numbering year
R: function(e, t) {
var r = Pt(e);
return T(r, t.length);
},
// Extended year. This is a single number designating the year of this calendar system.
// The main difference between `y` and `u` localizers are B.C. years:
// | Year | `y` | `u` |
// |------|-----|-----|
// | AC 1 | 1 | 1 |
// | BC 1 | 1 | 0 |
// | BC 2 | 2 | -1 |
// Also `yy` always returns the last two digits of a year,
// while `uu` pads single digit years to 2 characters and returns other years unchanged.
u: function(e, t) {
var r = e.getUTCFullYear();
return T(r, t.length);
},
// Quarter
Q: function(e, t, r) {
var a = Math.ceil((e.getUTCMonth() + 1) / 3);
switch (t) {
case "Q":
return String(a);
case "QQ":
return T(a, 2);
case "Qo":
return r.ordinalNumber(a, {
unit: "quarter"
});
case "QQQ":
return r.quarter(a, {
width: "abbreviated",
context: "formatting"
});
case "QQQQQ":
return r.quarter(a, {
width: "narrow",
context: "formatting"
});
case "QQQQ":
default:
return r.quarter(a, {
width: "wide",
context: "formatting"
});
}
},
// Stand-alone quarter
q: function(e, t, r) {
var a = Math.ceil((e.getUTCMonth() + 1) / 3);
switch (t) {
case "q":
return String(a);
case "qq":
return T(a, 2);
case "qo":
return r.ordinalNumber(a, {
unit: "quarter"
});
case "qqq":
return r.quarter(a, {
width: "abbreviated",
context: "standalone"
});
case "qqqqq":
return r.quarter(a, {
width: "narrow",
context: "standalone"
});
case "qqqq":
default:
return r.quarter(a, {
width: "wide",
context: "standalone"
});
}
},
// Month
M: function(e, t, r) {
var a = e.getUTCMonth();
switch (t) {
case "M":
case "MM":
return I.M(e, t);
case "Mo":
return r.ordinalNumber(a + 1, {
unit: "month"
});
case "MMM":
return r.month(a, {
width: "abbreviated",
context: "formatting"
});
case "MMMMM":
return r.month(a, {
width: "narrow",
context: "formatting"
});
case "MMMM":
default:
return r.month(a, {
width: "wide",
context: "formatting"
});
}
},
// Stand-alone month
L: function(e, t, r) {
var a = e.getUTCMonth();
switch (t) {
case "L":
return String(a + 1);
case "LL":
return T(a + 1, 2);
case "Lo":
return r.ordinalNumber(a + 1, {
unit: "month"
});
case "LLL":
return r.month(a, {
width: "abbreviated",
context: "standalone"
});
case "LLLLL":
return r.month(a, {
width: "narrow",
context: "standalone"
});
case "LLLL":
default:
return r.month(a, {
width: "wide",
context: "standalone"
});
}
},
// Local week of year
w: function(e, t, r, a) {
var s = Mn(e, a);
return t === "wo" ? r.ordinalNumber(s, {
unit: "week"
}) : T(s, t.length);
},
// ISO week of year
I: function(e, t, r) {
var a = Rn(e);
return t === "Io" ? r.ordinalNumber(a, {
unit: "week"
}) : T(a, t.length);
},
// Day of the month
d: function(e, t, r) {
return t === "do" ? r.ordinalNumber(e.getUTCDate(), {
unit: "date"
}) : I.d(e, t);
},
// Day of year
D: function(e, t, r) {
var a = En(e);
return t === "Do" ? r.ordinalNumber(a, {
unit: "dayOfYear"
}) : T(a, t.length);
},
// Day of week
E: function(e, t, r) {
var a = e.getUTCDay();
switch (t) {
case "E":
case "EE":
case "EEE":
return r.day(a, {
width: "abbreviated",
context: "formatting"
});
case "EEEEE":
return r.day(a, {
width: "narrow",
context: "formatting"
});
case "EEEEEE":
return r.day(a, {
width: "short",
context: "formatting"
});
case "EEEE":
default:
return r.day(a, {
width: "wide",
context: "formatting"
});
}
},
// Local day of week
e: function(e, t, r, a) {
var s = e.getUTCDay(), i = (s - a.weekStartsOn + 8) % 7 || 7;
switch (t) {
case "e":
return String(i);
case "ee":
return T(i, 2);
case "eo":
return r.ordinalNumber(i, {
unit: "day"
});
case "eee":
return r.day(s, {
width: "abbreviated",
context: "formatting"
});
case "eeeee":
return r.day(s, {
width: "narrow",
context: "formatting"
});
case "eeeeee":
return r.day(s, {
width: "short",
context: "formatting"
});
case "eeee":
default:
return r.day(s, {
width: "wide",
context: "formatting"
});
}
},
// Stand-alone local day of week
c: function(e, t, r, a) {
var s = e.getUTCDay(), i = (s - a.weekStartsOn + 8) % 7 || 7;
switch (t) {
case "c":
return String(i);
case "cc":
return T(i, t.length);
case "co":
return r.ordinalNumber(i, {
unit: "day"
});
case "ccc":
return r.day(s, {
width: "abbreviated",
context: "standalone"
});
case "ccccc":
return r.day(s, {
width: "narrow",
context: "standalone"
});
case "cccccc":
return r.day(s, {
width: "short",
context: "standalone"
});
case "cccc":
default:
return r.day(s, {
width: "wide",
context: "standalone"
});
}
},
// ISO day of week
i: function(e, t, r) {
var a = e.getUTCDay(), s = a === 0 ? 7 : a;
switch (t) {
case "i":
return String(s);
case "ii":
return T(s, t.length);
case "io":
return r.ordinalNumber(s, {
unit: "day"
});
case "iii":
return r.day(a, {
width: "abbreviated",
context: "formatting"
});
case "iiiii":
return r.day(a, {
width: "narrow",
context: "formatting"
});
case "iiiiii":
return r.day(a, {
width: "short",
context: "formatting"
});
case "iiii":
default:
return r.day(a, {
width: "wide",
context: "formatting"
});
}
},
// AM or PM
a: function(e, t, r) {
var a = e.getUTCHours(), s = a / 12 >= 1 ? "pm" : "am";
switch (t) {
case "a":
case "aa":
return r.dayPeriod(s, {
width: "abbreviated",
context: "formatting"
});
case "aaa":
return r.dayPeriod(s, {
width: "abbreviated",
context: "formatting"
}).toLowerCase();
case "aaaaa":
return r.dayPeriod(s, {
width: "narrow",
context: "formatting"
});
case "aaaa":
default:
return r.dayPeriod(s, {
width: "wide",
context: "formatting"
});
}
},
// AM, PM, midnight, noon
b: function(e, t, r) {
var a = e.getUTCHours(), s;
switch (a === 12 ? s = q.noon : a === 0 ? s = q.midnight : s = a / 12 >= 1 ? "pm" : "am", t) {
case "b":
case "bb":
return r.dayPeriod(s, {
width: "abbreviated",
context: "formatting"
});
case "bbb":
return r.dayPeriod(s, {
width: "abbreviated",
context: "formatting"
}).toLowerCase();
case "bbbbb":
return r.dayPeriod(s, {
width: "narrow",
context: "formatting"
});
case "bbbb":
default:
return r.dayPeriod(s, {
width: "wide",
context: "formatting"
});
}
},
// in the morning, in the afternoon, in the evening, at night
B: function(e, t, r) {
var a = e.getUTCHours(), s;
switch (a >= 17 ? s = q.evening : a >= 12 ? s = q.afternoon : a >= 4 ? s = q.morning : s = q.night, t) {
case "B":
case "BB":
case "BBB":
return r.dayPeriod(s, {
width: "abbreviated",
context: "formatting"
});
case "BBBBB":
return r.dayPeriod(s, {
width: "narrow",
context: "formatting"
});
case "BBBB":
default:
return r.dayPeriod(s, {
width: "wide",
context: "formatting"
});
}
},
// Hour [1-12]
h: function(e, t, r) {
if (t === "ho") {
var a = e.getUTCHours() % 12;
return a === 0 && (a = 12), r.ordinalNumber(a, {
unit: "hour"
});
}
return I.h(e, t);
},
// Hour [0-23]
H: function(e, t, r) {
return t === "Ho" ? r.ordinalNumber(e.getUTCHours(), {
unit: "hour"
}) : I.H(e, t);
},
// Hour [0-11]
K: function(e, t, r) {
var a = e.getUTCHours() % 12;
return t === "Ko" ? r.ordinalNumber(a, {
unit: "hour"
}) : T(a, t.length);
},
// Hour [1-24]
k: function(e, t, r) {
var a = e.getUTCHours();
return a === 0 && (a = 24), t === "ko" ? r.ordinalNumber(a, {
unit: "hour"
}) : T(a, t.length);
},
// Minute
m: function(e, t, r) {
return t === "mo" ? r.ordinalNumber(e.getUTCMinutes(), {
unit: "minute"
}) : I.m(e, t);
},
// Second
s: function(e, t, r) {
return t === "so" ? r.ordinalNumber(e.getUTCSeconds(), {
unit: "second"
}) : I.s(e, t);
},
// Fraction of second
S: function(e, t) {
return I.S(e, t);
},
// Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
X: function(e, t, r, a) {
var s = a._originalDate || e, i = s.getTimezoneOffset();
if (i === 0)
return "Z";
switch (t) {
case "X":
return Ze(i);
case "XXXX":
case "XX":
return W(i);
case "XXXXX":
case "XXX":
default:
return W(i, ":");
}
},
// Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
x: function(e, t, r, a) {
var s = a._originalDate || e, i = s.getTimezoneOffset();
switch (t) {
case "x":
return Ze(i);
case "xxxx":
case "xx":
return W(i);
case "xxxxx":
case "xxx":
default:
return W(i, ":");
}
},
// Timezone (GMT)
O: function(e, t, r, a) {
var s = a._originalDate || e, i = s.getTimezoneOffset();
switch (t) {
case "O":
case "OO":
case "OOO":
return "GMT" + Ge(i, ":");
case "OOOO":
default:
return "GMT" + W(i, ":");
}
},
// Timezone (specific non-location)
z: function(e, t, r, a) {
var s = a._originalDate || e, i = s.getTimezoneOffset();
switch (t) {
case "z":
case "zz":
case "zzz":
return "GMT" + Ge(i, ":");
case "zzzz":
default:
return "GMT" + W(i, ":");
}
},
// Seconds timestamp
t: function(e, t, r, a) {
var s = a._originalDate || e, i = Math.floor(s.getTime() / 1e3);
return T(i, t.length);
},
// Milliseconds timestamp
T: function(e, t, r, a) {
var s = a._originalDate || e, i = s.getTime();
return T(i, t.length);
}
};
function Ge(n, e) {
var t = n > 0 ? "-" : "+", r = Math.abs(n), a = Math.floor(r / 60), s = r % 60;
if (s === 0)
return t + String(a);
var i = e;
return t + String(a) + i + T(s, 2);
}
function Ze(n, e) {
if (n % 60 === 0) {
var t = n > 0 ? "-" : "+";
return t + T(Math.abs(n) / 60, 2);
}
return W(n, e);
}
function W(n, e) {
var t = e || "", r = n > 0 ? "-" : "+", a = Math.abs(n), s = T(Math.floor(a / 60), 2), i = T(a % 60, 2);
return r + s + t + i;
}
var et = function(e, t) {
switch (e) {
case "P":
return t.date({
width: "short"
});
case "PP":
return t.date({
width: "medium"
});
case "PPP":
return t.date({
width: "long"
});
case "PPPP":
default:
return t.date({
width: "full"
});
}
}, Lt = function(e, t) {
switch (e) {
case "p":
return t.time({
width: "short"
});
case "pp":
return t.time({
width: "medium"
});
case "ppp":
return t.time({
width: "long"
});
case "pppp":
default:
return t.time({
width: "full"
});
}
}, Fn = function(e, t) {
var r = e.match(/(P+)(p+)?/) || [], a = r[1], s = r[2];
if (!s)
return et(e, t);
var i;
switch (a) {
case "P":
i = t.dateTime({
width: "short"
});
break;
case "PP":
i = t.dateTime({
width: "medium"
});
break;
case "PPP":
i = t.dateTime({
width: "long"
});
break;
case "PPPP":
default:
i = t.dateTime({
width: "full"
});
break;
}
return i.replace("{{date}}", et(a, t)).replace("{{time}}", Lt(s, t));
}, Un = {
p: Lt,
P: Fn
}, Nn = ["D", "DD"], _n = ["YY", "YYYY"];
function $n(n) {
return Nn.indexOf(n) !== -1;
}
function Bn(n) {
return _n.indexOf(n) !== -1;
}
function tt(n, e, t) {
if (n === "YYYY")
throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(e, "`) for formatting years to the input `").concat(t, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
if (n === "YY")
throw new RangeError("Use `yy` instead of `YY` (in `".concat(e, "`) for formatting years to the input `").concat(t, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
if (n === "D")
throw new RangeError("Use `d` instead of `D` (in `".concat(e, "`) for formatting days of the month to the input `").concat(t, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
if (n === "DD")
throw new RangeError("Use `dd` instead of `DD` (in `".concat(e, "`) for formatting days of the month to the input `").concat(t, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
}
var In = {
lessThanXSeconds: {
one: "less than a second",
other: "less than {{count}} seconds"
},
xSeconds: {
one: "1 second",
other: "{{count}} seconds"
},
halfAMinute: "half a minute",
lessThanXMinutes: {
one: "less than a minute",
other: "less than {{count}} minutes"
},
xMinutes: {
one: "1 minute",
other: "{{count}} minutes"
},
aboutXHours: {
one: "about 1 hour",
other: "about {{count}} hours"
},
xHours: {
one: "1 hour",
other: "{{count}} hours"
},
xDays: {
one: "1 day",
other: "{{count}} days"
},
aboutXWeeks: {
one: "about 1 week",
other: "about {{count}} weeks"
},
xWeeks: {
one: "1 week",
other: "{{count}} weeks"
},
aboutXMonths: {
one: "about 1 month",
other: "about {{count}} months"
},
xMonths: {
one: "1 month",
other: "{{count}} months"
},
aboutXYears: {
one: "about 1 year",
other: "about {{count}} years"
},
xYears: {
one: "1 year",
other: "{{count}} years"
},
overXYears: {
one: "over 1 year",
other: "over {{count}} years"
},
almostXYears: {
one: "almost 1 year",
other: "almost {{count}} years"
}
}, Wn = function(e, t, r) {
var a, s = In[e];
return typeof s == "string" ? a = s : t === 1 ? a = s.one : a = s.other.replace("{{count}}", t.toString()), r != null && r.addSuffix ? r.comparison && r.comparison > 0 ? "in " + a : a + " ago" : a;
};
function Oe(n) {
return function() {
var e = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {}, t = e.width ? String(e.width) : n.defaultWidth, r = n.formats[t] || n.formats[n.defaultWidth];
return r;
};
}
var jn = {
full: "EEEE, MMMM do, y",
long: "MMMM do, y",
medium: "MMM d, y",
short: "MM/dd/yyyy"
}, zn = {
full: "h:mm:ss a zzzz",
long: "h:mm:ss a z",
medium: "h:mm:ss a",
short: "h:mm a"
}, Hn = {
full: "{{date}} 'at' {{time}}",
long: "{{date}} 'at' {{time}}",
medium: "{{date}}, {{time}}",
short: "{{date}}, {{time}}"
}, Yn = {
date: Oe({
formats: jn,
defaultWidth: "full"
}),
time: Oe({
formats: zn,
defaultWidth: "full"
}),
dateTime: Oe({
formats: Hn,
defaultWidth: "full"
})
}, qn = {
lastWeek: "'last' eeee 'at' p",
yesterday: "'yesterday at' p",
today: "'today at' p",
tomorrow: "'tomorrow at' p",
nextWeek: "eeee 'at' p",
other: "P"
}, Vn = function(e, t, r, a) {
return qn[e];
};
function Q(n) {
return function(e, t) {
var r = t != null && t.context ? String(t.context) : "standalone", a;
if (r === "formatting" && n.formattingValues) {
var s = n.defaultFormattingWidth || n.defaultWidth, i = t != null && t.width ? String(t.width) : s;
a = n.formattingValues[i] || n.formattingValues[s];
} else {
var o = n.defaultWidth, c = t != null && t.width ? String(t.width) : n.defaultWidth;
a = n.values[c] || n.values[o];
}
var l = n.argumentCallback ? n.argumentCallback(e) : e;
return a[l];
};
}
var Jn = {
narrow: ["B", "A"],
abbreviated: ["BC", "AD"],
wide: ["Before Christ", "Anno Domini"]
}, Kn = {
narrow: ["1", "2", "3", "4"],
abbreviated: ["Q1", "Q2", "Q3", "Q4"],
wide: ["1st quarter", "2nd quarter", "3rd quarter", "4th quarter"]
}, Xn = {
narrow: ["J", "F", "M", "A", "M", "J", "J", "A", "S", "O", "N", "D"],
abbreviated: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
wide: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
}, Qn = {
narrow: ["S", "M", "T", "W", "T", "F", "S"],
short: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"],
abbreviated: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
wide: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
}, Gn = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "morning",
afternoon: "afternoon",
evening: "evening",
night: "night"
}
}, Zn = {
narrow: {
am: "a",
pm: "p",
midnight: "mi",
noon: "n",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
abbreviated: {
am: "AM",
pm: "PM",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
},
wide: {
am: "a.m.",
pm: "p.m.",
midnight: "midnight",
noon: "noon",
morning: "in the morning",
afternoon: "in the afternoon",
evening: "in the evening",
night: "at night"
}
}, ea = function(e, t) {
var r = Number(e), a = r % 100;
if (a > 20 || a < 10)
switch (a % 10) {
case 1:
return r + "st";
case 2:
return r + "nd";
case 3:
return r + "rd";
}
return r + "th";
}, ta = {
ordinalNumber: ea,
era: Q({
values: Jn,
defaultWidth: "wide"
}),
quarter: Q({
values: Kn,
defaultWidth: "wide",
argumentCallback: function(e) {
return e - 1;
}
}),
month: Q({
values: Xn,
defaultWidth: "wide"
}),
day: Q({
values: Qn,
defaultWidth: "wide"
}),
dayPeriod: Q({
values: Gn,
defaultWidth: "wide",
formattingValues: Zn,
defaultFormattingWidth: "wide"
})
};
function G(n) {
return function(e) {
var t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, r = t.width, a = r && n.matchPatterns[r] || n.matchPatterns[n.defaultMatchWidth], s = e.match(a);
if (!s)
return null;
var i = s[0], o = r && n.parsePatterns[r] || n.parsePatterns[n.defaultParseWidth], c = Array.isArray(o) ? na(o, function(f) {
return f.test(i);
}) : ra(o, function(f) {
return f.test(i);
}), l;
l = n.valueCallback ? n.valueCallback(c) : c, l = t.valueCallback ? t.valueCallback(l) : l;
var d = e.slice(i.length);
return {
value: l,
rest: d
};
};
}
function ra(n, e) {
for (var t in n)
if (n.hasOwnProperty(t) && e(n[t]))
return t;
}
function na(n, e) {
for (var t = 0; t < n.length; t++)
if (e(n[t]))
return t;
}
function aa(n) {
return function(e) {
var t = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}, r = e.match(n.matchPattern);
if (!r) return null;
var a = r[0], s = e.match(n.parsePattern);
if (!s) return null;
var i = n.valueCallback ? n.valueCallback(s[0]) : s[0];
i = t.valueCallback ? t.valueCallback(i) : i;
var o = e.slice(a.length);
return {
value: i,
rest: o
};
};
}
var sa = /^(\d+)(th|st|nd|rd)?/i, ia = /\d+/i, oa = {
narrow: /^(b|a)/i,
abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
wide: /^(before christ|before common era|anno domini|common era)/i
}, ca = {
any: [/^b/i, /^(a|c)/i]
}, la = {
narrow: /^[1234]/i,
abbreviated: /^q[1234]/i,
wide: /^[1234](th|st|nd|rd)? quarter/i
}, ua = {
any: [/1/i, /2/i, /3/i, /4/i]
}, da = {
narrow: /^[jfmasond]/i,
abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
}, fa = {
narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
}, ha = {
narrow: /^[smtwf]/i,
short: /^(su|mo|tu|we|th|fr|sa)/i,
abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
}, ma = {
narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
}, pa = {
narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
}, ga = {
any: {
am: /^a/i,
pm: /^p/i,
midnight: /^mi/i,
noon: /^no/i,
morning: /morning/i,
afternoon: /afternoon/i,
evening: /evening/i,
night: /night/i
}
}, wa = {
ordinalNumber: aa({
matchPattern: sa,
parsePattern: ia,
valueCallback: function(e) {
return parseInt(e, 10);
}
}),
era: G({
matchPatterns: oa,
defaultMatchWidth: "wide",
parsePatterns: ca,
defaultParseWidth: "any"
}),
quarter: G({
matchPatterns: la,
defaultMatchWidth: "wide",
parsePatterns: ua,
defaultParseWidth: "any",
valueCallback: function(e) {
return e + 1;
}
}),
month: G({
matchPatterns: da,
defaultMatchWidth: "wide",
parsePatterns: fa,
defaultParseWidth: "any"
}),
day: G({
matchPatterns: ha,
defaultMatchWidth: "wide",
parsePatterns: ma,
defaultParseWidth: "any"
}),
dayPeriod: G({
matchPatterns: pa,
defaultMatchWidth: "any",
parsePatterns: ga,
defaultParseWidth: "any"
})
}, ya = {
code: "en-US",
formatDistance: Wn,
formatLong: Yn,
formatRelative: Vn,
localize: ta,
match: wa,
options: {
weekStartsOn: 0,
firstWeekContainsDate: 1
}
}, va = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g, ba = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g, Ta = /^'([^]*?)'?$/, Ca = /''/g, Sa = /[a-zA-Z]/;
function Oa(n, e, t) {
var r, a, s, i, o, c, l, d, f, m, w, h, g, p;
E(2, arguments);
var C = String(e), v = K(), O = (r = (a = void 0) !== null && a !== void 0 ? a : v.locale) !== null && r !== void 0 ? r : ya, P = _((s = (i = (o = (c = void 0) !== null && c !== void 0 ? c : void 0) !== null && o !== void 0 ? o : v.firstWeekContainsDate) !== null && i !== void 0 ? i : (l = v.locale) === null || l === void 0 || (d = l.options) === null || d === void 0 ? void 0 : d.firstWeekContainsDate) !== null && s !== void 0 ? s : 1);
if (!(P >= 1 && P <= 7))
throw new RangeError("firstWeekContainsDate must be between 1 and 7 inclusively");
var k = _((f = (m = (w = (h = void 0) !== null && h !== void 0 ? h : void 0) !== null && w !== void 0 ? w : v.weekStartsOn) !== null && m !== void 0 ? m : (g = v.locale) === null || g === void 0 || (p = g.options) === null || p === void 0 ? void 0 : p.weekStartsOn) !== null && f !== void 0 ? f : 0);
if (!(k >= 0 && k <= 6))
throw new RangeError("weekStartsOn must be between 0 and 6 inclusively");
if (!O.localize)
throw new RangeError("locale must contain localize property");
if (!O.formatLong)
throw new RangeError("locale must contain formatLong property");
var M = F(n);
if (!Fe(M))
throw new RangeError("Invalid time value");
var $ = Tn(M), Y = On(M, $), ne = {
firstWeekContainsDate: P,
weekStartsOn: k,
locale: O,
_originalDate: M
}, Ut = C.match(ba).map(function(L) {
var B = L[0];
if (B === "p" || B === "P") {
var ae = Un[B];
return ae(L, O.formatLong);
}
return L;
}).join("").match(va).map(function(L) {
if (L === "''")
return "'";
var B = L[0];
if (B === "'")
return ka(L);
var ae = Ln[B];
if (ae)
return Bn(L) && tt(L, e, String(n)), $n(L) && tt(L, e, String(n)), ae(Y, L, O.localize, ne);
if (B.match(Sa))
throw new RangeError("Format string contains an unescaped latin alphabet character `" + B + "`");
return L;
}).join("");
return Ut;
}
function ka(n) {
var e = n.match(Ta);
return e ? e[1].replace(Ca, "'") : n;
}
function Ea(n, e) {
var t;
E(1, arguments);
var r = _((t = void 0) !== null && t !== void 0 ? t : 2);
if (r !== 2 && r !== 1 && r !== 0)
throw new RangeError("additionalDigits must be 0, 1 or 2");
if (!(typeof n == "string" || Object.prototype.toString.call(n) === "[object String]"))
return /* @__PURE__ */ new Date(NaN);
var a = Aa(n), s;
if (a.date) {
var i = Pa(a.date, r);
s = Ma(i.restDateString, i.year);
}
if (!s || isNaN(s.getTime()))
return /* @__PURE__ */ new Date(NaN);
var o = s.getTime(), c = 0, l;
if (a.time && (c = La(a.time), isNaN(c)))
return /* @__PURE__ */ new Date(NaN);
if (a.timezone) {
if (l = Fa(a.timezone), isNaN(l))
return /* @__PURE__ */ new Date(NaN);
} else {
var d = new Date(o + c), f = /* @__PURE__ */ new Date(0);
return f.setFullYear(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()), f.setHours(d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()), f;
}
return new Date(o + c + l);
}
var se = {
dateTimeDelimiter: /[T ]/,
timeZoneDelimiter: /[Z ]/i,
timezone: /([Z+-].*)$/
}, xa = /^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/, Da = /^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/, Ra = /^([+-])(\d{2})(?::?(\d{2}))?$/;
function Aa(n) {
var e = {}, t = n.split(se.dateTimeDelimiter), r;
if (t.length > 2)
return e;
if (/:/.test(t[0]) ? r = t[0] : (e.date = t[0], r = t[1], se.timeZoneDelimiter.test(e.date) && (e.date = n.split(se.timeZoneDelimiter)[0], r = n.substr(e.date.length, n.length))), r) {
var a = se.timezone.exec(r);
a ? (e.time = r.replace(a[1], ""), e.timezone = a[1]) : e.time = r;
}
return e;
}
function Pa(n, e) {
var t = new RegExp("^(?:(\\d{4}|[+-]\\d{" + (4 + e) + "})|(\\d{2}|[+-]\\d{" + (2 + e) + "})$)"), r = n.match(t);
if (!r) return {
year: NaN,
restDateString: ""
};
var a = r[1] ? parseInt(r[1]) : null, s = r[2] ? parseInt(r[2]) : null;
return {
year: s === null ? a : s * 100,
restDateString: n.slice((r[1] || r[2]).length)
};
}
function Ma(n, e) {
if (e === null) return /* @__PURE__ */ new Date(NaN);
var t = n.match(xa);
if (!t) return /* @__PURE__ */ new Date(NaN);
var r = !!t[4], a = Z(t[1]), s = Z(t[2]) - 1, i = Z(t[3]), o = Z(t[4]), c = Z(t[5]) - 1;
if (r)
return Ba(e, o, c) ? Ua(e, o, c) : /* @__PURE__ */ new Date(NaN);
var l = /* @__PURE__ */ new Date(0);
return !_a(e, s, i) || !$a(e, a) ? /* @__PURE__ */ new Date(NaN) : (l.setUTCFullYear(e, s, Math.max(a, i)), l);
}
function Z(n) {
return n ? parseInt(n) : 1;
}
function La(n) {
var e = n.match(Da);
if (!e) return NaN;
var t = ke(e[1]), r = ke(e[2]), a = ke(e[3]);
return Ia(t, r, a) ? t * At + r * Rt + a * 1e3 : NaN;
}
function ke(n) {
return n && parseFloat(n.replace(",", ".")) || 0;
}
function Fa(n) {
if (n === "Z") return 0;
var e = n.match(Ra);
if (!e) return 0;
var t = e[1] === "+" ? -1 : 1, r = parseInt(e[2]), a = e[3] && parseInt(e[3]) || 0;
return Wa(r, a) ? t * (r * At + a * Rt) : NaN;
}
function Ua(n, e, t) {
var r = /* @__PURE__ */ new Date(0);
r.setUTCFullYear(n, 0, 4);
var a = r.getUTCDay() || 7, s = (e - 1) * 7 + t + 1 - a;
return r.setUTCDate(r.getUTCDate() + s), r;
}
var Na = [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function Ft(n) {
return n % 400 === 0 || n % 4 === 0 && n % 100 !== 0;
}
function _a(n, e, t) {
return e >= 0 && e <= 11 && t >= 1 && t <= (Na[e] || (Ft(n) ? 29 : 28));
}
function $a(n, e) {
return e >= 1 && e <= (Ft(n) ? 366 : 365);
}
function Ba(n, e, t) {
return e >= 1 && e <= 53 && t >= 0 && t <= 6;
}
function Ia(n, e, t) {
return n === 24 ? e === 0 && t === 0 : t >= 0 && t < 60 && e >= 0 && e < 60 && n >= 0 && n < 25;
}
function Wa(n, e) {
return e >= 0 && e <= 59;
}
function cs(n, e) {
return n;
}
function ls(n) {
if (n instanceof Date)
return Fe(n) ? n : /* @__PURE__ */ new Date();
const e = Ea(n);
return Fe(e) ? e : /* @__PURE__ */ new Date();
}
function Ee(n, e = "yyyy-MM-dd") {
return Oa(n, e);
}
function ja(n, e) {
const t = [];
return n.entries.forEach((r) => {
const a = e.entries.find(
(o) => o.title === r.title && o.artist === r.artist
);
let s = "new", i = 0;
if (a) {
const o = a.rank - r.rank;
i = o, o > 0 ? s = "up" : o < 0 ? s = "down" : s = "stable";
}
t.push({
entry: r,
trend: s,
positionChange: i,
weeklyData: [{
date: r.chartDate,
position: r.rank
}]
});
}), t;
}
function za(n, e) {
const t = {
totalEntries: n.entries.length,
newEntries: 0,
droppedEntries: 0,
trends: [],
topMovers: {
climbers: [],
fallers: []
}
};
if (!e)
return t.newEntries = n.entries.length, t;
const r = ja(n, e);
t.trends = r, t.newEntries = r.filter((i) => i.trend === "new").length, t.droppedEntries = e.entries.length - (n.entries.length - t.newEntries);
const a = r.filter((i) => i.trend === "up").sort((i, o) => o.positionChange - i.positionChange).slice(0, 10), s = r.filter((i) => i.trend === "down").sort((i, o) => i.positionChange - o.positionChange).slice(0, 10);
return t.topMovers = { climbers: a, fallers: s }, t;
}
function us(n, e) {
return n.filter((t) => !(e.artist && !t.artist.toLowerCase().includes(e.artist.toLowerCase()) || e.minWeeks && t.weeksOnChart && t.weeksOnChart < e.minWeeks || e.maxWeeks && t.weeksOnChart && t.weeksOnChart > e.maxWeeks || e.peakPosition && t.peakPosition && t.peakPosition > e.peakPosition));
}
function ds(n, e = "rank", t = "asc") {
return [...n].sort((r, a) => {
let s, i;
switch (e) {
case "rank":
s = r.rank, i = a.rank;
break;
case "title":
s = r.title.toLowerCase(), i = a.title.toLowerCase();
break;
case "artist":
s = r.artist.toLowerCase(), i = a.artist.toLowerCase();
break;
case "weeks":
s = r.weeksOnChart || 0, i = a.weeksOnChart || 0;
break;
case "peakPosition":
s = r.peakPosition || 999, i = a.peakPosition || 999;
break;
default:
s = r.rank, i = a.rank;
}
return t === "desc" ? s > i ? -1 : s < i ? 1 : 0 : s < i ? -1 : s > i ? 1 : 0;
});
}
function fs(n) {
return {
start: bn(n, { weekStartsOn: 1 }),
// Monday start
end: Sn(n, { weekStartsOn: 1 })
};
}
function hs(n, e) {
let t;
return function(...a) {
const s = () => {
clearTimeout(t), n(...a);
};
clearTimeout(t), t = setTimeout(s, e);
};
}
function rt(n) {
return `${n.title}-${n.artist}`.toLowerCase().replace(/[^a-z0-9]/g, "");
}
function ms(n) {
return n && typeof n.chartType == "string" && n.date instanceof Date && Array.isArray(n.entries) && typeof n.totalEntries == "number" && n.entries.every(
(e) => typeof e.rank == "number" && typeof e.title == "string" && typeof e.artist == "string"
);
}
class ps {
constructor(e = {}) {
this.clients = /* @__PURE__ */ new Map(), this.config = {
enableCache: !0,
defaultSource: b.BILLBOARD,
...e
}, this.dataManager = new wn(e.cacheOptions), this.initializeClients();
}
/**
* Initialize all available chart clients
*/
initializeClients() {
var e;
this.clients.set(b.BILLBOARD, new _t()), (e = this.config.apiKeys) != null && e.lastfm && this.clients.set(b.LASTFM, new pn(this.config.apiKeys.lastfm));
}
/**
* Get a chart from the specified source
*/
async getChart(e, t = this.config.defaultSource, r = {}) {
const a = this.getClient(t);
if (this.config.enableCache && r.useCache !== !1 && !r.forceRefresh) {
const i = await this.dataManager.getCachedChart(e, t, r.date);
if (i)
return i;
}
const s = await a.getChart(e, r);
return this.config.enableCache && await this.dataManager.cacheChart(s), s;
}
/**
* Get historical chart data
*/
async getHistoricalData(e, t, r = this.config.defaultSource) {
return await this.getClient(r).getHistoricalData(e, t);
}
/**
* Get available charts from a source
*/
async getAvailableCharts(e = this.config.defaultSource) {
return await this.getClient(e).getAvailableCharts();
}
/**
* Compare charts between different dates or sources
*/
async compareCharts(e, t, r, a = this.config.defaultSource) {
const [s, i] = await Promise.all([
this.getChart(e, a, { date: r }),
this.getChart(e, a, { date: t })
]);
return za(s, i);
}
/**
* Get trending analysis for a chart
*/
async getTrends(e, t = this.config.defaultSource, r = 1) {
const a = /* @__PURE__ */ new Date(), s = /* @__PURE__ */ new Date();
return s.setDate(a.getDate() - r * 7), await this.compareCharts(e, s, a, t);
}
/**
* Search for a specific track across charts
*/
async searchTrack(e, t, r, a = this.config.defaultSource) {
const s = this.getClient(a), i = r ? [r] : await s.getAvailableCharts(), o = [];
for (const c of i)
try {
const l = await this.getChart(c, a);
l.entries.find(
(f) => f.title.toLowerCase().includes(e.toLowerCase()) && f.artist.toLowerCase().includes(t.toLowerCase())
) && o.push(l);
} catch (l) {
console.warn(`Failed to search chart ${c}: ${l}`);
}
return o;
}
/**
* Get chart data for multiple sources and merge
*/
async getMultiSourceChart(e, t, r = {}) {
const a = /* @__PURE__ */ new Map(), s = t.map(async (i) => {
try {
const o = await this.getChart(e, i, r);
a.set(i, o);
} catch (o) {
console.warn(`Failed to fetch ${e} from ${i}: ${o}`);
}
});
return await Promise.all(s), a;
}
/**
* Clear cache for specific chart or all
*/
async clearCache(e, t) {
await this.dataManager.clearCache(e, t);
}
/**
* Get cache statistics
*/
async getCacheStats() {
return await this.dataManager.getCacheStats();
}
/**
* Add a custom chart client
*/
addClient(e, t) {
this.clients.set(e, t);
}
/**
* Remove a chart client
*/
removeClient(e) {
this.clients.delete(e);
}
/**
* Get available sources
*/
getAvailableSources() {
return Array.from(this.clients.keys());
}
/**
* Update configuration
*/
updateConfig(e) {
this.config = { ...this.config, ...e }, e.apiKeys && this.initializeClients();
}
/**
* Get client for a specific source
*/
getClient(e) {
const t = this.clients.get(e);
if (!t)
throw new Error(`No client available for source: ${e}`);
return t;
}
/**
* Health check for all clients
*/
async healthCheck() {
const e = /* @__PURE__ */ new Map();
for (const [t, r] of this.clients)
try {
await r.getAvailableCharts(), e.set(t, !0);
} catch {
e.set(t, !1);
}
return e;
}
}
class gs {
constructor() {
this.searchIndex = /* @__PURE__ */ new Map(), this.chartDataCache = /* @__PURE__ */ new Map();
}
/**
* Index chart data for faster searching
*/
indexChartData(e) {
e.forEach((t) => {
const r = `${t.source}-${t.chartType}-${t.date.toISOString()}`;
this.chartDataCache.set(r, t), t.entries.forEach((a) => {
this.addToIndex("title", a.title.toLowerCase(), a), this.addToIndex("artist", a.artist.toLowerCase(), a), a.album && this.addToIndex("album", a.album.toLowerCase(), a), this.addToIndex("full", `${a.title} ${a.artist}`.toLowerCase(), a);
});
});
}
/**
* Enhanced search with fuzzy matching and ranking
*/
search(e) {
const t = Date.now(), r = [], a = /* @__PURE__ */ new Set();
let s = 0, i = 0, o = 0;
this.getRelevantCharts(e).forEach((m) => {
a.add(`${m.source}-${m.chartType}`), m.entries.forEach((w) => {
const h = this.scoreEntry(w, m, e);
if (h && h.score > 0) {
r.push(h);
const g = h.matches.some((v) => v.matchType === "exact"), p = h.matches.some((v) => v.matchType === "partial"), C = h.matches.some((v) => v.matchType === "fuzzy");
g ? s++ : p ? i++ : C && o++;
}
});
}), r.sort((m, w) => w.score - m.score);
const l = e.limit ? r.slice(0, e.limit) : r, d = Date.now() - t, f = {
totalResults: l.length,
searchTime: d,
chartsSearched: a.size,
exactMatches: s,
partialMatches: i,
fuzzyMatches: o
};
return { results: l, stats: f };
}
/**
* Quick search for autocomplete
*/
quickSearch(e, t = "title", r = 10) {
const a = /* @__PURE__ */ new Set(), s = e.toLowerCase();
for (const [i, o] of this.searchIndex)
if (i.startsWith(`${t}:`) && i.includes(s) && o.forEach((c) => {
const l = t === "title" ? c.title : t === "artist" ? c.artist : c.album || "";
l.toLowerCase().includes(s) && a.add(l);
}), a.size >= r) break;
return Array.from(a).slice(0, r);
}
/**
* Search for similar entries
*/
findSimilar(e, t = 10) {
const r = {
artist: e.artist,
fuzzy: !0,
limit: t + 1
// +1 to exclude the original entry
}, { results: a } = this.search(r);
return a.filter(
(s) => rt(s.entry) !== rt(e)
).slice(0, t);
}
/**
* Get trending searches (placeholder for future implementation)
*/
getTrendingSearches() {
return [
"Taylor Swift",
"Drake",
"Morgan Wallen",
"Bad Bunny",
"Olivia Rodrigo"
];
}
/**
* Clear search index
*/
clearIndex() {
this.searchIndex.clear(), this.chartDataCache.clear();
}
/**
* Add entry to search index
*/
addToIndex(e, t, r) {
const a = `${e}:${t}`;
this.searchIndex.has(a) || this.searchIndex.set(a, []), this.searchIndex.get(a).push(r);
}
/**
* Get charts relevant to search query
*/
getRelevantCharts(e) {
const t = [];
for (const [, r] of this.chartDataCache)
e.source && r.source !== e.source || e.chartType && r.chartType !== e.chartType || e.dateRange && (r.date < e.dateRange.start || r.date > e.dateRange.end) || t.push(r);
return t;
}
/**
* Score an entry against search query
*/
scoreEntry(e, t, r) {
let a = 0;
const s = [];
if (r.rankRange && (e.rank < r.rankRange.min || e.rank > r.rankRange.max) || r.weeksRange && e.weeksOnChart && (e.weeksOnChart < r.weeksRange.min || e.weeksOnChart > r.weeksRange.max) || r.peakRange && e.peakPosition && (e.peakPosition < r.peakRange.min || e.peakPosition > r.peakRange.max) || r.newEntriesOnly && e.lastWeek)
return null;
if (r.title) {
const o = this.matchText(e.title, r.title, r.fuzzy);
if (o)
a += o.confidence * 3, s.push({ field: "title", value: e.title, ...o });
else if (!r.fuzzy)
return null;
}
if (r.artist) {
const o = this.matchText(e.artist, r.artist, r.fuzzy);
if (o)
a += o.confidence * 2, s.push({ field: "artist", value: e.artist, ...o });
else if (!r.fuzzy && !r.title)
return null;
}
if (r.album && e.album) {
const o = this.matchText(e.album, r.album, r.fuzzy);
o && (a += o.confidence * 1, s.push({ field: "album", value: e.album, ...o }));
}
a += (101 - e.rank) / 100;
const i = ((/* @__PURE__ */ new Date()).getTime() - t.date.getTime()) / (1e3 * 60 * 60 * 24);
return a += Math.max(0, (30 - i) / 30), a === 0 && s.length === 0 ? null : {
entry: e,
chartData: t,
score: a,
matches: s
};
}
/**
* Match text with different strategies
*/
matchText(e, t, r = !1) {
const a = e.toLowerCase(), s = t.toLowerCase();
if (a === s)
return { matchType: "exact", confidence: 1 };
if (a.includes(s))
return { matchType: "partial", confidence: s.length / a.length };
if (r) {
const i = this.calculateSimilarity(a, s);
if (i > 0.6)
return { matchType: "fuzzy", confidence: i };
}
return null;
}
/**
* Calculate string similarity (Levenshtein distance based)
*/
calculateSimilarity(e, t) {
const r = [];
for (let i = 0; i <= t.length; i++)
r[i] = [i];
for (let i = 0; i <= e.length; i++)
r[0][i] = i;
for (let i = 1; i <= t.length; i++)
for (let o = 1; o <= e.length; o++)
t.charAt(i - 1) === e.charAt(o - 1) ? r[i][o] = r[i - 1][o - 1] : r[i][o] = Math.min(
r[i - 1][o - 1] + 1,
r[i][o - 1] + 1,
r[i - 1][o] + 1
);
const a = r[t.length][e.length], s = Math.max(e.length, t.length);
return s === 0 ? 1 : (s - a) / s;
}
}
class ws {
/**
* Export chart data in specified format
*/
async exportChartData(e, t) {
try {
const r = t.filename || this.generateFilename(e, t.format);
switch (t.format) {
case "csv":
return await this.exportToCsv(e, r, t);
case "json":
return await this.exportToJson(e, r, t);
case "xlsx":
return await this.exportToExcel(e, r, t);
case "png":
case "svg":
return await this.exportToImage(e, r, t);
case "pdf":
return await this.exportToPdf(e, r, t);
default:
throw new Error(`Unsupported export format: ${t.format}`);
}
} catch (r) {
return {
success: !1,
filename: t.filename || "export",
error: r instanceof Error ? r.message : "Unknown export error"
};
}
}
/**
* Export trends data
*/
async exportTrends(e, t) {
var a;
const r = {
chartType: "trends",
date: /* @__PURE__ */ new Date(),
entries: e.map((s) => s.entry),
source: ((a = e[0]) == null ? void 0 : a.entry.source) || "unknown",
totalEntries: e.length,
metadata: {
exportType: "trends",
trendsData: e.map((s) => ({
trend: s.trend,
positionChange: s.positionChange
}))
}
};
return await this.exportChartData(r, t);
}
/**
* Export analytics data
*/
async exportAnalytics(e, t) {
if (t.format === "json") {
const a = JSON.stringify(e, null, 2), s = new Blob([a], { type: "application/json" }), i = URL.createObjectURL(s);
return {
success: !0,
data: e,
blob: s,
url: i,
filename: t.filename || "analytics.json",
size: s.size
};
}
const r = {
chartType: "analytics",
date: /* @__PURE__ */ new Date(),
entries: e.trends.map((a) => a.entry),
source: "analytics",
totalEntries: e.totalEntries,
metadata: {
exportType: "analytics",
analytics: e
}
};
return await this.exportChartData(r, t);
}
/**
* Generate automatic filename
*/
generateFilename(e, t) {
const r = Ee(/* @__PURE__ */ new Date(), "yyyy-MM-dd");
if (Array.isArray(e)) {
const a = [...new Set(e.map((i) => i.chartType))];
return `${a.length === 1 ? a[0] : "multiple-charts"}-${r}.${t}`;
} else
return `${e.chartType}-${r}.${t}`;
}
/**
* Export to CSV format
*/
async exportToCsv(e, t, r) {
const a = Array.isArray(e) ? e : [e], s = [], i = [
"Chart Type",
"Date",
"Rank",
"Title",
"Artist",
"Album",
"Last Week",
"Peak Position",
"Weeks on Chart",
"Source"
];
r.includeMetadata && i.push("Cover URL", "Metadata"), s.push(i.join(",")), a.forEach((d) => {
d.entries.forEach((f) => {
var w, h, g, p;
const m = [
this.escapeCsvValue(d.chartType),
this.escapeCsvValue(Ee(d.date, r.dateFormat || "yyyy-MM-dd")),
f.rank.toString(),
this.escapeCsvValue(f.title),
this.escapeCsvValue(f.artist),
this.escapeCsvValue(f.album || ""),
((w = f.lastWeek) == null ? void 0 : w.toString()) || "",
((h = f.peakPosition) == null ? void 0 : h.toString()) || "",
((g = f.weeksOnChart) == null ? void 0 : g.toString()) || "",
this.escapeCsvValue(f.source)
];
r.includeMetadata && m.push(
this.escapeCsvValue(((p = f.metadata) == null ? void 0 : p.cover) || ""),
this.escapeCsvValue(JSON.stringify(f.metadata || {}))
), s.push(m.join(","));
});
});
const o = s.join(`
`), c = new Blob([o], { type: "text/csv;charset=utf-8;" }), l = URL.createObjectURL(c);
return {
success: !0,
data: o,
blob: c,
url: l,
filename: t,
size: c.size
};
}
/**
* Export to JSON format
*/
async exportToJson(e, t, r) {
const a = {
exportDate: (/* @__PURE__ */ new Date()).toISOString(),
format: "json",
data: Array.isArray(e) ? e : [e],
metadata: r.includeMetadata ? {
totalCharts: Array.isArray(e) ? e.length : 1,
totalEntries: Array.isArray(e) ? e.reduce((c, l) => c + l.entries.length, 0) : e.entries.length,
sources: Array.isArray(e) ? [...new Set(e.map((c) => c.source))] : [e.source],
chartTypes: Array.isArray(e) ? [...new Set(e.map((c) => c.chartType))] : [e.chartType]
} : void 0
}, s = JSON.stringify(a, null, 2), i = new Blob([s], { type: "application/json" }), o = URL.createObjectURL(i);
return {
success: !0,
data: a,
blob: i,
url: o,
filename: t,
size: i.size
};
}
/**
* Export to Excel format (placeholder)
*/
async exportToExcel(e, t, r) {
const a = await this.exportToCsv(e, t.replace(".xlsx", ".csv"), r);
return {
...a,
filename: t.replace(".xlsx", ".csv"),
error: a.success ? "Exported as CSV (Excel compatible)" : a.error
};
}
/**
* Export to image format (PNG/SVG)
*/
async exportToImage(e, t, r) {
const a = r.imageOptions || {}, s = a.width || 800, i = a.height || 600, o = this.generateSvgChart(e, s, i), c = new Blob([o], { type: "image/svg+xml" }), l = URL.createObjectURL(c);
return {
success: !0,
data: o,
blob: c,
url: l,
filename: t,
size: c.size
};
}
/**
* Export to PDF format (placeholder)
*/
async exportToPdf(e, t, r) {
return {
success: !1,
filename: t,
error: "PDF export not yet implemented. Try CSV or JSON formats."
};
}
/**
* Generate a simple SVG chart representation
*/
generateSvgChart(e, t, r) {
const a = Array.isArray(e) ? e[0] : e, s = a.entries.slice(0, 20), i = (t - 100) / s.length, o = Math.max(...s.map((l) => l.rank));
let c = `<svg width="${t}" height="${r}" xmlns="http://www.w3.org/2000/svg">`;
return c += `<rect width="${t}" height="${r}" fill="white"/>`, c += `<text x="10" y="30" font-family="Arial" font-size="20" font-weight="bold">${a.chartType}</text>`, c += `<text x="10" y="50" font-family="Arial" font-size="14" fill="gray">${Ee(a.date)}</text>`, s.forEach((l, d) => {
const f = 50 + d * i, m = (r - 150) * (1 - l.rank / o), w = r - 100 - m;
c += `<rect x="${f}" y="${w}" width="${i - 2}" height="${m}" fill="hsl(${d * 20}, 70%, 50%)" opacity="0.8"/>`, c += `<text x="${f + i / 2}" y="${r - 80}" font-family="Arial" font-size="10" text-anchor="middle">#${l.rank}</text>`, c += `<text x="${f + i / 2}" y="${r - 65}" font-family="Arial" font-size="8" text-anchor="middle">${l.title.slice(0, 15)}...</text>`;
}), c += "</svg>", c;
}
/**
* Escape CSV values
*/
escapeCsvValue(e) {
return e.includes(",") || e.includes('"') || e.includes(`
`) ? `"${e.replace(/"/g, '""')}"` : e;
}
/**
* Download helper for browser environments
*/
static downloadBlob(e, t) {
if (typeof window < "u") {
const r = URL.createObjectURL(e), a = document.createElement("a");
a.href = r, a.download = t, document.body.appendChild(a), a.click(), document.body.removeChild(a), URL.revokeObjectURL(r);
}
}
/**
* Get supported formats
*/
static getSupportedFormats() {
return ["csv", "json", "xlsx", "png", "svg"];
}
/**
* Validate export options
*/
static validateOptions(e) {
var r, a;
const t = [];
return this.getSupportedFormats().includes(e.format) || t.push(`Unsupported format: ${e.format}`), e.filename && !/^[a-zA-Z0-9_-]+\.[a-zA-Z0-9]+$/.test(e.filename) && t.push("Invalid filename format"), (r = e.imageOptions) != null && r.width && e.imageOptions.width < 100 && t.push("Image width must be at least 100px"), (a = e.imageOptions) != null && a.height && e.imageOptions.height < 100 && t.push("Image height must be at least 100px"), {
valid: t.length === 0,
errors: t
};
}
}
export {
D as APIError,
_t as BillboardClient,
ps as BrickCharts,
nt as BrickChartsError,
xe as CacheError,
gn as ChartCache,
wn as ChartDataManager,
b as ChartSource,
ws as ExportManager,
pn as LastFMClient,
gs as SearchEngine,
ja as calculateTrends,
rt as createEntryHash,
hs as debounce,
us as filterChartEntries,
Ee as formatDate,
za as generateChartAnalytics,
fs as getChartWeek,
cs as normalizeChartData,
ls as parseDate,
ds as sortChartEntries,
ms as validateChartData
};