From da0462816a77bbd4b6ff0f45600d20853bca55b2 Mon Sep 17 00:00:00 2001 From: Nathaniel Lin Date: Sat, 24 Jun 2023 21:19:57 +0800 Subject: [PATCH] update in repo versions --- dist/package.json | 10 +++--- dist/tsdav.cjs | 90 +++++++++++++++++++++++++++------------------- dist/tsdav.cjs.js | 90 +++++++++++++++++++++++++++------------------- dist/tsdav.d.ts | 30 +++++++++++----- dist/tsdav.esm.js | 90 +++++++++++++++++++++++++++------------------- dist/tsdav.js | 90 +++++++++++++++++++++++++++------------------- dist/tsdav.min.cjs | 2 +- dist/tsdav.min.js | 4 +-- dist/tsdav.min.mjs | 2 +- dist/tsdav.mjs | 90 +++++++++++++++++++++++++++------------------- 10 files changed, 301 insertions(+), 197 deletions(-) diff --git a/dist/package.json b/dist/package.json index ff20e3b..78c7115 100644 --- a/dist/package.json +++ b/dist/package.json @@ -1,6 +1,6 @@ { "name": "tsdav", - "version": "2.0.4", + "version": "2.0.5", "description": "WebDAV, CALDAV, and CARDDAV client for Nodejs and the Browser", "keywords": [ "dav", @@ -54,18 +54,18 @@ "xml-js": "1.6.11" }, "devDependencies": { - "@rollup/plugin-commonjs": "25.0.1", + "@rollup/plugin-commonjs": "25.0.2", "@rollup/plugin-node-resolve": "15.1.0", "@rollup/plugin-typescript": "11.1.1", "@types/base-64": "1.0.0", "@types/debug": "4.1.8", "@types/jest": "29.5.2", "@types/node": "20.3.1", - "@typescript-eslint/eslint-plugin": "5.59.11", - "@typescript-eslint/parser": "5.59.11", + "@typescript-eslint/eslint-plugin": "5.60.0", + "@typescript-eslint/parser": "5.60.0", "copyfiles": "2.4.1", "cross-env": "7.0.3", - "dotenv": "16.3.0", + "dotenv": "16.3.1", "eslint": "8.43.0", "eslint-config-airbnb": "19.0.4", "eslint-config-airbnb-typescript": "17.0.0", diff --git a/dist/tsdav.cjs b/dist/tsdav.cjs index 322e62a..34f4add 100644 --- a/dist/tsdav.cjs +++ b/dist/tsdav.cjs @@ -131,10 +131,19 @@ const cleanupFalsy = (obj) => Object.entries(obj).reduce((prev, [key, value]) => return Object.assign(Object.assign({}, prev), { [key]: value }); return prev; }, {}); +const conditionalParam = (key, param) => { + if (param) { + return { + [key]: param, + }; + } + return {}; +}; var requestHelpers = /*#__PURE__*/Object.freeze({ __proto__: null, cleanupFalsy: cleanupFalsy, + conditionalParam: conditionalParam, getDAVAttribute: getDAVAttribute, urlContains: urlContains, urlEquals: urlEquals @@ -744,13 +753,7 @@ const calendarMultiGet = (params) => __awaiter(void 0, void 0, void 0, function* return collectionQuery({ url, body: { - 'calendar-multiget': { - _attributes: getDAVAttribute([exports.DAVNamespace.DAV, exports.DAVNamespace.CALDAV]), - [`${exports.DAVNamespaceShort.DAV}:prop`]: props, - [`${exports.DAVNamespaceShort.DAV}:href`]: objectUrls, - filter: filters, - timezone, - }, + 'calendar-multiget': Object.assign(Object.assign({ _attributes: getDAVAttribute([exports.DAVNamespace.DAV, exports.DAVNamespace.CALDAV]), [`${exports.DAVNamespaceShort.DAV}:prop`]: props, [`${exports.DAVNamespaceShort.DAV}:href`]: objectUrls }, conditionalParam('filter', filters)), { timezone }), }, defaultNamespace: exports.DAVNamespaceShort.CALDAV, depth, @@ -781,7 +784,7 @@ const makeCalendar = (params) => __awaiter(void 0, void 0, void 0, function* () }); }); const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { headers, account, props: customProps } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -815,23 +818,13 @@ const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* ( return components.some((c) => Object.values(ICALObjects).includes(c)); }) .map((rs) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; // debug(`Found calendar ${rs.props?.displayname}`); const description = (_a = rs.props) === null || _a === void 0 ? void 0 : _a.calendarDescription; const timezone = (_b = rs.props) === null || _b === void 0 ? void 0 : _b.calendarTimezone; - return { - description: typeof description === 'string' ? description : '', - timezone: typeof timezone === 'string' ? timezone : '', - url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, - ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, - calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, - displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, - components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) + return Object.assign({ description: typeof description === 'string' ? description : '', timezone: typeof timezone === 'string' ? timezone : '', url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) ? (_l = rs.props) === null || _l === void 0 ? void 0 : _l.supportedCalendarComponentSet.comp.map((sc) => sc._attributes.name) - : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], - resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), - syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken, - }; + : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken }, conditionalParam('projectedProps', Object.fromEntries(Object.entries((_q = rs.props) !== null && _q !== void 0 ? _q : {}).filter(([key]) => projectedProps === null || projectedProps === void 0 ? void 0 : projectedProps[key])))); }) .map((cal) => __awaiter(void 0, void 0, void 0, function* () { return (Object.assign(Object.assign({}, cal), { reports: yield supportedReportSet({ collection: cal, headers }) })); @@ -1334,14 +1327,27 @@ var authHelpers = /*#__PURE__*/Object.freeze({ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types const createDAVClient = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { serverUrl, credentials, authMethod, defaultAccountType } = params; - const authHeaders = - // eslint-disable-next-line no-nested-ternary - authMethod === 'Basic' - ? getBasicAuthHeaders(credentials) - : authMethod === 'Oauth' - ? (yield getOauthHeaders(credentials)).headers - : {}; + var _a; + const { serverUrl, credentials, authMethod, defaultAccountType, authFunction } = params; + let authHeaders = {}; + switch (authMethod) { + case 'Basic': + authHeaders = getBasicAuthHeaders(credentials); + break; + case 'Oauth': + authHeaders = (yield getOauthHeaders(credentials)).headers; + break; + case 'Digest': + authHeaders = { + Authorization: `Digest ${credentials.digestString}`, + }; + break; + case 'Custom': + authHeaders = (_a = (yield (authFunction === null || authFunction === void 0 ? void 0 : authFunction(credentials)))) !== null && _a !== void 0 ? _a : {}; + break; + default: + throw new Error('Invalid auth method'); + } const defaultAccount = defaultAccountType ? yield createAccount({ account: { serverUrl, credentials, accountType: defaultAccountType }, @@ -1459,14 +1465,26 @@ class DAVClient { this.accountType = (_b = params.defaultAccountType) !== null && _b !== void 0 ? _b : 'caldav'; } login() { + var _a; return __awaiter(this, void 0, void 0, function* () { - this.authHeaders = - // eslint-disable-next-line no-nested-ternary - this.authMethod === 'Basic' - ? getBasicAuthHeaders(this.credentials) - : this.authMethod === 'Oauth' - ? (yield getOauthHeaders(this.credentials)).headers - : {}; + switch (this.authMethod) { + case 'Basic': + this.authHeaders = getBasicAuthHeaders(this.credentials); + break; + case 'Oauth': + this.authHeaders = (yield getOauthHeaders(this.credentials)).headers; + break; + case 'Digest': + this.authHeaders = { + Authorization: `Digest ${this.credentials.digestString}`, + }; + break; + case 'Custom': + this.authHeaders = yield ((_a = this.authFunction) === null || _a === void 0 ? void 0 : _a.call(this, this.credentials)); + break; + default: + throw new Error('Invalid auth method'); + } this.account = this.accountType ? yield createAccount({ account: { diff --git a/dist/tsdav.cjs.js b/dist/tsdav.cjs.js index 322e62a..34f4add 100644 --- a/dist/tsdav.cjs.js +++ b/dist/tsdav.cjs.js @@ -131,10 +131,19 @@ const cleanupFalsy = (obj) => Object.entries(obj).reduce((prev, [key, value]) => return Object.assign(Object.assign({}, prev), { [key]: value }); return prev; }, {}); +const conditionalParam = (key, param) => { + if (param) { + return { + [key]: param, + }; + } + return {}; +}; var requestHelpers = /*#__PURE__*/Object.freeze({ __proto__: null, cleanupFalsy: cleanupFalsy, + conditionalParam: conditionalParam, getDAVAttribute: getDAVAttribute, urlContains: urlContains, urlEquals: urlEquals @@ -744,13 +753,7 @@ const calendarMultiGet = (params) => __awaiter(void 0, void 0, void 0, function* return collectionQuery({ url, body: { - 'calendar-multiget': { - _attributes: getDAVAttribute([exports.DAVNamespace.DAV, exports.DAVNamespace.CALDAV]), - [`${exports.DAVNamespaceShort.DAV}:prop`]: props, - [`${exports.DAVNamespaceShort.DAV}:href`]: objectUrls, - filter: filters, - timezone, - }, + 'calendar-multiget': Object.assign(Object.assign({ _attributes: getDAVAttribute([exports.DAVNamespace.DAV, exports.DAVNamespace.CALDAV]), [`${exports.DAVNamespaceShort.DAV}:prop`]: props, [`${exports.DAVNamespaceShort.DAV}:href`]: objectUrls }, conditionalParam('filter', filters)), { timezone }), }, defaultNamespace: exports.DAVNamespaceShort.CALDAV, depth, @@ -781,7 +784,7 @@ const makeCalendar = (params) => __awaiter(void 0, void 0, void 0, function* () }); }); const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { headers, account, props: customProps } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -815,23 +818,13 @@ const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* ( return components.some((c) => Object.values(ICALObjects).includes(c)); }) .map((rs) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; // debug(`Found calendar ${rs.props?.displayname}`); const description = (_a = rs.props) === null || _a === void 0 ? void 0 : _a.calendarDescription; const timezone = (_b = rs.props) === null || _b === void 0 ? void 0 : _b.calendarTimezone; - return { - description: typeof description === 'string' ? description : '', - timezone: typeof timezone === 'string' ? timezone : '', - url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, - ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, - calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, - displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, - components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) + return Object.assign({ description: typeof description === 'string' ? description : '', timezone: typeof timezone === 'string' ? timezone : '', url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) ? (_l = rs.props) === null || _l === void 0 ? void 0 : _l.supportedCalendarComponentSet.comp.map((sc) => sc._attributes.name) - : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], - resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), - syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken, - }; + : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken }, conditionalParam('projectedProps', Object.fromEntries(Object.entries((_q = rs.props) !== null && _q !== void 0 ? _q : {}).filter(([key]) => projectedProps === null || projectedProps === void 0 ? void 0 : projectedProps[key])))); }) .map((cal) => __awaiter(void 0, void 0, void 0, function* () { return (Object.assign(Object.assign({}, cal), { reports: yield supportedReportSet({ collection: cal, headers }) })); @@ -1334,14 +1327,27 @@ var authHelpers = /*#__PURE__*/Object.freeze({ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types const createDAVClient = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { serverUrl, credentials, authMethod, defaultAccountType } = params; - const authHeaders = - // eslint-disable-next-line no-nested-ternary - authMethod === 'Basic' - ? getBasicAuthHeaders(credentials) - : authMethod === 'Oauth' - ? (yield getOauthHeaders(credentials)).headers - : {}; + var _a; + const { serverUrl, credentials, authMethod, defaultAccountType, authFunction } = params; + let authHeaders = {}; + switch (authMethod) { + case 'Basic': + authHeaders = getBasicAuthHeaders(credentials); + break; + case 'Oauth': + authHeaders = (yield getOauthHeaders(credentials)).headers; + break; + case 'Digest': + authHeaders = { + Authorization: `Digest ${credentials.digestString}`, + }; + break; + case 'Custom': + authHeaders = (_a = (yield (authFunction === null || authFunction === void 0 ? void 0 : authFunction(credentials)))) !== null && _a !== void 0 ? _a : {}; + break; + default: + throw new Error('Invalid auth method'); + } const defaultAccount = defaultAccountType ? yield createAccount({ account: { serverUrl, credentials, accountType: defaultAccountType }, @@ -1459,14 +1465,26 @@ class DAVClient { this.accountType = (_b = params.defaultAccountType) !== null && _b !== void 0 ? _b : 'caldav'; } login() { + var _a; return __awaiter(this, void 0, void 0, function* () { - this.authHeaders = - // eslint-disable-next-line no-nested-ternary - this.authMethod === 'Basic' - ? getBasicAuthHeaders(this.credentials) - : this.authMethod === 'Oauth' - ? (yield getOauthHeaders(this.credentials)).headers - : {}; + switch (this.authMethod) { + case 'Basic': + this.authHeaders = getBasicAuthHeaders(this.credentials); + break; + case 'Oauth': + this.authHeaders = (yield getOauthHeaders(this.credentials)).headers; + break; + case 'Digest': + this.authHeaders = { + Authorization: `Digest ${this.credentials.digestString}`, + }; + break; + case 'Custom': + this.authHeaders = yield ((_a = this.authFunction) === null || _a === void 0 ? void 0 : _a.call(this, this.credentials)); + break; + default: + throw new Error('Invalid auth method'); + } this.account = this.accountType ? yield createAccount({ account: { diff --git a/dist/tsdav.d.ts b/dist/tsdav.d.ts index 9e6570a..d1eac00 100644 --- a/dist/tsdav.d.ts +++ b/dist/tsdav.d.ts @@ -81,6 +81,8 @@ type DAVCredentials = { accessToken?: string; refreshToken?: string; expiration?: number; + digestString?: string; + customData?: Record; }; type DAVAccount = { accountType: 'caldav' | 'carddav'; @@ -98,6 +100,7 @@ type DAVAddressBook = DAVCollection; type DAVCalendar = { components?: string[]; timezone?: string; + projectedProps?: Record; } & DAVCollection; interface SmartCollectionSync { @@ -221,9 +224,9 @@ declare const calendarMultiGet: (params: { url: string; props: ElementCompact; objectUrls?: string[]; - filters?: ElementCompact; timezone?: string; depth: DAVDepth; + filters?: ElementCompact; headers?: Record; }) => Promise; declare const makeCalendar: (params: { @@ -235,6 +238,7 @@ declare const makeCalendar: (params: { declare const fetchCalendars: (params?: { account?: DAVAccount; props?: ElementCompact; + projectedProps?: Record; headers?: Record; }) => Promise; declare const fetchCalendarObjects: (params: { @@ -347,7 +351,8 @@ declare const deleteObject: (params: { declare const createDAVClient: (params: { serverUrl: string; credentials: DAVCredentials; - authMethod?: 'Basic' | 'Oauth'; + authMethod?: "Basic" | "Oauth" | "Digest" | "Custom" | undefined; + authFunction?: ((credentials: DAVCredentials) => Promise>) | undefined; defaultAccountType?: DAVAccount['accountType'] | undefined; }) => Promise<{ davRequest: (params0: { @@ -416,9 +421,9 @@ declare const createDAVClient: (params: { url: string; props: xml_js.ElementCompact; objectUrls?: string[] | undefined; - filters?: xml_js.ElementCompact | undefined; timezone?: string | undefined; depth: DAVDepth; + filters?: xml_js.ElementCompact | undefined; headers?: Record | undefined; }) => Promise; makeCalendar: (params: { @@ -449,6 +454,7 @@ declare const createDAVClient: (params: { fetchCalendars: (params?: { account?: DAVAccount | undefined; props?: xml_js.ElementCompact | undefined; + projectedProps?: Record | undefined; headers?: Record | undefined; } | undefined) => Promise; fetchCalendarObjects: (params: { @@ -516,14 +522,16 @@ declare const createDAVClient: (params: { declare class DAVClient { serverUrl: string; credentials: DAVCredentials; - authMethod: 'Basic' | 'Oauth'; + authMethod: 'Basic' | 'Oauth' | 'Digest' | 'Custom'; accountType: DAVAccount['accountType']; authHeaders?: Record; account?: DAVAccount; + authFunction?: (credentials: DAVCredentials) => Promise>; constructor(params: { serverUrl: string; credentials: DAVCredentials; - authMethod?: 'Basic' | 'Oauth'; + authMethod?: 'Basic' | 'Oauth' | 'Digest' | 'Custom'; + authFunction?: (credentials: DAVCredentials) => Promise>; defaultAccountType?: DAVAccount['accountType'] | undefined; }); login(): Promise; @@ -606,6 +614,9 @@ declare const _default: { [key: string]: DAVNamespace; }; cleanupFalsy: (obj: T) => NoUndefinedField; + conditionalParam: (key: string, param: T_1) => { + [key: string]: T_1; + }; defaultParam: any>(fn: F, params: Partial[0]>) => (...args: Parameters) => ReturnType; getBasicAuthHeaders: (credentials: DAVCredentials) => { authorization?: string | undefined; @@ -633,9 +644,9 @@ declare const _default: { url: string; props: xml_js.ElementCompact; objectUrls?: string[] | undefined; - filters?: xml_js.ElementCompact | undefined; timezone?: string | undefined; depth: DAVDepth; + filters?: xml_js.ElementCompact | undefined; headers?: Record | undefined; }) => Promise; makeCalendar: (params: { @@ -647,6 +658,7 @@ declare const _default: { fetchCalendars: (params?: { account?: DAVAccount | undefined; props?: xml_js.ElementCompact | undefined; + projectedProps?: Record | undefined; headers?: Record | undefined; } | undefined) => Promise; fetchCalendarObjects: (params: { @@ -807,7 +819,8 @@ declare const _default: { createDAVClient: (params: { serverUrl: string; credentials: DAVCredentials; - authMethod?: "Basic" | "Oauth" | undefined; + authMethod?: "Basic" | "Oauth" | "Digest" | "Custom" | undefined; + authFunction?: ((credentials: DAVCredentials) => Promise>) | undefined; defaultAccountType?: "caldav" | "carddav" | undefined; }) => Promise<{ davRequest: (params0: { @@ -876,9 +889,9 @@ declare const _default: { url: string; props: xml_js.ElementCompact; objectUrls?: string[] | undefined; - filters?: xml_js.ElementCompact | undefined; timezone?: string | undefined; depth: DAVDepth; + filters?: xml_js.ElementCompact | undefined; headers?: Record | undefined; }) => Promise; makeCalendar: (params: { @@ -909,6 +922,7 @@ declare const _default: { fetchCalendars: (params?: { account?: DAVAccount | undefined; props?: xml_js.ElementCompact | undefined; + projectedProps?: Record | undefined; headers?: Record | undefined; } | undefined) => Promise; fetchCalendarObjects: (params: { diff --git a/dist/tsdav.esm.js b/dist/tsdav.esm.js index fe7b905..aacac24 100644 --- a/dist/tsdav.esm.js +++ b/dist/tsdav.esm.js @@ -127,10 +127,19 @@ const cleanupFalsy = (obj) => Object.entries(obj).reduce((prev, [key, value]) => return Object.assign(Object.assign({}, prev), { [key]: value }); return prev; }, {}); +const conditionalParam = (key, param) => { + if (param) { + return { + [key]: param, + }; + } + return {}; +}; var requestHelpers = /*#__PURE__*/Object.freeze({ __proto__: null, cleanupFalsy: cleanupFalsy, + conditionalParam: conditionalParam, getDAVAttribute: getDAVAttribute, urlContains: urlContains, urlEquals: urlEquals @@ -740,13 +749,7 @@ const calendarMultiGet = (params) => __awaiter(void 0, void 0, void 0, function* return collectionQuery({ url, body: { - 'calendar-multiget': { - _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), - [`${DAVNamespaceShort.DAV}:prop`]: props, - [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - filter: filters, - timezone, - }, + 'calendar-multiget': Object.assign(Object.assign({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls }, conditionalParam('filter', filters)), { timezone }), }, defaultNamespace: DAVNamespaceShort.CALDAV, depth, @@ -777,7 +780,7 @@ const makeCalendar = (params) => __awaiter(void 0, void 0, void 0, function* () }); }); const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { headers, account, props: customProps } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -811,23 +814,13 @@ const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* ( return components.some((c) => Object.values(ICALObjects).includes(c)); }) .map((rs) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; // debug(`Found calendar ${rs.props?.displayname}`); const description = (_a = rs.props) === null || _a === void 0 ? void 0 : _a.calendarDescription; const timezone = (_b = rs.props) === null || _b === void 0 ? void 0 : _b.calendarTimezone; - return { - description: typeof description === 'string' ? description : '', - timezone: typeof timezone === 'string' ? timezone : '', - url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, - ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, - calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, - displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, - components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) + return Object.assign({ description: typeof description === 'string' ? description : '', timezone: typeof timezone === 'string' ? timezone : '', url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) ? (_l = rs.props) === null || _l === void 0 ? void 0 : _l.supportedCalendarComponentSet.comp.map((sc) => sc._attributes.name) - : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], - resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), - syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken, - }; + : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken }, conditionalParam('projectedProps', Object.fromEntries(Object.entries((_q = rs.props) !== null && _q !== void 0 ? _q : {}).filter(([key]) => projectedProps === null || projectedProps === void 0 ? void 0 : projectedProps[key])))); }) .map((cal) => __awaiter(void 0, void 0, void 0, function* () { return (Object.assign(Object.assign({}, cal), { reports: yield supportedReportSet({ collection: cal, headers }) })); @@ -1330,14 +1323,27 @@ var authHelpers = /*#__PURE__*/Object.freeze({ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types const createDAVClient = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { serverUrl, credentials, authMethod, defaultAccountType } = params; - const authHeaders = - // eslint-disable-next-line no-nested-ternary - authMethod === 'Basic' - ? getBasicAuthHeaders(credentials) - : authMethod === 'Oauth' - ? (yield getOauthHeaders(credentials)).headers - : {}; + var _a; + const { serverUrl, credentials, authMethod, defaultAccountType, authFunction } = params; + let authHeaders = {}; + switch (authMethod) { + case 'Basic': + authHeaders = getBasicAuthHeaders(credentials); + break; + case 'Oauth': + authHeaders = (yield getOauthHeaders(credentials)).headers; + break; + case 'Digest': + authHeaders = { + Authorization: `Digest ${credentials.digestString}`, + }; + break; + case 'Custom': + authHeaders = (_a = (yield (authFunction === null || authFunction === void 0 ? void 0 : authFunction(credentials)))) !== null && _a !== void 0 ? _a : {}; + break; + default: + throw new Error('Invalid auth method'); + } const defaultAccount = defaultAccountType ? yield createAccount({ account: { serverUrl, credentials, accountType: defaultAccountType }, @@ -1455,14 +1461,26 @@ class DAVClient { this.accountType = (_b = params.defaultAccountType) !== null && _b !== void 0 ? _b : 'caldav'; } login() { + var _a; return __awaiter(this, void 0, void 0, function* () { - this.authHeaders = - // eslint-disable-next-line no-nested-ternary - this.authMethod === 'Basic' - ? getBasicAuthHeaders(this.credentials) - : this.authMethod === 'Oauth' - ? (yield getOauthHeaders(this.credentials)).headers - : {}; + switch (this.authMethod) { + case 'Basic': + this.authHeaders = getBasicAuthHeaders(this.credentials); + break; + case 'Oauth': + this.authHeaders = (yield getOauthHeaders(this.credentials)).headers; + break; + case 'Digest': + this.authHeaders = { + Authorization: `Digest ${this.credentials.digestString}`, + }; + break; + case 'Custom': + this.authHeaders = yield ((_a = this.authFunction) === null || _a === void 0 ? void 0 : _a.call(this, this.credentials)); + break; + default: + throw new Error('Invalid auth method'); + } this.account = this.accountType ? yield createAccount({ account: { diff --git a/dist/tsdav.js b/dist/tsdav.js index 1dc473d..7fa9f08 100644 --- a/dist/tsdav.js +++ b/dist/tsdav.js @@ -8947,10 +8947,19 @@ const cleanupFalsy = (obj) => Object.entries(obj).reduce((prev, [key, value]) => return Object.assign(Object.assign({}, prev), { [key]: value }); return prev; }, {}); +const conditionalParam = (key, param) => { + if (param) { + return { + [key]: param, + }; + } + return {}; +}; var requestHelpers = /*#__PURE__*/Object.freeze({ __proto__: null, cleanupFalsy: cleanupFalsy, + conditionalParam: conditionalParam, getDAVAttribute: getDAVAttribute, urlContains: urlContains, urlEquals: urlEquals @@ -9560,13 +9569,7 @@ const calendarMultiGet = (params) => __awaiter(void 0, void 0, void 0, function* return collectionQuery({ url, body: { - 'calendar-multiget': { - _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), - [`${DAVNamespaceShort.DAV}:prop`]: props, - [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - filter: filters, - timezone, - }, + 'calendar-multiget': Object.assign(Object.assign({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls }, conditionalParam('filter', filters)), { timezone }), }, defaultNamespace: DAVNamespaceShort.CALDAV, depth, @@ -9597,7 +9600,7 @@ const makeCalendar = (params) => __awaiter(void 0, void 0, void 0, function* () }); }); const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { headers, account, props: customProps } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -9631,23 +9634,13 @@ const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* ( return components.some((c) => Object.values(ICALObjects).includes(c)); }) .map((rs) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; // debug(`Found calendar ${rs.props?.displayname}`); const description = (_a = rs.props) === null || _a === void 0 ? void 0 : _a.calendarDescription; const timezone = (_b = rs.props) === null || _b === void 0 ? void 0 : _b.calendarTimezone; - return { - description: typeof description === 'string' ? description : '', - timezone: typeof timezone === 'string' ? timezone : '', - url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, - ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, - calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, - displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, - components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) + return Object.assign({ description: typeof description === 'string' ? description : '', timezone: typeof timezone === 'string' ? timezone : '', url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) ? (_l = rs.props) === null || _l === void 0 ? void 0 : _l.supportedCalendarComponentSet.comp.map((sc) => sc._attributes.name) - : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], - resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), - syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken, - }; + : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken }, conditionalParam('projectedProps', Object.fromEntries(Object.entries((_q = rs.props) !== null && _q !== void 0 ? _q : {}).filter(([key]) => projectedProps === null || projectedProps === void 0 ? void 0 : projectedProps[key])))); }) .map((cal) => __awaiter(void 0, void 0, void 0, function* () { return (Object.assign(Object.assign({}, cal), { reports: yield supportedReportSet({ collection: cal, headers }) })); @@ -10315,14 +10308,27 @@ var authHelpers = /*#__PURE__*/Object.freeze({ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types const createDAVClient = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { serverUrl, credentials, authMethod, defaultAccountType } = params; - const authHeaders = - // eslint-disable-next-line no-nested-ternary - authMethod === 'Basic' - ? getBasicAuthHeaders(credentials) - : authMethod === 'Oauth' - ? (yield getOauthHeaders(credentials)).headers - : {}; + var _a; + const { serverUrl, credentials, authMethod, defaultAccountType, authFunction } = params; + let authHeaders = {}; + switch (authMethod) { + case 'Basic': + authHeaders = getBasicAuthHeaders(credentials); + break; + case 'Oauth': + authHeaders = (yield getOauthHeaders(credentials)).headers; + break; + case 'Digest': + authHeaders = { + Authorization: `Digest ${credentials.digestString}`, + }; + break; + case 'Custom': + authHeaders = (_a = (yield (authFunction === null || authFunction === void 0 ? void 0 : authFunction(credentials)))) !== null && _a !== void 0 ? _a : {}; + break; + default: + throw new Error('Invalid auth method'); + } const defaultAccount = defaultAccountType ? yield createAccount({ account: { serverUrl, credentials, accountType: defaultAccountType }, @@ -10440,14 +10446,26 @@ class DAVClient { this.accountType = (_b = params.defaultAccountType) !== null && _b !== void 0 ? _b : 'caldav'; } login() { + var _a; return __awaiter(this, void 0, void 0, function* () { - this.authHeaders = - // eslint-disable-next-line no-nested-ternary - this.authMethod === 'Basic' - ? getBasicAuthHeaders(this.credentials) - : this.authMethod === 'Oauth' - ? (yield getOauthHeaders(this.credentials)).headers - : {}; + switch (this.authMethod) { + case 'Basic': + this.authHeaders = getBasicAuthHeaders(this.credentials); + break; + case 'Oauth': + this.authHeaders = (yield getOauthHeaders(this.credentials)).headers; + break; + case 'Digest': + this.authHeaders = { + Authorization: `Digest ${this.credentials.digestString}`, + }; + break; + case 'Custom': + this.authHeaders = yield ((_a = this.authFunction) === null || _a === void 0 ? void 0 : _a.call(this, this.credentials)); + break; + default: + throw new Error('Invalid auth method'); + } this.account = this.accountType ? yield createAccount({ account: { diff --git a/dist/tsdav.min.cjs b/dist/tsdav.min.cjs index d2fc9a8..c71a711 100644 --- a/dist/tsdav.min.cjs +++ b/dist/tsdav.min.cjs @@ -1 +1 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("cross-fetch"),r=require("debug"),o=require("xml-js"),a=require("base-64");function s(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(o=Object.getOwnPropertySymbols(e);a{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},u=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),o=t.trim();if(Math.abs(r.length-o.length)>1)return!1;const a="/"===r.slice(-1)?r.slice(0,-1):r,s="/"===o.slice(-1)?o.slice(0,-1):o;return e.includes(s)||t.includes(a)},p=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),o=t.trim(),a="/"===r.slice(-1)?r.slice(0,-1):r,s="/"===o.slice(-1)?o.slice(0,-1):o;return e.includes(s)||t.includes(a)},h=e=>e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[d[t]]:t})),{}),v=e=>Object.entries(e).reduce(((e,[t,r])=>r?Object.assign(Object.assign({},e),{[t]:r}):e),{});var f=Object.freeze({__proto__:null,cleanupFalsy:v,getDAVAttribute:h,urlContains:p,urlEquals:u});const m=r("tsdav:request"),A=e=>n(void 0,void 0,void 0,(function*(){var r;const{url:a,init:s,convertIncoming:n=!0,parseOutgoing:d=!0}=e,{headers:i={},body:c,namespace:u,method:p,attributes:h}=s,f=n?o.js2xml(Object.assign(Object.assign({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},c),{_attributes:h}),{compact:!0,spaces:2,elementNameFn:e=>u&&!/^.+:.+/.test(e)?`${u}:${e}`:e}):c,A=yield t.fetch(a,{headers:Object.assign({"Content-Type":"text/xml;charset=UTF-8"},v(i)),body:f,method:p}),D=yield A.text();if(!A.ok||!(null===(r=A.headers.get("content-type"))||void 0===r?void 0:r.includes("xml"))||!d)return[{href:A.url,ok:A.ok,status:A.status,statusText:A.statusText,raw:D}];const y=o.xml2js(D,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,o=Object.keys(r),a=o[o.length-1],s=r[a];if(s.length>0){s[s.length-1]=l(e)}else r[a]=l(e)}catch(e){m(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,(e=>e[1].toUpperCase())),attributesFn:e=>{const t=Object.assign({},e);return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(y.multistatus.response)?y.multistatus.response:[y.multistatus.response]).map((e=>{var t,r;if(!e)return{status:A.status,statusText:A.statusText,ok:A.ok};const o=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:y,href:e.href,status:(null==o?void 0:o.groups)?Number.parseInt(null==o?void 0:o.groups.status,10):A.status,statusText:null!==(r=null===(t=null==o?void 0:o.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:A.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce(((e,t)=>Object.assign(Object.assign({},e),null==t?void 0:t.prop)),{})}}))})),D=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:a}=e;return A({url:t,init:{method:"PROPFIND",headers:v(Object.assign({depth:o},a)),namespace:exports.DAVNamespaceShort.DAV,body:{propfind:{_attributes:h([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),prop:r}}}})})),y=e=>n(void 0,void 0,void 0,(function*(){const{url:r,data:o,headers:a}=e;return t.fetch(r,{method:"PUT",body:o,headers:a})})),g=e=>n(void 0,void 0,void 0,(function*(){const{url:r,data:o,etag:a,headers:s}=e;return t.fetch(r,{method:"PUT",body:o,headers:v(Object.assign({"If-Match":a},s))})})),V=e=>n(void 0,void 0,void 0,(function*(){const{url:r,headers:o,etag:a}=e;return t.fetch(r,{method:"DELETE",headers:v(Object.assign({"If-Match":a},o))})}));var b=Object.freeze({__proto__:null,createObject:y,davRequest:A,deleteObject:V,propfind:D,updateObject:g});function x(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const O=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),C=r("tsdav:collection"),j=e=>n(void 0,void 0,void 0,(function*(){const{url:t,body:r,depth:o,defaultNamespace:a=exports.DAVNamespaceShort.DAV,headers:s}=e,n=yield A({url:t,init:{method:"REPORT",headers:v(Object.assign({depth:o},s)),namespace:a,body:r}});return 1!==n.length||n[0].raw?n:[]})),S=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:a}=e;return A({url:t,init:{method:"MKCOL",headers:v(Object.assign({depth:o},a)),namespace:exports.DAVNamespaceShort.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0}})})),N=e=>n(void 0,void 0,void 0,(function*(){var t,r,o,a,s;const{collection:n,headers:d}=e;return null!==(s=null===(a=null===(o=null===(r=null===(t=(yield D({url:n.url,props:{[`${exports.DAVNamespaceShort.DAV}:supported-report-set`]:{}},depth:"0",headers:d}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===o?void 0:o.supportedReport)||void 0===a?void 0:a.map((e=>Object.keys(e.report)[0])))&&void 0!==s?s:[]})),$=e=>n(void 0,void 0,void 0,(function*(){var t,r,o;const{collection:a,headers:s}=e,n=(yield D({url:a.url,props:{[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:s})).filter((e=>p(a.url,e.href)))[0];if(!n)throw new Error("Collection does not exist on server");return{isDirty:a.ctag!==(null===(t=n.props)||void 0===t?void 0:t.getctag),newCtag:null===(o=null===(r=n.props)||void 0===r?void 0:r.getctag)||void 0===o?void 0:o.toString()}})),k=e=>{const{url:t,props:r,headers:o,syncLevel:a,syncToken:s}=e;return A({url:t,init:{method:"REPORT",namespace:exports.DAVNamespaceShort.DAV,headers:Object.assign({},o),body:{"sync-collection":{_attributes:h([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),"sync-level":a,"sync-token":s,[`${exports.DAVNamespaceShort.DAV}:prop`]:r}}}})},w=e=>n(void 0,void 0,void 0,(function*(){var t,r,o,a,s,n,d,i,c,l,u;const{collection:h,method:v,headers:f,account:m,detailedResult:A}=e,D=["accountType","homeUrl"];if(!m||!x(m,D)){if(!m)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${O(m,D)} before smartCollectionSync`)}const y=null!=v?v:(null===(t=h.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(C(`smart collection sync with type ${m.accountType} and method ${y}`),"webdav"===y){const e=yield k({url:h.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${"caldav"===m.accountType?exports.DAVNamespaceShort.CALDAV:exports.DAVNamespaceShort.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{},[`${exports.DAVNamespaceShort.DAV}:displayname`]:{}},syncLevel:1,syncToken:h.syncToken,headers:f}),t=e.filter((e=>{var t;const r="caldav"===m.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r})),c=t.filter((e=>404!==e.status)).map((e=>e.href)),l=t.filter((e=>404===e.status)).map((e=>e.href)),u=(c.length&&null!==(o=yield null===(r=null==h?void 0:h.objectMultiGet)||void 0===r?void 0:r.call(h,{url:h.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${"caldav"===m.accountType?exports.DAVNamespaceShort.CALDAV:exports.DAVNamespaceShort.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:c,depth:"1",headers:f}))&&void 0!==o?o:[]).map((e=>{var t,r,o,a,s,n,d,i,c,l;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==m?void 0:m.accountType)?null!==(s=null===(a=null===(o=e.props)||void 0===o?void 0:o.calendarData)||void 0===a?void 0:a._cdata)&&void 0!==s?s:null===(n=e.props)||void 0===n?void 0:n.calendarData:null!==(c=null===(i=null===(d=e.props)||void 0===d?void 0:d.addressData)||void 0===i?void 0:i._cdata)&&void 0!==c?c:null===(l=e.props)||void 0===l?void 0:l.addressData}})),v=null!==(a=h.objects)&&void 0!==a?a:[],D=u.filter((e=>v.every((t=>!p(t.url,e.url))))),y=v.reduce(((e,t)=>{const r=u.find((e=>p(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),g=l.map((e=>({url:e,etag:""}))),V=v.filter((e=>u.some((t=>p(e.url,t.url)&&t.etag===e.etag))));return Object.assign(Object.assign({},h),{objects:A?{created:D,updated:y,deleted:g}:[...V,...D,...y],syncToken:null!==(i=null===(d=null===(n=null===(s=e[0])||void 0===s?void 0:s.raw)||void 0===n?void 0:n.multistatus)||void 0===d?void 0:d.syncToken)&&void 0!==i?i:h.syncToken})}if("basic"===y){const{isDirty:e,newCtag:t}=yield $({collection:h,headers:f}),r=null!==(c=h.objects)&&void 0!==c?c:[],o=null!==(u=yield null===(l=h.fetchObjects)||void 0===l?void 0:l.call(h,{collection:h,headers:f}))&&void 0!==u?u:[],a=o.filter((e=>r.every((t=>!p(t.url,e.url))))),s=r.reduce(((e,t)=>{const r=o.find((e=>p(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),n=r.filter((e=>o.every((t=>!p(t.url,e.url))))),d=r.filter((e=>o.some((t=>p(e.url,t.url)&&t.etag===e.etag))));if(e)return Object.assign(Object.assign({},h),{objects:A?{created:a,updated:s,deleted:n}:[...d,...a,...s],ctag:t})}return A?Object.assign(Object.assign({},h),{objects:{created:[],updated:[],deleted:[]}}):h}));var _=Object.freeze({__proto__:null,collectionQuery:j,isCollectionDirty:$,makeCollection:S,smartCollectionSync:w,supportedReportSet:N,syncCollection:k});const R=r("tsdav:addressBook"),U=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:o,depth:a,headers:s}=e;return j({url:t,body:{"addressbook-query":{_attributes:h([exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:null!=o?o:{"prop-filter":{_attributes:{name:"FN"}}}}},defaultNamespace:exports.DAVNamespaceShort.CARDDAV,depth:a,headers:s})})),T=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:o,depth:a,headers:s}=e;return j({url:t,body:{"addressbook-multiget":{_attributes:h([exports.DAVNamespace.DAV,exports.DAVNamespace.CARDDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:o}},defaultNamespace:exports.DAVNamespaceShort.CARDDAV,depth:a,headers:s})})),E=e=>n(void 0,void 0,void 0,(function*(){const{account:t,headers:r,props:o}=null!=e?e:{},a=["homeUrl","rootUrl"];if(!t||!x(t,a)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${O(t,a)} before fetchAddressBooks`)}const s=yield D({url:t.homeUrl,props:null!=o?o:{[`${exports.DAVNamespaceShort.DAV}:displayname`]:{},[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{},[`${exports.DAVNamespaceShort.DAV}:resourcetype`]:{},[`${exports.DAVNamespaceShort.DAV}:sync-token`]:{}},depth:"1",headers:r});return Promise.all(s.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")})).map((e=>{var r,o,a,s,n,d,i,c,l;const u=null!==(a=null===(o=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===o?void 0:o._cdata)&&void 0!==a?a:null===(s=e.props)||void 0===s?void 0:s.displayname;return R(`Found address book named ${"string"==typeof u?u:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(n=e.href)&&void 0!==n?n:"",null!==(d=t.rootUrl)&&void 0!==d?d:"").href,ctag:null===(i=e.props)||void 0===i?void 0:i.getctag,displayName:"string"==typeof u?u:"",resourcetype:Object.keys(null===(c=e.props)||void 0===c?void 0:c.resourcetype),syncToken:null===(l=e.props)||void 0===l?void 0:l.syncToken}})).map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield N({collection:e,headers:r})})})))))})),L=e=>n(void 0,void 0,void 0,(function*(){const{addressBook:t,headers:r,objectUrls:o,urlFilter:a=(e=>e),useMultiGet:s=!0}=e;R(`Fetching vcards from ${null==t?void 0:t.url}`);const n=["url"];if(!t||!x(t,n)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${O(t,n)} before fetchVCards`)}const d=(null!=o?o:(yield U({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{}},depth:"1",headers:r})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(a).map((e=>new URL(e).pathname));let i=[];return d.length>0&&(i=s?yield T({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},objectUrls:d,depth:"1",headers:r}):yield U({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},depth:"1",headers:r})),i.map((e=>{var r,o,a,s,n,d;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(o=e.props)||void 0===o?void 0:o.getetag,data:null!==(n=null===(s=null===(a=e.props)||void 0===a?void 0:a.addressData)||void 0===s?void 0:s._cdata)&&void 0!==n?n:null===(d=e.props)||void 0===d?void 0:d.addressData}}))})),P=e=>n(void 0,void 0,void 0,(function*(){const{addressBook:t,vCardString:r,filename:o,headers:a}=e;return y({url:new URL(o,t.url).href,data:r,headers:Object.assign({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*"},a)})})),H=e=>n(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return g({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/vcard; charset=utf-8"},r)})})),B=e=>n(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return V({url:t.url,etag:t.etag,headers:r})}));var M=Object.freeze({__proto__:null,addressBookMultiGet:T,addressBookQuery:U,createVCard:P,deleteVCard:B,fetchAddressBooks:E,fetchVCards:L,updateVCard:H});const I=r("tsdav:calendar"),F=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:o,timezone:a,depth:s,headers:n}=e;return j({url:t,body:{"calendar-query":v({_attributes:h([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:o,timezone:a})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:s,headers:n})})),z=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:o,filters:a,timezone:s,depth:n,headers:d}=e;return j({url:t,body:{"calendar-multiget":{_attributes:h([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:o,filter:a,timezone:s}},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:n,headers:d})})),Z=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:a}=e;return A({url:t,init:{method:"MKCALENDAR",headers:v(Object.assign({depth:o},a)),namespace:exports.DAVNamespaceShort.DAV,body:{[`${exports.DAVNamespaceShort.CALDAV}:mkcalendar`]:{_attributes:h([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE]),set:{prop:r}}}}})})),q=e=>n(void 0,void 0,void 0,(function*(){const{headers:t,account:r,props:o}=null!=e?e:{},a=["homeUrl","rootUrl"];if(!r||!x(r,a)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${O(r,a)} before fetchCalendars`)}const s=yield D({url:r.homeUrl,props:null!=o?o:{[`${exports.DAVNamespaceShort.CALDAV}:calendar-description`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-timezone`]:{},[`${exports.DAVNamespaceShort.DAV}:displayname`]:{},[`${exports.DAVNamespaceShort.CALDAV_APPLE}:calendar-color`]:{},[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{},[`${exports.DAVNamespaceShort.DAV}:resourcetype`]:{},[`${exports.DAVNamespaceShort.CALDAV}:supported-calendar-component-set`]:{},[`${exports.DAVNamespaceShort.DAV}:sync-token`]:{}},depth:"1",headers:t});return Promise.all(s.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")})).filter((e=>{var t,r,o;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(o=e.props)||void 0===o?void 0:o.supportedCalendarComponentSet.comp._attributes.name]||[]).some((e=>Object.values(c).includes(e)))})).map((e=>{var t,o,a,s,n,d,i,c,l,u,p,h,v,f;const m=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,A=null===(o=e.props)||void 0===o?void 0:o.calendarTimezone;return{description:"string"==typeof m?m:"",timezone:"string"==typeof A?A:"",url:new URL(null!==(a=e.href)&&void 0!==a?a:"",null!==(s=r.rootUrl)&&void 0!==s?s:"").href,ctag:null===(n=e.props)||void 0===n?void 0:n.getctag,calendarColor:null===(d=e.props)||void 0===d?void 0:d.calendarColor,displayName:null!==(c=null===(i=e.props)||void 0===i?void 0:i.displayname._cdata)&&void 0!==c?c:null===(l=e.props)||void 0===l?void 0:l.displayname,components:Array.isArray(null===(u=e.props)||void 0===u?void 0:u.supportedCalendarComponentSet.comp)?null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(h=e.props)||void 0===h?void 0:h.supportedCalendarComponentSet.comp._attributes.name],resourcetype:Object.keys(null===(v=e.props)||void 0===v?void 0:v.resourcetype),syncToken:null===(f=e.props)||void 0===f?void 0:f.syncToken}})).map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield N({collection:e,headers:t})})})))))})),Q=e=>n(void 0,void 0,void 0,(function*(){const{calendar:t,objectUrls:r,filters:o,timeRange:a,headers:s,expand:n,urlFilter:d=(e=>Boolean(null==e?void 0:e.includes(".ics"))),useMultiGet:i=!0}=e;if(a){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(a.start)&&e.test(a.end)||t.test(a.start)&&t.test(a.end)))throw new Error("invalid timeRange format, not in ISO8601")}I(`Fetching calendar objects from ${null==t?void 0:t.url}`);const c=["url"];if(!t||!x(t,c)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${O(t,c)} before fetchCalendarObjects`)}const l=null!=o?o:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":Object.assign({_attributes:{name:"VEVENT"}},a?{"time-range":{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})}}],u=(null!=r?r:(yield F({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:Object.assign({},n&&a?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:l,depth:"1",headers:s})).map((e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(d).map((e=>new URL(e).pathname));let p=[];return u.length>0&&(p=!i||n?yield F({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:Object.assign({},n&&a?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:l,depth:"1",headers:s}):yield z({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:Object.assign({},n&&a?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},objectUrls:u,depth:"1",headers:s})),p.map((e=>{var r,o,a,s,n,d;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(o=e.props)||void 0===o?void 0:o.getetag}`,data:null!==(n=null===(s=null===(a=e.props)||void 0===a?void 0:a.calendarData)||void 0===s?void 0:s._cdata)&&void 0!==n?n:null===(d=e.props)||void 0===d?void 0:d.calendarData}}))})),G=e=>n(void 0,void 0,void 0,(function*(){const{calendar:t,iCalString:r,filename:o,headers:a}=e;return y({url:new URL(o,t.url).href,data:r,headers:Object.assign({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*"},a)})})),J=e=>n(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return g({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/calendar; charset=utf-8"},r)})})),K=e=>n(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return V({url:t.url,etag:t.etag,headers:r})})),W=e=>n(void 0,void 0,void 0,(function*(){var t;const{oldCalendars:r,account:o,detailedResult:a,headers:s}=e;if(!o)throw new Error("Must have account before syncCalendars");const d=null!==(t=null!=r?r:o.calendars)&&void 0!==t?t:[],i=yield q({account:o,headers:s}),c=i.filter((e=>d.every((t=>!p(t.url,e.url)))));I(`new calendars: ${c.map((e=>e.displayName))}`);const l=d.reduce(((e,t)=>{const r=i.find((e=>p(e.url,t.url)));return r&&(r.syncToken&&r.syncToken!==t.syncToken||r.ctag&&r.ctag!==t.ctag)?[...e,r]:e}),[]);I(`updated calendars: ${l.map((e=>e.displayName))}`);const u=yield Promise.all(l.map((e=>n(void 0,void 0,void 0,(function*(){return yield w({collection:Object.assign(Object.assign({},e),{objectMultiGet:z}),method:"webdav",headers:s,account:o})}))))),h=d.filter((e=>i.every((t=>!p(t.url,e.url)))));I(`deleted calendars: ${h.map((e=>e.displayName))}`);const v=d.filter((e=>i.some((t=>p(t.url,e.url)&&(t.syncToken&&t.syncToken!==e.syncToken||t.ctag&&t.ctag!==e.ctag)))));return a?{created:c,updated:l,deleted:h}:[...v,...c,...u]})),Y=e=>n(void 0,void 0,void 0,(function*(){const{url:t,timeRange:r,depth:o,headers:a}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(yield j({url:t,body:{"free-busy-query":v({_attributes:h([exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:o,headers:a}))[0]}));var X=Object.freeze({__proto__:null,calendarMultiGet:z,calendarQuery:F,createCalendarObject:G,deleteCalendarObject:K,fetchCalendarObjects:Q,fetchCalendars:q,freeBusyQuery:Y,makeCalendar:Z,syncCalendars:W,updateCalendarObject:J});const ee=r("tsdav:account"),te=e=>n(void 0,void 0,void 0,(function*(){var r,o;ee("Service discovery...");const{account:a,headers:s}=e,n=new URL(a.serverUrl),d=new URL(`/.well-known/${a.accountType}`,n);d.protocol=null!==(r=n.protocol)&&void 0!==r?r:"http";try{const e=yield t.fetch(d.href,{headers:s,method:"PROPFIND",redirect:"manual"});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){ee(`Service discovery redirected to ${t}`);const e=new URL(t,n);return e.hostname===d.hostname&&d.port&&!e.port&&(e.port=d.port),e.protocol=null!==(o=n.protocol)&&void 0!==o?o:"http",e.href}}}catch(e){ee(`Service discovery failed: ${e.stack}`)}return n.href})),re=e=>n(void 0,void 0,void 0,(function*(){var t,r,o,a,s;const{account:n,headers:d}=e,i=["rootUrl"];if(!x(n,i))throw new Error(`account must have ${O(n,i)} before fetchPrincipalUrl`);ee(`Fetching principal url from path ${n.rootUrl}`);const[c]=yield D({url:n.rootUrl,props:{[`${exports.DAVNamespaceShort.DAV}:current-user-principal`]:{}},depth:"0",headers:d});if(!c.ok&&(ee(`Fetch principal url failed: ${c.statusText}`),401===c.status))throw new Error("Invalid credentials");return ee(`Fetched principal url ${null===(r=null===(t=c.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(s=null===(a=null===(o=c.props)||void 0===o?void 0:o.currentUserPrincipal)||void 0===a?void 0:a.href)&&void 0!==s?s:"",n.rootUrl).href})),oe=e=>n(void 0,void 0,void 0,(function*(){var t,r;const{account:o,headers:a}=e,s=["principalUrl","rootUrl"];if(!x(o,s))throw new Error(`account must have ${O(o,s)} before fetchHomeUrl`);ee(`Fetch home url from ${o.principalUrl}`);const n=(yield D({url:o.principalUrl,props:"caldav"===o.accountType?{[`${exports.DAVNamespaceShort.CALDAV}:calendar-home-set`]:{}}:{[`${exports.DAVNamespaceShort.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:a})).find((e=>p(o.principalUrl,e.href)));if(!n||!n.ok)throw new Error("cannot find homeUrl");const d=new URL("caldav"===o.accountType?null===(t=null==n?void 0:n.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==n?void 0:n.props)||void 0===r?void 0:r.addressbookHomeSet.href,o.rootUrl).href;return ee(`Fetched home url ${d}`),d})),ae=e=>n(void 0,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:o=!1,loadObjects:a=!1}=e,s=Object.assign({},t);return s.rootUrl=yield te({account:t,headers:r}),s.principalUrl=yield re({account:s,headers:r}),s.homeUrl=yield oe({account:s,headers:r}),(o||a)&&("caldav"===t.accountType?s.calendars=yield q({headers:r,account:s}):"carddav"===t.accountType&&(s.addressBooks=yield E({headers:r,account:s}))),a&&("caldav"===t.accountType&&s.calendars?s.calendars=yield Promise.all(s.calendars.map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield Q({calendar:e,headers:r})})}))))):"carddav"===t.accountType&&s.addressBooks&&(s.addressBooks=yield Promise.all(s.addressBooks.map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield L({addressBook:e,headers:r})})}))))))),s}));var se=Object.freeze({__proto__:null,createAccount:ae,fetchHomeUrl:oe,fetchPrincipalUrl:re,serviceDiscovery:te});const ne=r("tsdav:authHelper"),de=(e,t)=>(...r)=>e(Object.assign(Object.assign({},t),r[0])),ie=e=>(ne(`Basic auth token generated: ${a.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${a.encode(`${e.username}:${e.password}`)}`}),ce=e=>n(void 0,void 0,void 0,(function*(){const r=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!x(e,r))throw new Error(`Oauth credentials missing: ${O(e,r)}`);const o=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ne(e.tokenUrl),ne(o.toString());const a=yield t.fetch(e.tokenUrl,{method:"POST",body:o.toString(),headers:{"content-length":`${o.toString().length}`,"content-type":"application/x-www-form-urlencoded"}});if(a.ok){return yield a.json()}return ne(`Fetch Oauth tokens failed: ${yield a.text()}`),{}})),le=e=>n(void 0,void 0,void 0,(function*(){const r=["refreshToken","clientId","clientSecret","tokenUrl"];if(!x(e,r))throw new Error(`Oauth credentials missing: ${O(e,r)}`);const o=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),a=yield t.fetch(e.tokenUrl,{method:"POST",body:o.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(a.ok){return yield a.json()}return ne(`Refresh access token failed: ${yield a.text()}`),{}})),ue=e=>n(void 0,void 0,void 0,(function*(){var t;ne("Fetching oauth headers");let r={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(t=e.expiration)&&void 0!==t?t:0))&&(r=yield le(e)):r=yield ce(e),ne(`Oauth tokens fetched: ${r.access_token}`),{tokens:r,headers:{authorization:`Bearer ${r.access_token}`}}}));var pe=Object.freeze({__proto__:null,defaultParam:de,fetchOauthTokens:ce,getBasicAuthHeaders:ie,getOauthHeaders:ue,refreshAccessToken:le});const he=e=>n(void 0,void 0,void 0,(function*(){const{serverUrl:t,credentials:r,authMethod:o,defaultAccountType:a}=e,d="Basic"===o?ie(r):"Oauth"===o?(yield ue(r)).headers:{},i=a?yield ae({account:{serverUrl:t,credentials:r,accountType:a},headers:d}):void 0,c=de(y,{url:t,headers:d}),l=de(g,{headers:d,url:t}),u=de(V,{headers:d,url:t}),p=de(D,{headers:d}),h=de(j,{headers:d}),v=de(S,{headers:d}),f=de(k,{headers:d}),m=de(N,{headers:d}),b=de($,{headers:d}),x=de(w,{headers:d,account:i}),O=de(F,{headers:d}),C=de(z,{headers:d}),_=de(Z,{headers:d}),R=de(q,{headers:d,account:i}),M=de(Q,{headers:d}),I=de(G,{headers:d}),Y=de(J,{headers:d}),X=de(K,{headers:d}),ee=de(W,{account:i,headers:d}),te=de(U,{headers:d}),re=de(T,{headers:d});return{davRequest:e=>n(void 0,void 0,void 0,(function*(){const{init:t}=e,r=s(e,["init"]),{headers:o}=t,a=s(t,["headers"]);return A(Object.assign(Object.assign({},r),{init:Object.assign(Object.assign({},a),{headers:Object.assign(Object.assign({},d),o)})}))})),propfind:p,createAccount:e=>n(void 0,void 0,void 0,(function*(){const{account:o,headers:a,loadCollections:s,loadObjects:n}=e;return ae({account:Object.assign({serverUrl:t,credentials:r},o),headers:Object.assign(Object.assign({},d),a),loadCollections:s,loadObjects:n})})),createObject:c,updateObject:l,deleteObject:u,calendarQuery:O,addressBookQuery:te,collectionQuery:h,makeCollection:v,calendarMultiGet:C,makeCalendar:_,syncCollection:f,supportedReportSet:m,isCollectionDirty:b,smartCollectionSync:x,fetchCalendars:R,fetchCalendarObjects:M,createCalendarObject:I,updateCalendarObject:Y,deleteCalendarObject:X,syncCalendars:ee,fetchAddressBooks:de(E,{account:i,headers:d}),addressBookMultiGet:re,fetchVCards:de(L,{headers:d}),createVCard:de(P,{headers:d}),updateVCard:de(H,{headers:d}),deleteVCard:de(B,{headers:d})}}));class ve{constructor(e){var t,r;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav"}login(){return n(this,void 0,void 0,(function*(){this.authHeaders="Basic"===this.authMethod?ie(this.credentials):"Oauth"===this.authMethod?(yield ue(this.credentials)).headers:{},this.account=this.accountType?yield ae({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders}):void 0}))}davRequest(e){return n(this,void 0,void 0,(function*(){const{init:t}=e,r=s(e,["init"]),{headers:o}=t,a=s(t,["headers"]);return A(Object.assign(Object.assign({},r),{init:Object.assign(Object.assign({},a),{headers:Object.assign(Object.assign({},this.authHeaders),o)})}))}))}createObject(...e){return n(this,void 0,void 0,(function*(){return de(y,{url:this.serverUrl,headers:this.authHeaders})(e[0])}))}updateObject(...e){return n(this,void 0,void 0,(function*(){return de(g,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}deleteObject(...e){return n(this,void 0,void 0,(function*(){return de(V,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}propfind(...e){return n(this,void 0,void 0,(function*(){return de(D,{headers:this.authHeaders})(e[0])}))}createAccount(e){return n(this,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:o,loadObjects:a}=e;return ae({account:Object.assign({serverUrl:this.serverUrl,credentials:this.credentials},t),headers:Object.assign(Object.assign({},this.authHeaders),r),loadCollections:o,loadObjects:a})}))}collectionQuery(...e){return n(this,void 0,void 0,(function*(){return de(j,{headers:this.authHeaders})(e[0])}))}makeCollection(...e){return n(this,void 0,void 0,(function*(){return de(S,{headers:this.authHeaders})(e[0])}))}syncCollection(...e){return n(this,void 0,void 0,(function*(){return de(k,{headers:this.authHeaders})(e[0])}))}supportedReportSet(...e){return n(this,void 0,void 0,(function*(){return de(N,{headers:this.authHeaders})(e[0])}))}isCollectionDirty(...e){return n(this,void 0,void 0,(function*(){return de($,{headers:this.authHeaders})(e[0])}))}smartCollectionSync(...e){return n(this,void 0,void 0,(function*(){return de(w,{headers:this.authHeaders,account:this.account})(e[0])}))}calendarQuery(...e){return n(this,void 0,void 0,(function*(){return de(F,{headers:this.authHeaders})(e[0])}))}makeCalendar(...e){return n(this,void 0,void 0,(function*(){return de(Z,{headers:this.authHeaders})(e[0])}))}calendarMultiGet(...e){return n(this,void 0,void 0,(function*(){return de(z,{headers:this.authHeaders})(e[0])}))}fetchCalendars(...e){return n(this,void 0,void 0,(function*(){return de(q,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchCalendarObjects(...e){return n(this,void 0,void 0,(function*(){return de(Q,{headers:this.authHeaders})(e[0])}))}createCalendarObject(...e){return n(this,void 0,void 0,(function*(){return de(G,{headers:this.authHeaders})(e[0])}))}updateCalendarObject(...e){return n(this,void 0,void 0,(function*(){return de(J,{headers:this.authHeaders})(e[0])}))}deleteCalendarObject(...e){return n(this,void 0,void 0,(function*(){return de(K,{headers:this.authHeaders})(e[0])}))}syncCalendars(...e){return n(this,void 0,void 0,(function*(){return de(W,{headers:this.authHeaders,account:this.account})(e[0])}))}addressBookQuery(...e){return n(this,void 0,void 0,(function*(){return de(U,{headers:this.authHeaders})(e[0])}))}addressBookMultiGet(...e){return n(this,void 0,void 0,(function*(){return de(T,{headers:this.authHeaders})(e[0])}))}fetchAddressBooks(...e){return n(this,void 0,void 0,(function*(){return de(E,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchVCards(...e){return n(this,void 0,void 0,(function*(){return de(L,{headers:this.authHeaders})(e[0])}))}createVCard(...e){return n(this,void 0,void 0,(function*(){return de(P,{headers:this.authHeaders})(e[0])}))}updateVCard(...e){return n(this,void 0,void 0,(function*(){return de(H,{headers:this.authHeaders})(e[0])}))}deleteVCard(...e){return n(this,void 0,void 0,(function*(){return de(B,{headers:this.authHeaders})(e[0])}))}}var fe=Object.freeze({__proto__:null,DAVClient:ve,createDAVClient:he}),me=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({DAVNamespace:exports.DAVNamespace,DAVNamespaceShort:exports.DAVNamespaceShort,DAVAttributeMap:d},fe),b),_),se),M),X),pe),f);exports.DAVAttributeMap=d,exports.DAVClient=ve,exports.addressBookQuery=U,exports.calendarMultiGet=z,exports.calendarQuery=F,exports.cleanupFalsy=v,exports.collectionQuery=j,exports.createAccount=ae,exports.createCalendarObject=G,exports.createDAVClient=he,exports.createObject=y,exports.createVCard=P,exports.davRequest=A,exports.default=me,exports.deleteCalendarObject=K,exports.deleteObject=V,exports.deleteVCard=B,exports.fetchAddressBooks=E,exports.fetchCalendarObjects=Q,exports.fetchCalendars=q,exports.fetchOauthTokens=ce,exports.fetchVCards=L,exports.freeBusyQuery=Y,exports.getBasicAuthHeaders=ie,exports.getDAVAttribute=h,exports.getOauthHeaders=ue,exports.isCollectionDirty=$,exports.makeCalendar=Z,exports.propfind=D,exports.refreshAccessToken=le,exports.smartCollectionSync=w,exports.supportedReportSet=N,exports.syncCalendars=W,exports.syncCollection=k,exports.updateCalendarObject=J,exports.updateObject=g,exports.updateVCard=H,exports.urlContains=p,exports.urlEquals=u; +"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,t=require("cross-fetch"),r=require("debug"),o=require("xml-js"),a=require("base-64");function s(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(o=Object.getOwnPropertySymbols(e);a{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},u=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),o=t.trim();if(Math.abs(r.length-o.length)>1)return!1;const a="/"===r.slice(-1)?r.slice(0,-1):r,s="/"===o.slice(-1)?o.slice(0,-1):o;return e.includes(s)||t.includes(a)},p=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),o=t.trim(),a="/"===r.slice(-1)?r.slice(0,-1):r,s="/"===o.slice(-1)?o.slice(0,-1):o;return e.includes(s)||t.includes(a)},h=e=>e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[d[t]]:t})),{}),v=e=>Object.entries(e).reduce(((e,[t,r])=>r?Object.assign(Object.assign({},e),{[t]:r}):e),{}),f=(e,t)=>t?{[e]:t}:{};var m=Object.freeze({__proto__:null,cleanupFalsy:v,conditionalParam:f,getDAVAttribute:h,urlContains:p,urlEquals:u});const A=r("tsdav:request"),D=e=>n(void 0,void 0,void 0,(function*(){var r;const{url:a,init:s,convertIncoming:n=!0,parseOutgoing:d=!0}=e,{headers:i={},body:c,namespace:u,method:p,attributes:h}=s,f=n?o.js2xml(Object.assign(Object.assign({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},c),{_attributes:h}),{compact:!0,spaces:2,elementNameFn:e=>u&&!/^.+:.+/.test(e)?`${u}:${e}`:e}):c,m=yield t.fetch(a,{headers:Object.assign({"Content-Type":"text/xml;charset=UTF-8"},v(i)),body:f,method:p}),D=yield m.text();if(!m.ok||!(null===(r=m.headers.get("content-type"))||void 0===r?void 0:r.includes("xml"))||!d)return[{href:m.url,ok:m.ok,status:m.status,statusText:m.statusText,raw:D}];const g=o.xml2js(D,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,o=Object.keys(r),a=o[o.length-1],s=r[a];if(s.length>0){s[s.length-1]=l(e)}else r[a]=l(e)}catch(e){A(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,(e=>e[1].toUpperCase())),attributesFn:e=>{const t=Object.assign({},e);return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(g.multistatus.response)?g.multistatus.response:[g.multistatus.response]).map((e=>{var t,r;if(!e)return{status:m.status,statusText:m.statusText,ok:m.ok};const o=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:g,href:e.href,status:(null==o?void 0:o.groups)?Number.parseInt(null==o?void 0:o.groups.status,10):m.status,statusText:null!==(r=null===(t=null==o?void 0:o.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:m.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce(((e,t)=>Object.assign(Object.assign({},e),null==t?void 0:t.prop)),{})}}))})),g=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:a}=e;return D({url:t,init:{method:"PROPFIND",headers:v(Object.assign({depth:o},a)),namespace:exports.DAVNamespaceShort.DAV,body:{propfind:{_attributes:h([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),prop:r}}}})})),y=e=>n(void 0,void 0,void 0,(function*(){const{url:r,data:o,headers:a}=e;return t.fetch(r,{method:"PUT",body:o,headers:a})})),b=e=>n(void 0,void 0,void 0,(function*(){const{url:r,data:o,etag:a,headers:s}=e;return t.fetch(r,{method:"PUT",body:o,headers:v(Object.assign({"If-Match":a},s))})})),V=e=>n(void 0,void 0,void 0,(function*(){const{url:r,headers:o,etag:a}=e;return t.fetch(r,{method:"DELETE",headers:v(Object.assign({"If-Match":a},o))})}));var O=Object.freeze({__proto__:null,createObject:y,davRequest:D,deleteObject:V,propfind:g,updateObject:b});function x(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const C=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),j=r("tsdav:collection"),S=e=>n(void 0,void 0,void 0,(function*(){const{url:t,body:r,depth:o,defaultNamespace:a=exports.DAVNamespaceShort.DAV,headers:s}=e,n=yield D({url:t,init:{method:"REPORT",headers:v(Object.assign({depth:o},s)),namespace:a,body:r}});return 1!==n.length||n[0].raw?n:[]})),N=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:a}=e;return D({url:t,init:{method:"MKCOL",headers:v(Object.assign({depth:o},a)),namespace:exports.DAVNamespaceShort.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0}})})),k=e=>n(void 0,void 0,void 0,(function*(){var t,r,o,a,s;const{collection:n,headers:d}=e;return null!==(s=null===(a=null===(o=null===(r=null===(t=(yield g({url:n.url,props:{[`${exports.DAVNamespaceShort.DAV}:supported-report-set`]:{}},depth:"0",headers:d}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===o?void 0:o.supportedReport)||void 0===a?void 0:a.map((e=>Object.keys(e.report)[0])))&&void 0!==s?s:[]})),$=e=>n(void 0,void 0,void 0,(function*(){var t,r,o;const{collection:a,headers:s}=e,n=(yield g({url:a.url,props:{[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:s})).filter((e=>p(a.url,e.href)))[0];if(!n)throw new Error("Collection does not exist on server");return{isDirty:a.ctag!==(null===(t=n.props)||void 0===t?void 0:t.getctag),newCtag:null===(o=null===(r=n.props)||void 0===r?void 0:r.getctag)||void 0===o?void 0:o.toString()}})),w=e=>{const{url:t,props:r,headers:o,syncLevel:a,syncToken:s}=e;return D({url:t,init:{method:"REPORT",namespace:exports.DAVNamespaceShort.DAV,headers:Object.assign({},o),body:{"sync-collection":{_attributes:h([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),"sync-level":a,"sync-token":s,[`${exports.DAVNamespaceShort.DAV}:prop`]:r}}}})},_=e=>n(void 0,void 0,void 0,(function*(){var t,r,o,a,s,n,d,i,c,l,u;const{collection:h,method:v,headers:f,account:m,detailedResult:A}=e,D=["accountType","homeUrl"];if(!m||!x(m,D)){if(!m)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${C(m,D)} before smartCollectionSync`)}const g=null!=v?v:(null===(t=h.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(j(`smart collection sync with type ${m.accountType} and method ${g}`),"webdav"===g){const e=yield w({url:h.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${"caldav"===m.accountType?exports.DAVNamespaceShort.CALDAV:exports.DAVNamespaceShort.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{},[`${exports.DAVNamespaceShort.DAV}:displayname`]:{}},syncLevel:1,syncToken:h.syncToken,headers:f}),t=e.filter((e=>{var t;const r="caldav"===m.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r})),c=t.filter((e=>404!==e.status)).map((e=>e.href)),l=t.filter((e=>404===e.status)).map((e=>e.href)),u=(c.length&&null!==(o=yield null===(r=null==h?void 0:h.objectMultiGet)||void 0===r?void 0:r.call(h,{url:h.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${"caldav"===m.accountType?exports.DAVNamespaceShort.CALDAV:exports.DAVNamespaceShort.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:c,depth:"1",headers:f}))&&void 0!==o?o:[]).map((e=>{var t,r,o,a,s,n,d,i,c,l;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==m?void 0:m.accountType)?null!==(s=null===(a=null===(o=e.props)||void 0===o?void 0:o.calendarData)||void 0===a?void 0:a._cdata)&&void 0!==s?s:null===(n=e.props)||void 0===n?void 0:n.calendarData:null!==(c=null===(i=null===(d=e.props)||void 0===d?void 0:d.addressData)||void 0===i?void 0:i._cdata)&&void 0!==c?c:null===(l=e.props)||void 0===l?void 0:l.addressData}})),v=null!==(a=h.objects)&&void 0!==a?a:[],D=u.filter((e=>v.every((t=>!p(t.url,e.url))))),g=v.reduce(((e,t)=>{const r=u.find((e=>p(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),y=l.map((e=>({url:e,etag:""}))),b=v.filter((e=>u.some((t=>p(e.url,t.url)&&t.etag===e.etag))));return Object.assign(Object.assign({},h),{objects:A?{created:D,updated:g,deleted:y}:[...b,...D,...g],syncToken:null!==(i=null===(d=null===(n=null===(s=e[0])||void 0===s?void 0:s.raw)||void 0===n?void 0:n.multistatus)||void 0===d?void 0:d.syncToken)&&void 0!==i?i:h.syncToken})}if("basic"===g){const{isDirty:e,newCtag:t}=yield $({collection:h,headers:f}),r=null!==(c=h.objects)&&void 0!==c?c:[],o=null!==(u=yield null===(l=h.fetchObjects)||void 0===l?void 0:l.call(h,{collection:h,headers:f}))&&void 0!==u?u:[],a=o.filter((e=>r.every((t=>!p(t.url,e.url))))),s=r.reduce(((e,t)=>{const r=o.find((e=>p(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),n=r.filter((e=>o.every((t=>!p(t.url,e.url))))),d=r.filter((e=>o.some((t=>p(e.url,t.url)&&t.etag===e.etag))));if(e)return Object.assign(Object.assign({},h),{objects:A?{created:a,updated:s,deleted:n}:[...d,...a,...s],ctag:t})}return A?Object.assign(Object.assign({},h),{objects:{created:[],updated:[],deleted:[]}}):h}));var R=Object.freeze({__proto__:null,collectionQuery:S,isCollectionDirty:$,makeCollection:N,smartCollectionSync:_,supportedReportSet:k,syncCollection:w});const U=r("tsdav:addressBook"),E=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:o,depth:a,headers:s}=e;return S({url:t,body:{"addressbook-query":{_attributes:h([exports.DAVNamespace.CARDDAV,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:null!=o?o:{"prop-filter":{_attributes:{name:"FN"}}}}},defaultNamespace:exports.DAVNamespaceShort.CARDDAV,depth:a,headers:s})})),T=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:o,depth:a,headers:s}=e;return S({url:t,body:{"addressbook-multiget":{_attributes:h([exports.DAVNamespace.DAV,exports.DAVNamespace.CARDDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:o}},defaultNamespace:exports.DAVNamespaceShort.CARDDAV,depth:a,headers:s})})),L=e=>n(void 0,void 0,void 0,(function*(){const{account:t,headers:r,props:o}=null!=e?e:{},a=["homeUrl","rootUrl"];if(!t||!x(t,a)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${C(t,a)} before fetchAddressBooks`)}const s=yield g({url:t.homeUrl,props:null!=o?o:{[`${exports.DAVNamespaceShort.DAV}:displayname`]:{},[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{},[`${exports.DAVNamespaceShort.DAV}:resourcetype`]:{},[`${exports.DAVNamespaceShort.DAV}:sync-token`]:{}},depth:"1",headers:r});return Promise.all(s.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")})).map((e=>{var r,o,a,s,n,d,i,c,l;const u=null!==(a=null===(o=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===o?void 0:o._cdata)&&void 0!==a?a:null===(s=e.props)||void 0===s?void 0:s.displayname;return U(`Found address book named ${"string"==typeof u?u:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(n=e.href)&&void 0!==n?n:"",null!==(d=t.rootUrl)&&void 0!==d?d:"").href,ctag:null===(i=e.props)||void 0===i?void 0:i.getctag,displayName:"string"==typeof u?u:"",resourcetype:Object.keys(null===(c=e.props)||void 0===c?void 0:c.resourcetype),syncToken:null===(l=e.props)||void 0===l?void 0:l.syncToken}})).map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield k({collection:e,headers:r})})})))))})),P=e=>n(void 0,void 0,void 0,(function*(){const{addressBook:t,headers:r,objectUrls:o,urlFilter:a=(e=>e),useMultiGet:s=!0}=e;U(`Fetching vcards from ${null==t?void 0:t.url}`);const n=["url"];if(!t||!x(t,n)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${C(t,n)} before fetchVCards`)}const d=(null!=o?o:(yield E({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{}},depth:"1",headers:r})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(a).map((e=>new URL(e).pathname));let i=[];return d.length>0&&(i=s?yield T({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},objectUrls:d,depth:"1",headers:r}):yield E({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CARDDAV}:address-data`]:{}},depth:"1",headers:r})),i.map((e=>{var r,o,a,s,n,d;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(o=e.props)||void 0===o?void 0:o.getetag,data:null!==(n=null===(s=null===(a=e.props)||void 0===a?void 0:a.addressData)||void 0===s?void 0:s._cdata)&&void 0!==n?n:null===(d=e.props)||void 0===d?void 0:d.addressData}}))})),H=e=>n(void 0,void 0,void 0,(function*(){const{addressBook:t,vCardString:r,filename:o,headers:a}=e;return y({url:new URL(o,t.url).href,data:r,headers:Object.assign({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*"},a)})})),B=e=>n(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return b({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/vcard; charset=utf-8"},r)})})),I=e=>n(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return V({url:t.url,etag:t.etag,headers:r})}));var M=Object.freeze({__proto__:null,addressBookMultiGet:T,addressBookQuery:E,createVCard:H,deleteVCard:I,fetchAddressBooks:L,fetchVCards:P,updateVCard:B});const F=r("tsdav:calendar"),z=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:o,timezone:a,depth:s,headers:n}=e;return S({url:t,body:{"calendar-query":v({_attributes:h([exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALENDAR_SERVER,exports.DAVNamespace.CALDAV_APPLE,exports.DAVNamespace.DAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,filter:o,timezone:a})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:s,headers:n})})),Z=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:o,filters:a,timezone:s,depth:n,headers:d}=e;return S({url:t,body:{"calendar-multiget":Object.assign(Object.assign({_attributes:h([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.DAV}:prop`]:r,[`${exports.DAVNamespaceShort.DAV}:href`]:o},f("filter",a)),{timezone:s})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:n,headers:d})})),q=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:a}=e;return D({url:t,init:{method:"MKCALENDAR",headers:v(Object.assign({depth:o},a)),namespace:exports.DAVNamespaceShort.DAV,body:{[`${exports.DAVNamespaceShort.CALDAV}:mkcalendar`]:{_attributes:h([exports.DAVNamespace.DAV,exports.DAVNamespace.CALDAV,exports.DAVNamespace.CALDAV_APPLE]),set:{prop:r}}}}})})),Q=e=>n(void 0,void 0,void 0,(function*(){const{headers:t,account:r,props:o,projectedProps:a}=null!=e?e:{},s=["homeUrl","rootUrl"];if(!r||!x(r,s)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${C(r,s)} before fetchCalendars`)}const d=yield g({url:r.homeUrl,props:null!=o?o:{[`${exports.DAVNamespaceShort.CALDAV}:calendar-description`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-timezone`]:{},[`${exports.DAVNamespaceShort.DAV}:displayname`]:{},[`${exports.DAVNamespaceShort.CALDAV_APPLE}:calendar-color`]:{},[`${exports.DAVNamespaceShort.CALENDAR_SERVER}:getctag`]:{},[`${exports.DAVNamespaceShort.DAV}:resourcetype`]:{},[`${exports.DAVNamespaceShort.CALDAV}:supported-calendar-component-set`]:{},[`${exports.DAVNamespaceShort.DAV}:sync-token`]:{}},depth:"1",headers:t});return Promise.all(d.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")})).filter((e=>{var t,r,o;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(o=e.props)||void 0===o?void 0:o.supportedCalendarComponentSet.comp._attributes.name]||[]).some((e=>Object.values(c).includes(e)))})).map((e=>{var t,o,s,n,d,i,c,l,u,p,h,v,m,A,D;const g=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,y=null===(o=e.props)||void 0===o?void 0:o.calendarTimezone;return Object.assign({description:"string"==typeof g?g:"",timezone:"string"==typeof y?y:"",url:new URL(null!==(s=e.href)&&void 0!==s?s:"",null!==(n=r.rootUrl)&&void 0!==n?n:"").href,ctag:null===(d=e.props)||void 0===d?void 0:d.getctag,calendarColor:null===(i=e.props)||void 0===i?void 0:i.calendarColor,displayName:null!==(l=null===(c=e.props)||void 0===c?void 0:c.displayname._cdata)&&void 0!==l?l:null===(u=e.props)||void 0===u?void 0:u.displayname,components:Array.isArray(null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp)?null===(h=e.props)||void 0===h?void 0:h.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(v=e.props)||void 0===v?void 0:v.supportedCalendarComponentSet.comp._attributes.name],resourcetype:Object.keys(null===(m=e.props)||void 0===m?void 0:m.resourcetype),syncToken:null===(A=e.props)||void 0===A?void 0:A.syncToken},f("projectedProps",Object.fromEntries(Object.entries(null!==(D=e.props)&&void 0!==D?D:{}).filter((([e])=>null==a?void 0:a[e])))))})).map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield k({collection:e,headers:t})})})))))})),G=e=>n(void 0,void 0,void 0,(function*(){const{calendar:t,objectUrls:r,filters:o,timeRange:a,headers:s,expand:n,urlFilter:d=(e=>Boolean(null==e?void 0:e.includes(".ics"))),useMultiGet:i=!0}=e;if(a){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(a.start)&&e.test(a.end)||t.test(a.start)&&t.test(a.end)))throw new Error("invalid timeRange format, not in ISO8601")}F(`Fetching calendar objects from ${null==t?void 0:t.url}`);const c=["url"];if(!t||!x(t,c)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${C(t,c)} before fetchCalendarObjects`)}const l=null!=o?o:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":Object.assign({_attributes:{name:"VEVENT"}},a?{"time-range":{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})}}],u=(null!=r?r:(yield z({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:Object.assign({},n&&a?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:l,depth:"1",headers:s})).map((e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(d).map((e=>new URL(e).pathname));let p=[];return u.length>0&&(p=!i||n?yield z({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:Object.assign({},n&&a?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:l,depth:"1",headers:s}):yield Z({url:t.url,props:{[`${exports.DAVNamespaceShort.DAV}:getetag`]:{},[`${exports.DAVNamespaceShort.CALDAV}:calendar-data`]:Object.assign({},n&&a?{[`${exports.DAVNamespaceShort.CALDAV}:expand`]:{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},objectUrls:u,depth:"1",headers:s})),p.map((e=>{var r,o,a,s,n,d;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(o=e.props)||void 0===o?void 0:o.getetag}`,data:null!==(n=null===(s=null===(a=e.props)||void 0===a?void 0:a.calendarData)||void 0===s?void 0:s._cdata)&&void 0!==n?n:null===(d=e.props)||void 0===d?void 0:d.calendarData}}))})),J=e=>n(void 0,void 0,void 0,(function*(){const{calendar:t,iCalString:r,filename:o,headers:a}=e;return y({url:new URL(o,t.url).href,data:r,headers:Object.assign({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*"},a)})})),K=e=>n(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return b({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/calendar; charset=utf-8"},r)})})),W=e=>n(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return V({url:t.url,etag:t.etag,headers:r})})),Y=e=>n(void 0,void 0,void 0,(function*(){var t;const{oldCalendars:r,account:o,detailedResult:a,headers:s}=e;if(!o)throw new Error("Must have account before syncCalendars");const d=null!==(t=null!=r?r:o.calendars)&&void 0!==t?t:[],i=yield Q({account:o,headers:s}),c=i.filter((e=>d.every((t=>!p(t.url,e.url)))));F(`new calendars: ${c.map((e=>e.displayName))}`);const l=d.reduce(((e,t)=>{const r=i.find((e=>p(e.url,t.url)));return r&&(r.syncToken&&r.syncToken!==t.syncToken||r.ctag&&r.ctag!==t.ctag)?[...e,r]:e}),[]);F(`updated calendars: ${l.map((e=>e.displayName))}`);const u=yield Promise.all(l.map((e=>n(void 0,void 0,void 0,(function*(){return yield _({collection:Object.assign(Object.assign({},e),{objectMultiGet:Z}),method:"webdav",headers:s,account:o})}))))),h=d.filter((e=>i.every((t=>!p(t.url,e.url)))));F(`deleted calendars: ${h.map((e=>e.displayName))}`);const v=d.filter((e=>i.some((t=>p(t.url,e.url)&&(t.syncToken&&t.syncToken!==e.syncToken||t.ctag&&t.ctag!==e.ctag)))));return a?{created:c,updated:l,deleted:h}:[...v,...c,...u]})),X=e=>n(void 0,void 0,void 0,(function*(){const{url:t,timeRange:r,depth:o,headers:a}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(yield S({url:t,body:{"free-busy-query":v({_attributes:h([exports.DAVNamespace.CALDAV]),[`${exports.DAVNamespaceShort.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:exports.DAVNamespaceShort.CALDAV,depth:o,headers:a}))[0]}));var ee=Object.freeze({__proto__:null,calendarMultiGet:Z,calendarQuery:z,createCalendarObject:J,deleteCalendarObject:W,fetchCalendarObjects:G,fetchCalendars:Q,freeBusyQuery:X,makeCalendar:q,syncCalendars:Y,updateCalendarObject:K});const te=r("tsdav:account"),re=e=>n(void 0,void 0,void 0,(function*(){var r,o;te("Service discovery...");const{account:a,headers:s}=e,n=new URL(a.serverUrl),d=new URL(`/.well-known/${a.accountType}`,n);d.protocol=null!==(r=n.protocol)&&void 0!==r?r:"http";try{const e=yield t.fetch(d.href,{headers:s,method:"PROPFIND",redirect:"manual"});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){te(`Service discovery redirected to ${t}`);const e=new URL(t,n);return e.hostname===d.hostname&&d.port&&!e.port&&(e.port=d.port),e.protocol=null!==(o=n.protocol)&&void 0!==o?o:"http",e.href}}}catch(e){te(`Service discovery failed: ${e.stack}`)}return n.href})),oe=e=>n(void 0,void 0,void 0,(function*(){var t,r,o,a,s;const{account:n,headers:d}=e,i=["rootUrl"];if(!x(n,i))throw new Error(`account must have ${C(n,i)} before fetchPrincipalUrl`);te(`Fetching principal url from path ${n.rootUrl}`);const[c]=yield g({url:n.rootUrl,props:{[`${exports.DAVNamespaceShort.DAV}:current-user-principal`]:{}},depth:"0",headers:d});if(!c.ok&&(te(`Fetch principal url failed: ${c.statusText}`),401===c.status))throw new Error("Invalid credentials");return te(`Fetched principal url ${null===(r=null===(t=c.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(s=null===(a=null===(o=c.props)||void 0===o?void 0:o.currentUserPrincipal)||void 0===a?void 0:a.href)&&void 0!==s?s:"",n.rootUrl).href})),ae=e=>n(void 0,void 0,void 0,(function*(){var t,r;const{account:o,headers:a}=e,s=["principalUrl","rootUrl"];if(!x(o,s))throw new Error(`account must have ${C(o,s)} before fetchHomeUrl`);te(`Fetch home url from ${o.principalUrl}`);const n=(yield g({url:o.principalUrl,props:"caldav"===o.accountType?{[`${exports.DAVNamespaceShort.CALDAV}:calendar-home-set`]:{}}:{[`${exports.DAVNamespaceShort.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:a})).find((e=>p(o.principalUrl,e.href)));if(!n||!n.ok)throw new Error("cannot find homeUrl");const d=new URL("caldav"===o.accountType?null===(t=null==n?void 0:n.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==n?void 0:n.props)||void 0===r?void 0:r.addressbookHomeSet.href,o.rootUrl).href;return te(`Fetched home url ${d}`),d})),se=e=>n(void 0,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:o=!1,loadObjects:a=!1}=e,s=Object.assign({},t);return s.rootUrl=yield re({account:t,headers:r}),s.principalUrl=yield oe({account:s,headers:r}),s.homeUrl=yield ae({account:s,headers:r}),(o||a)&&("caldav"===t.accountType?s.calendars=yield Q({headers:r,account:s}):"carddav"===t.accountType&&(s.addressBooks=yield L({headers:r,account:s}))),a&&("caldav"===t.accountType&&s.calendars?s.calendars=yield Promise.all(s.calendars.map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield G({calendar:e,headers:r})})}))))):"carddav"===t.accountType&&s.addressBooks&&(s.addressBooks=yield Promise.all(s.addressBooks.map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield P({addressBook:e,headers:r})})}))))))),s}));var ne=Object.freeze({__proto__:null,createAccount:se,fetchHomeUrl:ae,fetchPrincipalUrl:oe,serviceDiscovery:re});const de=r("tsdav:authHelper"),ie=(e,t)=>(...r)=>e(Object.assign(Object.assign({},t),r[0])),ce=e=>(de(`Basic auth token generated: ${a.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${a.encode(`${e.username}:${e.password}`)}`}),le=e=>n(void 0,void 0,void 0,(function*(){const r=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!x(e,r))throw new Error(`Oauth credentials missing: ${C(e,r)}`);const o=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});de(e.tokenUrl),de(o.toString());const a=yield t.fetch(e.tokenUrl,{method:"POST",body:o.toString(),headers:{"content-length":`${o.toString().length}`,"content-type":"application/x-www-form-urlencoded"}});if(a.ok){return yield a.json()}return de(`Fetch Oauth tokens failed: ${yield a.text()}`),{}})),ue=e=>n(void 0,void 0,void 0,(function*(){const r=["refreshToken","clientId","clientSecret","tokenUrl"];if(!x(e,r))throw new Error(`Oauth credentials missing: ${C(e,r)}`);const o=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),a=yield t.fetch(e.tokenUrl,{method:"POST",body:o.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(a.ok){return yield a.json()}return de(`Refresh access token failed: ${yield a.text()}`),{}})),pe=e=>n(void 0,void 0,void 0,(function*(){var t;de("Fetching oauth headers");let r={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(t=e.expiration)&&void 0!==t?t:0))&&(r=yield ue(e)):r=yield le(e),de(`Oauth tokens fetched: ${r.access_token}`),{tokens:r,headers:{authorization:`Bearer ${r.access_token}`}}}));var he=Object.freeze({__proto__:null,defaultParam:ie,fetchOauthTokens:le,getBasicAuthHeaders:ce,getOauthHeaders:pe,refreshAccessToken:ue});const ve=e=>n(void 0,void 0,void 0,(function*(){var t;const{serverUrl:r,credentials:o,authMethod:a,defaultAccountType:d,authFunction:i}=e;let c={};switch(a){case"Basic":c=ce(o);break;case"Oauth":c=(yield pe(o)).headers;break;case"Digest":c={Authorization:`Digest ${o.digestString}`};break;case"Custom":c=null!==(t=yield null==i?void 0:i(o))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const l=d?yield se({account:{serverUrl:r,credentials:o,accountType:d},headers:c}):void 0,u=ie(y,{url:r,headers:c}),p=ie(b,{headers:c,url:r}),h=ie(V,{headers:c,url:r}),v=ie(g,{headers:c}),f=ie(S,{headers:c}),m=ie(N,{headers:c}),A=ie(w,{headers:c}),O=ie(k,{headers:c}),x=ie($,{headers:c}),C=ie(_,{headers:c,account:l}),j=ie(z,{headers:c}),R=ie(Z,{headers:c}),U=ie(q,{headers:c}),M=ie(Q,{headers:c,account:l}),F=ie(G,{headers:c}),X=ie(J,{headers:c}),ee=ie(K,{headers:c}),te=ie(W,{headers:c}),re=ie(Y,{account:l,headers:c}),oe=ie(E,{headers:c}),ae=ie(T,{headers:c});return{davRequest:e=>n(void 0,void 0,void 0,(function*(){const{init:t}=e,r=s(e,["init"]),{headers:o}=t,a=s(t,["headers"]);return D(Object.assign(Object.assign({},r),{init:Object.assign(Object.assign({},a),{headers:Object.assign(Object.assign({},c),o)})}))})),propfind:v,createAccount:e=>n(void 0,void 0,void 0,(function*(){const{account:t,headers:a,loadCollections:s,loadObjects:n}=e;return se({account:Object.assign({serverUrl:r,credentials:o},t),headers:Object.assign(Object.assign({},c),a),loadCollections:s,loadObjects:n})})),createObject:u,updateObject:p,deleteObject:h,calendarQuery:j,addressBookQuery:oe,collectionQuery:f,makeCollection:m,calendarMultiGet:R,makeCalendar:U,syncCollection:A,supportedReportSet:O,isCollectionDirty:x,smartCollectionSync:C,fetchCalendars:M,fetchCalendarObjects:F,createCalendarObject:X,updateCalendarObject:ee,deleteCalendarObject:te,syncCalendars:re,fetchAddressBooks:ie(L,{account:l,headers:c}),addressBookMultiGet:ae,fetchVCards:ie(P,{headers:c}),createVCard:ie(H,{headers:c}),updateVCard:ie(B,{headers:c}),deleteVCard:ie(I,{headers:c})}}));class fe{constructor(e){var t,r;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav"}login(){var e;return n(this,void 0,void 0,(function*(){switch(this.authMethod){case"Basic":this.authHeaders=ce(this.credentials);break;case"Oauth":this.authHeaders=(yield pe(this.credentials)).headers;break;case"Digest":this.authHeaders={Authorization:`Digest ${this.credentials.digestString}`};break;case"Custom":this.authHeaders=yield null===(e=this.authFunction)||void 0===e?void 0:e.call(this,this.credentials);break;default:throw new Error("Invalid auth method")}this.account=this.accountType?yield se({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders}):void 0}))}davRequest(e){return n(this,void 0,void 0,(function*(){const{init:t}=e,r=s(e,["init"]),{headers:o}=t,a=s(t,["headers"]);return D(Object.assign(Object.assign({},r),{init:Object.assign(Object.assign({},a),{headers:Object.assign(Object.assign({},this.authHeaders),o)})}))}))}createObject(...e){return n(this,void 0,void 0,(function*(){return ie(y,{url:this.serverUrl,headers:this.authHeaders})(e[0])}))}updateObject(...e){return n(this,void 0,void 0,(function*(){return ie(b,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}deleteObject(...e){return n(this,void 0,void 0,(function*(){return ie(V,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}propfind(...e){return n(this,void 0,void 0,(function*(){return ie(g,{headers:this.authHeaders})(e[0])}))}createAccount(e){return n(this,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:o,loadObjects:a}=e;return se({account:Object.assign({serverUrl:this.serverUrl,credentials:this.credentials},t),headers:Object.assign(Object.assign({},this.authHeaders),r),loadCollections:o,loadObjects:a})}))}collectionQuery(...e){return n(this,void 0,void 0,(function*(){return ie(S,{headers:this.authHeaders})(e[0])}))}makeCollection(...e){return n(this,void 0,void 0,(function*(){return ie(N,{headers:this.authHeaders})(e[0])}))}syncCollection(...e){return n(this,void 0,void 0,(function*(){return ie(w,{headers:this.authHeaders})(e[0])}))}supportedReportSet(...e){return n(this,void 0,void 0,(function*(){return ie(k,{headers:this.authHeaders})(e[0])}))}isCollectionDirty(...e){return n(this,void 0,void 0,(function*(){return ie($,{headers:this.authHeaders})(e[0])}))}smartCollectionSync(...e){return n(this,void 0,void 0,(function*(){return ie(_,{headers:this.authHeaders,account:this.account})(e[0])}))}calendarQuery(...e){return n(this,void 0,void 0,(function*(){return ie(z,{headers:this.authHeaders})(e[0])}))}makeCalendar(...e){return n(this,void 0,void 0,(function*(){return ie(q,{headers:this.authHeaders})(e[0])}))}calendarMultiGet(...e){return n(this,void 0,void 0,(function*(){return ie(Z,{headers:this.authHeaders})(e[0])}))}fetchCalendars(...e){return n(this,void 0,void 0,(function*(){return ie(Q,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchCalendarObjects(...e){return n(this,void 0,void 0,(function*(){return ie(G,{headers:this.authHeaders})(e[0])}))}createCalendarObject(...e){return n(this,void 0,void 0,(function*(){return ie(J,{headers:this.authHeaders})(e[0])}))}updateCalendarObject(...e){return n(this,void 0,void 0,(function*(){return ie(K,{headers:this.authHeaders})(e[0])}))}deleteCalendarObject(...e){return n(this,void 0,void 0,(function*(){return ie(W,{headers:this.authHeaders})(e[0])}))}syncCalendars(...e){return n(this,void 0,void 0,(function*(){return ie(Y,{headers:this.authHeaders,account:this.account})(e[0])}))}addressBookQuery(...e){return n(this,void 0,void 0,(function*(){return ie(E,{headers:this.authHeaders})(e[0])}))}addressBookMultiGet(...e){return n(this,void 0,void 0,(function*(){return ie(T,{headers:this.authHeaders})(e[0])}))}fetchAddressBooks(...e){return n(this,void 0,void 0,(function*(){return ie(L,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchVCards(...e){return n(this,void 0,void 0,(function*(){return ie(P,{headers:this.authHeaders})(e[0])}))}createVCard(...e){return n(this,void 0,void 0,(function*(){return ie(H,{headers:this.authHeaders})(e[0])}))}updateVCard(...e){return n(this,void 0,void 0,(function*(){return ie(B,{headers:this.authHeaders})(e[0])}))}deleteVCard(...e){return n(this,void 0,void 0,(function*(){return ie(I,{headers:this.authHeaders})(e[0])}))}}var me=Object.freeze({__proto__:null,DAVClient:fe,createDAVClient:ve}),Ae=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({DAVNamespace:exports.DAVNamespace,DAVNamespaceShort:exports.DAVNamespaceShort,DAVAttributeMap:d},me),O),R),ne),M),ee),he),m);exports.DAVAttributeMap=d,exports.DAVClient=fe,exports.addressBookQuery=E,exports.calendarMultiGet=Z,exports.calendarQuery=z,exports.cleanupFalsy=v,exports.collectionQuery=S,exports.createAccount=se,exports.createCalendarObject=J,exports.createDAVClient=ve,exports.createObject=y,exports.createVCard=H,exports.davRequest=D,exports.default=Ae,exports.deleteCalendarObject=W,exports.deleteObject=V,exports.deleteVCard=I,exports.fetchAddressBooks=L,exports.fetchCalendarObjects=G,exports.fetchCalendars=Q,exports.fetchOauthTokens=le,exports.fetchVCards=P,exports.freeBusyQuery=X,exports.getBasicAuthHeaders=ce,exports.getDAVAttribute=h,exports.getOauthHeaders=pe,exports.isCollectionDirty=$,exports.makeCalendar=q,exports.propfind=g,exports.refreshAccessToken=ue,exports.smartCollectionSync=_,exports.supportedReportSet=k,exports.syncCalendars=Y,exports.syncCollection=w,exports.updateCalendarObject=K,exports.updateObject=b,exports.updateVCard=B,exports.urlContains=p,exports.urlEquals=u; diff --git a/dist/tsdav.min.js b/dist/tsdav.min.js index b07fb9c..4c4e84c 100644 --- a/dist/tsdav.min.js +++ b/dist/tsdav.min.js @@ -1,2 +1,2 @@ -function e(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i-1};function c(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function l(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return n&&(t[Symbol.iterator]=function(){return t}),t}function h(e){this.map={},e instanceof h?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function f(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function p(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function g(e){var t=new FileReader,r=p(t);return t.readAsArrayBuffer(e),r}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():a&&i&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a&&(ArrayBuffer.prototype.isPrototypeOf(e)||u(e))?this._bodyArrayBuffer=y(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=f(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var e,t,r,n=f(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=p(t),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?t:e}(t.method||this.method||"GET"),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function w(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}})),t}function E(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})},v.call(b.prototype),v.call(E.prototype),E.prototype.clone=function(){return new E(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},E.error=function(){var e=new E(null,{status:0,statusText:""});return e.type="error",e};var A=[301,302,303,307,308];E.redirect=function(e,t){if(-1===A.indexOf(t))throw new RangeError("Invalid status code");return new E(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function T(e,r){return new Promise((function(n,o){var a=new b(e,r);if(a.signal&&a.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var s=new XMLHttpRequest;function u(){s.abort()}s.onload=function(){var e,t,r={status:s.status,statusText:s.statusText,headers:(e=s.getAllResponseHeaders()||"",t=new h,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}})),t)};r.url="responseURL"in s?s.responseURL:r.headers.get("X-Request-URL");var i="response"in s?s.response:s.responseText;n(new E(i,r))},s.onerror=function(){o(new TypeError("Network request failed"))},s.ontimeout=function(){o(new TypeError("Network request failed"))},s.onabort=function(){o(new t.DOMException("Aborted","AbortError"))},s.open(a.method,a.url,!0),"include"===a.credentials?s.withCredentials=!0:"omit"===a.credentials&&(s.withCredentials=!1),"responseType"in s&&i&&(s.responseType="blob"),a.headers.forEach((function(e,t){s.setRequestHeader(t,e)})),a.signal&&(a.signal.addEventListener("abort",u),s.onreadystatechange=function(){4===s.readyState&&a.signal.removeEventListener("abort",u)}),s.send(void 0===a._bodyInit?null:a._bodyInit)}))}T.polyfill=!0,e.fetch||(e.fetch=T,e.Headers=h,e.Request=b,e.Response=E),t.Headers=h,t.Request=b,t.Response=E,t.fetch=T,Object.defineProperty(t,"__esModule",{value:!0})}({})}(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var o=i;(t=o.fetch).default=o.fetch,t.fetch=o.fetch,t.Headers=o.Headers,t.Request=o.Request,t.Response=o.Response,e.exports=t}(o,o.exports);var a=o.exports,s="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function u(){throw new Error("setTimeout has not been defined")}function c(){throw new Error("clearTimeout has not been defined")}var l=u,d=c;function h(e){if(l===setTimeout)return setTimeout(e,0);if((l===u||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}"function"==typeof s.setTimeout&&(l=setTimeout),"function"==typeof s.clearTimeout&&(d=clearTimeout);var f,p=[],g=!1,y=-1;function v(){g&&f&&(g=!1,f.length?p=f.concat(p):y=-1,p.length&&m())}function m(){if(!g){var e=h(v);g=!0;for(var t=p.length;t;){for(f=p,p=[];++y1)for(var r=1;r=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return N=function(s,u){u=u||{};var c=typeof s;if("string"===c&&s.length>0)return function(a){if((a=String(a)).length>100)return;var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!s)return;var u=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return u*o;case"weeks":case"week":case"w":return u*i;case"days":case"day":case"d":return u*n;case"hours":case"hour":case"hrs":case"hr":case"h":return u*r;case"minutes":case"minute":case"mins":case"min":case"m":return u*t;case"seconds":case"second":case"secs":case"sec":case"s":return u*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return u;default:return}}(s);if("number"===c&&isFinite(s))return u.long?function(i){var o=Math.abs(i);if(o>=n)return a(i,o,n,"day");if(o>=r)return a(i,o,r,"hour");if(o>=t)return a(i,o,t,"minute");if(o>=e)return a(i,o,e,"second");return i+" ms"}(s):function(i){var o=Math.abs(i);if(o>=n)return Math.round(i/n)+"d";if(o>=r)return Math.round(i/r)+"h";if(o>=t)return Math.round(i/t)+"m";if(o>=e)return Math.round(i/e)+"s";return i+"ms"}(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))},N}var P=function(e){function t(e){let n,i,o,a=null;function s(...e){if(!s.enabled)return;const r=s,i=Number(new Date),o=i-(n||i);r.diff=o,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";a++;const o=t.formatters[i];if("function"==typeof o){const t=e[a];n=o.call(r,t),e.splice(a,1),a--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=r,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{a=e}}),"function"==typeof t.init&&t.init(s),s}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&void 0!==j&&"env"in j&&(e=j.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=P(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(I,I.exports);var U,B=n(I.exports);!function(e){e.CALENDAR_SERVER="http://calendarserver.org/ns/",e.CALDAV_APPLE="http://apple.com/ns/ical/",e.CALDAV="urn:ietf:params:xml:ns:caldav",e.CARDDAV="urn:ietf:params:xml:ns:carddav",e.DAV="DAV:"}(U||(U={}));const M={[U.CALDAV]:"xmlns:c",[U.CARDDAV]:"xmlns:card",[U.CALENDAR_SERVER]:"xmlns:cs",[U.CALDAV_APPLE]:"xmlns:ca",[U.DAV]:"xmlns:d"};var V,K;!function(e){e.CALDAV="c",e.CARDDAV="card",e.CALENDAR_SERVER="cs",e.CALDAV_APPLE="ca",e.DAV="d"}(V||(V={})),function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(K||(K={}));var $=[],Y=[],H="undefined"!=typeof Uint8Array?Uint8Array:Array,q=!1;function z(){q=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,r=e.length;t>18&63]+$[i>>12&63]+$[i>>6&63]+$[63&i]);return o.join("")}function W(e){var t;q||z();for(var r=e.length,n=r%3,i="",o=[],a=16383,s=0,u=r-n;su?u:s+a));return 1===n?(t=e[r-1],i+=$[t>>2],i+=$[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=$[t>>10],i+=$[t>>4&63],i+=$[t<<2&63],i+="="),o.push(i),o.join("")}function Q(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,l=-7,d=r?i-1:0,h=r?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-l)-1,f>>=-l,l+=s;l>0;o=256*o+e[t+d],d+=h,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+d],d+=h,l-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),o-=c}return(f?-1:1)*a*Math.pow(2,o-n)}function X(e,t,r,n,i,o){var a,s,u,c=8*o-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+d>=1?h/u:h*Math.pow(2,1-d))*u>=2&&(a++,u/=2),a+d>=l?(s=0,a=l):a+d>=1?(s=(t*u-1)*Math.pow(2,i),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;e[r+f]=255&s,f+=p,s/=256,i-=8);for(a=a<0;e[r+f]=255&a,f+=p,a/=256,c-=8);e[r+f-p]|=128*g}var Z={}.toString,J=Array.isArray||function(e){return"[object Array]"==Z.call(e)};function ee(){return re.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function te(e,t){if(ee()=ee())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ee().toString(16)+" bytes");return 0|e}function ue(e){return!(null==e||!e._isBuffer)}function ce(e,t){if(ue(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return Ie(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return ke(e).length;default:if(n)return Ie(e).length;t=(""+t).toLowerCase(),n=!0}}function le(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return _e(this,t,r);case"utf8":case"utf-8":return Ee(this,t,r);case"ascii":return Ae(this,t,r);case"latin1":case"binary":return Te(this,t,r);case"base64":return we(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ce(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function de(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function he(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=re.from(t,n)),ue(t))return 0===t.length?-1:fe(e,t,r,n,i);if("number"==typeof t)return t&=255,re.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):fe(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function fe(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var l=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var d=!0,h=0;hi&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function we(e,t,r){return 0===t&&r===e.length?W(e):W(e.slice(t,r))}function Ee(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+d<=r)switch(d){case 1:c<128&&(l=c);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(l=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&c)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(l=u)}null===l?(l=65533,d=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=d}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var r="",n=0;for(;n0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},re.prototype.compare=function(e,t,r,n,i){if(!ue(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),s=Math.min(o,a),u=this.slice(n,i),c=e.slice(t,r),l=0;li)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return pe(this,e,t,r);case"utf8":case"utf-8":return ge(this,e,t,r);case"ascii":return ye(this,e,t,r);case"latin1":case"binary":return ve(this,e,t,r);case"base64":return me(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return be(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},re.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ae(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function De(e,t,r,n,i,o){if(!ue(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function xe(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function Re(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function Fe(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Se(e,t,r,n,i){return i||Fe(e,0,r,4),X(e,t,r,n,23,4),r+4}function Ne(e,t,r,n,i){return i||Fe(e,0,r,8),X(e,t,r,n,52,8),r+8}re.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},re.prototype.readUInt8=function(e,t){return t||Oe(e,1,this.length),this[e]},re.prototype.readUInt16LE=function(e,t){return t||Oe(e,2,this.length),this[e]|this[e+1]<<8},re.prototype.readUInt16BE=function(e,t){return t||Oe(e,2,this.length),this[e]<<8|this[e+1]},re.prototype.readUInt32LE=function(e,t){return t||Oe(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},re.prototype.readUInt32BE=function(e,t){return t||Oe(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},re.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Oe(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},re.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Oe(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},re.prototype.readInt8=function(e,t){return t||Oe(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},re.prototype.readInt16LE=function(e,t){t||Oe(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},re.prototype.readInt16BE=function(e,t){t||Oe(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},re.prototype.readInt32LE=function(e,t){return t||Oe(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},re.prototype.readInt32BE=function(e,t){return t||Oe(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},re.prototype.readFloatLE=function(e,t){return t||Oe(e,4,this.length),Q(this,e,!0,23,4)},re.prototype.readFloatBE=function(e,t){return t||Oe(e,4,this.length),Q(this,e,!1,23,4)},re.prototype.readDoubleLE=function(e,t){return t||Oe(e,8,this.length),Q(this,e,!0,52,8)},re.prototype.readDoubleBE=function(e,t){return t||Oe(e,8,this.length),Q(this,e,!1,52,8)},re.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||De(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+r},re.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,1,255,0),re.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},re.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,2,65535,0),re.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):xe(this,e,t,!0),t+2},re.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,2,65535,0),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):xe(this,e,t,!1),t+2},re.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,4,4294967295,0),re.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Re(this,e,t,!0),t+4},re.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,4,4294967295,0),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Re(this,e,t,!1),t+4},re.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);De(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},re.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);De(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},re.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,1,127,-128),re.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},re.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,2,32767,-32768),re.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):xe(this,e,t,!0),t+2},re.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,2,32767,-32768),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):xe(this,e,t,!1),t+2},re.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,4,2147483647,-2147483648),re.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Re(this,e,t,!0),t+4},re.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Re(this,e,t,!1),t+4},re.prototype.writeFloatLE=function(e,t,r){return Se(this,e,t,!0,r)},re.prototype.writeFloatBE=function(e,t,r){return Se(this,e,t,!1,r)},re.prototype.writeDoubleLE=function(e,t,r){return Ne(this,e,t,!0,r)},re.prototype.writeDoubleBE=function(e,t,r){return Ne(this,e,t,!1,r)},re.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!re.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function ke(e){return function(e){var t,r,n,i,o,a;q||z();var s=e.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[s-2]?2:"="===e[s-1]?1:0,a=new H(3*s/4-o),n=o>0?s-4:s;var u=0;for(t=0,r=0;t>16&255,a[u++]=i>>8&255,a[u++]=255&i;return 2===o?(i=Y[e.charCodeAt(t)]<<2|Y[e.charCodeAt(t+1)]>>4,a[u++]=255&i):1===o&&(i=Y[e.charCodeAt(t)]<<10|Y[e.charCodeAt(t+1)]<<4|Y[e.charCodeAt(t+2)]>>2,a[u++]=i>>8&255,a[u++]=255&i),a}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(Le,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Pe(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function Ue(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}var Be={};function Me(){}function Ve(){Ve.init.call(this)}function Ke(e){return void 0===e._maxListeners?Ve.defaultMaxListeners:e._maxListeners}function $e(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Xe(e,n),o=0;o0&&a.length>i){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,s=u,"function"==typeof console.warn?console.warn(s):console.log(s)}}else a=o[t]=r,++e._eventsCount;return e}function We(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function Qe(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Xe(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Me.prototype=Object.create(null),Ve.EventEmitter=Ve,Ve.usingDomains=!1,Ve.prototype.domain=void 0,Ve.prototype._events=void 0,Ve.prototype._maxListeners=void 0,Ve.defaultMaxListeners=10,Ve.init=function(){this.domain=null,Ve.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Me,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Ve.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Ve.prototype.getMaxListeners=function(){return Ke(this)},Ve.prototype.emit=function(e){var t,r,n,i,o,a,s,u="error"===e;if(a=this._events)u=u&&null==a.error;else if(!u)return!1;if(s=this.domain,u){if(t=arguments[1],!s){if(t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=s,t.domainThrown=!1,s.emit("error",t),!1}if(!(r=a[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:$e(r,l,this);break;case 2:Ye(r,l,this,arguments[1]);break;case 3:He(r,l,this,arguments[1],arguments[2]);break;case 4:qe(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===t||r[o].listener&&r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new Me,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n0?Reflect.ownKeys(this._events):[]};var Ze="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e},Je=/%[sdj%]/g;function et(e){if(!ht(e)){for(var t=[],r=0;r=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}})),a=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),lt(t)?r.showHidden=t:t&&wt(r,t),ft(r.showHidden)&&(r.showHidden=!1),ft(r.depth)&&(r.depth=2),ft(r.colors)&&(r.colors=!1),ft(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=ot),st(r,e,r.depth)}function ot(e,t){var r=it.styles[t];return r?"["+it.colors[r][0]+"m"+e+"["+it.colors[r][1]+"m":e}function at(e,t){return e}function st(e,t,r){if(e.customInspect&&t&&mt(t.inspect)&&t.inspect!==it&&(!t.constructor||t.constructor.prototype!==t)){var n=t.inspect(r,e);return ht(n)||(n=st(e,n,r)),n}var i=function(e,t){if(ft(t))return e.stylize("undefined","undefined");if(ht(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(n=t,"number"==typeof n)return e.stylize(""+t,"number");var n;if(lt(t))return e.stylize(""+t,"boolean");if(dt(t))return e.stylize("null","null")}(e,t);if(i)return i;var o=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),vt(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return ut(t);if(0===o.length){if(mt(t)){var s=t.name?": "+t.name:"";return e.stylize("[Function"+s+"]","special")}if(pt(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(yt(t))return e.stylize(Date.prototype.toString.call(t),"date");if(vt(t))return ut(t)}var u,c,l="",d=!1,h=["{","}"];(u=t,Array.isArray(u)&&(d=!0,h=["[","]"]),mt(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return pt(t)&&(l=" "+RegExp.prototype.toString.call(t)),yt(t)&&(l=" "+Date.prototype.toUTCString.call(t)),vt(t)&&(l=" "+ut(t)),0!==o.length||d&&0!=t.length?r<0?pt(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),c=d?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,l,h)):h[0]+l+h[1]}function ut(e){return"["+Error.prototype.toString.call(e)+"]"}function ct(e,t,r,n,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),Et(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(u.value)<0?(s=dt(r)?st(e,u.value,null):st(e,u.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+s.split("\n").map((function(e){return" "+e})).join("\n")):s=e.stylize("[Circular]","special")),ft(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function lt(e){return"boolean"==typeof e}function dt(e){return null===e}function ht(e){return"string"==typeof e}function ft(e){return void 0===e}function pt(e){return gt(e)&&"[object RegExp]"===bt(e)}function gt(e){return"object"==typeof e&&null!==e}function yt(e){return gt(e)&&"[object Date]"===bt(e)}function vt(e){return gt(e)&&("[object Error]"===bt(e)||e instanceof Error)}function mt(e){return"function"==typeof e}function bt(e){return Object.prototype.toString.call(e)}function wt(e,t){if(!t||!gt(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}function Et(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function At(){this.head=null,this.tail=null,this.length=0}it.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},it.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},At.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},At.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},At.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},At.prototype.clear=function(){this.head=this.tail=null,this.length=0},At.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},At.prototype.concat=function(e){if(0===this.length)return re.alloc(0);if(1===this.length)return this.head.data;for(var t=re.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t};var Tt=re.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function _t(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),function(e){if(e&&!Tt(e))throw new Error("Unknown encoding: "+e)}(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Ot;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Dt;break;default:return void(this.write=Ct)}this.charBuffer=new re(6),this.charReceived=0,this.charLength=0}function Ct(e){return e.toString(this.encoding)}function Ot(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function Dt(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}_t.prototype.write=function(e){for(var t="";this.charLength;){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var n=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,n),n-=this.charReceived);var i;n=(t+=e.toString(this.encoding,0,n)).length-1;if((i=t.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,n)}return t},_t.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t},_t.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;t+=n.slice(0,r).toString(i)}return t};var xt=Object.freeze({__proto__:null,StringDecoder:_t});St.ReadableState=Ft;var Rt=function(e){if(ft(rt)&&(rt=j.env.NODE_DEBUG||""),e=e.toUpperCase(),!nt[e])if(new RegExp("\\b"+e+"\\b","i").test(rt)){nt[e]=function(){var t=et.apply(null,arguments);console.error("%s %d: %s",e,0,t)}}else nt[e]=function(){};return nt[e]}("stream");function Ft(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof ir&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new At,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(this.decoder=new _t(e.encoding),this.encoding=e.encoding)}function St(e){if(!(this instanceof St))return new St(e);this._readableState=new Ft(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),Ve.call(this)}function Nt(e,t,r,n,i){var o=function(e,t){var r=null;re.isBuffer(t)||"string"==typeof t||null==t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(t,r);if(o)e.emit("error",o);else if(null===r)t.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,jt(e)}(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||n||(r=t.decoder.write(r),u=!t.objectMode&&0===r.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&jt(e))),function(e,t){t.readingMore||(t.readingMore=!0,b(kt,e,t))}(e,t)}else i||(t.reading=!1);return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function jt(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(Rt("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?b(It,e):It(e))}function It(e){Rt("emit readable"),e.emit("readable"),Bt(e)}function kt(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=re.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),0===(e-=a)){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function Vt(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,b(Kt,t,e))}function Kt(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function $t(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return Rt("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?Vt(this):jt(this),null;if(0===(e=Lt(e,t))&&t.ended)return 0===t.length&&Vt(this),null;var n,i=t.needReadable;return Rt("need readable",i),(0===t.length||t.length-e0?Mt(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&Vt(this)),null!==n&&this.emit("data",n),n},St.prototype._read=function(e){this.emit("error",new Error("not implemented"))},St.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e)}n.pipesCount+=1,Rt("pipe count=%d opts=%j",n.pipesCount,t);var i=!t||!1!==t.end?a:c;function o(e){Rt("onunpipe"),e===r&&c()}function a(){Rt("onend"),e.end()}n.endEmitted?b(i):r.once("end",i),e.on("unpipe",o);var s=function(e){return function(){var t=e._readableState;Rt("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,Bt(e))}}(r);e.on("drain",s);var u=!1;function c(){Rt("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),e.removeListener("drain",s),e.removeListener("error",h),e.removeListener("unpipe",o),r.removeListener("end",a),r.removeListener("end",c),r.removeListener("data",d),u=!0,!n.awaitDrain||e._writableState&&!e._writableState.needDrain||s()}var l=!1;function d(t){Rt("ondata"),l=!1,!1!==e.write(t)||l||((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==$t(n.pipes,e))&&!u&&(Rt("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function h(t){var r;Rt("onerror",t),g(),e.removeListener("error",h),0===(r="error",e.listeners(r).length)&&e.emit("error",t)}function f(){e.removeListener("finish",p),g()}function p(){Rt("onfinish"),e.removeListener("close",f),g()}function g(){Rt("unpipe"),r.unpipe(e)}return r.on("data",d),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",h),e.once("close",f),e.once("finish",p),e.emit("pipe",r),n.flowing||(Rt("pipe resume"),r.resume()),e},St.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this)),this;if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},zt.prototype._write=function(e,t,r){r(new Error("not implemented"))},zt.prototype._writev=null,zt.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,Jt(e,t),r&&(t.finished?b(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Ze(ir,St);for(var tr=Object.keys(zt.prototype),rr=0;rr"===o?(_(n,"onsgmldeclaration",n.sgmlDecl),n.sgmlDecl="",n.state=E.TEXT):p(o)?(n.state=E.SGML_DECL_QUOTED,n.sgmlDecl+=o):n.sgmlDecl+=o;continue;case E.SGML_DECL_QUOTED:o===n.q&&(n.state=E.SGML_DECL,n.q=""),n.sgmlDecl+=o;continue;case E.DOCTYPE:">"===o?(n.state=E.TEXT,_(n,"ondoctype",n.doctype),n.doctype=!0):(n.doctype+=o,"["===o?n.state=E.DOCTYPE_DTD:p(o)&&(n.state=E.DOCTYPE_QUOTED,n.q=o));continue;case E.DOCTYPE_QUOTED:n.doctype+=o,o===n.q&&(n.q="",n.state=E.DOCTYPE);continue;case E.DOCTYPE_DTD:n.doctype+=o,"]"===o?n.state=E.DOCTYPE:p(o)&&(n.state=E.DOCTYPE_DTD_QUOTED,n.q=o);continue;case E.DOCTYPE_DTD_QUOTED:n.doctype+=o,o===n.q&&(n.state=E.DOCTYPE_DTD,n.q="");continue;case E.COMMENT:"-"===o?n.state=E.COMMENT_ENDING:n.comment+=o;continue;case E.COMMENT_ENDING:"-"===o?(n.state=E.COMMENT_ENDED,n.comment=O(n.opt,n.comment),n.comment&&_(n,"oncomment",n.comment),n.comment=""):(n.comment+="-"+o,n.state=E.COMMENT);continue;case E.COMMENT_ENDED:">"!==o?(R(n,"Malformed comment"),n.comment+="--"+o,n.state=E.COMMENT):n.state=E.TEXT;continue;case E.CDATA:"]"===o?n.state=E.CDATA_ENDING:n.cdata+=o;continue;case E.CDATA_ENDING:"]"===o?n.state=E.CDATA_ENDING_2:(n.cdata+="]"+o,n.state=E.CDATA);continue;case E.CDATA_ENDING_2:">"===o?(n.cdata&&_(n,"oncdata",n.cdata),_(n,"onclosecdata"),n.cdata="",n.state=E.TEXT):"]"===o?n.cdata+="]":(n.cdata+="]]"+o,n.state=E.CDATA);continue;case E.PROC_INST:"?"===o?n.state=E.PROC_INST_ENDING:f(o)?n.state=E.PROC_INST_BODY:n.procInstName+=o;continue;case E.PROC_INST_BODY:if(!n.procInstBody&&f(o))continue;"?"===o?n.state=E.PROC_INST_ENDING:n.procInstBody+=o;continue;case E.PROC_INST_ENDING:">"===o?(_(n,"onprocessinginstruction",{name:n.procInstName,body:n.procInstBody}),n.procInstName=n.procInstBody="",n.state=E.TEXT):(n.procInstBody+="?"+o,n.state=E.PROC_INST_BODY);continue;case E.OPEN_TAG:y(l,o)?n.tagName+=o:(F(n),">"===o?L(n):"/"===o?n.state=E.OPEN_TAG_SLASH:(f(o)||R(n,"Invalid character in tag name"),n.state=E.ATTRIB));continue;case E.OPEN_TAG_SLASH:">"===o?(L(n,!0),j(n)):(R(n,"Forward-slash in opening tag not followed by >"),n.state=E.ATTRIB);continue;case E.ATTRIB:if(f(o))continue;">"===o?L(n):"/"===o?n.state=E.OPEN_TAG_SLASH:y(c,o)?(n.attribName=o,n.attribValue="",n.state=E.ATTRIB_NAME):R(n,"Invalid attribute name");continue;case E.ATTRIB_NAME:"="===o?n.state=E.ATTRIB_VALUE:">"===o?(R(n,"Attribute without value"),n.attribValue=n.attribName,N(n),L(n)):f(o)?n.state=E.ATTRIB_NAME_SAW_WHITE:y(l,o)?n.attribName+=o:R(n,"Invalid attribute name");continue;case E.ATTRIB_NAME_SAW_WHITE:if("="===o)n.state=E.ATTRIB_VALUE;else{if(f(o))continue;R(n,"Attribute without value"),n.tag.attributes[n.attribName]="",n.attribValue="",_(n,"onattribute",{name:n.attribName,value:""}),n.attribName="",">"===o?L(n):y(c,o)?(n.attribName=o,n.state=E.ATTRIB_NAME):(R(n,"Invalid attribute name"),n.state=E.ATTRIB)}continue;case E.ATTRIB_VALUE:if(f(o))continue;p(o)?(n.q=o,n.state=E.ATTRIB_VALUE_QUOTED):(R(n,"Unquoted attribute value"),n.state=E.ATTRIB_VALUE_UNQUOTED,n.attribValue=o);continue;case E.ATTRIB_VALUE_QUOTED:if(o!==n.q){"&"===o?n.state=E.ATTRIB_VALUE_ENTITY_Q:n.attribValue+=o;continue}N(n),n.q="",n.state=E.ATTRIB_VALUE_CLOSED;continue;case E.ATTRIB_VALUE_CLOSED:f(o)?n.state=E.ATTRIB:">"===o?L(n):"/"===o?n.state=E.OPEN_TAG_SLASH:y(c,o)?(R(n,"No whitespace between attributes"),n.attribName=o,n.attribValue="",n.state=E.ATTRIB_NAME):R(n,"Invalid attribute name");continue;case E.ATTRIB_VALUE_UNQUOTED:if(!g(o)){"&"===o?n.state=E.ATTRIB_VALUE_ENTITY_U:n.attribValue+=o;continue}N(n),">"===o?L(n):n.state=E.ATTRIB;continue;case E.CLOSE_TAG:if(n.tagName)">"===o?j(n):y(l,o)?n.tagName+=o:n.script?(n.script+=""===o?j(n):R(n,"Invalid characters in closing tag");continue;case E.TEXT_ENTITY:case E.ATTRIB_VALUE_ENTITY_Q:case E.ATTRIB_VALUE_ENTITY_U:var u,m;switch(n.state){case E.TEXT_ENTITY:u=E.TEXT,m="textNode";break;case E.ATTRIB_VALUE_ENTITY_Q:u=E.ATTRIB_VALUE_QUOTED,m="attribValue";break;case E.ATTRIB_VALUE_ENTITY_U:u=E.ATTRIB_VALUE_UNQUOTED,m="attribValue"}";"===o?(n[m]+=I(n),n.entity="",n.state=u):y(n.entity.length?h:d,o)?n.entity+=o:(R(n,"Invalid character in entity name"),n[m]+="&"+n.entity+o,n.entity="",n.state=u);continue;default:throw new Error(n,"Unknown state: "+n.state)}return n.position>=n.bufferCheckPosition&&function(t){for(var n=Math.max(e.MAX_BUFFER_LENGTH,10),i=0,o=0,a=r.length;on)switch(r[o]){case"textNode":C(t);break;case"cdata":_(t,"oncdata",t.cdata),t.cdata="";break;case"script":_(t,"onscript",t.script),t.script="";break;default:D(t,"Max buffer length exceeded: "+r[o])}i=Math.max(i,s)}var u=e.MAX_BUFFER_LENGTH-i;t.bufferCheckPosition=u+t.position}(n),n} -/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){var e;C(e=this),""!==e.cdata&&(_(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(_(e,"onscript",e.script),e.script="")}};try{t=hr.Stream}catch(e){t=function(){}}var i=e.EVENTS.filter((function(e){return"error"!==e&&"end"!==e}));function o(e,r){if(!(this instanceof o))return new o(e,r);t.apply(this),this._parser=new n(e,r),this.writable=!0,this.readable=!0;var a=this;this._parser.onend=function(){a.emit("end")},this._parser.onerror=function(e){a.emit("error",e),a._parser.error=null},this._decoder=null,i.forEach((function(e){Object.defineProperty(a,"on"+e,{get:function(){return a._parser["on"+e]},set:function(t){if(!t)return a.removeAllListeners(e),a._parser["on"+e]=t,t;a.on(e,t)},enumerable:!0,configurable:!1})}))}o.prototype=Object.create(t.prototype,{constructor:{value:o}}),o.prototype.write=function(e){if("function"==typeof re.isBuffer&&re.isBuffer(e)){if(!this._decoder){var t=fr.StringDecoder;this._decoder=new t("utf8")}e=this._decoder.write(e)}return this._parser.write(e.toString()),this.emit("data",e),!0},o.prototype.end=function(e){return e&&e.length&&this.write(e),this._parser.end(),!0},o.prototype.on=function(e,r){var n=this;return n._parser["on"+e]||-1===i.indexOf(e)||(n._parser["on"+e]=function(){var t=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),n.emit.apply(n,t)}),t.prototype.on.call(n,e,r)};var a="http://www.w3.org/XML/1998/namespace",s="http://www.w3.org/2000/xmlns/",u={xml:a,xmlns:s},c=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,l=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,d=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,h=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function f(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function p(e){return'"'===e||"'"===e}function g(e){return">"===e||f(e)}function y(e,t){return e.test(t)}function v(e,t){return!y(e,t)}var m,b,w,E=0;for(var A in e.STATE={BEGIN:E++,BEGIN_WHITESPACE:E++,TEXT:E++,TEXT_ENTITY:E++,OPEN_WAKA:E++,SGML_DECL:E++,SGML_DECL_QUOTED:E++,DOCTYPE:E++,DOCTYPE_QUOTED:E++,DOCTYPE_DTD:E++,DOCTYPE_DTD_QUOTED:E++,COMMENT_STARTING:E++,COMMENT:E++,COMMENT_ENDING:E++,COMMENT_ENDED:E++,CDATA:E++,CDATA_ENDING:E++,CDATA_ENDING_2:E++,PROC_INST:E++,PROC_INST_BODY:E++,PROC_INST_ENDING:E++,OPEN_TAG:E++,OPEN_TAG_SLASH:E++,ATTRIB:E++,ATTRIB_NAME:E++,ATTRIB_NAME_SAW_WHITE:E++,ATTRIB_VALUE:E++,ATTRIB_VALUE_QUOTED:E++,ATTRIB_VALUE_CLOSED:E++,ATTRIB_VALUE_UNQUOTED:E++,ATTRIB_VALUE_ENTITY_Q:E++,ATTRIB_VALUE_ENTITY_U:E++,CLOSE_TAG:E++,CLOSE_TAG_SAW_WHITE:E++,SCRIPT:E++,SCRIPT_ENDING:E++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach((function(t){var r=e.ENTITIES[t],n="number"==typeof r?String.fromCharCode(r):r;e.ENTITIES[t]=n})),e.STATE)e.STATE[e.STATE[A]]=A;function T(e,t,r){e[t]&&e[t](r)}function _(e,t,r){e.textNode&&C(e),T(e,t,r)}function C(e){e.textNode=O(e.opt,e.textNode),e.textNode&&T(e,"ontext",e.textNode),e.textNode=""}function O(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g," ")),t}function D(e,t){return C(e),e.trackPosition&&(t+="\nLine: "+e.line+"\nColumn: "+e.column+"\nChar: "+e.c),t=new Error(t),e.error=t,T(e,"onerror",t),e}function x(e){return e.sawRoot&&!e.closedRoot&&R(e,"Unclosed root tag"),e.state!==E.BEGIN&&e.state!==E.BEGIN_WHITESPACE&&e.state!==E.TEXT&&D(e,"Unexpected end"),C(e),e.c="",e.closed=!0,T(e,"onend"),n.call(e,e.strict,e.opt),e}function R(e,t){if("object"!=typeof e||!(e instanceof n))throw new Error("bad call to strictFail");e.strict&&D(e,t)}function F(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,r=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(r.ns=t.ns),e.attribList.length=0,_(e,"onopentagstart",r)}function S(e,t){var r=e.indexOf(":")<0?["",e]:e.split(":"),n=r[0],i=r[1];return t&&"xmlns"===e&&(n="xmlns",i=""),{prefix:n,local:i}}function N(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),-1!==e.attribList.indexOf(e.attribName)||e.tag.attributes.hasOwnProperty(e.attribName))e.attribName=e.attribValue="";else{if(e.opt.xmlns){var t=S(e.attribName,!0),r=t.prefix,n=t.local;if("xmlns"===r)if("xml"===n&&e.attribValue!==a)R(e,"xml: prefix must be bound to "+a+"\nActual: "+e.attribValue);else if("xmlns"===n&&e.attribValue!==s)R(e,"xmlns: prefix must be bound to "+s+"\nActual: "+e.attribValue);else{var i=e.tag,o=e.tags[e.tags.length-1]||e;i.ns===o.ns&&(i.ns=Object.create(o.ns)),i.ns[n]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,_(e,"onattribute",{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=""}}function L(e,t){if(e.opt.xmlns){var r=e.tag,n=S(e.tagName);r.prefix=n.prefix,r.local=n.local,r.uri=r.ns[n.prefix]||"",r.prefix&&!r.uri&&(R(e,"Unbound namespace prefix: "+JSON.stringify(e.tagName)),r.uri=n.prefix);var i=e.tags[e.tags.length-1]||e;r.ns&&i.ns!==r.ns&&Object.keys(r.ns).forEach((function(t){_(e,"onopennamespace",{prefix:t,uri:r.ns[t]})}));for(var o=0,a=e.attribList.length;o",e.tagName="",void(e.state=E.SCRIPT);_(e,"onscript",e.script),e.script=""}var t=e.tags.length,r=e.tagName;e.strict||(r=r[e.looseCase]());for(var n=r;t--&&e.tags[t].name!==n;)R(e,"Unexpected close tag");if(t<0)return R(e,"Unmatched closing tag: "+e.tagName),e.textNode+="",void(e.state=E.TEXT);e.tagName=r;for(var i=e.tags.length;i-- >t;){var o=e.tag=e.tags.pop();e.tagName=e.tag.name,_(e,"onclosetag",e.tagName);var a={};for(var s in o.ns)a[s]=o.ns[s];var u=e.tags[e.tags.length-1]||e;e.opt.xmlns&&o.ns!==u.ns&&Object.keys(o.ns).forEach((function(t){var r=o.ns[t];_(e,"onclosenamespace",{prefix:t,uri:r})}))}0===t&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName="",e.attribList.length=0,e.state=E.TEXT}function I(e){var t,r=e.entity,n=r.toLowerCase(),i="";return e.ENTITIES[r]?e.ENTITIES[r]:e.ENTITIES[n]?e.ENTITIES[n]:("#"===(r=n).charAt(0)&&("x"===r.charAt(1)?(r=r.slice(2),i=(t=parseInt(r,16)).toString(16)):(r=r.slice(1),i=(t=parseInt(r,10)).toString(10))),r=r.replace(/^0+/,""),isNaN(t)||i.toLowerCase()!==r?(R(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function k(e,t){"<"===t?(e.state=E.OPEN_WAKA,e.startTagPosition=e.position):f(t)||(R(e,"Non-whitespace before first tag."),e.textNode=t,e.state=E.TEXT)}function P(e,t){var r="";return t1114111||b(s)!==s)throw RangeError("Invalid code point: "+s);s<=65535?n.push(s):(e=55296+((s-=65536)>>10),t=s%1024+56320,n.push(e,t)),(i+1===o||n.length>r)&&(a+=m.apply(null,n),n.length=0)}return a},Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:w,configurable:!0,writable:!0}):String.fromCodePoint=w)}(Be);var pr,gr,yr=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)},vr=yr,mr={copyOptions:function(e){var t,r={};for(t in e)e.hasOwnProperty(t)&&(r[t]=e[t]);return r},ensureFlagExists:function(e,t){e in t&&"boolean"==typeof t[e]||(t[e]=!1)},ensureSpacesExists:function(e){(!("spaces"in e)||"number"!=typeof e.spaces&&"string"!=typeof e.spaces)&&(e.spaces=0)},ensureAlwaysArrayExists:function(e){"alwaysArray"in e&&("boolean"==typeof e.alwaysArray||vr(e.alwaysArray))||(e.alwaysArray=!1)},ensureKeyExists:function(e,t){e+"Key"in t&&"string"==typeof t[e+"Key"]||(t[e+"Key"]=t.compact?"_"+e:e)},checkFnExists:function(e,t){return e+"Fn"in t}},br=Be,wr=mr,Er=yr;function Ar(e){var t=Number(e);if(!isNaN(t))return t;var r=e.toLowerCase();return"true"===r||"false"!==r&&e}function Tr(e,t){var r;if(pr.compact){if(!gr[pr[e+"Key"]]&&(Er(pr.alwaysArray)?-1!==pr.alwaysArray.indexOf(pr[e+"Key"]):pr.alwaysArray)&&(gr[pr[e+"Key"]]=[]),gr[pr[e+"Key"]]&&!Er(gr[pr[e+"Key"]])&&(gr[pr[e+"Key"]]=[gr[pr[e+"Key"]]]),e+"Fn"in pr&&"string"==typeof t&&(t=pr[e+"Fn"](t,gr)),"instruction"===e&&("instructionFn"in pr||"instructionNameFn"in pr))for(r in t)if(t.hasOwnProperty(r))if("instructionFn"in pr)t[r]=pr.instructionFn(t[r],r,gr);else{var n=t[r];delete t[r],t[pr.instructionNameFn(r,n,gr)]=n}Er(gr[pr[e+"Key"]])?gr[pr[e+"Key"]].push(t):gr[pr[e+"Key"]]=t}else{gr[pr.elementsKey]||(gr[pr.elementsKey]=[]);var i={};if(i[pr.typeKey]=e,"instruction"===e){for(r in t)if(t.hasOwnProperty(r))break;i[pr.nameKey]="instructionNameFn"in pr?pr.instructionNameFn(r,t,gr):r,pr.instructionHasAttributes?(i[pr.attributesKey]=t[r][pr.attributesKey],"instructionFn"in pr&&(i[pr.attributesKey]=pr.instructionFn(i[pr.attributesKey],r,gr))):("instructionFn"in pr&&(t[r]=pr.instructionFn(t[r],r,gr)),i[pr.instructionKey]=t[r])}else e+"Fn"in pr&&(t=pr[e+"Fn"](t,gr)),i[pr[e+"Key"]]=t;pr.addParent&&(i[pr.parentKey]=gr),gr[pr.elementsKey].push(i)}}function _r(e){var t;if("attributesFn"in pr&&e&&(e=pr.attributesFn(e,gr)),(pr.trim||"attributeValueFn"in pr||"attributeNameFn"in pr||pr.nativeTypeAttributes)&&e)for(t in e)if(e.hasOwnProperty(t)&&(pr.trim&&(e[t]=e[t].trim()),pr.nativeTypeAttributes&&(e[t]=Ar(e[t])),"attributeValueFn"in pr&&(e[t]=pr.attributeValueFn(e[t],t,gr)),"attributeNameFn"in pr)){var r=e[t];delete e[t],e[pr.attributeNameFn(t,e[t],gr)]=r}return e}function Cr(e){var t={};if(e.body&&("xml"===e.name.toLowerCase()||pr.instructionHasAttributes)){for(var r,n=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g;null!==(r=n.exec(e.body));)t[r[1]]=r[2]||r[3]||r[4];t=_r(t)}if("xml"===e.name.toLowerCase()){if(pr.ignoreDeclaration)return;gr[pr.declarationKey]={},Object.keys(t).length&&(gr[pr.declarationKey][pr.attributesKey]=t),pr.addParent&&(gr[pr.declarationKey][pr.parentKey]=gr)}else{if(pr.ignoreInstruction)return;pr.trim&&(e.body=e.body.trim());var i={};pr.instructionHasAttributes&&Object.keys(t).length?(i[e.name]={},i[e.name][pr.attributesKey]=t):i[e.name]=e.body,Tr("instruction",i)}}function Or(e,t){var r;if("object"==typeof e&&(t=e.attributes,e=e.name),t=_r(t),"elementNameFn"in pr&&(e=pr.elementNameFn(e,gr)),pr.compact){var n;if(r={},!pr.ignoreAttributes&&t&&Object.keys(t).length)for(n in r[pr.attributesKey]={},t)t.hasOwnProperty(n)&&(r[pr.attributesKey][n]=t[n]);!(e in gr)&&(Er(pr.alwaysArray)?-1!==pr.alwaysArray.indexOf(e):pr.alwaysArray)&&(gr[e]=[]),gr[e]&&!Er(gr[e])&&(gr[e]=[gr[e]]),Er(gr[e])?gr[e].push(r):gr[e]=r}else gr[pr.elementsKey]||(gr[pr.elementsKey]=[]),(r={})[pr.typeKey]="element",r[pr.nameKey]=e,!pr.ignoreAttributes&&t&&Object.keys(t).length&&(r[pr.attributesKey]=t),pr.alwaysChildren&&(r[pr.elementsKey]=[]),gr[pr.elementsKey].push(r);r[pr.parentKey]=gr,gr=r}function Dr(e){pr.ignoreText||(e.trim()||pr.captureSpacesBetweenElements)&&(pr.trim&&(e=e.trim()),pr.nativeType&&(e=Ar(e)),pr.sanitize&&(e=e.replace(/&/g,"&").replace(//g,">")),Tr("text",e))}function xr(e){pr.ignoreComment||(pr.trim&&(e=e.trim()),Tr("comment",e))}function Rr(e){var t=gr[pr.parentKey];pr.addParent||delete gr[pr.parentKey],gr=t}function Fr(e){pr.ignoreCdata||(pr.trim&&(e=e.trim()),Tr("cdata",e))}function Sr(e){pr.ignoreDoctype||(e=e.replace(/^ /,""),pr.trim&&(e=e.trim()),Tr("doctype",e))}function Nr(e){e.note=e}var Lr=function(e,t){var r=br.parser(!0,{}),n={};if(gr=n,pr=function(e){return pr=wr.copyOptions(e),wr.ensureFlagExists("ignoreDeclaration",pr),wr.ensureFlagExists("ignoreInstruction",pr),wr.ensureFlagExists("ignoreAttributes",pr),wr.ensureFlagExists("ignoreText",pr),wr.ensureFlagExists("ignoreComment",pr),wr.ensureFlagExists("ignoreCdata",pr),wr.ensureFlagExists("ignoreDoctype",pr),wr.ensureFlagExists("compact",pr),wr.ensureFlagExists("alwaysChildren",pr),wr.ensureFlagExists("addParent",pr),wr.ensureFlagExists("trim",pr),wr.ensureFlagExists("nativeType",pr),wr.ensureFlagExists("nativeTypeAttributes",pr),wr.ensureFlagExists("sanitize",pr),wr.ensureFlagExists("instructionHasAttributes",pr),wr.ensureFlagExists("captureSpacesBetweenElements",pr),wr.ensureAlwaysArrayExists(pr),wr.ensureKeyExists("declaration",pr),wr.ensureKeyExists("instruction",pr),wr.ensureKeyExists("attributes",pr),wr.ensureKeyExists("text",pr),wr.ensureKeyExists("comment",pr),wr.ensureKeyExists("cdata",pr),wr.ensureKeyExists("doctype",pr),wr.ensureKeyExists("type",pr),wr.ensureKeyExists("name",pr),wr.ensureKeyExists("elements",pr),wr.ensureKeyExists("parent",pr),wr.checkFnExists("doctype",pr),wr.checkFnExists("instruction",pr),wr.checkFnExists("cdata",pr),wr.checkFnExists("comment",pr),wr.checkFnExists("text",pr),wr.checkFnExists("instructionName",pr),wr.checkFnExists("elementName",pr),wr.checkFnExists("attributeName",pr),wr.checkFnExists("attributeValue",pr),wr.checkFnExists("attributes",pr),pr}(t),r.opt={strictEntities:!0},r.onopentag=Or,r.ontext=Dr,r.oncomment=xr,r.onclosetag=Rr,r.onerror=Nr,r.oncdata=Fr,r.ondoctype=Sr,r.onprocessinginstruction=Cr,r.write(e).close(),n[pr.elementsKey]){var i=n[pr.elementsKey];delete n[pr.elementsKey],n[pr.elementsKey]=i,delete n.text}return n},jr=mr,Ir=Lr;var kr,Pr,Ur=mr,Br=yr;function Mr(e,t,r){return(!r&&e.spaces?"\n":"")+Array(t+1).join(e.spaces)}function Vr(e,t,r){if(t.ignoreAttributes)return"";"attributesFn"in t&&(e=t.attributesFn(e,Pr,kr));var n,i,o,a,s=[];for(n in e)e.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]&&(a=t.noQuotesForNativeAttributes&&"string"!=typeof e[n]?"":'"',i=(i=""+e[n]).replace(/"/g,"""),o="attributeNameFn"in t?t.attributeNameFn(n,i,Pr,kr):n,s.push(t.spaces&&t.indentAttributes?Mr(t,r+1,!1):" "),s.push(o+"="+a+("attributeValueFn"in t?t.attributeValueFn(i,n,Pr,kr):i)+a));return e&&Object.keys(e).length&&t.spaces&&t.indentAttributes&&s.push(Mr(t,r,!1)),s.join("")}function Kr(e,t,r){return kr=e,Pr="xml",t.ignoreDeclaration?"":""}function $r(e,t,r){if(t.ignoreInstruction)return"";var n;for(n in e)if(e.hasOwnProperty(n))break;var i="instructionNameFn"in t?t.instructionNameFn(n,e[n],Pr,kr):n;if("object"==typeof e[n])return kr=e,Pr=i,"";var o=e[n]?e[n]:"";return"instructionFn"in t&&(o=t.instructionFn(o,n,Pr,kr)),""}function Yr(e,t){return t.ignoreComment?"":"\x3c!--"+("commentFn"in t?t.commentFn(e,Pr,kr):e)+"--\x3e"}function Hr(e,t){return t.ignoreCdata?"":"","]]]]>"))+"]]>"}function qr(e,t){return t.ignoreDoctype?"":""}function zr(e,t){return t.ignoreText?"":(e=(e=(e=""+e).replace(/&/g,"&")).replace(/&/g,"&").replace(//g,">"),"textFn"in t?t.textFn(e,Pr,kr):e)}function Gr(e,t,r,n){return e.reduce((function(e,i){var o=Mr(t,r,n&&!e);switch(i.type){case"element":return e+o+function(e,t,r){kr=e,Pr=e.name;var n=[],i="elementNameFn"in t?t.elementNameFn(e.name,e):e.name;n.push("<"+i),e[t.attributesKey]&&n.push(Vr(e[t.attributesKey],t,r));var o=e[t.elementsKey]&&e[t.elementsKey].length||e[t.attributesKey]&&"preserve"===e[t.attributesKey]["xml:space"];return o||(o="fullTagEmptyElementFn"in t?t.fullTagEmptyElementFn(e.name,e):t.fullTagEmptyElement),o?(n.push(">"),e[t.elementsKey]&&e[t.elementsKey].length&&(n.push(Gr(e[t.elementsKey],t,r+1)),kr=e,Pr=e.name),n.push(t.spaces&&function(e,t){var r;if(e.elements&&e.elements.length)for(r=0;r")):n.push("/>"),n.join("")}(i,t,r);case"comment":return e+o+Yr(i[t.commentKey],t);case"doctype":return e+o+qr(i[t.doctypeKey],t);case"cdata":return e+(t.indentCdata?o:"")+Hr(i[t.cdataKey],t);case"text":return e+(t.indentText?o:"")+zr(i[t.textKey],t);case"instruction":var a={};return a[i[t.nameKey]]=i[t.attributesKey]?i:i[t.instructionKey],e+(t.indentInstruction?o:"")+$r(a,t,r)}}),"")}function Wr(e,t,r){var n;for(n in e)if(e.hasOwnProperty(n))switch(n){case t.parentKey:case t.attributesKey:break;case t.textKey:if(t.indentText||r)return!0;break;case t.cdataKey:if(t.indentCdata||r)return!0;break;case t.instructionKey:if(t.indentInstruction||r)return!0;break;case t.doctypeKey:case t.commentKey:default:return!0}return!1}function Qr(e,t,r,n,i){kr=e,Pr=t;var o="elementNameFn"in r?r.elementNameFn(t,e):t;if(null==e||""===e)return"fullTagEmptyElementFn"in r&&r.fullTagEmptyElementFn(t,e)||r.fullTagEmptyElement?"<"+o+">":"<"+o+"/>";var a=[];if(t){if(a.push("<"+o),"object"!=typeof e)return a.push(">"+zr(e,r)+""),a.join("");e[r.attributesKey]&&a.push(Vr(e[r.attributesKey],r,n));var s=Wr(e,r,!0)||e[r.attributesKey]&&"preserve"===e[r.attributesKey]["xml:space"];if(s||(s="fullTagEmptyElementFn"in r?r.fullTagEmptyElementFn(t,e):r.fullTagEmptyElement),!s)return a.push("/>"),a.join("");a.push(">")}return a.push(Xr(e,r,n+1,!1)),kr=e,Pr=t,t&&a.push((i?Mr(r,n,!1):"")+""),a.join("")}function Xr(e,t,r,n){var i,o,a,s=[];for(o in e)if(e.hasOwnProperty(o))for(a=Br(e[o])?e[o]:[e[o]],i=0;i{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},on=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),n=t.trim();if(Math.abs(r.length-n.length)>1)return!1;const i="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===n.slice(-1)?n.slice(0,-1):n;return e.includes(o)||t.includes(i)},an=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),n=t.trim(),i="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===n.slice(-1)?n.slice(0,-1):n;return e.includes(o)||t.includes(i)},sn=e=>e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[M[t]]:t})),{}),un=e=>Object.entries(e).reduce(((e,[t,r])=>r?Object.assign(Object.assign({},e),{[t]:r}):e),{});var cn=Object.freeze({__proto__:null,cleanupFalsy:un,getDAVAttribute:sn,urlContains:an,urlEquals:on});const ln=B("tsdav:request"),dn=e=>t(void 0,void 0,void 0,(function*(){var t;const{url:r,init:n,convertIncoming:i=!0,parseOutgoing:o=!0}=e,{headers:s={},body:u,namespace:c,method:l,attributes:d}=n,h=i?rn.js2xml(Object.assign(Object.assign({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},u),{_attributes:d}),{compact:!0,spaces:2,elementNameFn:e=>c&&!/^.+:.+/.test(e)?`${c}:${e}`:e}):u,f=yield a.fetch(r,{headers:Object.assign({"Content-Type":"text/xml;charset=UTF-8"},un(s)),body:h,method:l}),p=yield f.text();if(!f.ok||!(null===(t=f.headers.get("content-type"))||void 0===t?void 0:t.includes("xml"))||!o)return[{href:f.url,ok:f.ok,status:f.status,statusText:f.statusText,raw:p}];const g=rn.xml2js(p,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,n=Object.keys(r),i=n[n.length-1],o=r[i];if(o.length>0){o[o.length-1]=nn(e)}else r[i]=nn(e)}catch(e){ln(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,(e=>e[1].toUpperCase())),attributesFn:e=>{const t=Object.assign({},e);return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(g.multistatus.response)?g.multistatus.response:[g.multistatus.response]).map((e=>{var t,r;if(!e)return{status:f.status,statusText:f.statusText,ok:f.ok};const n=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:g,href:e.href,status:(null==n?void 0:n.groups)?Number.parseInt(null==n?void 0:n.groups.status,10):f.status,statusText:null!==(r=null===(t=null==n?void 0:n.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:f.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce(((e,t)=>Object.assign(Object.assign({},e),null==t?void 0:t.prop)),{})}}))})),hn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:n,headers:i}=e;return dn({url:t,init:{method:"PROPFIND",headers:un(Object.assign({depth:n},i)),namespace:V.DAV,body:{propfind:{_attributes:sn([U.CALDAV,U.CALDAV_APPLE,U.CALENDAR_SERVER,U.CARDDAV,U.DAV]),prop:r}}}})})),fn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,data:r,headers:n}=e;return a.fetch(t,{method:"PUT",body:r,headers:n})})),pn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,data:r,etag:n,headers:i}=e;return a.fetch(t,{method:"PUT",body:r,headers:un(Object.assign({"If-Match":n},i))})})),gn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,headers:r,etag:n}=e;return a.fetch(t,{method:"DELETE",headers:un(Object.assign({"If-Match":n},r))})}));var yn=Object.freeze({__proto__:null,createObject:fn,davRequest:dn,deleteObject:gn,propfind:hn,updateObject:pn});function vn(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const mn=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),bn=B("tsdav:collection"),wn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,body:r,depth:n,defaultNamespace:i=V.DAV,headers:o}=e,a=yield dn({url:t,init:{method:"REPORT",headers:un(Object.assign({depth:n},o)),namespace:i,body:r}});return 1!==a.length||a[0].raw?a:[]})),En=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:n,headers:i}=e;return dn({url:t,init:{method:"MKCOL",headers:un(Object.assign({depth:n},i)),namespace:V.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0}})})),An=e=>t(void 0,void 0,void 0,(function*(){var t,r,n,i,o;const{collection:a,headers:s}=e;return null!==(o=null===(i=null===(n=null===(r=null===(t=(yield hn({url:a.url,props:{[`${V.DAV}:supported-report-set`]:{}},depth:"0",headers:s}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===n?void 0:n.supportedReport)||void 0===i?void 0:i.map((e=>Object.keys(e.report)[0])))&&void 0!==o?o:[]})),Tn=e=>t(void 0,void 0,void 0,(function*(){var t,r,n;const{collection:i,headers:o}=e,a=(yield hn({url:i.url,props:{[`${V.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:o})).filter((e=>an(i.url,e.href)))[0];if(!a)throw new Error("Collection does not exist on server");return{isDirty:i.ctag!==(null===(t=a.props)||void 0===t?void 0:t.getctag),newCtag:null===(n=null===(r=a.props)||void 0===r?void 0:r.getctag)||void 0===n?void 0:n.toString()}})),_n=e=>{const{url:t,props:r,headers:n,syncLevel:i,syncToken:o}=e;return dn({url:t,init:{method:"REPORT",namespace:V.DAV,headers:Object.assign({},n),body:{"sync-collection":{_attributes:sn([U.CALDAV,U.CARDDAV,U.DAV]),"sync-level":i,"sync-token":o,[`${V.DAV}:prop`]:r}}}})},Cn=e=>t(void 0,void 0,void 0,(function*(){var t,r,n,i,o,a,s,u,c,l,d;const{collection:h,method:f,headers:p,account:g,detailedResult:y}=e,v=["accountType","homeUrl"];if(!g||!vn(g,v)){if(!g)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${mn(g,v)} before smartCollectionSync`)}const m=null!=f?f:(null===(t=h.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(bn(`smart collection sync with type ${g.accountType} and method ${m}`),"webdav"===m){const e=yield _n({url:h.url,props:{[`${V.DAV}:getetag`]:{},[`${"caldav"===g.accountType?V.CALDAV:V.CARDDAV}:${"caldav"===g.accountType?"calendar-data":"address-data"}`]:{},[`${V.DAV}:displayname`]:{}},syncLevel:1,syncToken:h.syncToken,headers:p}),t=e.filter((e=>{var t;const r="caldav"===g.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r})),c=t.filter((e=>404!==e.status)).map((e=>e.href)),l=t.filter((e=>404===e.status)).map((e=>e.href)),d=(c.length&&null!==(n=yield null===(r=null==h?void 0:h.objectMultiGet)||void 0===r?void 0:r.call(h,{url:h.url,props:{[`${V.DAV}:getetag`]:{},[`${"caldav"===g.accountType?V.CALDAV:V.CARDDAV}:${"caldav"===g.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:c,depth:"1",headers:p}))&&void 0!==n?n:[]).map((e=>{var t,r,n,i,o,a,s,u,c,l;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==g?void 0:g.accountType)?null!==(o=null===(i=null===(n=e.props)||void 0===n?void 0:n.calendarData)||void 0===i?void 0:i._cdata)&&void 0!==o?o:null===(a=e.props)||void 0===a?void 0:a.calendarData:null!==(c=null===(u=null===(s=e.props)||void 0===s?void 0:s.addressData)||void 0===u?void 0:u._cdata)&&void 0!==c?c:null===(l=e.props)||void 0===l?void 0:l.addressData}})),f=null!==(i=h.objects)&&void 0!==i?i:[],v=d.filter((e=>f.every((t=>!an(t.url,e.url))))),m=f.reduce(((e,t)=>{const r=d.find((e=>an(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),b=l.map((e=>({url:e,etag:""}))),w=f.filter((e=>d.some((t=>an(e.url,t.url)&&t.etag===e.etag))));return Object.assign(Object.assign({},h),{objects:y?{created:v,updated:m,deleted:b}:[...w,...v,...m],syncToken:null!==(u=null===(s=null===(a=null===(o=e[0])||void 0===o?void 0:o.raw)||void 0===a?void 0:a.multistatus)||void 0===s?void 0:s.syncToken)&&void 0!==u?u:h.syncToken})}if("basic"===m){const{isDirty:e,newCtag:t}=yield Tn({collection:h,headers:p}),r=null!==(c=h.objects)&&void 0!==c?c:[],n=null!==(d=yield null===(l=h.fetchObjects)||void 0===l?void 0:l.call(h,{collection:h,headers:p}))&&void 0!==d?d:[],i=n.filter((e=>r.every((t=>!an(t.url,e.url))))),o=r.reduce(((e,t)=>{const r=n.find((e=>an(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),a=r.filter((e=>n.every((t=>!an(t.url,e.url))))),s=r.filter((e=>n.some((t=>an(e.url,t.url)&&t.etag===e.etag))));if(e)return Object.assign(Object.assign({},h),{objects:y?{created:i,updated:o,deleted:a}:[...s,...i,...o],ctag:t})}return y?Object.assign(Object.assign({},h),{objects:{created:[],updated:[],deleted:[]}}):h}));var On=Object.freeze({__proto__:null,collectionQuery:wn,isCollectionDirty:Tn,makeCollection:En,smartCollectionSync:Cn,supportedReportSet:An,syncCollection:_n});const Dn=B("tsdav:addressBook"),xn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:n,depth:i,headers:o}=e;return wn({url:t,body:{"addressbook-query":{_attributes:sn([U.CARDDAV,U.DAV]),[`${V.DAV}:prop`]:r,filter:null!=n?n:{"prop-filter":{_attributes:{name:"FN"}}}}},defaultNamespace:V.CARDDAV,depth:i,headers:o})})),Rn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:n,depth:i,headers:o}=e;return wn({url:t,body:{"addressbook-multiget":{_attributes:sn([U.DAV,U.CARDDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n}},defaultNamespace:V.CARDDAV,depth:i,headers:o})})),Fn=e=>t(void 0,void 0,void 0,(function*(){const{account:r,headers:n,props:i}=null!=e?e:{},o=["homeUrl","rootUrl"];if(!r||!vn(r,o)){if(!r)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${mn(r,o)} before fetchAddressBooks`)}const a=yield hn({url:r.homeUrl,props:null!=i?i:{[`${V.DAV}:displayname`]:{},[`${V.CALENDAR_SERVER}:getctag`]:{},[`${V.DAV}:resourcetype`]:{},[`${V.DAV}:sync-token`]:{}},depth:"1",headers:n});return Promise.all(a.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")})).map((e=>{var t,n,i,o,a,s,u,c,l;const d=null!==(i=null===(n=null===(t=e.props)||void 0===t?void 0:t.displayname)||void 0===n?void 0:n._cdata)&&void 0!==i?i:null===(o=e.props)||void 0===o?void 0:o.displayname;return Dn(`Found address book named ${"string"==typeof d?d:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(a=e.href)&&void 0!==a?a:"",null!==(s=r.rootUrl)&&void 0!==s?s:"").href,ctag:null===(u=e.props)||void 0===u?void 0:u.getctag,displayName:"string"==typeof d?d:"",resourcetype:Object.keys(null===(c=e.props)||void 0===c?void 0:c.resourcetype),syncToken:null===(l=e.props)||void 0===l?void 0:l.syncToken}})).map((e=>t(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield An({collection:e,headers:n})})})))))})),Sn=e=>t(void 0,void 0,void 0,(function*(){const{addressBook:t,headers:r,objectUrls:n,urlFilter:i=(e=>e),useMultiGet:o=!0}=e;Dn(`Fetching vcards from ${null==t?void 0:t.url}`);const a=["url"];if(!t||!vn(t,a)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${mn(t,a)} before fetchVCards`)}const s=(null!=n?n:(yield xn({url:t.url,props:{[`${V.DAV}:getetag`]:{}},depth:"1",headers:r})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(i).map((e=>new URL(e).pathname));let u=[];return s.length>0&&(u=o?yield Rn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CARDDAV}:address-data`]:{}},objectUrls:s,depth:"1",headers:r}):yield xn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CARDDAV}:address-data`]:{}},depth:"1",headers:r})),u.map((e=>{var r,n,i,o,a,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(n=e.props)||void 0===n?void 0:n.getetag,data:null!==(a=null===(o=null===(i=e.props)||void 0===i?void 0:i.addressData)||void 0===o?void 0:o._cdata)&&void 0!==a?a:null===(s=e.props)||void 0===s?void 0:s.addressData}}))})),Nn=e=>t(void 0,void 0,void 0,(function*(){const{addressBook:t,vCardString:r,filename:n,headers:i}=e;return fn({url:new URL(n,t.url).href,data:r,headers:Object.assign({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*"},i)})})),Ln=e=>t(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return pn({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/vcard; charset=utf-8"},r)})})),jn=e=>t(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return gn({url:t.url,etag:t.etag,headers:r})}));var In=Object.freeze({__proto__:null,addressBookMultiGet:Rn,addressBookQuery:xn,createVCard:Nn,deleteVCard:jn,fetchAddressBooks:Fn,fetchVCards:Sn,updateVCard:Ln});const kn=B("tsdav:calendar"),Pn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:n,timezone:i,depth:o,headers:a}=e;return wn({url:t,body:{"calendar-query":un({_attributes:sn([U.CALDAV,U.CALENDAR_SERVER,U.CALDAV_APPLE,U.DAV]),[`${V.DAV}:prop`]:r,filter:n,timezone:i})},defaultNamespace:V.CALDAV,depth:o,headers:a})})),Un=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:n,filters:i,timezone:o,depth:a,headers:s}=e;return wn({url:t,body:{"calendar-multiget":{_attributes:sn([U.DAV,U.CALDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n,filter:i,timezone:o}},defaultNamespace:V.CALDAV,depth:a,headers:s})})),Bn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:n,headers:i}=e;return dn({url:t,init:{method:"MKCALENDAR",headers:un(Object.assign({depth:n},i)),namespace:V.DAV,body:{[`${V.CALDAV}:mkcalendar`]:{_attributes:sn([U.DAV,U.CALDAV,U.CALDAV_APPLE]),set:{prop:r}}}}})})),Mn=e=>t(void 0,void 0,void 0,(function*(){const{headers:r,account:n,props:i}=null!=e?e:{},o=["homeUrl","rootUrl"];if(!n||!vn(n,o)){if(!n)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${mn(n,o)} before fetchCalendars`)}const a=yield hn({url:n.homeUrl,props:null!=i?i:{[`${V.CALDAV}:calendar-description`]:{},[`${V.CALDAV}:calendar-timezone`]:{},[`${V.DAV}:displayname`]:{},[`${V.CALDAV_APPLE}:calendar-color`]:{},[`${V.CALENDAR_SERVER}:getctag`]:{},[`${V.DAV}:resourcetype`]:{},[`${V.CALDAV}:supported-calendar-component-set`]:{},[`${V.DAV}:sync-token`]:{}},depth:"1",headers:r});return Promise.all(a.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")})).filter((e=>{var t,r,n;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(n=e.props)||void 0===n?void 0:n.supportedCalendarComponentSet.comp._attributes.name]||[]).some((e=>Object.values(K).includes(e)))})).map((e=>{var t,r,i,o,a,s,u,c,l,d,h,f,p,g;const y=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,v=null===(r=e.props)||void 0===r?void 0:r.calendarTimezone;return{description:"string"==typeof y?y:"",timezone:"string"==typeof v?v:"",url:new URL(null!==(i=e.href)&&void 0!==i?i:"",null!==(o=n.rootUrl)&&void 0!==o?o:"").href,ctag:null===(a=e.props)||void 0===a?void 0:a.getctag,calendarColor:null===(s=e.props)||void 0===s?void 0:s.calendarColor,displayName:null!==(c=null===(u=e.props)||void 0===u?void 0:u.displayname._cdata)&&void 0!==c?c:null===(l=e.props)||void 0===l?void 0:l.displayname,components:Array.isArray(null===(d=e.props)||void 0===d?void 0:d.supportedCalendarComponentSet.comp)?null===(h=e.props)||void 0===h?void 0:h.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(f=e.props)||void 0===f?void 0:f.supportedCalendarComponentSet.comp._attributes.name],resourcetype:Object.keys(null===(p=e.props)||void 0===p?void 0:p.resourcetype),syncToken:null===(g=e.props)||void 0===g?void 0:g.syncToken}})).map((e=>t(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield An({collection:e,headers:r})})})))))})),Vn=e=>t(void 0,void 0,void 0,(function*(){const{calendar:t,objectUrls:r,filters:n,timeRange:i,headers:o,expand:a,urlFilter:s=(e=>Boolean(null==e?void 0:e.includes(".ics"))),useMultiGet:u=!0}=e;if(i){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(i.start)&&e.test(i.end)||t.test(i.start)&&t.test(i.end)))throw new Error("invalid timeRange format, not in ISO8601")}kn(`Fetching calendar objects from ${null==t?void 0:t.url}`);const c=["url"];if(!t||!vn(t,c)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${mn(t,c)} before fetchCalendarObjects`)}const l=null!=n?n:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":Object.assign({_attributes:{name:"VEVENT"}},i?{"time-range":{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})}}],d=(null!=r?r:(yield Pn({url:t.url,props:{[`${V.DAV}:getetag`]:Object.assign({},a&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:l,depth:"1",headers:o})).map((e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(s).map((e=>new URL(e).pathname));let h=[];return d.length>0&&(h=!u||a?yield Pn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:Object.assign({},a&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:l,depth:"1",headers:o}):yield Un({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:Object.assign({},a&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},objectUrls:d,depth:"1",headers:o})),h.map((e=>{var r,n,i,o,a,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(n=e.props)||void 0===n?void 0:n.getetag}`,data:null!==(a=null===(o=null===(i=e.props)||void 0===i?void 0:i.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==a?a:null===(s=e.props)||void 0===s?void 0:s.calendarData}}))})),Kn=e=>t(void 0,void 0,void 0,(function*(){const{calendar:t,iCalString:r,filename:n,headers:i}=e;return fn({url:new URL(n,t.url).href,data:r,headers:Object.assign({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*"},i)})})),$n=e=>t(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return pn({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/calendar; charset=utf-8"},r)})})),Yn=e=>t(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return gn({url:t.url,etag:t.etag,headers:r})})),Hn=e=>t(void 0,void 0,void 0,(function*(){var r;const{oldCalendars:n,account:i,detailedResult:o,headers:a}=e;if(!i)throw new Error("Must have account before syncCalendars");const s=null!==(r=null!=n?n:i.calendars)&&void 0!==r?r:[],u=yield Mn({account:i,headers:a}),c=u.filter((e=>s.every((t=>!an(t.url,e.url)))));kn(`new calendars: ${c.map((e=>e.displayName))}`);const l=s.reduce(((e,t)=>{const r=u.find((e=>an(e.url,t.url)));return r&&(r.syncToken&&r.syncToken!==t.syncToken||r.ctag&&r.ctag!==t.ctag)?[...e,r]:e}),[]);kn(`updated calendars: ${l.map((e=>e.displayName))}`);const d=yield Promise.all(l.map((e=>t(void 0,void 0,void 0,(function*(){return yield Cn({collection:Object.assign(Object.assign({},e),{objectMultiGet:Un}),method:"webdav",headers:a,account:i})}))))),h=s.filter((e=>u.every((t=>!an(t.url,e.url)))));kn(`deleted calendars: ${h.map((e=>e.displayName))}`);const f=s.filter((e=>u.some((t=>an(t.url,e.url)&&(t.syncToken&&t.syncToken!==e.syncToken||t.ctag&&t.ctag!==e.ctag)))));return o?{created:c,updated:l,deleted:h}:[...f,...c,...d]})),qn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,timeRange:r,depth:n,headers:i}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(yield wn({url:t,body:{"free-busy-query":un({_attributes:sn([U.CALDAV]),[`${V.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:V.CALDAV,depth:n,headers:i}))[0]}));var zn=Object.freeze({__proto__:null,calendarMultiGet:Un,calendarQuery:Pn,createCalendarObject:Kn,deleteCalendarObject:Yn,fetchCalendarObjects:Vn,fetchCalendars:Mn,freeBusyQuery:qn,makeCalendar:Bn,syncCalendars:Hn,updateCalendarObject:$n});const Gn=B("tsdav:account"),Wn=e=>t(void 0,void 0,void 0,(function*(){var t,r;Gn("Service discovery...");const{account:n,headers:i}=e,o=new URL(n.serverUrl),s=new URL(`/.well-known/${n.accountType}`,o);s.protocol=null!==(t=o.protocol)&&void 0!==t?t:"http";try{const e=yield a.fetch(s.href,{headers:i,method:"PROPFIND",redirect:"manual"});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){Gn(`Service discovery redirected to ${t}`);const e=new URL(t,o);return e.hostname===s.hostname&&s.port&&!e.port&&(e.port=s.port),e.protocol=null!==(r=o.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){Gn(`Service discovery failed: ${e.stack}`)}return o.href})),Qn=e=>t(void 0,void 0,void 0,(function*(){var t,r,n,i,o;const{account:a,headers:s}=e,u=["rootUrl"];if(!vn(a,u))throw new Error(`account must have ${mn(a,u)} before fetchPrincipalUrl`);Gn(`Fetching principal url from path ${a.rootUrl}`);const[c]=yield hn({url:a.rootUrl,props:{[`${V.DAV}:current-user-principal`]:{}},depth:"0",headers:s});if(!c.ok&&(Gn(`Fetch principal url failed: ${c.statusText}`),401===c.status))throw new Error("Invalid credentials");return Gn(`Fetched principal url ${null===(r=null===(t=c.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(o=null===(i=null===(n=c.props)||void 0===n?void 0:n.currentUserPrincipal)||void 0===i?void 0:i.href)&&void 0!==o?o:"",a.rootUrl).href})),Xn=e=>t(void 0,void 0,void 0,(function*(){var t,r;const{account:n,headers:i}=e,o=["principalUrl","rootUrl"];if(!vn(n,o))throw new Error(`account must have ${mn(n,o)} before fetchHomeUrl`);Gn(`Fetch home url from ${n.principalUrl}`);const a=(yield hn({url:n.principalUrl,props:"caldav"===n.accountType?{[`${V.CALDAV}:calendar-home-set`]:{}}:{[`${V.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:i})).find((e=>an(n.principalUrl,e.href)));if(!a||!a.ok)throw new Error("cannot find homeUrl");const s=new URL("caldav"===n.accountType?null===(t=null==a?void 0:a.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==a?void 0:a.props)||void 0===r?void 0:r.addressbookHomeSet.href,n.rootUrl).href;return Gn(`Fetched home url ${s}`),s})),Zn=e=>t(void 0,void 0,void 0,(function*(){const{account:r,headers:n,loadCollections:i=!1,loadObjects:o=!1}=e,a=Object.assign({},r);return a.rootUrl=yield Wn({account:r,headers:n}),a.principalUrl=yield Qn({account:a,headers:n}),a.homeUrl=yield Xn({account:a,headers:n}),(i||o)&&("caldav"===r.accountType?a.calendars=yield Mn({headers:n,account:a}):"carddav"===r.accountType&&(a.addressBooks=yield Fn({headers:n,account:a}))),o&&("caldav"===r.accountType&&a.calendars?a.calendars=yield Promise.all(a.calendars.map((e=>t(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield Vn({calendar:e,headers:n})})}))))):"carddav"===r.accountType&&a.addressBooks&&(a.addressBooks=yield Promise.all(a.addressBooks.map((e=>t(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield Sn({addressBook:e,headers:n})})}))))))),a}));var Jn,ei,ti=Object.freeze({__proto__:null,createAccount:Zn,fetchHomeUrl:Xn,fetchPrincipalUrl:Qn,serviceDiscovery:Wn}),ri={exports:{}};Jn=ri,ei=ri.exports,function(e){var t=ei,n=Jn&&Jn.exports==t&&Jn,i="object"==typeof r&&r;i.global!==i&&i.window!==i||(e=i);var o=function(e){this.message=e};(o.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new o(e)},s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=/[\t\n\f\r ]/g,c={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,i,o=e.length%3,u="",c=-1,l=e.length-o;++c>18&63)+s.charAt(i>>12&63)+s.charAt(i>>6&63)+s.charAt(63&i);return 2==o?(t=e.charCodeAt(c)<<8,r=e.charCodeAt(++c),u+=s.charAt((i=t+r)>>10)+s.charAt(i>>4&63)+s.charAt(i<<2&63)+"="):1==o&&(i=e.charCodeAt(c),u+=s.charAt(i>>2)+s.charAt(i<<4&63)+"=="),u},decode:function(e){var t=(e=String(e).replace(u,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,i=0,o="",c=-1;++c>(-2*i&6)));return o},version:"1.0.0"};if(t&&!t.nodeType)if(n)n.exports=c;else for(var l in c)c.hasOwnProperty(l)&&(t[l]=c[l]);else e.base64=c}(r);var ni=ri.exports;const ii=B("tsdav:authHelper"),oi=(e,t)=>(...r)=>e(Object.assign(Object.assign({},t),r[0])),ai=e=>(ii(`Basic auth token generated: ${ni.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${ni.encode(`${e.username}:${e.password}`)}`}),si=e=>t(void 0,void 0,void 0,(function*(){const t=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!vn(e,t))throw new Error(`Oauth credentials missing: ${mn(e,t)}`);const r=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});ii(e.tokenUrl),ii(r.toString());const n=yield a.fetch(e.tokenUrl,{method:"POST",body:r.toString(),headers:{"content-length":`${r.toString().length}`,"content-type":"application/x-www-form-urlencoded"}});if(n.ok){return yield n.json()}return ii(`Fetch Oauth tokens failed: ${yield n.text()}`),{}})),ui=e=>t(void 0,void 0,void 0,(function*(){const t=["refreshToken","clientId","clientSecret","tokenUrl"];if(!vn(e,t))throw new Error(`Oauth credentials missing: ${mn(e,t)}`);const r=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),n=yield a.fetch(e.tokenUrl,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(n.ok){return yield n.json()}return ii(`Refresh access token failed: ${yield n.text()}`),{}})),ci=e=>t(void 0,void 0,void 0,(function*(){var t;ii("Fetching oauth headers");let r={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(t=e.expiration)&&void 0!==t?t:0))&&(r=yield ui(e)):r=yield si(e),ii(`Oauth tokens fetched: ${r.access_token}`),{tokens:r,headers:{authorization:`Bearer ${r.access_token}`}}}));var li=Object.freeze({__proto__:null,defaultParam:oi,fetchOauthTokens:si,getBasicAuthHeaders:ai,getOauthHeaders:ci,refreshAccessToken:ui});const di=r=>t(void 0,void 0,void 0,(function*(){const{serverUrl:n,credentials:i,authMethod:o,defaultAccountType:a}=r,s="Basic"===o?ai(i):"Oauth"===o?(yield ci(i)).headers:{},u=a?yield Zn({account:{serverUrl:n,credentials:i,accountType:a},headers:s}):void 0,c=oi(fn,{url:n,headers:s}),l=oi(pn,{headers:s,url:n}),d=oi(gn,{headers:s,url:n}),h=oi(hn,{headers:s}),f=oi(wn,{headers:s}),p=oi(En,{headers:s}),g=oi(_n,{headers:s}),y=oi(An,{headers:s}),v=oi(Tn,{headers:s}),m=oi(Cn,{headers:s,account:u}),b=oi(Pn,{headers:s}),w=oi(Un,{headers:s}),E=oi(Bn,{headers:s}),A=oi(Mn,{headers:s,account:u}),T=oi(Vn,{headers:s}),_=oi(Kn,{headers:s}),C=oi($n,{headers:s}),O=oi(Yn,{headers:s}),D=oi(Hn,{account:u,headers:s}),x=oi(xn,{headers:s}),R=oi(Rn,{headers:s});return{davRequest:r=>t(void 0,void 0,void 0,(function*(){const{init:t}=r,n=e(r,["init"]),{headers:i}=t,o=e(t,["headers"]);return dn(Object.assign(Object.assign({},n),{init:Object.assign(Object.assign({},o),{headers:Object.assign(Object.assign({},s),i)})}))})),propfind:h,createAccount:e=>t(void 0,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:o,loadObjects:a}=e;return Zn({account:Object.assign({serverUrl:n,credentials:i},t),headers:Object.assign(Object.assign({},s),r),loadCollections:o,loadObjects:a})})),createObject:c,updateObject:l,deleteObject:d,calendarQuery:b,addressBookQuery:x,collectionQuery:f,makeCollection:p,calendarMultiGet:w,makeCalendar:E,syncCollection:g,supportedReportSet:y,isCollectionDirty:v,smartCollectionSync:m,fetchCalendars:A,fetchCalendarObjects:T,createCalendarObject:_,updateCalendarObject:C,deleteCalendarObject:O,syncCalendars:D,fetchAddressBooks:oi(Fn,{account:u,headers:s}),addressBookMultiGet:R,fetchVCards:oi(Sn,{headers:s}),createVCard:oi(Nn,{headers:s}),updateVCard:oi(Ln,{headers:s}),deleteVCard:oi(jn,{headers:s})}}));class hi{constructor(e){var t,r;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav"}login(){return t(this,void 0,void 0,(function*(){this.authHeaders="Basic"===this.authMethod?ai(this.credentials):"Oauth"===this.authMethod?(yield ci(this.credentials)).headers:{},this.account=this.accountType?yield Zn({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders}):void 0}))}davRequest(r){return t(this,void 0,void 0,(function*(){const{init:t}=r,n=e(r,["init"]),{headers:i}=t,o=e(t,["headers"]);return dn(Object.assign(Object.assign({},n),{init:Object.assign(Object.assign({},o),{headers:Object.assign(Object.assign({},this.authHeaders),i)})}))}))}createObject(...e){return t(this,void 0,void 0,(function*(){return oi(fn,{url:this.serverUrl,headers:this.authHeaders})(e[0])}))}updateObject(...e){return t(this,void 0,void 0,(function*(){return oi(pn,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}deleteObject(...e){return t(this,void 0,void 0,(function*(){return oi(gn,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}propfind(...e){return t(this,void 0,void 0,(function*(){return oi(hn,{headers:this.authHeaders})(e[0])}))}createAccount(e){return t(this,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:n,loadObjects:i}=e;return Zn({account:Object.assign({serverUrl:this.serverUrl,credentials:this.credentials},t),headers:Object.assign(Object.assign({},this.authHeaders),r),loadCollections:n,loadObjects:i})}))}collectionQuery(...e){return t(this,void 0,void 0,(function*(){return oi(wn,{headers:this.authHeaders})(e[0])}))}makeCollection(...e){return t(this,void 0,void 0,(function*(){return oi(En,{headers:this.authHeaders})(e[0])}))}syncCollection(...e){return t(this,void 0,void 0,(function*(){return oi(_n,{headers:this.authHeaders})(e[0])}))}supportedReportSet(...e){return t(this,void 0,void 0,(function*(){return oi(An,{headers:this.authHeaders})(e[0])}))}isCollectionDirty(...e){return t(this,void 0,void 0,(function*(){return oi(Tn,{headers:this.authHeaders})(e[0])}))}smartCollectionSync(...e){return t(this,void 0,void 0,(function*(){return oi(Cn,{headers:this.authHeaders,account:this.account})(e[0])}))}calendarQuery(...e){return t(this,void 0,void 0,(function*(){return oi(Pn,{headers:this.authHeaders})(e[0])}))}makeCalendar(...e){return t(this,void 0,void 0,(function*(){return oi(Bn,{headers:this.authHeaders})(e[0])}))}calendarMultiGet(...e){return t(this,void 0,void 0,(function*(){return oi(Un,{headers:this.authHeaders})(e[0])}))}fetchCalendars(...e){return t(this,void 0,void 0,(function*(){return oi(Mn,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchCalendarObjects(...e){return t(this,void 0,void 0,(function*(){return oi(Vn,{headers:this.authHeaders})(e[0])}))}createCalendarObject(...e){return t(this,void 0,void 0,(function*(){return oi(Kn,{headers:this.authHeaders})(e[0])}))}updateCalendarObject(...e){return t(this,void 0,void 0,(function*(){return oi($n,{headers:this.authHeaders})(e[0])}))}deleteCalendarObject(...e){return t(this,void 0,void 0,(function*(){return oi(Yn,{headers:this.authHeaders})(e[0])}))}syncCalendars(...e){return t(this,void 0,void 0,(function*(){return oi(Hn,{headers:this.authHeaders,account:this.account})(e[0])}))}addressBookQuery(...e){return t(this,void 0,void 0,(function*(){return oi(xn,{headers:this.authHeaders})(e[0])}))}addressBookMultiGet(...e){return t(this,void 0,void 0,(function*(){return oi(Rn,{headers:this.authHeaders})(e[0])}))}fetchAddressBooks(...e){return t(this,void 0,void 0,(function*(){return oi(Fn,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchVCards(...e){return t(this,void 0,void 0,(function*(){return oi(Sn,{headers:this.authHeaders})(e[0])}))}createVCard(...e){return t(this,void 0,void 0,(function*(){return oi(Nn,{headers:this.authHeaders})(e[0])}))}updateVCard(...e){return t(this,void 0,void 0,(function*(){return oi(Ln,{headers:this.authHeaders})(e[0])}))}deleteVCard(...e){return t(this,void 0,void 0,(function*(){return oi(jn,{headers:this.authHeaders})(e[0])}))}}var fi=Object.freeze({__proto__:null,DAVClient:hi,createDAVClient:di}),pi=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({DAVNamespace:U,DAVNamespaceShort:V,DAVAttributeMap:M},fi),yn),On),ti),In),zn),li),cn);export{M as DAVAttributeMap,hi as DAVClient,U as DAVNamespace,V as DAVNamespaceShort,xn as addressBookQuery,Un as calendarMultiGet,Pn as calendarQuery,un as cleanupFalsy,wn as collectionQuery,Zn as createAccount,Kn as createCalendarObject,di as createDAVClient,fn as createObject,Nn as createVCard,dn as davRequest,pi as default,Yn as deleteCalendarObject,gn as deleteObject,jn as deleteVCard,Fn as fetchAddressBooks,Vn as fetchCalendarObjects,Mn as fetchCalendars,si as fetchOauthTokens,Sn as fetchVCards,qn as freeBusyQuery,ai as getBasicAuthHeaders,sn as getDAVAttribute,ci as getOauthHeaders,Tn as isCollectionDirty,Bn as makeCalendar,hn as propfind,ui as refreshAccessToken,Cn as smartCollectionSync,An as supportedReportSet,Hn as syncCalendars,_n as syncCollection,$n as updateCalendarObject,pn as updateObject,Ln as updateVCard,an as urlContains,on as urlEquals}; +function e(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(n=Object.getOwnPropertySymbols(e);i-1};function c(e){if("string"!=typeof e&&(e=String(e)),/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(e))throw new TypeError("Invalid character in header field name");return e.toLowerCase()}function l(e){return"string"!=typeof e&&(e=String(e)),e}function d(e){var t={next:function(){var t=e.shift();return{done:void 0===t,value:t}}};return n&&(t[Symbol.iterator]=function(){return t}),t}function h(e){this.map={},e instanceof h?e.forEach((function(e,t){this.append(t,e)}),this):Array.isArray(e)?e.forEach((function(e){this.append(e[0],e[1])}),this):e&&Object.getOwnPropertyNames(e).forEach((function(t){this.append(t,e[t])}),this)}function f(e){if(e.bodyUsed)return Promise.reject(new TypeError("Already read"));e.bodyUsed=!0}function p(e){return new Promise((function(t,r){e.onload=function(){t(e.result)},e.onerror=function(){r(e.error)}}))}function g(e){var t=new FileReader,r=p(t);return t.readAsArrayBuffer(e),r}function y(e){if(e.slice)return e.slice(0);var t=new Uint8Array(e.byteLength);return t.set(new Uint8Array(e)),t.buffer}function v(){return this.bodyUsed=!1,this._initBody=function(e){var t;this._bodyInit=e,e?"string"==typeof e?this._bodyText=e:i&&Blob.prototype.isPrototypeOf(e)?this._bodyBlob=e:o&&FormData.prototype.isPrototypeOf(e)?this._bodyFormData=e:r&&URLSearchParams.prototype.isPrototypeOf(e)?this._bodyText=e.toString():a&&i&&((t=e)&&DataView.prototype.isPrototypeOf(t))?(this._bodyArrayBuffer=y(e.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):a&&(ArrayBuffer.prototype.isPrototypeOf(e)||u(e))?this._bodyArrayBuffer=y(e):this._bodyText=e=Object.prototype.toString.call(e):this._bodyText="",this.headers.get("content-type")||("string"==typeof e?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):r&&URLSearchParams.prototype.isPrototypeOf(e)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},i&&(this.blob=function(){var e=f(this);if(e)return e;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?f(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(g)}),this.text=function(){var e,t,r,n=f(this);if(n)return n;if(this._bodyBlob)return e=this._bodyBlob,t=new FileReader,r=p(t),t.readAsText(e),r;if(this._bodyArrayBuffer)return Promise.resolve(function(e){for(var t=new Uint8Array(e),r=new Array(t.length),n=0;n-1?t:e}(t.method||this.method||"GET"),this.mode=t.mode||this.mode||null,this.signal=t.signal||this.signal,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&r)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(r)}function w(e){var t=new FormData;return e.trim().split("&").forEach((function(e){if(e){var r=e.split("="),n=r.shift().replace(/\+/g," "),i=r.join("=").replace(/\+/g," ");t.append(decodeURIComponent(n),decodeURIComponent(i))}})),t}function E(e,t){t||(t={}),this.type="default",this.status=void 0===t.status?200:t.status,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in t?t.statusText:"OK",this.headers=new h(t.headers),this.url=t.url||"",this._initBody(e)}b.prototype.clone=function(){return new b(this,{body:this._bodyInit})},v.call(b.prototype),v.call(E.prototype),E.prototype.clone=function(){return new E(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new h(this.headers),url:this.url})},E.error=function(){var e=new E(null,{status:0,statusText:""});return e.type="error",e};var A=[301,302,303,307,308];E.redirect=function(e,t){if(-1===A.indexOf(t))throw new RangeError("Invalid status code");return new E(null,{status:t,headers:{location:e}})},t.DOMException=e.DOMException;try{new t.DOMException}catch(e){t.DOMException=function(e,t){this.message=e,this.name=t;var r=Error(e);this.stack=r.stack},t.DOMException.prototype=Object.create(Error.prototype),t.DOMException.prototype.constructor=t.DOMException}function T(e,r){return new Promise((function(n,o){var a=new b(e,r);if(a.signal&&a.signal.aborted)return o(new t.DOMException("Aborted","AbortError"));var s=new XMLHttpRequest;function u(){s.abort()}s.onload=function(){var e,t,r={status:s.status,statusText:s.statusText,headers:(e=s.getAllResponseHeaders()||"",t=new h,e.replace(/\r?\n[\t ]+/g," ").split(/\r?\n/).forEach((function(e){var r=e.split(":"),n=r.shift().trim();if(n){var i=r.join(":").trim();t.append(n,i)}})),t)};r.url="responseURL"in s?s.responseURL:r.headers.get("X-Request-URL");var i="response"in s?s.response:s.responseText;n(new E(i,r))},s.onerror=function(){o(new TypeError("Network request failed"))},s.ontimeout=function(){o(new TypeError("Network request failed"))},s.onabort=function(){o(new t.DOMException("Aborted","AbortError"))},s.open(a.method,a.url,!0),"include"===a.credentials?s.withCredentials=!0:"omit"===a.credentials&&(s.withCredentials=!1),"responseType"in s&&i&&(s.responseType="blob"),a.headers.forEach((function(e,t){s.setRequestHeader(t,e)})),a.signal&&(a.signal.addEventListener("abort",u),s.onreadystatechange=function(){4===s.readyState&&a.signal.removeEventListener("abort",u)}),s.send(void 0===a._bodyInit?null:a._bodyInit)}))}T.polyfill=!0,e.fetch||(e.fetch=T,e.Headers=h,e.Request=b,e.Response=E),t.Headers=h,t.Request=b,t.Response=E,t.fetch=T,Object.defineProperty(t,"__esModule",{value:!0})}({})}(i),i.fetch.ponyfill=!0,delete i.fetch.polyfill;var o=i;(t=o.fetch).default=o.fetch,t.fetch=o.fetch,t.Headers=o.Headers,t.Request=o.Request,t.Response=o.Response,e.exports=t}(o,o.exports);var a=o.exports,s="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function u(){throw new Error("setTimeout has not been defined")}function c(){throw new Error("clearTimeout has not been defined")}var l=u,d=c;function h(e){if(l===setTimeout)return setTimeout(e,0);if((l===u||!l)&&setTimeout)return l=setTimeout,setTimeout(e,0);try{return l(e,0)}catch(t){try{return l.call(null,e,0)}catch(t){return l.call(this,e,0)}}}"function"==typeof s.setTimeout&&(l=setTimeout),"function"==typeof s.clearTimeout&&(d=clearTimeout);var f,p=[],g=!1,y=-1;function v(){g&&f&&(g=!1,f.length?p=f.concat(p):y=-1,p.length&&m())}function m(){if(!g){var e=h(v);g=!0;for(var t=p.length;t;){for(f=p,p=[];++y1)for(var r=1;r=1.5*r;return Math.round(e/r)+" "+n+(i?"s":"")}return N=function(s,u){u=u||{};var c=typeof s;if("string"===c&&s.length>0)return function(a){if((a=String(a)).length>100)return;var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(a);if(!s)return;var u=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return u*o;case"weeks":case"week":case"w":return u*i;case"days":case"day":case"d":return u*n;case"hours":case"hour":case"hrs":case"hr":case"h":return u*r;case"minutes":case"minute":case"mins":case"min":case"m":return u*t;case"seconds":case"second":case"secs":case"sec":case"s":return u*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return u;default:return}}(s);if("number"===c&&isFinite(s))return u.long?function(i){var o=Math.abs(i);if(o>=n)return a(i,o,n,"day");if(o>=r)return a(i,o,r,"hour");if(o>=t)return a(i,o,t,"minute");if(o>=e)return a(i,o,e,"second");return i+" ms"}(s):function(i){var o=Math.abs(i);if(o>=n)return Math.round(i/n)+"d";if(o>=r)return Math.round(i/r)+"h";if(o>=t)return Math.round(i/t)+"m";if(o>=e)return Math.round(i/e)+"s";return i+"ms"}(s);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(s))},N}var P=function(e){function t(e){let n,i,o,a=null;function s(...e){if(!s.enabled)return;const r=s,i=Number(new Date),o=i-(n||i);r.diff=o,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let a=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";a++;const o=t.formatters[i];if("function"==typeof o){const t=e[a];n=o.call(r,t),e.splice(a,1),a--}return n})),t.formatArgs.call(r,e);(r.log||t.log).apply(r,e)}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=r,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{a=e}}),"function"==typeof t.init&&t.init(s),s}function r(e,r){const n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){if(e instanceof Error)return e.stack||e.message;return e},t.disable=function(){const e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t{"%%"!==e&&(n++,"%c"===e&&(i=n))})),t.splice(i,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}!e&&void 0!==L&&"env"in L&&(e=L.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=P(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}}(k,k.exports);var U,B=n(k.exports);!function(e){e.CALENDAR_SERVER="http://calendarserver.org/ns/",e.CALDAV_APPLE="http://apple.com/ns/ical/",e.CALDAV="urn:ietf:params:xml:ns:caldav",e.CARDDAV="urn:ietf:params:xml:ns:carddav",e.DAV="DAV:"}(U||(U={}));const M={[U.CALDAV]:"xmlns:c",[U.CARDDAV]:"xmlns:card",[U.CALENDAR_SERVER]:"xmlns:cs",[U.CALDAV_APPLE]:"xmlns:ca",[U.DAV]:"xmlns:d"};var V,K;!function(e){e.CALDAV="c",e.CARDDAV="card",e.CALENDAR_SERVER="cs",e.CALDAV_APPLE="ca",e.DAV="d"}(V||(V={})),function(e){e.VEVENT="VEVENT",e.VTODO="VTODO",e.VJOURNAL="VJOURNAL",e.VFREEBUSY="VFREEBUSY",e.VTIMEZONE="VTIMEZONE",e.VALARM="VALARM"}(K||(K={}));var $=[],H=[],Y="undefined"!=typeof Uint8Array?Uint8Array:Array,z=!1;function q(){z=!0;for(var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",t=0,r=e.length;t>18&63]+$[i>>12&63]+$[i>>6&63]+$[63&i]);return o.join("")}function W(e){var t;z||q();for(var r=e.length,n=r%3,i="",o=[],a=16383,s=0,u=r-n;su?u:s+a));return 1===n?(t=e[r-1],i+=$[t>>2],i+=$[t<<4&63],i+="=="):2===n&&(t=(e[r-2]<<8)+e[r-1],i+=$[t>>10],i+=$[t>>4&63],i+=$[t<<2&63],i+="="),o.push(i),o.join("")}function Q(e,t,r,n,i){var o,a,s=8*i-n-1,u=(1<>1,l=-7,d=r?i-1:0,h=r?-1:1,f=e[t+d];for(d+=h,o=f&(1<<-l)-1,f>>=-l,l+=s;l>0;o=256*o+e[t+d],d+=h,l-=8);for(a=o&(1<<-l)-1,o>>=-l,l+=n;l>0;a=256*a+e[t+d],d+=h,l-=8);if(0===o)o=1-c;else{if(o===u)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),o-=c}return(f?-1:1)*a*Math.pow(2,o-n)}function X(e,t,r,n,i,o){var a,s,u,c=8*o-i-1,l=(1<>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:o-1,p=n?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-a))<1&&(a--,u*=2),(t+=a+d>=1?h/u:h*Math.pow(2,1-d))*u>=2&&(a++,u/=2),a+d>=l?(s=0,a=l):a+d>=1?(s=(t*u-1)*Math.pow(2,i),a+=d):(s=t*Math.pow(2,d-1)*Math.pow(2,i),a=0));i>=8;e[r+f]=255&s,f+=p,s/=256,i-=8);for(a=a<0;e[r+f]=255&a,f+=p,a/=256,c-=8);e[r+f-p]|=128*g}var Z={}.toString,J=Array.isArray||function(e){return"[object Array]"==Z.call(e)};function ee(){return re.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function te(e,t){if(ee()=ee())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+ee().toString(16)+" bytes");return 0|e}function ue(e){return!(null==e||!e._isBuffer)}function ce(e,t){if(ue(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return ke(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Ie(e).length;default:if(n)return ke(e).length;t=(""+t).toLowerCase(),n=!0}}function le(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return _e(this,t,r);case"utf8":case"utf-8":return Ee(this,t,r);case"ascii":return Ae(this,t,r);case"latin1":case"binary":return Te(this,t,r);case"base64":return we(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ce(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function de(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function he(e,t,r,n,i){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=i?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(i)return-1;r=e.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof t&&(t=re.from(t,n)),ue(t))return 0===t.length?-1:fe(e,t,r,n,i);if("number"==typeof t)return t&=255,re.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):fe(e,[t],r,n,i);throw new TypeError("val must be string, number or Buffer")}function fe(e,t,r,n,i){var o,a=1,s=e.length,u=t.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;a=2,s/=2,u/=2,r/=2}function c(e,t){return 1===a?e[t]:e.readUInt16BE(t*a)}if(i){var l=-1;for(o=r;os&&(r=s-u),o=r;o>=0;o--){for(var d=!0,h=0;hi&&(n=i):n=i;var o=t.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var a=0;a>8,i=r%256,o.push(i),o.push(n);return o}(t,e.length-r),e,r,n)}function we(e,t,r){return 0===t&&r===e.length?W(e):W(e.slice(t,r))}function Ee(e,t,r){r=Math.min(e.length,r);for(var n=[],i=t;i239?4:c>223?3:c>191?2:1;if(i+d<=r)switch(d){case 1:c<128&&(l=c);break;case 2:128==(192&(o=e[i+1]))&&(u=(31&c)<<6|63&o)>127&&(l=u);break;case 3:o=e[i+1],a=e[i+2],128==(192&o)&&128==(192&a)&&(u=(15&c)<<12|(63&o)<<6|63&a)>2047&&(u<55296||u>57343)&&(l=u);break;case 4:o=e[i+1],a=e[i+2],s=e[i+3],128==(192&o)&&128==(192&a)&&128==(192&s)&&(u=(15&c)<<18|(63&o)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(l=u)}null===l?(l=65533,d=1):l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|1023&l),n.push(l),i+=d}return function(e){var t=e.length;if(t<=4096)return String.fromCharCode.apply(String,e);var r="",n=0;for(;n0&&(e=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(e+=" ... ")),""},re.prototype.compare=function(e,t,r,n,i){if(!ue(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),t<0||r>e.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&t>=r)return 0;if(n>=i)return-1;if(t>=r)return 1;if(this===e)return 0;for(var o=(i>>>=0)-(n>>>=0),a=(r>>>=0)-(t>>>=0),s=Math.min(o,a),u=this.slice(n,i),c=e.slice(t,r),l=0;li)&&(r=i),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return pe(this,e,t,r);case"utf8":case"utf-8":return ge(this,e,t,r);case"ascii":return ye(this,e,t,r);case"latin1":case"binary":return ve(this,e,t,r);case"base64":return me(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return be(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},re.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function Ae(e,t,r){var n="";r=Math.min(e.length,r);for(var i=t;in)&&(r=n);for(var i="",o=t;or)throw new RangeError("Trying to access beyond buffer length")}function De(e,t,r,n,i,o){if(!ue(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||te.length)throw new RangeError("Index out of range")}function xe(e,t,r,n){t<0&&(t=65535+t+1);for(var i=0,o=Math.min(e.length-r,2);i>>8*(n?i:1-i)}function Re(e,t,r,n){t<0&&(t=4294967295+t+1);for(var i=0,o=Math.min(e.length-r,4);i>>8*(n?i:3-i)&255}function Fe(e,t,r,n,i,o){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function Se(e,t,r,n,i){return i||Fe(e,0,r,4),X(e,t,r,n,23,4),r+4}function Ne(e,t,r,n,i){return i||Fe(e,0,r,8),X(e,t,r,n,52,8),r+8}re.prototype.slice=function(e,t){var r,n=this.length;if((e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t0&&(i*=256);)n+=this[e+--t]*i;return n},re.prototype.readUInt8=function(e,t){return t||Oe(e,1,this.length),this[e]},re.prototype.readUInt16LE=function(e,t){return t||Oe(e,2,this.length),this[e]|this[e+1]<<8},re.prototype.readUInt16BE=function(e,t){return t||Oe(e,2,this.length),this[e]<<8|this[e+1]},re.prototype.readUInt32LE=function(e,t){return t||Oe(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},re.prototype.readUInt32BE=function(e,t){return t||Oe(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},re.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||Oe(e,t,this.length);for(var n=this[e],i=1,o=0;++o=(i*=128)&&(n-=Math.pow(2,8*t)),n},re.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||Oe(e,t,this.length);for(var n=t,i=1,o=this[e+--n];n>0&&(i*=256);)o+=this[e+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*t)),o},re.prototype.readInt8=function(e,t){return t||Oe(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},re.prototype.readInt16LE=function(e,t){t||Oe(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},re.prototype.readInt16BE=function(e,t){t||Oe(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},re.prototype.readInt32LE=function(e,t){return t||Oe(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},re.prototype.readInt32BE=function(e,t){return t||Oe(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},re.prototype.readFloatLE=function(e,t){return t||Oe(e,4,this.length),Q(this,e,!0,23,4)},re.prototype.readFloatBE=function(e,t){return t||Oe(e,4,this.length),Q(this,e,!1,23,4)},re.prototype.readDoubleLE=function(e,t){return t||Oe(e,8,this.length),Q(this,e,!0,52,8)},re.prototype.readDoubleBE=function(e,t){return t||Oe(e,8,this.length),Q(this,e,!1,52,8)},re.prototype.writeUIntLE=function(e,t,r,n){(e=+e,t|=0,r|=0,n)||De(this,e,t,r,Math.pow(2,8*r)-1,0);var i=1,o=0;for(this[t]=255&e;++o=0&&(o*=256);)this[t+i]=e/o&255;return t+r},re.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,1,255,0),re.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},re.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,2,65535,0),re.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):xe(this,e,t,!0),t+2},re.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,2,65535,0),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):xe(this,e,t,!1),t+2},re.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,4,4294967295,0),re.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):Re(this,e,t,!0),t+4},re.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,4,4294967295,0),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Re(this,e,t,!1),t+4},re.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);De(this,e,t,r,i-1,-i)}var o=0,a=1,s=0;for(this[t]=255&e;++o>0)-s&255;return t+r},re.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var i=Math.pow(2,8*r-1);De(this,e,t,r,i-1,-i)}var o=r-1,a=1,s=0;for(this[t+o]=255&e;--o>=0&&(a*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/a>>0)-s&255;return t+r},re.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,1,127,-128),re.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},re.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,2,32767,-32768),re.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):xe(this,e,t,!0),t+2},re.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,2,32767,-32768),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):xe(this,e,t,!1),t+2},re.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,4,2147483647,-2147483648),re.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):Re(this,e,t,!0),t+4},re.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||De(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),re.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):Re(this,e,t,!1),t+4},re.prototype.writeFloatLE=function(e,t,r){return Se(this,e,t,!0,r)},re.prototype.writeFloatBE=function(e,t,r){return Se(this,e,t,!1,r)},re.prototype.writeDoubleLE=function(e,t,r){return Ne(this,e,t,!0,r)},re.prototype.writeDoubleBE=function(e,t,r){return Ne(this,e,t,!1,r)},re.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t=0;--i)e[i+t]=this[i+r];else if(o<1e3||!re.TYPED_ARRAY_SUPPORT)for(i=0;i>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o55295&&r<57344){if(!i){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(a+1===n){(t-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(t-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function Ie(e){return function(e){var t,r,n,i,o,a;z||q();var s=e.length;if(s%4>0)throw new Error("Invalid string. Length must be a multiple of 4");o="="===e[s-2]?2:"="===e[s-1]?1:0,a=new Y(3*s/4-o),n=o>0?s-4:s;var u=0;for(t=0,r=0;t>16&255,a[u++]=i>>8&255,a[u++]=255&i;return 2===o?(i=H[e.charCodeAt(t)]<<2|H[e.charCodeAt(t+1)]>>4,a[u++]=255&i):1===o&&(i=H[e.charCodeAt(t)]<<10|H[e.charCodeAt(t+1)]<<4|H[e.charCodeAt(t+2)]>>2,a[u++]=i>>8&255,a[u++]=255&i),a}(function(e){if((e=function(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}(e).replace(je,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Pe(e,t,r,n){for(var i=0;i=t.length||i>=e.length);++i)t[i+r]=e[i];return i}function Ue(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}var Be={};function Me(){}function Ve(){Ve.init.call(this)}function Ke(e){return void 0===e._maxListeners?Ve.defaultMaxListeners:e._maxListeners}function $e(e,t,r){if(t)e.call(r);else for(var n=e.length,i=Xe(e,n),o=0;o0&&a.length>i){a.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+a.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=a.length,s=u,"function"==typeof console.warn?console.warn(s):console.log(s)}}else a=o[t]=r,++e._eventsCount;return e}function We(e,t,r){var n=!1;function i(){e.removeListener(t,i),n||(n=!0,r.apply(e,arguments))}return i.listener=r,i}function Qe(e){var t=this._events;if(t){var r=t[e];if("function"==typeof r)return 1;if(r)return r.length}return 0}function Xe(e,t){for(var r=new Array(t);t--;)r[t]=e[t];return r}Me.prototype=Object.create(null),Ve.EventEmitter=Ve,Ve.usingDomains=!1,Ve.prototype.domain=void 0,Ve.prototype._events=void 0,Ve.prototype._maxListeners=void 0,Ve.defaultMaxListeners=10,Ve.init=function(){this.domain=null,Ve.usingDomains&&undefined.active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new Me,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},Ve.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},Ve.prototype.getMaxListeners=function(){return Ke(this)},Ve.prototype.emit=function(e){var t,r,n,i,o,a,s,u="error"===e;if(a=this._events)u=u&&null==a.error;else if(!u)return!1;if(s=this.domain,u){if(t=arguments[1],!s){if(t instanceof Error)throw t;var c=new Error('Uncaught, unspecified "error" event. ('+t+")");throw c.context=t,c}return t||(t=new Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=s,t.domainThrown=!1,s.emit("error",t),!1}if(!(r=a[e]))return!1;var l="function"==typeof r;switch(n=arguments.length){case 1:$e(r,l,this);break;case 2:He(r,l,this,arguments[1]);break;case 3:Ye(r,l,this,arguments[1],arguments[2]);break;case 4:ze(r,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=new Array(n-1),o=1;o0;)if(r[o]===t||r[o].listener&&r[o].listener===t){a=r[o].listener,i=o;break}if(i<0)return this;if(1===r.length){if(r[0]=void 0,0==--this._eventsCount)return this._events=new Me,this;delete n[e]}else!function(e,t){for(var r=t,n=r+1,i=e.length;n0?Reflect.ownKeys(this._events):[]};var Ze="function"==typeof Object.create?function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e},Je=/%[sdj%]/g;function et(e){if(!ht(e)){for(var t=[],r=0;r=i)return e;switch(e){case"%s":return String(n[r++]);case"%d":return Number(n[r++]);case"%j":try{return JSON.stringify(n[r++])}catch(e){return"[Circular]"}default:return e}})),a=n[r];r=3&&(r.depth=arguments[2]),arguments.length>=4&&(r.colors=arguments[3]),lt(t)?r.showHidden=t:t&&wt(r,t),ft(r.showHidden)&&(r.showHidden=!1),ft(r.depth)&&(r.depth=2),ft(r.colors)&&(r.colors=!1),ft(r.customInspect)&&(r.customInspect=!0),r.colors&&(r.stylize=ot),st(r,e,r.depth)}function ot(e,t){var r=it.styles[t];return r?"["+it.colors[r][0]+"m"+e+"["+it.colors[r][1]+"m":e}function at(e,t){return e}function st(e,t,r){if(e.customInspect&&t&&mt(t.inspect)&&t.inspect!==it&&(!t.constructor||t.constructor.prototype!==t)){var n=t.inspect(r,e);return ht(n)||(n=st(e,n,r)),n}var i=function(e,t){if(ft(t))return e.stylize("undefined","undefined");if(ht(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(n=t,"number"==typeof n)return e.stylize(""+t,"number");var n;if(lt(t))return e.stylize(""+t,"boolean");if(dt(t))return e.stylize("null","null")}(e,t);if(i)return i;var o=Object.keys(t),a=function(e){var t={};return e.forEach((function(e,r){t[e]=!0})),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(t)),vt(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return ut(t);if(0===o.length){if(mt(t)){var s=t.name?": "+t.name:"";return e.stylize("[Function"+s+"]","special")}if(pt(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(yt(t))return e.stylize(Date.prototype.toString.call(t),"date");if(vt(t))return ut(t)}var u,c,l="",d=!1,h=["{","}"];(u=t,Array.isArray(u)&&(d=!0,h=["[","]"]),mt(t))&&(l=" [Function"+(t.name?": "+t.name:"")+"]");return pt(t)&&(l=" "+RegExp.prototype.toString.call(t)),yt(t)&&(l=" "+Date.prototype.toUTCString.call(t)),vt(t)&&(l=" "+ut(t)),0!==o.length||d&&0!=t.length?r<0?pt(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special"):(e.seen.push(t),c=d?function(e,t,r,n,i){for(var o=[],a=0,s=t.length;a60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(c,l,h)):h[0]+l+h[1]}function ut(e){return"["+Error.prototype.toString.call(e)+"]"}function ct(e,t,r,n,i,o){var a,s,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),Et(n,i)||(a="["+i+"]"),s||(e.seen.indexOf(u.value)<0?(s=dt(r)?st(e,u.value,null):st(e,u.value,r-1)).indexOf("\n")>-1&&(s=o?s.split("\n").map((function(e){return" "+e})).join("\n").substr(2):"\n"+s.split("\n").map((function(e){return" "+e})).join("\n")):s=e.stylize("[Circular]","special")),ft(a)){if(o&&i.match(/^\d+$/))return s;(a=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+s}function lt(e){return"boolean"==typeof e}function dt(e){return null===e}function ht(e){return"string"==typeof e}function ft(e){return void 0===e}function pt(e){return gt(e)&&"[object RegExp]"===bt(e)}function gt(e){return"object"==typeof e&&null!==e}function yt(e){return gt(e)&&"[object Date]"===bt(e)}function vt(e){return gt(e)&&("[object Error]"===bt(e)||e instanceof Error)}function mt(e){return"function"==typeof e}function bt(e){return Object.prototype.toString.call(e)}function wt(e,t){if(!t||!gt(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}function Et(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function At(){this.head=null,this.tail=null,this.length=0}it.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},it.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},At.prototype.push=function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length},At.prototype.unshift=function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length},At.prototype.shift=function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}},At.prototype.clear=function(){this.head=this.tail=null,this.length=0},At.prototype.join=function(e){if(0===this.length)return"";for(var t=this.head,r=""+t.data;t=t.next;)r+=e+t.data;return r},At.prototype.concat=function(e){if(0===this.length)return re.alloc(0);if(1===this.length)return this.head.data;for(var t=re.allocUnsafe(e>>>0),r=this.head,n=0;r;)r.data.copy(t,n),n+=r.data.length,r=r.next;return t};var Tt=re.isEncoding||function(e){switch(e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function _t(e){switch(this.encoding=(e||"utf8").toLowerCase().replace(/[-_]/,""),function(e){if(e&&!Tt(e))throw new Error("Unknown encoding: "+e)}(e),this.encoding){case"utf8":this.surrogateSize=3;break;case"ucs2":case"utf16le":this.surrogateSize=2,this.detectIncompleteChar=Ot;break;case"base64":this.surrogateSize=3,this.detectIncompleteChar=Dt;break;default:return void(this.write=Ct)}this.charBuffer=new re(6),this.charReceived=0,this.charLength=0}function Ct(e){return e.toString(this.encoding)}function Ot(e){this.charReceived=e.length%2,this.charLength=this.charReceived?2:0}function Dt(e){this.charReceived=e.length%3,this.charLength=this.charReceived?3:0}_t.prototype.write=function(e){for(var t="";this.charLength;){var r=e.length>=this.charLength-this.charReceived?this.charLength-this.charReceived:e.length;if(e.copy(this.charBuffer,this.charReceived,0,r),this.charReceived+=r,this.charReceived=55296&&i<=56319)){if(this.charReceived=this.charLength=0,0===e.length)return t;break}this.charLength+=this.surrogateSize,t=""}this.detectIncompleteChar(e);var n=e.length;this.charLength&&(e.copy(this.charBuffer,0,e.length-this.charReceived,n),n-=this.charReceived);var i;n=(t+=e.toString(this.encoding,0,n)).length-1;if((i=t.charCodeAt(n))>=55296&&i<=56319){var o=this.surrogateSize;return this.charLength+=o,this.charReceived+=o,this.charBuffer.copy(this.charBuffer,o,0,o),e.copy(this.charBuffer,0,0,o),t.substring(0,n)}return t},_t.prototype.detectIncompleteChar=function(e){for(var t=e.length>=3?3:e.length;t>0;t--){var r=e[e.length-t];if(1==t&&r>>5==6){this.charLength=2;break}if(t<=2&&r>>4==14){this.charLength=3;break}if(t<=3&&r>>3==30){this.charLength=4;break}}this.charReceived=t},_t.prototype.end=function(e){var t="";if(e&&e.length&&(t=this.write(e)),this.charReceived){var r=this.charReceived,n=this.charBuffer,i=this.encoding;t+=n.slice(0,r).toString(i)}return t};var xt=Object.freeze({__proto__:null,StringDecoder:_t});St.ReadableState=Ft;var Rt=function(e){if(ft(rt)&&(rt=L.env.NODE_DEBUG||""),e=e.toUpperCase(),!nt[e])if(new RegExp("\\b"+e+"\\b","i").test(rt)){nt[e]=function(){var t=et.apply(null,arguments);console.error("%s %d: %s",e,0,t)}}else nt[e]=function(){};return nt[e]}("stream");function Ft(e,t){e=e||{},this.objectMode=!!e.objectMode,t instanceof ir&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,n=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n,this.highWaterMark=~~this.highWaterMark,this.buffer=new At,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.ranOut=!1,this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(this.decoder=new _t(e.encoding),this.encoding=e.encoding)}function St(e){if(!(this instanceof St))return new St(e);this._readableState=new Ft(e,this),this.readable=!0,e&&"function"==typeof e.read&&(this._read=e.read),Ve.call(this)}function Nt(e,t,r,n,i){var o=function(e,t){var r=null;re.isBuffer(t)||"string"==typeof t||null==t||e.objectMode||(r=new TypeError("Invalid non-string/buffer chunk"));return r}(t,r);if(o)e.emit("error",o);else if(null===r)t.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var r=t.decoder.end();r&&r.length&&(t.buffer.push(r),t.length+=t.objectMode?1:r.length)}t.ended=!0,Lt(e)}(e,t);else if(t.objectMode||r&&r.length>0)if(t.ended&&!i){var a=new Error("stream.push() after EOF");e.emit("error",a)}else if(t.endEmitted&&i){var s=new Error("stream.unshift() after end event");e.emit("error",s)}else{var u;!t.decoder||i||n||(r=t.decoder.write(r),u=!t.objectMode&&0===r.length),i||(t.reading=!1),u||(t.flowing&&0===t.length&&!t.sync?(e.emit("data",r),e.read(0)):(t.length+=t.objectMode?1:r.length,i?t.buffer.unshift(r):t.buffer.push(r),t.needReadable&&Lt(e))),function(e,t){t.readingMore||(t.readingMore=!0,b(It,e,t))}(e,t)}else i||(t.reading=!1);return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=8388608?e=8388608:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function Lt(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(Rt("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?b(kt,e):kt(e))}function kt(e){Rt("emit readable"),e.emit("readable"),Bt(e)}function It(e,t){for(var r=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(r=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):r=function(e,t,r){var n;eo.length?o.length:e;if(a===o.length?i+=o:i+=o.slice(0,e),0===(e-=a)){a===o.length?(++n,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=o.slice(a));break}++n}return t.length-=n,i}(e,t):function(e,t){var r=re.allocUnsafe(e),n=t.head,i=1;n.data.copy(r),e-=n.data.length;for(;n=n.next;){var o=n.data,a=e>o.length?o.length:e;if(o.copy(r,r.length-e,0,a),0===(e-=a)){a===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(a));break}++i}return t.length-=i,r}(e,t);return n}(e,t.buffer,t.decoder),r);var r}function Vt(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,b(Kt,t,e))}function Kt(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function $t(e,t){for(var r=0,n=e.length;r=t.highWaterMark||t.ended))return Rt("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?Vt(this):Lt(this),null;if(0===(e=jt(e,t))&&t.ended)return 0===t.length&&Vt(this),null;var n,i=t.needReadable;return Rt("need readable",i),(0===t.length||t.length-e0?Mt(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),r!==e&&t.ended&&Vt(this)),null!==n&&this.emit("data",n),n},St.prototype._read=function(e){this.emit("error",new Error("not implemented"))},St.prototype.pipe=function(e,t){var r=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e)}n.pipesCount+=1,Rt("pipe count=%d opts=%j",n.pipesCount,t);var i=!t||!1!==t.end?a:c;function o(e){Rt("onunpipe"),e===r&&c()}function a(){Rt("onend"),e.end()}n.endEmitted?b(i):r.once("end",i),e.on("unpipe",o);var s=function(e){return function(){var t=e._readableState;Rt("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&e.listeners("data").length&&(t.flowing=!0,Bt(e))}}(r);e.on("drain",s);var u=!1;function c(){Rt("cleanup"),e.removeListener("close",f),e.removeListener("finish",p),e.removeListener("drain",s),e.removeListener("error",h),e.removeListener("unpipe",o),r.removeListener("end",a),r.removeListener("end",c),r.removeListener("data",d),u=!0,!n.awaitDrain||e._writableState&&!e._writableState.needDrain||s()}var l=!1;function d(t){Rt("ondata"),l=!1,!1!==e.write(t)||l||((1===n.pipesCount&&n.pipes===e||n.pipesCount>1&&-1!==$t(n.pipes,e))&&!u&&(Rt("false write response, pause",r._readableState.awaitDrain),r._readableState.awaitDrain++,l=!0),r.pause())}function h(t){var r;Rt("onerror",t),g(),e.removeListener("error",h),0===(r="error",e.listeners(r).length)&&e.emit("error",t)}function f(){e.removeListener("finish",p),g()}function p(){Rt("onfinish"),e.removeListener("close",f),g()}function g(){Rt("unpipe"),r.unpipe(e)}return r.on("data",d),function(e,t,r){if("function"==typeof e.prependListener)return e.prependListener(t,r);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(r):e._events[t]=[r,e._events[t]]:e.on(t,r)}(e,"error",h),e.once("close",f),e.once("finish",p),e.emit("pipe",r),n.flowing||(Rt("pipe resume"),r.resume()),e},St.prototype.unpipe=function(e){var t=this._readableState;if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this)),this;if(!e){var r=t.pipes,n=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var i=0;i-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},qt.prototype._write=function(e,t,r){r(new Error("not implemented"))},qt.prototype._writev=null,qt.prototype.end=function(e,t,r){var n=this._writableState;"function"==typeof e?(r=e,e=null,t=null):"function"==typeof t&&(r=t,t=null),null!=e&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||n.finished||function(e,t,r){t.ending=!0,Jt(e,t),r&&(t.finished?b(r):e.once("finish",r));t.ended=!0,e.writable=!1}(this,n,r)},Ze(ir,St);for(var tr=Object.keys(qt.prototype),rr=0;rr"===o?(_(n,"onsgmldeclaration",n.sgmlDecl),n.sgmlDecl="",n.state=E.TEXT):p(o)?(n.state=E.SGML_DECL_QUOTED,n.sgmlDecl+=o):n.sgmlDecl+=o;continue;case E.SGML_DECL_QUOTED:o===n.q&&(n.state=E.SGML_DECL,n.q=""),n.sgmlDecl+=o;continue;case E.DOCTYPE:">"===o?(n.state=E.TEXT,_(n,"ondoctype",n.doctype),n.doctype=!0):(n.doctype+=o,"["===o?n.state=E.DOCTYPE_DTD:p(o)&&(n.state=E.DOCTYPE_QUOTED,n.q=o));continue;case E.DOCTYPE_QUOTED:n.doctype+=o,o===n.q&&(n.q="",n.state=E.DOCTYPE);continue;case E.DOCTYPE_DTD:n.doctype+=o,"]"===o?n.state=E.DOCTYPE:p(o)&&(n.state=E.DOCTYPE_DTD_QUOTED,n.q=o);continue;case E.DOCTYPE_DTD_QUOTED:n.doctype+=o,o===n.q&&(n.state=E.DOCTYPE_DTD,n.q="");continue;case E.COMMENT:"-"===o?n.state=E.COMMENT_ENDING:n.comment+=o;continue;case E.COMMENT_ENDING:"-"===o?(n.state=E.COMMENT_ENDED,n.comment=O(n.opt,n.comment),n.comment&&_(n,"oncomment",n.comment),n.comment=""):(n.comment+="-"+o,n.state=E.COMMENT);continue;case E.COMMENT_ENDED:">"!==o?(R(n,"Malformed comment"),n.comment+="--"+o,n.state=E.COMMENT):n.state=E.TEXT;continue;case E.CDATA:"]"===o?n.state=E.CDATA_ENDING:n.cdata+=o;continue;case E.CDATA_ENDING:"]"===o?n.state=E.CDATA_ENDING_2:(n.cdata+="]"+o,n.state=E.CDATA);continue;case E.CDATA_ENDING_2:">"===o?(n.cdata&&_(n,"oncdata",n.cdata),_(n,"onclosecdata"),n.cdata="",n.state=E.TEXT):"]"===o?n.cdata+="]":(n.cdata+="]]"+o,n.state=E.CDATA);continue;case E.PROC_INST:"?"===o?n.state=E.PROC_INST_ENDING:f(o)?n.state=E.PROC_INST_BODY:n.procInstName+=o;continue;case E.PROC_INST_BODY:if(!n.procInstBody&&f(o))continue;"?"===o?n.state=E.PROC_INST_ENDING:n.procInstBody+=o;continue;case E.PROC_INST_ENDING:">"===o?(_(n,"onprocessinginstruction",{name:n.procInstName,body:n.procInstBody}),n.procInstName=n.procInstBody="",n.state=E.TEXT):(n.procInstBody+="?"+o,n.state=E.PROC_INST_BODY);continue;case E.OPEN_TAG:y(l,o)?n.tagName+=o:(F(n),">"===o?j(n):"/"===o?n.state=E.OPEN_TAG_SLASH:(f(o)||R(n,"Invalid character in tag name"),n.state=E.ATTRIB));continue;case E.OPEN_TAG_SLASH:">"===o?(j(n,!0),L(n)):(R(n,"Forward-slash in opening tag not followed by >"),n.state=E.ATTRIB);continue;case E.ATTRIB:if(f(o))continue;">"===o?j(n):"/"===o?n.state=E.OPEN_TAG_SLASH:y(c,o)?(n.attribName=o,n.attribValue="",n.state=E.ATTRIB_NAME):R(n,"Invalid attribute name");continue;case E.ATTRIB_NAME:"="===o?n.state=E.ATTRIB_VALUE:">"===o?(R(n,"Attribute without value"),n.attribValue=n.attribName,N(n),j(n)):f(o)?n.state=E.ATTRIB_NAME_SAW_WHITE:y(l,o)?n.attribName+=o:R(n,"Invalid attribute name");continue;case E.ATTRIB_NAME_SAW_WHITE:if("="===o)n.state=E.ATTRIB_VALUE;else{if(f(o))continue;R(n,"Attribute without value"),n.tag.attributes[n.attribName]="",n.attribValue="",_(n,"onattribute",{name:n.attribName,value:""}),n.attribName="",">"===o?j(n):y(c,o)?(n.attribName=o,n.state=E.ATTRIB_NAME):(R(n,"Invalid attribute name"),n.state=E.ATTRIB)}continue;case E.ATTRIB_VALUE:if(f(o))continue;p(o)?(n.q=o,n.state=E.ATTRIB_VALUE_QUOTED):(R(n,"Unquoted attribute value"),n.state=E.ATTRIB_VALUE_UNQUOTED,n.attribValue=o);continue;case E.ATTRIB_VALUE_QUOTED:if(o!==n.q){"&"===o?n.state=E.ATTRIB_VALUE_ENTITY_Q:n.attribValue+=o;continue}N(n),n.q="",n.state=E.ATTRIB_VALUE_CLOSED;continue;case E.ATTRIB_VALUE_CLOSED:f(o)?n.state=E.ATTRIB:">"===o?j(n):"/"===o?n.state=E.OPEN_TAG_SLASH:y(c,o)?(R(n,"No whitespace between attributes"),n.attribName=o,n.attribValue="",n.state=E.ATTRIB_NAME):R(n,"Invalid attribute name");continue;case E.ATTRIB_VALUE_UNQUOTED:if(!g(o)){"&"===o?n.state=E.ATTRIB_VALUE_ENTITY_U:n.attribValue+=o;continue}N(n),">"===o?j(n):n.state=E.ATTRIB;continue;case E.CLOSE_TAG:if(n.tagName)">"===o?L(n):y(l,o)?n.tagName+=o:n.script?(n.script+=""===o?L(n):R(n,"Invalid characters in closing tag");continue;case E.TEXT_ENTITY:case E.ATTRIB_VALUE_ENTITY_Q:case E.ATTRIB_VALUE_ENTITY_U:var u,m;switch(n.state){case E.TEXT_ENTITY:u=E.TEXT,m="textNode";break;case E.ATTRIB_VALUE_ENTITY_Q:u=E.ATTRIB_VALUE_QUOTED,m="attribValue";break;case E.ATTRIB_VALUE_ENTITY_U:u=E.ATTRIB_VALUE_UNQUOTED,m="attribValue"}";"===o?(n[m]+=k(n),n.entity="",n.state=u):y(n.entity.length?h:d,o)?n.entity+=o:(R(n,"Invalid character in entity name"),n[m]+="&"+n.entity+o,n.entity="",n.state=u);continue;default:throw new Error(n,"Unknown state: "+n.state)}return n.position>=n.bufferCheckPosition&&function(t){for(var n=Math.max(e.MAX_BUFFER_LENGTH,10),i=0,o=0,a=r.length;on)switch(r[o]){case"textNode":C(t);break;case"cdata":_(t,"oncdata",t.cdata),t.cdata="";break;case"script":_(t,"onscript",t.script),t.script="";break;default:D(t,"Max buffer length exceeded: "+r[o])}i=Math.max(i,s)}var u=e.MAX_BUFFER_LENGTH-i;t.bufferCheckPosition=u+t.position}(n),n} +/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){var e;C(e=this),""!==e.cdata&&(_(e,"oncdata",e.cdata),e.cdata=""),""!==e.script&&(_(e,"onscript",e.script),e.script="")}};try{t=hr.Stream}catch(e){t=function(){}}var i=e.EVENTS.filter((function(e){return"error"!==e&&"end"!==e}));function o(e,r){if(!(this instanceof o))return new o(e,r);t.apply(this),this._parser=new n(e,r),this.writable=!0,this.readable=!0;var a=this;this._parser.onend=function(){a.emit("end")},this._parser.onerror=function(e){a.emit("error",e),a._parser.error=null},this._decoder=null,i.forEach((function(e){Object.defineProperty(a,"on"+e,{get:function(){return a._parser["on"+e]},set:function(t){if(!t)return a.removeAllListeners(e),a._parser["on"+e]=t,t;a.on(e,t)},enumerable:!0,configurable:!1})}))}o.prototype=Object.create(t.prototype,{constructor:{value:o}}),o.prototype.write=function(e){if("function"==typeof re.isBuffer&&re.isBuffer(e)){if(!this._decoder){var t=fr.StringDecoder;this._decoder=new t("utf8")}e=this._decoder.write(e)}return this._parser.write(e.toString()),this.emit("data",e),!0},o.prototype.end=function(e){return e&&e.length&&this.write(e),this._parser.end(),!0},o.prototype.on=function(e,r){var n=this;return n._parser["on"+e]||-1===i.indexOf(e)||(n._parser["on"+e]=function(){var t=1===arguments.length?[arguments[0]]:Array.apply(null,arguments);t.splice(0,0,e),n.emit.apply(n,t)}),t.prototype.on.call(n,e,r)};var a="http://www.w3.org/XML/1998/namespace",s="http://www.w3.org/2000/xmlns/",u={xml:a,xmlns:s},c=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,l=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,d=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,h=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function f(e){return" "===e||"\n"===e||"\r"===e||"\t"===e}function p(e){return'"'===e||"'"===e}function g(e){return">"===e||f(e)}function y(e,t){return e.test(t)}function v(e,t){return!y(e,t)}var m,b,w,E=0;for(var A in e.STATE={BEGIN:E++,BEGIN_WHITESPACE:E++,TEXT:E++,TEXT_ENTITY:E++,OPEN_WAKA:E++,SGML_DECL:E++,SGML_DECL_QUOTED:E++,DOCTYPE:E++,DOCTYPE_QUOTED:E++,DOCTYPE_DTD:E++,DOCTYPE_DTD_QUOTED:E++,COMMENT_STARTING:E++,COMMENT:E++,COMMENT_ENDING:E++,COMMENT_ENDED:E++,CDATA:E++,CDATA_ENDING:E++,CDATA_ENDING_2:E++,PROC_INST:E++,PROC_INST_BODY:E++,PROC_INST_ENDING:E++,OPEN_TAG:E++,OPEN_TAG_SLASH:E++,ATTRIB:E++,ATTRIB_NAME:E++,ATTRIB_NAME_SAW_WHITE:E++,ATTRIB_VALUE:E++,ATTRIB_VALUE_QUOTED:E++,ATTRIB_VALUE_CLOSED:E++,ATTRIB_VALUE_UNQUOTED:E++,ATTRIB_VALUE_ENTITY_Q:E++,ATTRIB_VALUE_ENTITY_U:E++,CLOSE_TAG:E++,CLOSE_TAG_SAW_WHITE:E++,SCRIPT:E++,SCRIPT_ENDING:E++},e.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},e.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(e.ENTITIES).forEach((function(t){var r=e.ENTITIES[t],n="number"==typeof r?String.fromCharCode(r):r;e.ENTITIES[t]=n})),e.STATE)e.STATE[e.STATE[A]]=A;function T(e,t,r){e[t]&&e[t](r)}function _(e,t,r){e.textNode&&C(e),T(e,t,r)}function C(e){e.textNode=O(e.opt,e.textNode),e.textNode&&T(e,"ontext",e.textNode),e.textNode=""}function O(e,t){return e.trim&&(t=t.trim()),e.normalize&&(t=t.replace(/\s+/g," ")),t}function D(e,t){return C(e),e.trackPosition&&(t+="\nLine: "+e.line+"\nColumn: "+e.column+"\nChar: "+e.c),t=new Error(t),e.error=t,T(e,"onerror",t),e}function x(e){return e.sawRoot&&!e.closedRoot&&R(e,"Unclosed root tag"),e.state!==E.BEGIN&&e.state!==E.BEGIN_WHITESPACE&&e.state!==E.TEXT&&D(e,"Unexpected end"),C(e),e.c="",e.closed=!0,T(e,"onend"),n.call(e,e.strict,e.opt),e}function R(e,t){if("object"!=typeof e||!(e instanceof n))throw new Error("bad call to strictFail");e.strict&&D(e,t)}function F(e){e.strict||(e.tagName=e.tagName[e.looseCase]());var t=e.tags[e.tags.length-1]||e,r=e.tag={name:e.tagName,attributes:{}};e.opt.xmlns&&(r.ns=t.ns),e.attribList.length=0,_(e,"onopentagstart",r)}function S(e,t){var r=e.indexOf(":")<0?["",e]:e.split(":"),n=r[0],i=r[1];return t&&"xmlns"===e&&(n="xmlns",i=""),{prefix:n,local:i}}function N(e){if(e.strict||(e.attribName=e.attribName[e.looseCase]()),-1!==e.attribList.indexOf(e.attribName)||e.tag.attributes.hasOwnProperty(e.attribName))e.attribName=e.attribValue="";else{if(e.opt.xmlns){var t=S(e.attribName,!0),r=t.prefix,n=t.local;if("xmlns"===r)if("xml"===n&&e.attribValue!==a)R(e,"xml: prefix must be bound to "+a+"\nActual: "+e.attribValue);else if("xmlns"===n&&e.attribValue!==s)R(e,"xmlns: prefix must be bound to "+s+"\nActual: "+e.attribValue);else{var i=e.tag,o=e.tags[e.tags.length-1]||e;i.ns===o.ns&&(i.ns=Object.create(o.ns)),i.ns[n]=e.attribValue}e.attribList.push([e.attribName,e.attribValue])}else e.tag.attributes[e.attribName]=e.attribValue,_(e,"onattribute",{name:e.attribName,value:e.attribValue});e.attribName=e.attribValue=""}}function j(e,t){if(e.opt.xmlns){var r=e.tag,n=S(e.tagName);r.prefix=n.prefix,r.local=n.local,r.uri=r.ns[n.prefix]||"",r.prefix&&!r.uri&&(R(e,"Unbound namespace prefix: "+JSON.stringify(e.tagName)),r.uri=n.prefix);var i=e.tags[e.tags.length-1]||e;r.ns&&i.ns!==r.ns&&Object.keys(r.ns).forEach((function(t){_(e,"onopennamespace",{prefix:t,uri:r.ns[t]})}));for(var o=0,a=e.attribList.length;o",e.tagName="",void(e.state=E.SCRIPT);_(e,"onscript",e.script),e.script=""}var t=e.tags.length,r=e.tagName;e.strict||(r=r[e.looseCase]());for(var n=r;t--&&e.tags[t].name!==n;)R(e,"Unexpected close tag");if(t<0)return R(e,"Unmatched closing tag: "+e.tagName),e.textNode+="",void(e.state=E.TEXT);e.tagName=r;for(var i=e.tags.length;i-- >t;){var o=e.tag=e.tags.pop();e.tagName=e.tag.name,_(e,"onclosetag",e.tagName);var a={};for(var s in o.ns)a[s]=o.ns[s];var u=e.tags[e.tags.length-1]||e;e.opt.xmlns&&o.ns!==u.ns&&Object.keys(o.ns).forEach((function(t){var r=o.ns[t];_(e,"onclosenamespace",{prefix:t,uri:r})}))}0===t&&(e.closedRoot=!0),e.tagName=e.attribValue=e.attribName="",e.attribList.length=0,e.state=E.TEXT}function k(e){var t,r=e.entity,n=r.toLowerCase(),i="";return e.ENTITIES[r]?e.ENTITIES[r]:e.ENTITIES[n]?e.ENTITIES[n]:("#"===(r=n).charAt(0)&&("x"===r.charAt(1)?(r=r.slice(2),i=(t=parseInt(r,16)).toString(16)):(r=r.slice(1),i=(t=parseInt(r,10)).toString(10))),r=r.replace(/^0+/,""),isNaN(t)||i.toLowerCase()!==r?(R(e,"Invalid character entity"),"&"+e.entity+";"):String.fromCodePoint(t))}function I(e,t){"<"===t?(e.state=E.OPEN_WAKA,e.startTagPosition=e.position):f(t)||(R(e,"Non-whitespace before first tag."),e.textNode=t,e.state=E.TEXT)}function P(e,t){var r="";return t1114111||b(s)!==s)throw RangeError("Invalid code point: "+s);s<=65535?n.push(s):(e=55296+((s-=65536)>>10),t=s%1024+56320,n.push(e,t)),(i+1===o||n.length>r)&&(a+=m.apply(null,n),n.length=0)}return a},Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:w,configurable:!0,writable:!0}):String.fromCodePoint=w)}(Be);var pr,gr,yr=function(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)},vr=yr,mr={copyOptions:function(e){var t,r={};for(t in e)e.hasOwnProperty(t)&&(r[t]=e[t]);return r},ensureFlagExists:function(e,t){e in t&&"boolean"==typeof t[e]||(t[e]=!1)},ensureSpacesExists:function(e){(!("spaces"in e)||"number"!=typeof e.spaces&&"string"!=typeof e.spaces)&&(e.spaces=0)},ensureAlwaysArrayExists:function(e){"alwaysArray"in e&&("boolean"==typeof e.alwaysArray||vr(e.alwaysArray))||(e.alwaysArray=!1)},ensureKeyExists:function(e,t){e+"Key"in t&&"string"==typeof t[e+"Key"]||(t[e+"Key"]=t.compact?"_"+e:e)},checkFnExists:function(e,t){return e+"Fn"in t}},br=Be,wr=mr,Er=yr;function Ar(e){var t=Number(e);if(!isNaN(t))return t;var r=e.toLowerCase();return"true"===r||"false"!==r&&e}function Tr(e,t){var r;if(pr.compact){if(!gr[pr[e+"Key"]]&&(Er(pr.alwaysArray)?-1!==pr.alwaysArray.indexOf(pr[e+"Key"]):pr.alwaysArray)&&(gr[pr[e+"Key"]]=[]),gr[pr[e+"Key"]]&&!Er(gr[pr[e+"Key"]])&&(gr[pr[e+"Key"]]=[gr[pr[e+"Key"]]]),e+"Fn"in pr&&"string"==typeof t&&(t=pr[e+"Fn"](t,gr)),"instruction"===e&&("instructionFn"in pr||"instructionNameFn"in pr))for(r in t)if(t.hasOwnProperty(r))if("instructionFn"in pr)t[r]=pr.instructionFn(t[r],r,gr);else{var n=t[r];delete t[r],t[pr.instructionNameFn(r,n,gr)]=n}Er(gr[pr[e+"Key"]])?gr[pr[e+"Key"]].push(t):gr[pr[e+"Key"]]=t}else{gr[pr.elementsKey]||(gr[pr.elementsKey]=[]);var i={};if(i[pr.typeKey]=e,"instruction"===e){for(r in t)if(t.hasOwnProperty(r))break;i[pr.nameKey]="instructionNameFn"in pr?pr.instructionNameFn(r,t,gr):r,pr.instructionHasAttributes?(i[pr.attributesKey]=t[r][pr.attributesKey],"instructionFn"in pr&&(i[pr.attributesKey]=pr.instructionFn(i[pr.attributesKey],r,gr))):("instructionFn"in pr&&(t[r]=pr.instructionFn(t[r],r,gr)),i[pr.instructionKey]=t[r])}else e+"Fn"in pr&&(t=pr[e+"Fn"](t,gr)),i[pr[e+"Key"]]=t;pr.addParent&&(i[pr.parentKey]=gr),gr[pr.elementsKey].push(i)}}function _r(e){var t;if("attributesFn"in pr&&e&&(e=pr.attributesFn(e,gr)),(pr.trim||"attributeValueFn"in pr||"attributeNameFn"in pr||pr.nativeTypeAttributes)&&e)for(t in e)if(e.hasOwnProperty(t)&&(pr.trim&&(e[t]=e[t].trim()),pr.nativeTypeAttributes&&(e[t]=Ar(e[t])),"attributeValueFn"in pr&&(e[t]=pr.attributeValueFn(e[t],t,gr)),"attributeNameFn"in pr)){var r=e[t];delete e[t],e[pr.attributeNameFn(t,e[t],gr)]=r}return e}function Cr(e){var t={};if(e.body&&("xml"===e.name.toLowerCase()||pr.instructionHasAttributes)){for(var r,n=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|(\w+))\s*/g;null!==(r=n.exec(e.body));)t[r[1]]=r[2]||r[3]||r[4];t=_r(t)}if("xml"===e.name.toLowerCase()){if(pr.ignoreDeclaration)return;gr[pr.declarationKey]={},Object.keys(t).length&&(gr[pr.declarationKey][pr.attributesKey]=t),pr.addParent&&(gr[pr.declarationKey][pr.parentKey]=gr)}else{if(pr.ignoreInstruction)return;pr.trim&&(e.body=e.body.trim());var i={};pr.instructionHasAttributes&&Object.keys(t).length?(i[e.name]={},i[e.name][pr.attributesKey]=t):i[e.name]=e.body,Tr("instruction",i)}}function Or(e,t){var r;if("object"==typeof e&&(t=e.attributes,e=e.name),t=_r(t),"elementNameFn"in pr&&(e=pr.elementNameFn(e,gr)),pr.compact){var n;if(r={},!pr.ignoreAttributes&&t&&Object.keys(t).length)for(n in r[pr.attributesKey]={},t)t.hasOwnProperty(n)&&(r[pr.attributesKey][n]=t[n]);!(e in gr)&&(Er(pr.alwaysArray)?-1!==pr.alwaysArray.indexOf(e):pr.alwaysArray)&&(gr[e]=[]),gr[e]&&!Er(gr[e])&&(gr[e]=[gr[e]]),Er(gr[e])?gr[e].push(r):gr[e]=r}else gr[pr.elementsKey]||(gr[pr.elementsKey]=[]),(r={})[pr.typeKey]="element",r[pr.nameKey]=e,!pr.ignoreAttributes&&t&&Object.keys(t).length&&(r[pr.attributesKey]=t),pr.alwaysChildren&&(r[pr.elementsKey]=[]),gr[pr.elementsKey].push(r);r[pr.parentKey]=gr,gr=r}function Dr(e){pr.ignoreText||(e.trim()||pr.captureSpacesBetweenElements)&&(pr.trim&&(e=e.trim()),pr.nativeType&&(e=Ar(e)),pr.sanitize&&(e=e.replace(/&/g,"&").replace(//g,">")),Tr("text",e))}function xr(e){pr.ignoreComment||(pr.trim&&(e=e.trim()),Tr("comment",e))}function Rr(e){var t=gr[pr.parentKey];pr.addParent||delete gr[pr.parentKey],gr=t}function Fr(e){pr.ignoreCdata||(pr.trim&&(e=e.trim()),Tr("cdata",e))}function Sr(e){pr.ignoreDoctype||(e=e.replace(/^ /,""),pr.trim&&(e=e.trim()),Tr("doctype",e))}function Nr(e){e.note=e}var jr=function(e,t){var r=br.parser(!0,{}),n={};if(gr=n,pr=function(e){return pr=wr.copyOptions(e),wr.ensureFlagExists("ignoreDeclaration",pr),wr.ensureFlagExists("ignoreInstruction",pr),wr.ensureFlagExists("ignoreAttributes",pr),wr.ensureFlagExists("ignoreText",pr),wr.ensureFlagExists("ignoreComment",pr),wr.ensureFlagExists("ignoreCdata",pr),wr.ensureFlagExists("ignoreDoctype",pr),wr.ensureFlagExists("compact",pr),wr.ensureFlagExists("alwaysChildren",pr),wr.ensureFlagExists("addParent",pr),wr.ensureFlagExists("trim",pr),wr.ensureFlagExists("nativeType",pr),wr.ensureFlagExists("nativeTypeAttributes",pr),wr.ensureFlagExists("sanitize",pr),wr.ensureFlagExists("instructionHasAttributes",pr),wr.ensureFlagExists("captureSpacesBetweenElements",pr),wr.ensureAlwaysArrayExists(pr),wr.ensureKeyExists("declaration",pr),wr.ensureKeyExists("instruction",pr),wr.ensureKeyExists("attributes",pr),wr.ensureKeyExists("text",pr),wr.ensureKeyExists("comment",pr),wr.ensureKeyExists("cdata",pr),wr.ensureKeyExists("doctype",pr),wr.ensureKeyExists("type",pr),wr.ensureKeyExists("name",pr),wr.ensureKeyExists("elements",pr),wr.ensureKeyExists("parent",pr),wr.checkFnExists("doctype",pr),wr.checkFnExists("instruction",pr),wr.checkFnExists("cdata",pr),wr.checkFnExists("comment",pr),wr.checkFnExists("text",pr),wr.checkFnExists("instructionName",pr),wr.checkFnExists("elementName",pr),wr.checkFnExists("attributeName",pr),wr.checkFnExists("attributeValue",pr),wr.checkFnExists("attributes",pr),pr}(t),r.opt={strictEntities:!0},r.onopentag=Or,r.ontext=Dr,r.oncomment=xr,r.onclosetag=Rr,r.onerror=Nr,r.oncdata=Fr,r.ondoctype=Sr,r.onprocessinginstruction=Cr,r.write(e).close(),n[pr.elementsKey]){var i=n[pr.elementsKey];delete n[pr.elementsKey],n[pr.elementsKey]=i,delete n.text}return n},Lr=mr,kr=jr;var Ir,Pr,Ur=mr,Br=yr;function Mr(e,t,r){return(!r&&e.spaces?"\n":"")+Array(t+1).join(e.spaces)}function Vr(e,t,r){if(t.ignoreAttributes)return"";"attributesFn"in t&&(e=t.attributesFn(e,Pr,Ir));var n,i,o,a,s=[];for(n in e)e.hasOwnProperty(n)&&null!==e[n]&&void 0!==e[n]&&(a=t.noQuotesForNativeAttributes&&"string"!=typeof e[n]?"":'"',i=(i=""+e[n]).replace(/"/g,"""),o="attributeNameFn"in t?t.attributeNameFn(n,i,Pr,Ir):n,s.push(t.spaces&&t.indentAttributes?Mr(t,r+1,!1):" "),s.push(o+"="+a+("attributeValueFn"in t?t.attributeValueFn(i,n,Pr,Ir):i)+a));return e&&Object.keys(e).length&&t.spaces&&t.indentAttributes&&s.push(Mr(t,r,!1)),s.join("")}function Kr(e,t,r){return Ir=e,Pr="xml",t.ignoreDeclaration?"":""}function $r(e,t,r){if(t.ignoreInstruction)return"";var n;for(n in e)if(e.hasOwnProperty(n))break;var i="instructionNameFn"in t?t.instructionNameFn(n,e[n],Pr,Ir):n;if("object"==typeof e[n])return Ir=e,Pr=i,"";var o=e[n]?e[n]:"";return"instructionFn"in t&&(o=t.instructionFn(o,n,Pr,Ir)),""}function Hr(e,t){return t.ignoreComment?"":"\x3c!--"+("commentFn"in t?t.commentFn(e,Pr,Ir):e)+"--\x3e"}function Yr(e,t){return t.ignoreCdata?"":"","]]]]>"))+"]]>"}function zr(e,t){return t.ignoreDoctype?"":""}function qr(e,t){return t.ignoreText?"":(e=(e=(e=""+e).replace(/&/g,"&")).replace(/&/g,"&").replace(//g,">"),"textFn"in t?t.textFn(e,Pr,Ir):e)}function Gr(e,t,r,n){return e.reduce((function(e,i){var o=Mr(t,r,n&&!e);switch(i.type){case"element":return e+o+function(e,t,r){Ir=e,Pr=e.name;var n=[],i="elementNameFn"in t?t.elementNameFn(e.name,e):e.name;n.push("<"+i),e[t.attributesKey]&&n.push(Vr(e[t.attributesKey],t,r));var o=e[t.elementsKey]&&e[t.elementsKey].length||e[t.attributesKey]&&"preserve"===e[t.attributesKey]["xml:space"];return o||(o="fullTagEmptyElementFn"in t?t.fullTagEmptyElementFn(e.name,e):t.fullTagEmptyElement),o?(n.push(">"),e[t.elementsKey]&&e[t.elementsKey].length&&(n.push(Gr(e[t.elementsKey],t,r+1)),Ir=e,Pr=e.name),n.push(t.spaces&&function(e,t){var r;if(e.elements&&e.elements.length)for(r=0;r")):n.push("/>"),n.join("")}(i,t,r);case"comment":return e+o+Hr(i[t.commentKey],t);case"doctype":return e+o+zr(i[t.doctypeKey],t);case"cdata":return e+(t.indentCdata?o:"")+Yr(i[t.cdataKey],t);case"text":return e+(t.indentText?o:"")+qr(i[t.textKey],t);case"instruction":var a={};return a[i[t.nameKey]]=i[t.attributesKey]?i:i[t.instructionKey],e+(t.indentInstruction?o:"")+$r(a,t,r)}}),"")}function Wr(e,t,r){var n;for(n in e)if(e.hasOwnProperty(n))switch(n){case t.parentKey:case t.attributesKey:break;case t.textKey:if(t.indentText||r)return!0;break;case t.cdataKey:if(t.indentCdata||r)return!0;break;case t.instructionKey:if(t.indentInstruction||r)return!0;break;case t.doctypeKey:case t.commentKey:default:return!0}return!1}function Qr(e,t,r,n,i){Ir=e,Pr=t;var o="elementNameFn"in r?r.elementNameFn(t,e):t;if(null==e||""===e)return"fullTagEmptyElementFn"in r&&r.fullTagEmptyElementFn(t,e)||r.fullTagEmptyElement?"<"+o+">":"<"+o+"/>";var a=[];if(t){if(a.push("<"+o),"object"!=typeof e)return a.push(">"+qr(e,r)+""),a.join("");e[r.attributesKey]&&a.push(Vr(e[r.attributesKey],r,n));var s=Wr(e,r,!0)||e[r.attributesKey]&&"preserve"===e[r.attributesKey]["xml:space"];if(s||(s="fullTagEmptyElementFn"in r?r.fullTagEmptyElementFn(t,e):r.fullTagEmptyElement),!s)return a.push("/>"),a.join("");a.push(">")}return a.push(Xr(e,r,n+1,!1)),Ir=e,Pr=t,t&&a.push((i?Mr(r,n,!1):"")+""),a.join("")}function Xr(e,t,r,n){var i,o,a,s=[];for(o in e)if(e.hasOwnProperty(o))for(a=Br(e[o])?e[o]:[e[o]],i=0;i{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},on=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),n=t.trim();if(Math.abs(r.length-n.length)>1)return!1;const i="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===n.slice(-1)?n.slice(0,-1):n;return e.includes(o)||t.includes(i)},an=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),n=t.trim(),i="/"===r.slice(-1)?r.slice(0,-1):r,o="/"===n.slice(-1)?n.slice(0,-1):n;return e.includes(o)||t.includes(i)},sn=e=>e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[M[t]]:t})),{}),un=e=>Object.entries(e).reduce(((e,[t,r])=>r?Object.assign(Object.assign({},e),{[t]:r}):e),{}),cn=(e,t)=>t?{[e]:t}:{};var ln=Object.freeze({__proto__:null,cleanupFalsy:un,conditionalParam:cn,getDAVAttribute:sn,urlContains:an,urlEquals:on});const dn=B("tsdav:request"),hn=e=>t(void 0,void 0,void 0,(function*(){var t;const{url:r,init:n,convertIncoming:i=!0,parseOutgoing:o=!0}=e,{headers:s={},body:u,namespace:c,method:l,attributes:d}=n,h=i?rn.js2xml(Object.assign(Object.assign({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},u),{_attributes:d}),{compact:!0,spaces:2,elementNameFn:e=>c&&!/^.+:.+/.test(e)?`${c}:${e}`:e}):u,f=yield a.fetch(r,{headers:Object.assign({"Content-Type":"text/xml;charset=UTF-8"},un(s)),body:h,method:l}),p=yield f.text();if(!f.ok||!(null===(t=f.headers.get("content-type"))||void 0===t?void 0:t.includes("xml"))||!o)return[{href:f.url,ok:f.ok,status:f.status,statusText:f.statusText,raw:p}];const g=rn.xml2js(p,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,n=Object.keys(r),i=n[n.length-1],o=r[i];if(o.length>0){o[o.length-1]=nn(e)}else r[i]=nn(e)}catch(e){dn(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,(e=>e[1].toUpperCase())),attributesFn:e=>{const t=Object.assign({},e);return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(g.multistatus.response)?g.multistatus.response:[g.multistatus.response]).map((e=>{var t,r;if(!e)return{status:f.status,statusText:f.statusText,ok:f.ok};const n=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:g,href:e.href,status:(null==n?void 0:n.groups)?Number.parseInt(null==n?void 0:n.groups.status,10):f.status,statusText:null!==(r=null===(t=null==n?void 0:n.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:f.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce(((e,t)=>Object.assign(Object.assign({},e),null==t?void 0:t.prop)),{})}}))})),fn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:n,headers:i}=e;return hn({url:t,init:{method:"PROPFIND",headers:un(Object.assign({depth:n},i)),namespace:V.DAV,body:{propfind:{_attributes:sn([U.CALDAV,U.CALDAV_APPLE,U.CALENDAR_SERVER,U.CARDDAV,U.DAV]),prop:r}}}})})),pn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,data:r,headers:n}=e;return a.fetch(t,{method:"PUT",body:r,headers:n})})),gn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,data:r,etag:n,headers:i}=e;return a.fetch(t,{method:"PUT",body:r,headers:un(Object.assign({"If-Match":n},i))})})),yn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,headers:r,etag:n}=e;return a.fetch(t,{method:"DELETE",headers:un(Object.assign({"If-Match":n},r))})}));var vn=Object.freeze({__proto__:null,createObject:pn,davRequest:hn,deleteObject:yn,propfind:fn,updateObject:gn});function mn(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const bn=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),wn=B("tsdav:collection"),En=e=>t(void 0,void 0,void 0,(function*(){const{url:t,body:r,depth:n,defaultNamespace:i=V.DAV,headers:o}=e,a=yield hn({url:t,init:{method:"REPORT",headers:un(Object.assign({depth:n},o)),namespace:i,body:r}});return 1!==a.length||a[0].raw?a:[]})),An=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:n,headers:i}=e;return hn({url:t,init:{method:"MKCOL",headers:un(Object.assign({depth:n},i)),namespace:V.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0}})})),Tn=e=>t(void 0,void 0,void 0,(function*(){var t,r,n,i,o;const{collection:a,headers:s}=e;return null!==(o=null===(i=null===(n=null===(r=null===(t=(yield fn({url:a.url,props:{[`${V.DAV}:supported-report-set`]:{}},depth:"0",headers:s}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===n?void 0:n.supportedReport)||void 0===i?void 0:i.map((e=>Object.keys(e.report)[0])))&&void 0!==o?o:[]})),_n=e=>t(void 0,void 0,void 0,(function*(){var t,r,n;const{collection:i,headers:o}=e,a=(yield fn({url:i.url,props:{[`${V.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:o})).filter((e=>an(i.url,e.href)))[0];if(!a)throw new Error("Collection does not exist on server");return{isDirty:i.ctag!==(null===(t=a.props)||void 0===t?void 0:t.getctag),newCtag:null===(n=null===(r=a.props)||void 0===r?void 0:r.getctag)||void 0===n?void 0:n.toString()}})),Cn=e=>{const{url:t,props:r,headers:n,syncLevel:i,syncToken:o}=e;return hn({url:t,init:{method:"REPORT",namespace:V.DAV,headers:Object.assign({},n),body:{"sync-collection":{_attributes:sn([U.CALDAV,U.CARDDAV,U.DAV]),"sync-level":i,"sync-token":o,[`${V.DAV}:prop`]:r}}}})},On=e=>t(void 0,void 0,void 0,(function*(){var t,r,n,i,o,a,s,u,c,l,d;const{collection:h,method:f,headers:p,account:g,detailedResult:y}=e,v=["accountType","homeUrl"];if(!g||!mn(g,v)){if(!g)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${bn(g,v)} before smartCollectionSync`)}const m=null!=f?f:(null===(t=h.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(wn(`smart collection sync with type ${g.accountType} and method ${m}`),"webdav"===m){const e=yield Cn({url:h.url,props:{[`${V.DAV}:getetag`]:{},[`${"caldav"===g.accountType?V.CALDAV:V.CARDDAV}:${"caldav"===g.accountType?"calendar-data":"address-data"}`]:{},[`${V.DAV}:displayname`]:{}},syncLevel:1,syncToken:h.syncToken,headers:p}),t=e.filter((e=>{var t;const r="caldav"===g.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r})),c=t.filter((e=>404!==e.status)).map((e=>e.href)),l=t.filter((e=>404===e.status)).map((e=>e.href)),d=(c.length&&null!==(n=yield null===(r=null==h?void 0:h.objectMultiGet)||void 0===r?void 0:r.call(h,{url:h.url,props:{[`${V.DAV}:getetag`]:{},[`${"caldav"===g.accountType?V.CALDAV:V.CARDDAV}:${"caldav"===g.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:c,depth:"1",headers:p}))&&void 0!==n?n:[]).map((e=>{var t,r,n,i,o,a,s,u,c,l;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==g?void 0:g.accountType)?null!==(o=null===(i=null===(n=e.props)||void 0===n?void 0:n.calendarData)||void 0===i?void 0:i._cdata)&&void 0!==o?o:null===(a=e.props)||void 0===a?void 0:a.calendarData:null!==(c=null===(u=null===(s=e.props)||void 0===s?void 0:s.addressData)||void 0===u?void 0:u._cdata)&&void 0!==c?c:null===(l=e.props)||void 0===l?void 0:l.addressData}})),f=null!==(i=h.objects)&&void 0!==i?i:[],v=d.filter((e=>f.every((t=>!an(t.url,e.url))))),m=f.reduce(((e,t)=>{const r=d.find((e=>an(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),b=l.map((e=>({url:e,etag:""}))),w=f.filter((e=>d.some((t=>an(e.url,t.url)&&t.etag===e.etag))));return Object.assign(Object.assign({},h),{objects:y?{created:v,updated:m,deleted:b}:[...w,...v,...m],syncToken:null!==(u=null===(s=null===(a=null===(o=e[0])||void 0===o?void 0:o.raw)||void 0===a?void 0:a.multistatus)||void 0===s?void 0:s.syncToken)&&void 0!==u?u:h.syncToken})}if("basic"===m){const{isDirty:e,newCtag:t}=yield _n({collection:h,headers:p}),r=null!==(c=h.objects)&&void 0!==c?c:[],n=null!==(d=yield null===(l=h.fetchObjects)||void 0===l?void 0:l.call(h,{collection:h,headers:p}))&&void 0!==d?d:[],i=n.filter((e=>r.every((t=>!an(t.url,e.url))))),o=r.reduce(((e,t)=>{const r=n.find((e=>an(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),a=r.filter((e=>n.every((t=>!an(t.url,e.url))))),s=r.filter((e=>n.some((t=>an(e.url,t.url)&&t.etag===e.etag))));if(e)return Object.assign(Object.assign({},h),{objects:y?{created:i,updated:o,deleted:a}:[...s,...i,...o],ctag:t})}return y?Object.assign(Object.assign({},h),{objects:{created:[],updated:[],deleted:[]}}):h}));var Dn=Object.freeze({__proto__:null,collectionQuery:En,isCollectionDirty:_n,makeCollection:An,smartCollectionSync:On,supportedReportSet:Tn,syncCollection:Cn});const xn=B("tsdav:addressBook"),Rn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:n,depth:i,headers:o}=e;return En({url:t,body:{"addressbook-query":{_attributes:sn([U.CARDDAV,U.DAV]),[`${V.DAV}:prop`]:r,filter:null!=n?n:{"prop-filter":{_attributes:{name:"FN"}}}}},defaultNamespace:V.CARDDAV,depth:i,headers:o})})),Fn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:n,depth:i,headers:o}=e;return En({url:t,body:{"addressbook-multiget":{_attributes:sn([U.DAV,U.CARDDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n}},defaultNamespace:V.CARDDAV,depth:i,headers:o})})),Sn=e=>t(void 0,void 0,void 0,(function*(){const{account:r,headers:n,props:i}=null!=e?e:{},o=["homeUrl","rootUrl"];if(!r||!mn(r,o)){if(!r)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${bn(r,o)} before fetchAddressBooks`)}const a=yield fn({url:r.homeUrl,props:null!=i?i:{[`${V.DAV}:displayname`]:{},[`${V.CALENDAR_SERVER}:getctag`]:{},[`${V.DAV}:resourcetype`]:{},[`${V.DAV}:sync-token`]:{}},depth:"1",headers:n});return Promise.all(a.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")})).map((e=>{var t,n,i,o,a,s,u,c,l;const d=null!==(i=null===(n=null===(t=e.props)||void 0===t?void 0:t.displayname)||void 0===n?void 0:n._cdata)&&void 0!==i?i:null===(o=e.props)||void 0===o?void 0:o.displayname;return xn(`Found address book named ${"string"==typeof d?d:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(a=e.href)&&void 0!==a?a:"",null!==(s=r.rootUrl)&&void 0!==s?s:"").href,ctag:null===(u=e.props)||void 0===u?void 0:u.getctag,displayName:"string"==typeof d?d:"",resourcetype:Object.keys(null===(c=e.props)||void 0===c?void 0:c.resourcetype),syncToken:null===(l=e.props)||void 0===l?void 0:l.syncToken}})).map((e=>t(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield Tn({collection:e,headers:n})})})))))})),Nn=e=>t(void 0,void 0,void 0,(function*(){const{addressBook:t,headers:r,objectUrls:n,urlFilter:i=(e=>e),useMultiGet:o=!0}=e;xn(`Fetching vcards from ${null==t?void 0:t.url}`);const a=["url"];if(!t||!mn(t,a)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${bn(t,a)} before fetchVCards`)}const s=(null!=n?n:(yield Rn({url:t.url,props:{[`${V.DAV}:getetag`]:{}},depth:"1",headers:r})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(i).map((e=>new URL(e).pathname));let u=[];return s.length>0&&(u=o?yield Fn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CARDDAV}:address-data`]:{}},objectUrls:s,depth:"1",headers:r}):yield Rn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CARDDAV}:address-data`]:{}},depth:"1",headers:r})),u.map((e=>{var r,n,i,o,a,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(n=e.props)||void 0===n?void 0:n.getetag,data:null!==(a=null===(o=null===(i=e.props)||void 0===i?void 0:i.addressData)||void 0===o?void 0:o._cdata)&&void 0!==a?a:null===(s=e.props)||void 0===s?void 0:s.addressData}}))})),jn=e=>t(void 0,void 0,void 0,(function*(){const{addressBook:t,vCardString:r,filename:n,headers:i}=e;return pn({url:new URL(n,t.url).href,data:r,headers:Object.assign({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*"},i)})})),Ln=e=>t(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return gn({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/vcard; charset=utf-8"},r)})})),kn=e=>t(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return yn({url:t.url,etag:t.etag,headers:r})}));var In=Object.freeze({__proto__:null,addressBookMultiGet:Fn,addressBookQuery:Rn,createVCard:jn,deleteVCard:kn,fetchAddressBooks:Sn,fetchVCards:Nn,updateVCard:Ln});const Pn=B("tsdav:calendar"),Un=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:n,timezone:i,depth:o,headers:a}=e;return En({url:t,body:{"calendar-query":un({_attributes:sn([U.CALDAV,U.CALENDAR_SERVER,U.CALDAV_APPLE,U.DAV]),[`${V.DAV}:prop`]:r,filter:n,timezone:i})},defaultNamespace:V.CALDAV,depth:o,headers:a})})),Bn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:n,filters:i,timezone:o,depth:a,headers:s}=e;return En({url:t,body:{"calendar-multiget":Object.assign(Object.assign({_attributes:sn([U.DAV,U.CALDAV]),[`${V.DAV}:prop`]:r,[`${V.DAV}:href`]:n},cn("filter",i)),{timezone:o})},defaultNamespace:V.CALDAV,depth:a,headers:s})})),Mn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:n,headers:i}=e;return hn({url:t,init:{method:"MKCALENDAR",headers:un(Object.assign({depth:n},i)),namespace:V.DAV,body:{[`${V.CALDAV}:mkcalendar`]:{_attributes:sn([U.DAV,U.CALDAV,U.CALDAV_APPLE]),set:{prop:r}}}}})})),Vn=e=>t(void 0,void 0,void 0,(function*(){const{headers:r,account:n,props:i,projectedProps:o}=null!=e?e:{},a=["homeUrl","rootUrl"];if(!n||!mn(n,a)){if(!n)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${bn(n,a)} before fetchCalendars`)}const s=yield fn({url:n.homeUrl,props:null!=i?i:{[`${V.CALDAV}:calendar-description`]:{},[`${V.CALDAV}:calendar-timezone`]:{},[`${V.DAV}:displayname`]:{},[`${V.CALDAV_APPLE}:calendar-color`]:{},[`${V.CALENDAR_SERVER}:getctag`]:{},[`${V.DAV}:resourcetype`]:{},[`${V.CALDAV}:supported-calendar-component-set`]:{},[`${V.DAV}:sync-token`]:{}},depth:"1",headers:r});return Promise.all(s.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")})).filter((e=>{var t,r,n;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(n=e.props)||void 0===n?void 0:n.supportedCalendarComponentSet.comp._attributes.name]||[]).some((e=>Object.values(K).includes(e)))})).map((e=>{var t,r,i,a,s,u,c,l,d,h,f,p,g,y,v;const m=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,b=null===(r=e.props)||void 0===r?void 0:r.calendarTimezone;return Object.assign({description:"string"==typeof m?m:"",timezone:"string"==typeof b?b:"",url:new URL(null!==(i=e.href)&&void 0!==i?i:"",null!==(a=n.rootUrl)&&void 0!==a?a:"").href,ctag:null===(s=e.props)||void 0===s?void 0:s.getctag,calendarColor:null===(u=e.props)||void 0===u?void 0:u.calendarColor,displayName:null!==(l=null===(c=e.props)||void 0===c?void 0:c.displayname._cdata)&&void 0!==l?l:null===(d=e.props)||void 0===d?void 0:d.displayname,components:Array.isArray(null===(h=e.props)||void 0===h?void 0:h.supportedCalendarComponentSet.comp)?null===(f=e.props)||void 0===f?void 0:f.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp._attributes.name],resourcetype:Object.keys(null===(g=e.props)||void 0===g?void 0:g.resourcetype),syncToken:null===(y=e.props)||void 0===y?void 0:y.syncToken},cn("projectedProps",Object.fromEntries(Object.entries(null!==(v=e.props)&&void 0!==v?v:{}).filter((([e])=>null==o?void 0:o[e])))))})).map((e=>t(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield Tn({collection:e,headers:r})})})))))})),Kn=e=>t(void 0,void 0,void 0,(function*(){const{calendar:t,objectUrls:r,filters:n,timeRange:i,headers:o,expand:a,urlFilter:s=(e=>Boolean(null==e?void 0:e.includes(".ics"))),useMultiGet:u=!0}=e;if(i){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(i.start)&&e.test(i.end)||t.test(i.start)&&t.test(i.end)))throw new Error("invalid timeRange format, not in ISO8601")}Pn(`Fetching calendar objects from ${null==t?void 0:t.url}`);const c=["url"];if(!t||!mn(t,c)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${bn(t,c)} before fetchCalendarObjects`)}const l=null!=n?n:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":Object.assign({_attributes:{name:"VEVENT"}},i?{"time-range":{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})}}],d=(null!=r?r:(yield Un({url:t.url,props:{[`${V.DAV}:getetag`]:Object.assign({},a&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:l,depth:"1",headers:o})).map((e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(s).map((e=>new URL(e).pathname));let h=[];return d.length>0&&(h=!u||a?yield Un({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:Object.assign({},a&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:l,depth:"1",headers:o}):yield Bn({url:t.url,props:{[`${V.DAV}:getetag`]:{},[`${V.CALDAV}:calendar-data`]:Object.assign({},a&&i?{[`${V.CALDAV}:expand`]:{_attributes:{start:`${new Date(i.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(i.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},objectUrls:d,depth:"1",headers:o})),h.map((e=>{var r,n,i,o,a,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(n=e.props)||void 0===n?void 0:n.getetag}`,data:null!==(a=null===(o=null===(i=e.props)||void 0===i?void 0:i.calendarData)||void 0===o?void 0:o._cdata)&&void 0!==a?a:null===(s=e.props)||void 0===s?void 0:s.calendarData}}))})),$n=e=>t(void 0,void 0,void 0,(function*(){const{calendar:t,iCalString:r,filename:n,headers:i}=e;return pn({url:new URL(n,t.url).href,data:r,headers:Object.assign({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*"},i)})})),Hn=e=>t(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return gn({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/calendar; charset=utf-8"},r)})})),Yn=e=>t(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return yn({url:t.url,etag:t.etag,headers:r})})),zn=e=>t(void 0,void 0,void 0,(function*(){var r;const{oldCalendars:n,account:i,detailedResult:o,headers:a}=e;if(!i)throw new Error("Must have account before syncCalendars");const s=null!==(r=null!=n?n:i.calendars)&&void 0!==r?r:[],u=yield Vn({account:i,headers:a}),c=u.filter((e=>s.every((t=>!an(t.url,e.url)))));Pn(`new calendars: ${c.map((e=>e.displayName))}`);const l=s.reduce(((e,t)=>{const r=u.find((e=>an(e.url,t.url)));return r&&(r.syncToken&&r.syncToken!==t.syncToken||r.ctag&&r.ctag!==t.ctag)?[...e,r]:e}),[]);Pn(`updated calendars: ${l.map((e=>e.displayName))}`);const d=yield Promise.all(l.map((e=>t(void 0,void 0,void 0,(function*(){return yield On({collection:Object.assign(Object.assign({},e),{objectMultiGet:Bn}),method:"webdav",headers:a,account:i})}))))),h=s.filter((e=>u.every((t=>!an(t.url,e.url)))));Pn(`deleted calendars: ${h.map((e=>e.displayName))}`);const f=s.filter((e=>u.some((t=>an(t.url,e.url)&&(t.syncToken&&t.syncToken!==e.syncToken||t.ctag&&t.ctag!==e.ctag)))));return o?{created:c,updated:l,deleted:h}:[...f,...c,...d]})),qn=e=>t(void 0,void 0,void 0,(function*(){const{url:t,timeRange:r,depth:n,headers:i}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(yield En({url:t,body:{"free-busy-query":un({_attributes:sn([U.CALDAV]),[`${V.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:V.CALDAV,depth:n,headers:i}))[0]}));var Gn=Object.freeze({__proto__:null,calendarMultiGet:Bn,calendarQuery:Un,createCalendarObject:$n,deleteCalendarObject:Yn,fetchCalendarObjects:Kn,fetchCalendars:Vn,freeBusyQuery:qn,makeCalendar:Mn,syncCalendars:zn,updateCalendarObject:Hn});const Wn=B("tsdav:account"),Qn=e=>t(void 0,void 0,void 0,(function*(){var t,r;Wn("Service discovery...");const{account:n,headers:i}=e,o=new URL(n.serverUrl),s=new URL(`/.well-known/${n.accountType}`,o);s.protocol=null!==(t=o.protocol)&&void 0!==t?t:"http";try{const e=yield a.fetch(s.href,{headers:i,method:"PROPFIND",redirect:"manual"});if(e.status>=300&&e.status<400){const t=e.headers.get("Location");if("string"==typeof t&&t.length){Wn(`Service discovery redirected to ${t}`);const e=new URL(t,o);return e.hostname===s.hostname&&s.port&&!e.port&&(e.port=s.port),e.protocol=null!==(r=o.protocol)&&void 0!==r?r:"http",e.href}}}catch(e){Wn(`Service discovery failed: ${e.stack}`)}return o.href})),Xn=e=>t(void 0,void 0,void 0,(function*(){var t,r,n,i,o;const{account:a,headers:s}=e,u=["rootUrl"];if(!mn(a,u))throw new Error(`account must have ${bn(a,u)} before fetchPrincipalUrl`);Wn(`Fetching principal url from path ${a.rootUrl}`);const[c]=yield fn({url:a.rootUrl,props:{[`${V.DAV}:current-user-principal`]:{}},depth:"0",headers:s});if(!c.ok&&(Wn(`Fetch principal url failed: ${c.statusText}`),401===c.status))throw new Error("Invalid credentials");return Wn(`Fetched principal url ${null===(r=null===(t=c.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(o=null===(i=null===(n=c.props)||void 0===n?void 0:n.currentUserPrincipal)||void 0===i?void 0:i.href)&&void 0!==o?o:"",a.rootUrl).href})),Zn=e=>t(void 0,void 0,void 0,(function*(){var t,r;const{account:n,headers:i}=e,o=["principalUrl","rootUrl"];if(!mn(n,o))throw new Error(`account must have ${bn(n,o)} before fetchHomeUrl`);Wn(`Fetch home url from ${n.principalUrl}`);const a=(yield fn({url:n.principalUrl,props:"caldav"===n.accountType?{[`${V.CALDAV}:calendar-home-set`]:{}}:{[`${V.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:i})).find((e=>an(n.principalUrl,e.href)));if(!a||!a.ok)throw new Error("cannot find homeUrl");const s=new URL("caldav"===n.accountType?null===(t=null==a?void 0:a.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==a?void 0:a.props)||void 0===r?void 0:r.addressbookHomeSet.href,n.rootUrl).href;return Wn(`Fetched home url ${s}`),s})),Jn=e=>t(void 0,void 0,void 0,(function*(){const{account:r,headers:n,loadCollections:i=!1,loadObjects:o=!1}=e,a=Object.assign({},r);return a.rootUrl=yield Qn({account:r,headers:n}),a.principalUrl=yield Xn({account:a,headers:n}),a.homeUrl=yield Zn({account:a,headers:n}),(i||o)&&("caldav"===r.accountType?a.calendars=yield Vn({headers:n,account:a}):"carddav"===r.accountType&&(a.addressBooks=yield Sn({headers:n,account:a}))),o&&("caldav"===r.accountType&&a.calendars?a.calendars=yield Promise.all(a.calendars.map((e=>t(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield Kn({calendar:e,headers:n})})}))))):"carddav"===r.accountType&&a.addressBooks&&(a.addressBooks=yield Promise.all(a.addressBooks.map((e=>t(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield Nn({addressBook:e,headers:n})})}))))))),a}));var ei,ti,ri=Object.freeze({__proto__:null,createAccount:Jn,fetchHomeUrl:Zn,fetchPrincipalUrl:Xn,serviceDiscovery:Qn}),ni={exports:{}};ei=ni,ti=ni.exports,function(e){var t=ti,n=ei&&ei.exports==t&&ei,i="object"==typeof r&&r;i.global!==i&&i.window!==i||(e=i);var o=function(e){this.message=e};(o.prototype=new Error).name="InvalidCharacterError";var a=function(e){throw new o(e)},s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",u=/[\t\n\f\r ]/g,c={encode:function(e){e=String(e),/[^\0-\xFF]/.test(e)&&a("The string to be encoded contains characters outside of the Latin1 range.");for(var t,r,n,i,o=e.length%3,u="",c=-1,l=e.length-o;++c>18&63)+s.charAt(i>>12&63)+s.charAt(i>>6&63)+s.charAt(63&i);return 2==o?(t=e.charCodeAt(c)<<8,r=e.charCodeAt(++c),u+=s.charAt((i=t+r)>>10)+s.charAt(i>>4&63)+s.charAt(i<<2&63)+"="):1==o&&(i=e.charCodeAt(c),u+=s.charAt(i>>2)+s.charAt(i<<4&63)+"=="),u},decode:function(e){var t=(e=String(e).replace(u,"")).length;t%4==0&&(t=(e=e.replace(/==?$/,"")).length),(t%4==1||/[^+a-zA-Z0-9/]/.test(e))&&a("Invalid character: the string to be decoded is not correctly encoded.");for(var r,n,i=0,o="",c=-1;++c>(-2*i&6)));return o},version:"1.0.0"};if(t&&!t.nodeType)if(n)n.exports=c;else for(var l in c)c.hasOwnProperty(l)&&(t[l]=c[l]);else e.base64=c}(r);var ii=ni.exports;const oi=B("tsdav:authHelper"),ai=(e,t)=>(...r)=>e(Object.assign(Object.assign({},t),r[0])),si=e=>(oi(`Basic auth token generated: ${ii.encode(`${e.username}:${e.password}`)}`),{authorization:`Basic ${ii.encode(`${e.username}:${e.password}`)}`}),ui=e=>t(void 0,void 0,void 0,(function*(){const t=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!mn(e,t))throw new Error(`Oauth credentials missing: ${bn(e,t)}`);const r=new URLSearchParams({grant_type:"authorization_code",code:e.authorizationCode,redirect_uri:e.redirectUrl,client_id:e.clientId,client_secret:e.clientSecret});oi(e.tokenUrl),oi(r.toString());const n=yield a.fetch(e.tokenUrl,{method:"POST",body:r.toString(),headers:{"content-length":`${r.toString().length}`,"content-type":"application/x-www-form-urlencoded"}});if(n.ok){return yield n.json()}return oi(`Fetch Oauth tokens failed: ${yield n.text()}`),{}})),ci=e=>t(void 0,void 0,void 0,(function*(){const t=["refreshToken","clientId","clientSecret","tokenUrl"];if(!mn(e,t))throw new Error(`Oauth credentials missing: ${bn(e,t)}`);const r=new URLSearchParams({client_id:e.clientId,client_secret:e.clientSecret,refresh_token:e.refreshToken,grant_type:"refresh_token"}),n=yield a.fetch(e.tokenUrl,{method:"POST",body:r.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(n.ok){return yield n.json()}return oi(`Refresh access token failed: ${yield n.text()}`),{}})),li=e=>t(void 0,void 0,void 0,(function*(){var t;oi("Fetching oauth headers");let r={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(t=e.expiration)&&void 0!==t?t:0))&&(r=yield ci(e)):r=yield ui(e),oi(`Oauth tokens fetched: ${r.access_token}`),{tokens:r,headers:{authorization:`Bearer ${r.access_token}`}}}));var di=Object.freeze({__proto__:null,defaultParam:ai,fetchOauthTokens:ui,getBasicAuthHeaders:si,getOauthHeaders:li,refreshAccessToken:ci});const hi=r=>t(void 0,void 0,void 0,(function*(){var n;const{serverUrl:i,credentials:o,authMethod:a,defaultAccountType:s,authFunction:u}=r;let c={};switch(a){case"Basic":c=si(o);break;case"Oauth":c=(yield li(o)).headers;break;case"Digest":c={Authorization:`Digest ${o.digestString}`};break;case"Custom":c=null!==(n=yield null==u?void 0:u(o))&&void 0!==n?n:{};break;default:throw new Error("Invalid auth method")}const l=s?yield Jn({account:{serverUrl:i,credentials:o,accountType:s},headers:c}):void 0,d=ai(pn,{url:i,headers:c}),h=ai(gn,{headers:c,url:i}),f=ai(yn,{headers:c,url:i}),p=ai(fn,{headers:c}),g=ai(En,{headers:c}),y=ai(An,{headers:c}),v=ai(Cn,{headers:c}),m=ai(Tn,{headers:c}),b=ai(_n,{headers:c}),w=ai(On,{headers:c,account:l}),E=ai(Un,{headers:c}),A=ai(Bn,{headers:c}),T=ai(Mn,{headers:c}),_=ai(Vn,{headers:c,account:l}),C=ai(Kn,{headers:c}),O=ai($n,{headers:c}),D=ai(Hn,{headers:c}),x=ai(Yn,{headers:c}),R=ai(zn,{account:l,headers:c}),F=ai(Rn,{headers:c}),S=ai(Fn,{headers:c});return{davRequest:r=>t(void 0,void 0,void 0,(function*(){const{init:t}=r,n=e(r,["init"]),{headers:i}=t,o=e(t,["headers"]);return hn(Object.assign(Object.assign({},n),{init:Object.assign(Object.assign({},o),{headers:Object.assign(Object.assign({},c),i)})}))})),propfind:p,createAccount:e=>t(void 0,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:n,loadObjects:a}=e;return Jn({account:Object.assign({serverUrl:i,credentials:o},t),headers:Object.assign(Object.assign({},c),r),loadCollections:n,loadObjects:a})})),createObject:d,updateObject:h,deleteObject:f,calendarQuery:E,addressBookQuery:F,collectionQuery:g,makeCollection:y,calendarMultiGet:A,makeCalendar:T,syncCollection:v,supportedReportSet:m,isCollectionDirty:b,smartCollectionSync:w,fetchCalendars:_,fetchCalendarObjects:C,createCalendarObject:O,updateCalendarObject:D,deleteCalendarObject:x,syncCalendars:R,fetchAddressBooks:ai(Sn,{account:l,headers:c}),addressBookMultiGet:S,fetchVCards:ai(Nn,{headers:c}),createVCard:ai(jn,{headers:c}),updateVCard:ai(Ln,{headers:c}),deleteVCard:ai(kn,{headers:c})}}));class fi{constructor(e){var t,r;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav"}login(){var e;return t(this,void 0,void 0,(function*(){switch(this.authMethod){case"Basic":this.authHeaders=si(this.credentials);break;case"Oauth":this.authHeaders=(yield li(this.credentials)).headers;break;case"Digest":this.authHeaders={Authorization:`Digest ${this.credentials.digestString}`};break;case"Custom":this.authHeaders=yield null===(e=this.authFunction)||void 0===e?void 0:e.call(this,this.credentials);break;default:throw new Error("Invalid auth method")}this.account=this.accountType?yield Jn({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders}):void 0}))}davRequest(r){return t(this,void 0,void 0,(function*(){const{init:t}=r,n=e(r,["init"]),{headers:i}=t,o=e(t,["headers"]);return hn(Object.assign(Object.assign({},n),{init:Object.assign(Object.assign({},o),{headers:Object.assign(Object.assign({},this.authHeaders),i)})}))}))}createObject(...e){return t(this,void 0,void 0,(function*(){return ai(pn,{url:this.serverUrl,headers:this.authHeaders})(e[0])}))}updateObject(...e){return t(this,void 0,void 0,(function*(){return ai(gn,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}deleteObject(...e){return t(this,void 0,void 0,(function*(){return ai(yn,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}propfind(...e){return t(this,void 0,void 0,(function*(){return ai(fn,{headers:this.authHeaders})(e[0])}))}createAccount(e){return t(this,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:n,loadObjects:i}=e;return Jn({account:Object.assign({serverUrl:this.serverUrl,credentials:this.credentials},t),headers:Object.assign(Object.assign({},this.authHeaders),r),loadCollections:n,loadObjects:i})}))}collectionQuery(...e){return t(this,void 0,void 0,(function*(){return ai(En,{headers:this.authHeaders})(e[0])}))}makeCollection(...e){return t(this,void 0,void 0,(function*(){return ai(An,{headers:this.authHeaders})(e[0])}))}syncCollection(...e){return t(this,void 0,void 0,(function*(){return ai(Cn,{headers:this.authHeaders})(e[0])}))}supportedReportSet(...e){return t(this,void 0,void 0,(function*(){return ai(Tn,{headers:this.authHeaders})(e[0])}))}isCollectionDirty(...e){return t(this,void 0,void 0,(function*(){return ai(_n,{headers:this.authHeaders})(e[0])}))}smartCollectionSync(...e){return t(this,void 0,void 0,(function*(){return ai(On,{headers:this.authHeaders,account:this.account})(e[0])}))}calendarQuery(...e){return t(this,void 0,void 0,(function*(){return ai(Un,{headers:this.authHeaders})(e[0])}))}makeCalendar(...e){return t(this,void 0,void 0,(function*(){return ai(Mn,{headers:this.authHeaders})(e[0])}))}calendarMultiGet(...e){return t(this,void 0,void 0,(function*(){return ai(Bn,{headers:this.authHeaders})(e[0])}))}fetchCalendars(...e){return t(this,void 0,void 0,(function*(){return ai(Vn,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchCalendarObjects(...e){return t(this,void 0,void 0,(function*(){return ai(Kn,{headers:this.authHeaders})(e[0])}))}createCalendarObject(...e){return t(this,void 0,void 0,(function*(){return ai($n,{headers:this.authHeaders})(e[0])}))}updateCalendarObject(...e){return t(this,void 0,void 0,(function*(){return ai(Hn,{headers:this.authHeaders})(e[0])}))}deleteCalendarObject(...e){return t(this,void 0,void 0,(function*(){return ai(Yn,{headers:this.authHeaders})(e[0])}))}syncCalendars(...e){return t(this,void 0,void 0,(function*(){return ai(zn,{headers:this.authHeaders,account:this.account})(e[0])}))}addressBookQuery(...e){return t(this,void 0,void 0,(function*(){return ai(Rn,{headers:this.authHeaders})(e[0])}))}addressBookMultiGet(...e){return t(this,void 0,void 0,(function*(){return ai(Fn,{headers:this.authHeaders})(e[0])}))}fetchAddressBooks(...e){return t(this,void 0,void 0,(function*(){return ai(Sn,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchVCards(...e){return t(this,void 0,void 0,(function*(){return ai(Nn,{headers:this.authHeaders})(e[0])}))}createVCard(...e){return t(this,void 0,void 0,(function*(){return ai(jn,{headers:this.authHeaders})(e[0])}))}updateVCard(...e){return t(this,void 0,void 0,(function*(){return ai(Ln,{headers:this.authHeaders})(e[0])}))}deleteVCard(...e){return t(this,void 0,void 0,(function*(){return ai(kn,{headers:this.authHeaders})(e[0])}))}}var pi=Object.freeze({__proto__:null,DAVClient:fi,createDAVClient:hi}),gi=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({DAVNamespace:U,DAVNamespaceShort:V,DAVAttributeMap:M},pi),vn),Dn),ri),In),Gn),di),ln);export{M as DAVAttributeMap,fi as DAVClient,U as DAVNamespace,V as DAVNamespaceShort,Rn as addressBookQuery,Bn as calendarMultiGet,Un as calendarQuery,un as cleanupFalsy,En as collectionQuery,Jn as createAccount,$n as createCalendarObject,hi as createDAVClient,pn as createObject,jn as createVCard,hn as davRequest,gi as default,Yn as deleteCalendarObject,yn as deleteObject,kn as deleteVCard,Sn as fetchAddressBooks,Kn as fetchCalendarObjects,Vn as fetchCalendars,ui as fetchOauthTokens,Nn as fetchVCards,qn as freeBusyQuery,si as getBasicAuthHeaders,sn as getDAVAttribute,li as getOauthHeaders,_n as isCollectionDirty,Mn as makeCalendar,fn as propfind,ci as refreshAccessToken,On as smartCollectionSync,Tn as supportedReportSet,zn as syncCalendars,Cn as syncCollection,Hn as updateCalendarObject,gn as updateObject,Ln as updateVCard,an as urlContains,on as urlEquals}; diff --git a/dist/tsdav.min.mjs b/dist/tsdav.min.mjs index acb8719..402228c 100644 --- a/dist/tsdav.min.mjs +++ b/dist/tsdav.min.mjs @@ -1 +1 @@ -import{fetch as e}from"cross-fetch";import t from"debug";import r from"xml-js";import{encode as o}from"base-64";function n(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(o=Object.getOwnPropertySymbols(e);n{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},u=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),o=t.trim();if(Math.abs(r.length-o.length)>1)return!1;const n="/"===r.slice(-1)?r.slice(0,-1):r,a="/"===o.slice(-1)?o.slice(0,-1):o;return e.includes(a)||t.includes(n)},h=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),o=t.trim(),n="/"===r.slice(-1)?r.slice(0,-1):r,a="/"===o.slice(-1)?o.slice(0,-1):o;return e.includes(a)||t.includes(n)},p=e=>e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[s[t]]:t})),{}),v=e=>Object.entries(e).reduce(((e,[t,r])=>r?Object.assign(Object.assign({},e),{[t]:r}):e),{});var f=Object.freeze({__proto__:null,cleanupFalsy:v,getDAVAttribute:p,urlContains:h,urlEquals:u});const g=t("tsdav:request"),m=t=>a(void 0,void 0,void 0,(function*(){var o;const{url:n,init:a,convertIncoming:d=!0,parseOutgoing:s=!0}=t,{headers:i={},body:c,namespace:u,method:h,attributes:p}=a,f=d?r.js2xml(Object.assign(Object.assign({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},c),{_attributes:p}),{compact:!0,spaces:2,elementNameFn:e=>u&&!/^.+:.+/.test(e)?`${u}:${e}`:e}):c,m=yield e(n,{headers:Object.assign({"Content-Type":"text/xml;charset=UTF-8"},v(i)),body:f,method:h}),y=yield m.text();if(!m.ok||!(null===(o=m.headers.get("content-type"))||void 0===o?void 0:o.includes("xml"))||!s)return[{href:m.url,ok:m.ok,status:m.status,statusText:m.statusText,raw:y}];const b=r.xml2js(y,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,o=Object.keys(r),n=o[o.length-1],a=r[n];if(a.length>0){a[a.length-1]=l(e)}else r[n]=l(e)}catch(e){g(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,(e=>e[1].toUpperCase())),attributesFn:e=>{const t=Object.assign({},e);return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(b.multistatus.response)?b.multistatus.response:[b.multistatus.response]).map((e=>{var t,r;if(!e)return{status:m.status,statusText:m.statusText,ok:m.ok};const o=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:b,href:e.href,status:(null==o?void 0:o.groups)?Number.parseInt(null==o?void 0:o.groups.status,10):m.status,statusText:null!==(r=null===(t=null==o?void 0:o.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:m.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce(((e,t)=>Object.assign(Object.assign({},e),null==t?void 0:t.prop)),{})}}))})),y=e=>a(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:n}=e;return m({url:t,init:{method:"PROPFIND",headers:v(Object.assign({depth:o},n)),namespace:i.DAV,body:{propfind:{_attributes:p([d.CALDAV,d.CALDAV_APPLE,d.CALENDAR_SERVER,d.CARDDAV,d.DAV]),prop:r}}}})})),b=t=>a(void 0,void 0,void 0,(function*(){const{url:r,data:o,headers:n}=t;return e(r,{method:"PUT",body:o,headers:n})})),A=t=>a(void 0,void 0,void 0,(function*(){const{url:r,data:o,etag:n,headers:a}=t;return e(r,{method:"PUT",body:o,headers:v(Object.assign({"If-Match":n},a))})})),O=t=>a(void 0,void 0,void 0,(function*(){const{url:r,headers:o,etag:n}=t;return e(r,{method:"DELETE",headers:v(Object.assign({"If-Match":n},o))})}));var C=Object.freeze({__proto__:null,createObject:b,davRequest:m,deleteObject:O,propfind:y,updateObject:A});function D(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const j=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),V=t("tsdav:collection"),$=e=>a(void 0,void 0,void 0,(function*(){const{url:t,body:r,depth:o,defaultNamespace:n=i.DAV,headers:a}=e,d=yield m({url:t,init:{method:"REPORT",headers:v(Object.assign({depth:o},a)),namespace:n,body:r}});return 1!==d.length||d[0].raw?d:[]})),w=e=>a(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:n}=e;return m({url:t,init:{method:"MKCOL",headers:v(Object.assign({depth:o},n)),namespace:i.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0}})})),k=e=>a(void 0,void 0,void 0,(function*(){var t,r,o,n,a;const{collection:d,headers:s}=e;return null!==(a=null===(n=null===(o=null===(r=null===(t=(yield y({url:d.url,props:{[`${i.DAV}:supported-report-set`]:{}},depth:"0",headers:s}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===o?void 0:o.supportedReport)||void 0===n?void 0:n.map((e=>Object.keys(e.report)[0])))&&void 0!==a?a:[]})),_=e=>a(void 0,void 0,void 0,(function*(){var t,r,o;const{collection:n,headers:a}=e,d=(yield y({url:n.url,props:{[`${i.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:a})).filter((e=>h(n.url,e.href)))[0];if(!d)throw new Error("Collection does not exist on server");return{isDirty:n.ctag!==(null===(t=d.props)||void 0===t?void 0:t.getctag),newCtag:null===(o=null===(r=d.props)||void 0===r?void 0:r.getctag)||void 0===o?void 0:o.toString()}})),R=e=>{const{url:t,props:r,headers:o,syncLevel:n,syncToken:a}=e;return m({url:t,init:{method:"REPORT",namespace:i.DAV,headers:Object.assign({},o),body:{"sync-collection":{_attributes:p([d.CALDAV,d.CARDDAV,d.DAV]),"sync-level":n,"sync-token":a,[`${i.DAV}:prop`]:r}}}})},U=e=>a(void 0,void 0,void 0,(function*(){var t,r,o,n,a,d,s,c,l,u,p;const{collection:v,method:f,headers:g,account:m,detailedResult:y}=e,b=["accountType","homeUrl"];if(!m||!D(m,b)){if(!m)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${j(m,b)} before smartCollectionSync`)}const A=null!=f?f:(null===(t=v.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if(V(`smart collection sync with type ${m.accountType} and method ${A}`),"webdav"===A){const e=yield R({url:v.url,props:{[`${i.DAV}:getetag`]:{},[`${"caldav"===m.accountType?i.CALDAV:i.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{},[`${i.DAV}:displayname`]:{}},syncLevel:1,syncToken:v.syncToken,headers:g}),t=e.filter((e=>{var t;const r="caldav"===m.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r})),l=t.filter((e=>404!==e.status)).map((e=>e.href)),u=t.filter((e=>404===e.status)).map((e=>e.href)),p=(l.length&&null!==(o=yield null===(r=null==v?void 0:v.objectMultiGet)||void 0===r?void 0:r.call(v,{url:v.url,props:{[`${i.DAV}:getetag`]:{},[`${"caldav"===m.accountType?i.CALDAV:i.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:l,depth:"1",headers:g}))&&void 0!==o?o:[]).map((e=>{var t,r,o,n,a,d,s,i,c,l;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==m?void 0:m.accountType)?null!==(a=null===(n=null===(o=e.props)||void 0===o?void 0:o.calendarData)||void 0===n?void 0:n._cdata)&&void 0!==a?a:null===(d=e.props)||void 0===d?void 0:d.calendarData:null!==(c=null===(i=null===(s=e.props)||void 0===s?void 0:s.addressData)||void 0===i?void 0:i._cdata)&&void 0!==c?c:null===(l=e.props)||void 0===l?void 0:l.addressData}})),f=null!==(n=v.objects)&&void 0!==n?n:[],b=p.filter((e=>f.every((t=>!h(t.url,e.url))))),A=f.reduce(((e,t)=>{const r=p.find((e=>h(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),O=u.map((e=>({url:e,etag:""}))),C=f.filter((e=>p.some((t=>h(e.url,t.url)&&t.etag===e.etag))));return Object.assign(Object.assign({},v),{objects:y?{created:b,updated:A,deleted:O}:[...C,...b,...A],syncToken:null!==(c=null===(s=null===(d=null===(a=e[0])||void 0===a?void 0:a.raw)||void 0===d?void 0:d.multistatus)||void 0===s?void 0:s.syncToken)&&void 0!==c?c:v.syncToken})}if("basic"===A){const{isDirty:e,newCtag:t}=yield _({collection:v,headers:g}),r=null!==(l=v.objects)&&void 0!==l?l:[],o=null!==(p=yield null===(u=v.fetchObjects)||void 0===u?void 0:u.call(v,{collection:v,headers:g}))&&void 0!==p?p:[],n=o.filter((e=>r.every((t=>!h(t.url,e.url))))),a=r.reduce(((e,t)=>{const r=o.find((e=>h(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),d=r.filter((e=>o.every((t=>!h(t.url,e.url))))),s=r.filter((e=>o.some((t=>h(e.url,t.url)&&t.etag===e.etag))));if(e)return Object.assign(Object.assign({},v),{objects:y?{created:n,updated:a,deleted:d}:[...s,...n,...a],ctag:t})}return y?Object.assign(Object.assign({},v),{objects:{created:[],updated:[],deleted:[]}}):v}));var L=Object.freeze({__proto__:null,collectionQuery:$,isCollectionDirty:_,makeCollection:w,smartCollectionSync:U,supportedReportSet:k,syncCollection:R});const T=t("tsdav:addressBook"),E=e=>a(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:o,depth:n,headers:a}=e;return $({url:t,body:{"addressbook-query":{_attributes:p([d.CARDDAV,d.DAV]),[`${i.DAV}:prop`]:r,filter:null!=o?o:{"prop-filter":{_attributes:{name:"FN"}}}}},defaultNamespace:i.CARDDAV,depth:n,headers:a})})),S=e=>a(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:o,depth:n,headers:a}=e;return $({url:t,body:{"addressbook-multiget":{_attributes:p([d.DAV,d.CARDDAV]),[`${i.DAV}:prop`]:r,[`${i.DAV}:href`]:o}},defaultNamespace:i.CARDDAV,depth:n,headers:a})})),x=e=>a(void 0,void 0,void 0,(function*(){const{account:t,headers:r,props:o}=null!=e?e:{},n=["homeUrl","rootUrl"];if(!t||!D(t,n)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${j(t,n)} before fetchAddressBooks`)}const d=yield y({url:t.homeUrl,props:null!=o?o:{[`${i.DAV}:displayname`]:{},[`${i.CALENDAR_SERVER}:getctag`]:{},[`${i.DAV}:resourcetype`]:{},[`${i.DAV}:sync-token`]:{}},depth:"1",headers:r});return Promise.all(d.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")})).map((e=>{var r,o,n,a,d,s,i,c,l;const u=null!==(n=null===(o=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===o?void 0:o._cdata)&&void 0!==n?n:null===(a=e.props)||void 0===a?void 0:a.displayname;return T(`Found address book named ${"string"==typeof u?u:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(d=e.href)&&void 0!==d?d:"",null!==(s=t.rootUrl)&&void 0!==s?s:"").href,ctag:null===(i=e.props)||void 0===i?void 0:i.getctag,displayName:"string"==typeof u?u:"",resourcetype:Object.keys(null===(c=e.props)||void 0===c?void 0:c.resourcetype),syncToken:null===(l=e.props)||void 0===l?void 0:l.syncToken}})).map((e=>a(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield k({collection:e,headers:r})})})))))})),N=e=>a(void 0,void 0,void 0,(function*(){const{addressBook:t,headers:r,objectUrls:o,urlFilter:n=(e=>e),useMultiGet:a=!0}=e;T(`Fetching vcards from ${null==t?void 0:t.url}`);const d=["url"];if(!t||!D(t,d)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${j(t,d)} before fetchVCards`)}const s=(null!=o?o:(yield E({url:t.url,props:{[`${i.DAV}:getetag`]:{}},depth:"1",headers:r})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(n).map((e=>new URL(e).pathname));let c=[];return s.length>0&&(c=a?yield S({url:t.url,props:{[`${i.DAV}:getetag`]:{},[`${i.CARDDAV}:address-data`]:{}},objectUrls:s,depth:"1",headers:r}):yield E({url:t.url,props:{[`${i.DAV}:getetag`]:{},[`${i.CARDDAV}:address-data`]:{}},depth:"1",headers:r})),c.map((e=>{var r,o,n,a,d,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(o=e.props)||void 0===o?void 0:o.getetag,data:null!==(d=null===(a=null===(n=e.props)||void 0===n?void 0:n.addressData)||void 0===a?void 0:a._cdata)&&void 0!==d?d:null===(s=e.props)||void 0===s?void 0:s.addressData}}))})),P=e=>a(void 0,void 0,void 0,(function*(){const{addressBook:t,vCardString:r,filename:o,headers:n}=e;return b({url:new URL(o,t.url).href,data:r,headers:Object.assign({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*"},n)})})),H=e=>a(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return A({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/vcard; charset=utf-8"},r)})})),B=e=>a(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return O({url:t.url,etag:t.etag,headers:r})}));var I=Object.freeze({__proto__:null,addressBookMultiGet:S,addressBookQuery:E,createVCard:P,deleteVCard:B,fetchAddressBooks:x,fetchVCards:N,updateVCard:H});const M=t("tsdav:calendar"),F=e=>a(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:o,timezone:n,depth:a,headers:s}=e;return $({url:t,body:{"calendar-query":v({_attributes:p([d.CALDAV,d.CALENDAR_SERVER,d.CALDAV_APPLE,d.DAV]),[`${i.DAV}:prop`]:r,filter:o,timezone:n})},defaultNamespace:i.CALDAV,depth:a,headers:s})})),z=e=>a(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:o,filters:n,timezone:a,depth:s,headers:c}=e;return $({url:t,body:{"calendar-multiget":{_attributes:p([d.DAV,d.CALDAV]),[`${i.DAV}:prop`]:r,[`${i.DAV}:href`]:o,filter:n,timezone:a}},defaultNamespace:i.CALDAV,depth:s,headers:c})})),Z=e=>a(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:n}=e;return m({url:t,init:{method:"MKCALENDAR",headers:v(Object.assign({depth:o},n)),namespace:i.DAV,body:{[`${i.CALDAV}:mkcalendar`]:{_attributes:p([d.DAV,d.CALDAV,d.CALDAV_APPLE]),set:{prop:r}}}}})})),G=e=>a(void 0,void 0,void 0,(function*(){const{headers:t,account:r,props:o}=null!=e?e:{},n=["homeUrl","rootUrl"];if(!r||!D(r,n)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${j(r,n)} before fetchCalendars`)}const d=yield y({url:r.homeUrl,props:null!=o?o:{[`${i.CALDAV}:calendar-description`]:{},[`${i.CALDAV}:calendar-timezone`]:{},[`${i.DAV}:displayname`]:{},[`${i.CALDAV_APPLE}:calendar-color`]:{},[`${i.CALENDAR_SERVER}:getctag`]:{},[`${i.DAV}:resourcetype`]:{},[`${i.CALDAV}:supported-calendar-component-set`]:{},[`${i.DAV}:sync-token`]:{}},depth:"1",headers:t});return Promise.all(d.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")})).filter((e=>{var t,r,o;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(o=e.props)||void 0===o?void 0:o.supportedCalendarComponentSet.comp._attributes.name]||[]).some((e=>Object.values(c).includes(e)))})).map((e=>{var t,o,n,a,d,s,i,c,l,u,h,p,v,f;const g=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,m=null===(o=e.props)||void 0===o?void 0:o.calendarTimezone;return{description:"string"==typeof g?g:"",timezone:"string"==typeof m?m:"",url:new URL(null!==(n=e.href)&&void 0!==n?n:"",null!==(a=r.rootUrl)&&void 0!==a?a:"").href,ctag:null===(d=e.props)||void 0===d?void 0:d.getctag,calendarColor:null===(s=e.props)||void 0===s?void 0:s.calendarColor,displayName:null!==(c=null===(i=e.props)||void 0===i?void 0:i.displayname._cdata)&&void 0!==c?c:null===(l=e.props)||void 0===l?void 0:l.displayname,components:Array.isArray(null===(u=e.props)||void 0===u?void 0:u.supportedCalendarComponentSet.comp)?null===(h=e.props)||void 0===h?void 0:h.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp._attributes.name],resourcetype:Object.keys(null===(v=e.props)||void 0===v?void 0:v.resourcetype),syncToken:null===(f=e.props)||void 0===f?void 0:f.syncToken}})).map((e=>a(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield k({collection:e,headers:t})})})))))})),Q=e=>a(void 0,void 0,void 0,(function*(){const{calendar:t,objectUrls:r,filters:o,timeRange:n,headers:a,expand:d,urlFilter:s=(e=>Boolean(null==e?void 0:e.includes(".ics"))),useMultiGet:c=!0}=e;if(n){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(n.start)&&e.test(n.end)||t.test(n.start)&&t.test(n.end)))throw new Error("invalid timeRange format, not in ISO8601")}M(`Fetching calendar objects from ${null==t?void 0:t.url}`);const l=["url"];if(!t||!D(t,l)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${j(t,l)} before fetchCalendarObjects`)}const u=null!=o?o:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":Object.assign({_attributes:{name:"VEVENT"}},n?{"time-range":{_attributes:{start:`${new Date(n.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(n.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})}}],h=(null!=r?r:(yield F({url:t.url,props:{[`${i.DAV}:getetag`]:Object.assign({},d&&n?{[`${i.CALDAV}:expand`]:{_attributes:{start:`${new Date(n.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(n.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:u,depth:"1",headers:a})).map((e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(s).map((e=>new URL(e).pathname));let p=[];return h.length>0&&(p=!c||d?yield F({url:t.url,props:{[`${i.DAV}:getetag`]:{},[`${i.CALDAV}:calendar-data`]:Object.assign({},d&&n?{[`${i.CALDAV}:expand`]:{_attributes:{start:`${new Date(n.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(n.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:u,depth:"1",headers:a}):yield z({url:t.url,props:{[`${i.DAV}:getetag`]:{},[`${i.CALDAV}:calendar-data`]:Object.assign({},d&&n?{[`${i.CALDAV}:expand`]:{_attributes:{start:`${new Date(n.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(n.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},objectUrls:h,depth:"1",headers:a})),p.map((e=>{var r,o,n,a,d,s;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(o=e.props)||void 0===o?void 0:o.getetag}`,data:null!==(d=null===(a=null===(n=e.props)||void 0===n?void 0:n.calendarData)||void 0===a?void 0:a._cdata)&&void 0!==d?d:null===(s=e.props)||void 0===s?void 0:s.calendarData}}))})),q=e=>a(void 0,void 0,void 0,(function*(){const{calendar:t,iCalString:r,filename:o,headers:n}=e;return b({url:new URL(o,t.url).href,data:r,headers:Object.assign({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*"},n)})})),J=e=>a(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return A({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/calendar; charset=utf-8"},r)})})),K=e=>a(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return O({url:t.url,etag:t.etag,headers:r})})),W=e=>a(void 0,void 0,void 0,(function*(){var t;const{oldCalendars:r,account:o,detailedResult:n,headers:d}=e;if(!o)throw new Error("Must have account before syncCalendars");const s=null!==(t=null!=r?r:o.calendars)&&void 0!==t?t:[],i=yield G({account:o,headers:d}),c=i.filter((e=>s.every((t=>!h(t.url,e.url)))));M(`new calendars: ${c.map((e=>e.displayName))}`);const l=s.reduce(((e,t)=>{const r=i.find((e=>h(e.url,t.url)));return r&&(r.syncToken&&r.syncToken!==t.syncToken||r.ctag&&r.ctag!==t.ctag)?[...e,r]:e}),[]);M(`updated calendars: ${l.map((e=>e.displayName))}`);const u=yield Promise.all(l.map((e=>a(void 0,void 0,void 0,(function*(){return yield U({collection:Object.assign(Object.assign({},e),{objectMultiGet:z}),method:"webdav",headers:d,account:o})}))))),p=s.filter((e=>i.every((t=>!h(t.url,e.url)))));M(`deleted calendars: ${p.map((e=>e.displayName))}`);const v=s.filter((e=>i.some((t=>h(t.url,e.url)&&(t.syncToken&&t.syncToken!==e.syncToken||t.ctag&&t.ctag!==e.ctag)))));return n?{created:c,updated:l,deleted:p}:[...v,...c,...u]})),Y=e=>a(void 0,void 0,void 0,(function*(){const{url:t,timeRange:r,depth:o,headers:n}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(yield $({url:t,body:{"free-busy-query":v({_attributes:p([d.CALDAV]),[`${i.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:i.CALDAV,depth:o,headers:n}))[0]}));var X=Object.freeze({__proto__:null,calendarMultiGet:z,calendarQuery:F,createCalendarObject:q,deleteCalendarObject:K,fetchCalendarObjects:Q,fetchCalendars:G,freeBusyQuery:Y,makeCalendar:Z,syncCalendars:W,updateCalendarObject:J});const ee=t("tsdav:account"),te=t=>a(void 0,void 0,void 0,(function*(){var r,o;ee("Service discovery...");const{account:n,headers:a}=t,d=new URL(n.serverUrl),s=new URL(`/.well-known/${n.accountType}`,d);s.protocol=null!==(r=d.protocol)&&void 0!==r?r:"http";try{const t=yield e(s.href,{headers:a,method:"PROPFIND",redirect:"manual"});if(t.status>=300&&t.status<400){const e=t.headers.get("Location");if("string"==typeof e&&e.length){ee(`Service discovery redirected to ${e}`);const t=new URL(e,d);return t.hostname===s.hostname&&s.port&&!t.port&&(t.port=s.port),t.protocol=null!==(o=d.protocol)&&void 0!==o?o:"http",t.href}}}catch(e){ee(`Service discovery failed: ${e.stack}`)}return d.href})),re=e=>a(void 0,void 0,void 0,(function*(){var t,r,o,n,a;const{account:d,headers:s}=e,c=["rootUrl"];if(!D(d,c))throw new Error(`account must have ${j(d,c)} before fetchPrincipalUrl`);ee(`Fetching principal url from path ${d.rootUrl}`);const[l]=yield y({url:d.rootUrl,props:{[`${i.DAV}:current-user-principal`]:{}},depth:"0",headers:s});if(!l.ok&&(ee(`Fetch principal url failed: ${l.statusText}`),401===l.status))throw new Error("Invalid credentials");return ee(`Fetched principal url ${null===(r=null===(t=l.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(a=null===(n=null===(o=l.props)||void 0===o?void 0:o.currentUserPrincipal)||void 0===n?void 0:n.href)&&void 0!==a?a:"",d.rootUrl).href})),oe=e=>a(void 0,void 0,void 0,(function*(){var t,r;const{account:o,headers:n}=e,a=["principalUrl","rootUrl"];if(!D(o,a))throw new Error(`account must have ${j(o,a)} before fetchHomeUrl`);ee(`Fetch home url from ${o.principalUrl}`);const d=(yield y({url:o.principalUrl,props:"caldav"===o.accountType?{[`${i.CALDAV}:calendar-home-set`]:{}}:{[`${i.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:n})).find((e=>h(o.principalUrl,e.href)));if(!d||!d.ok)throw new Error("cannot find homeUrl");const s=new URL("caldav"===o.accountType?null===(t=null==d?void 0:d.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==d?void 0:d.props)||void 0===r?void 0:r.addressbookHomeSet.href,o.rootUrl).href;return ee(`Fetched home url ${s}`),s})),ne=e=>a(void 0,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:o=!1,loadObjects:n=!1}=e,d=Object.assign({},t);return d.rootUrl=yield te({account:t,headers:r}),d.principalUrl=yield re({account:d,headers:r}),d.homeUrl=yield oe({account:d,headers:r}),(o||n)&&("caldav"===t.accountType?d.calendars=yield G({headers:r,account:d}):"carddav"===t.accountType&&(d.addressBooks=yield x({headers:r,account:d}))),n&&("caldav"===t.accountType&&d.calendars?d.calendars=yield Promise.all(d.calendars.map((e=>a(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield Q({calendar:e,headers:r})})}))))):"carddav"===t.accountType&&d.addressBooks&&(d.addressBooks=yield Promise.all(d.addressBooks.map((e=>a(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield N({addressBook:e,headers:r})})}))))))),d}));var ae=Object.freeze({__proto__:null,createAccount:ne,fetchHomeUrl:oe,fetchPrincipalUrl:re,serviceDiscovery:te});const de=t("tsdav:authHelper"),se=(e,t)=>(...r)=>e(Object.assign(Object.assign({},t),r[0])),ie=e=>(de(`Basic auth token generated: ${o(`${e.username}:${e.password}`)}`),{authorization:`Basic ${o(`${e.username}:${e.password}`)}`}),ce=t=>a(void 0,void 0,void 0,(function*(){const r=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!D(t,r))throw new Error(`Oauth credentials missing: ${j(t,r)}`);const o=new URLSearchParams({grant_type:"authorization_code",code:t.authorizationCode,redirect_uri:t.redirectUrl,client_id:t.clientId,client_secret:t.clientSecret});de(t.tokenUrl),de(o.toString());const n=yield e(t.tokenUrl,{method:"POST",body:o.toString(),headers:{"content-length":`${o.toString().length}`,"content-type":"application/x-www-form-urlencoded"}});if(n.ok){return yield n.json()}return de(`Fetch Oauth tokens failed: ${yield n.text()}`),{}})),le=t=>a(void 0,void 0,void 0,(function*(){const r=["refreshToken","clientId","clientSecret","tokenUrl"];if(!D(t,r))throw new Error(`Oauth credentials missing: ${j(t,r)}`);const o=new URLSearchParams({client_id:t.clientId,client_secret:t.clientSecret,refresh_token:t.refreshToken,grant_type:"refresh_token"}),n=yield e(t.tokenUrl,{method:"POST",body:o.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(n.ok){return yield n.json()}return de(`Refresh access token failed: ${yield n.text()}`),{}})),ue=e=>a(void 0,void 0,void 0,(function*(){var t;de("Fetching oauth headers");let r={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(t=e.expiration)&&void 0!==t?t:0))&&(r=yield le(e)):r=yield ce(e),de(`Oauth tokens fetched: ${r.access_token}`),{tokens:r,headers:{authorization:`Bearer ${r.access_token}`}}}));var he=Object.freeze({__proto__:null,defaultParam:se,fetchOauthTokens:ce,getBasicAuthHeaders:ie,getOauthHeaders:ue,refreshAccessToken:le});const pe=e=>a(void 0,void 0,void 0,(function*(){const{serverUrl:t,credentials:r,authMethod:o,defaultAccountType:d}=e,s="Basic"===o?ie(r):"Oauth"===o?(yield ue(r)).headers:{},i=d?yield ne({account:{serverUrl:t,credentials:r,accountType:d},headers:s}):void 0,c=se(b,{url:t,headers:s}),l=se(A,{headers:s,url:t}),u=se(O,{headers:s,url:t}),h=se(y,{headers:s}),p=se($,{headers:s}),v=se(w,{headers:s}),f=se(R,{headers:s}),g=se(k,{headers:s}),C=se(_,{headers:s}),D=se(U,{headers:s,account:i}),j=se(F,{headers:s}),V=se(z,{headers:s}),L=se(Z,{headers:s}),T=se(G,{headers:s,account:i}),I=se(Q,{headers:s}),M=se(q,{headers:s}),Y=se(J,{headers:s}),X=se(K,{headers:s}),ee=se(W,{account:i,headers:s}),te=se(E,{headers:s}),re=se(S,{headers:s});return{davRequest:e=>a(void 0,void 0,void 0,(function*(){const{init:t}=e,r=n(e,["init"]),{headers:o}=t,a=n(t,["headers"]);return m(Object.assign(Object.assign({},r),{init:Object.assign(Object.assign({},a),{headers:Object.assign(Object.assign({},s),o)})}))})),propfind:h,createAccount:e=>a(void 0,void 0,void 0,(function*(){const{account:o,headers:n,loadCollections:a,loadObjects:d}=e;return ne({account:Object.assign({serverUrl:t,credentials:r},o),headers:Object.assign(Object.assign({},s),n),loadCollections:a,loadObjects:d})})),createObject:c,updateObject:l,deleteObject:u,calendarQuery:j,addressBookQuery:te,collectionQuery:p,makeCollection:v,calendarMultiGet:V,makeCalendar:L,syncCollection:f,supportedReportSet:g,isCollectionDirty:C,smartCollectionSync:D,fetchCalendars:T,fetchCalendarObjects:I,createCalendarObject:M,updateCalendarObject:Y,deleteCalendarObject:X,syncCalendars:ee,fetchAddressBooks:se(x,{account:i,headers:s}),addressBookMultiGet:re,fetchVCards:se(N,{headers:s}),createVCard:se(P,{headers:s}),updateVCard:se(H,{headers:s}),deleteVCard:se(B,{headers:s})}}));class ve{constructor(e){var t,r;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav"}login(){return a(this,void 0,void 0,(function*(){this.authHeaders="Basic"===this.authMethod?ie(this.credentials):"Oauth"===this.authMethod?(yield ue(this.credentials)).headers:{},this.account=this.accountType?yield ne({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders}):void 0}))}davRequest(e){return a(this,void 0,void 0,(function*(){const{init:t}=e,r=n(e,["init"]),{headers:o}=t,a=n(t,["headers"]);return m(Object.assign(Object.assign({},r),{init:Object.assign(Object.assign({},a),{headers:Object.assign(Object.assign({},this.authHeaders),o)})}))}))}createObject(...e){return a(this,void 0,void 0,(function*(){return se(b,{url:this.serverUrl,headers:this.authHeaders})(e[0])}))}updateObject(...e){return a(this,void 0,void 0,(function*(){return se(A,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}deleteObject(...e){return a(this,void 0,void 0,(function*(){return se(O,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}propfind(...e){return a(this,void 0,void 0,(function*(){return se(y,{headers:this.authHeaders})(e[0])}))}createAccount(e){return a(this,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:o,loadObjects:n}=e;return ne({account:Object.assign({serverUrl:this.serverUrl,credentials:this.credentials},t),headers:Object.assign(Object.assign({},this.authHeaders),r),loadCollections:o,loadObjects:n})}))}collectionQuery(...e){return a(this,void 0,void 0,(function*(){return se($,{headers:this.authHeaders})(e[0])}))}makeCollection(...e){return a(this,void 0,void 0,(function*(){return se(w,{headers:this.authHeaders})(e[0])}))}syncCollection(...e){return a(this,void 0,void 0,(function*(){return se(R,{headers:this.authHeaders})(e[0])}))}supportedReportSet(...e){return a(this,void 0,void 0,(function*(){return se(k,{headers:this.authHeaders})(e[0])}))}isCollectionDirty(...e){return a(this,void 0,void 0,(function*(){return se(_,{headers:this.authHeaders})(e[0])}))}smartCollectionSync(...e){return a(this,void 0,void 0,(function*(){return se(U,{headers:this.authHeaders,account:this.account})(e[0])}))}calendarQuery(...e){return a(this,void 0,void 0,(function*(){return se(F,{headers:this.authHeaders})(e[0])}))}makeCalendar(...e){return a(this,void 0,void 0,(function*(){return se(Z,{headers:this.authHeaders})(e[0])}))}calendarMultiGet(...e){return a(this,void 0,void 0,(function*(){return se(z,{headers:this.authHeaders})(e[0])}))}fetchCalendars(...e){return a(this,void 0,void 0,(function*(){return se(G,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchCalendarObjects(...e){return a(this,void 0,void 0,(function*(){return se(Q,{headers:this.authHeaders})(e[0])}))}createCalendarObject(...e){return a(this,void 0,void 0,(function*(){return se(q,{headers:this.authHeaders})(e[0])}))}updateCalendarObject(...e){return a(this,void 0,void 0,(function*(){return se(J,{headers:this.authHeaders})(e[0])}))}deleteCalendarObject(...e){return a(this,void 0,void 0,(function*(){return se(K,{headers:this.authHeaders})(e[0])}))}syncCalendars(...e){return a(this,void 0,void 0,(function*(){return se(W,{headers:this.authHeaders,account:this.account})(e[0])}))}addressBookQuery(...e){return a(this,void 0,void 0,(function*(){return se(E,{headers:this.authHeaders})(e[0])}))}addressBookMultiGet(...e){return a(this,void 0,void 0,(function*(){return se(S,{headers:this.authHeaders})(e[0])}))}fetchAddressBooks(...e){return a(this,void 0,void 0,(function*(){return se(x,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchVCards(...e){return a(this,void 0,void 0,(function*(){return se(N,{headers:this.authHeaders})(e[0])}))}createVCard(...e){return a(this,void 0,void 0,(function*(){return se(P,{headers:this.authHeaders})(e[0])}))}updateVCard(...e){return a(this,void 0,void 0,(function*(){return se(H,{headers:this.authHeaders})(e[0])}))}deleteVCard(...e){return a(this,void 0,void 0,(function*(){return se(B,{headers:this.authHeaders})(e[0])}))}}var fe=Object.freeze({__proto__:null,DAVClient:ve,createDAVClient:pe}),ge=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({DAVNamespace:d,DAVNamespaceShort:i,DAVAttributeMap:s},fe),C),L),ae),I),X),he),f);export{s as DAVAttributeMap,ve as DAVClient,d as DAVNamespace,i as DAVNamespaceShort,E as addressBookQuery,z as calendarMultiGet,F as calendarQuery,v as cleanupFalsy,$ as collectionQuery,ne as createAccount,q as createCalendarObject,pe as createDAVClient,b as createObject,P as createVCard,m as davRequest,ge as default,K as deleteCalendarObject,O as deleteObject,B as deleteVCard,x as fetchAddressBooks,Q as fetchCalendarObjects,G as fetchCalendars,ce as fetchOauthTokens,N as fetchVCards,Y as freeBusyQuery,ie as getBasicAuthHeaders,p as getDAVAttribute,ue as getOauthHeaders,_ as isCollectionDirty,Z as makeCalendar,y as propfind,le as refreshAccessToken,U as smartCollectionSync,k as supportedReportSet,W as syncCalendars,R as syncCollection,J as updateCalendarObject,A as updateObject,H as updateVCard,h as urlContains,u as urlEquals}; +import{fetch as e}from"cross-fetch";import t from"debug";import r from"xml-js";import{encode as o}from"base-64";function a(e,t){var r={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(r[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var a=0;for(o=Object.getOwnPropertySymbols(e);a{const t=Number(e);if(!Number.isNaN(t))return t;const r=e.toLowerCase();return"true"===r||"false"!==r&&e},u=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),o=t.trim();if(Math.abs(r.length-o.length)>1)return!1;const a="/"===r.slice(-1)?r.slice(0,-1):r,n="/"===o.slice(-1)?o.slice(0,-1):o;return e.includes(n)||t.includes(a)},h=(e,t)=>{if(!e&&!t)return!0;if(!e||!t)return!1;const r=e.trim(),o=t.trim(),a="/"===r.slice(-1)?r.slice(0,-1):r,n="/"===o.slice(-1)?o.slice(0,-1):o;return e.includes(n)||t.includes(a)},p=e=>e.reduce(((e,t)=>Object.assign(Object.assign({},e),{[d[t]]:t})),{}),v=e=>Object.entries(e).reduce(((e,[t,r])=>r?Object.assign(Object.assign({},e),{[t]:r}):e),{}),f=(e,t)=>t?{[e]:t}:{};var g=Object.freeze({__proto__:null,cleanupFalsy:v,conditionalParam:f,getDAVAttribute:p,urlContains:h,urlEquals:u});const m=t("tsdav:request"),y=t=>n(void 0,void 0,void 0,(function*(){var o;const{url:a,init:n,convertIncoming:s=!0,parseOutgoing:d=!0}=t,{headers:i={},body:c,namespace:u,method:h,attributes:p}=n,f=s?r.js2xml(Object.assign(Object.assign({_declaration:{_attributes:{version:"1.0",encoding:"utf-8"}}},c),{_attributes:p}),{compact:!0,spaces:2,elementNameFn:e=>u&&!/^.+:.+/.test(e)?`${u}:${e}`:e}):c,g=yield e(a,{headers:Object.assign({"Content-Type":"text/xml;charset=UTF-8"},v(i)),body:f,method:h}),y=yield g.text();if(!g.ok||!(null===(o=g.headers.get("content-type"))||void 0===o?void 0:o.includes("xml"))||!d)return[{href:g.url,ok:g.ok,status:g.status,statusText:g.statusText,raw:y}];const b=r.xml2js(y,{compact:!0,trim:!0,textFn:(e,t)=>{try{const r=t._parent,o=Object.keys(r),a=o[o.length-1],n=r[a];if(n.length>0){n[n.length-1]=l(e)}else r[a]=l(e)}catch(e){m(e.stack)}},elementNameFn:e=>e.replace(/^.+:/,"").replace(/([-_]\w)/g,(e=>e[1].toUpperCase())),attributesFn:e=>{const t=Object.assign({},e);return delete t.xmlns,t},ignoreDeclaration:!0});return(Array.isArray(b.multistatus.response)?b.multistatus.response:[b.multistatus.response]).map((e=>{var t,r;if(!e)return{status:g.status,statusText:g.statusText,ok:g.ok};const o=/^\S+\s(?\d+)\s(?.+)$/.exec(e.status);return{raw:b,href:e.href,status:(null==o?void 0:o.groups)?Number.parseInt(null==o?void 0:o.groups.status,10):g.status,statusText:null!==(r=null===(t=null==o?void 0:o.groups)||void 0===t?void 0:t.statusText)&&void 0!==r?r:g.statusText,ok:!e.error,error:e.error,responsedescription:e.responsedescription,props:(Array.isArray(e.propstat)?e.propstat:[e.propstat]).reduce(((e,t)=>Object.assign(Object.assign({},e),null==t?void 0:t.prop)),{})}}))})),b=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:a}=e;return y({url:t,init:{method:"PROPFIND",headers:v(Object.assign({depth:o},a)),namespace:i.DAV,body:{propfind:{_attributes:p([s.CALDAV,s.CALDAV_APPLE,s.CALENDAR_SERVER,s.CARDDAV,s.DAV]),prop:r}}}})})),A=t=>n(void 0,void 0,void 0,(function*(){const{url:r,data:o,headers:a}=t;return e(r,{method:"PUT",body:o,headers:a})})),O=t=>n(void 0,void 0,void 0,(function*(){const{url:r,data:o,etag:a,headers:n}=t;return e(r,{method:"PUT",body:o,headers:v(Object.assign({"If-Match":a},n))})})),D=t=>n(void 0,void 0,void 0,(function*(){const{url:r,headers:o,etag:a}=t;return e(r,{method:"DELETE",headers:v(Object.assign({"If-Match":a},o))})}));var j=Object.freeze({__proto__:null,createObject:A,davRequest:y,deleteObject:D,propfind:b,updateObject:O});function C(e,t){const r=e=>t.every((t=>e[t]));return Array.isArray(e)?e.every((e=>r(e))):r(e)}const V=(e,t)=>t.reduce(((t,r)=>e[r]?t:`${t.length?`${t},`:""}${r.toString()}`),""),$=t("tsdav:collection"),w=e=>n(void 0,void 0,void 0,(function*(){const{url:t,body:r,depth:o,defaultNamespace:a=i.DAV,headers:n}=e,s=yield y({url:t,init:{method:"REPORT",headers:v(Object.assign({depth:o},n)),namespace:a,body:r}});return 1!==s.length||s[0].raw?s:[]})),k=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:a}=e;return y({url:t,init:{method:"MKCOL",headers:v(Object.assign({depth:o},a)),namespace:i.DAV,body:r?{mkcol:{set:{prop:r}}}:void 0}})})),_=e=>n(void 0,void 0,void 0,(function*(){var t,r,o,a,n;const{collection:s,headers:d}=e;return null!==(n=null===(a=null===(o=null===(r=null===(t=(yield b({url:s.url,props:{[`${i.DAV}:supported-report-set`]:{}},depth:"0",headers:d}))[0])||void 0===t?void 0:t.props)||void 0===r?void 0:r.supportedReportSet)||void 0===o?void 0:o.supportedReport)||void 0===a?void 0:a.map((e=>Object.keys(e.report)[0])))&&void 0!==n?n:[]})),R=e=>n(void 0,void 0,void 0,(function*(){var t,r,o;const{collection:a,headers:n}=e,s=(yield b({url:a.url,props:{[`${i.CALENDAR_SERVER}:getctag`]:{}},depth:"0",headers:n})).filter((e=>h(a.url,e.href)))[0];if(!s)throw new Error("Collection does not exist on server");return{isDirty:a.ctag!==(null===(t=s.props)||void 0===t?void 0:t.getctag),newCtag:null===(o=null===(r=s.props)||void 0===r?void 0:r.getctag)||void 0===o?void 0:o.toString()}})),U=e=>{const{url:t,props:r,headers:o,syncLevel:a,syncToken:n}=e;return y({url:t,init:{method:"REPORT",namespace:i.DAV,headers:Object.assign({},o),body:{"sync-collection":{_attributes:p([s.CALDAV,s.CARDDAV,s.DAV]),"sync-level":a,"sync-token":n,[`${i.DAV}:prop`]:r}}}})},E=e=>n(void 0,void 0,void 0,(function*(){var t,r,o,a,n,s,d,c,l,u,p;const{collection:v,method:f,headers:g,account:m,detailedResult:y}=e,b=["accountType","homeUrl"];if(!m||!C(m,b)){if(!m)throw new Error("no account for smartCollectionSync");throw new Error(`account must have ${V(m,b)} before smartCollectionSync`)}const A=null!=f?f:(null===(t=v.reports)||void 0===t?void 0:t.includes("syncCollection"))?"webdav":"basic";if($(`smart collection sync with type ${m.accountType} and method ${A}`),"webdav"===A){const e=yield U({url:v.url,props:{[`${i.DAV}:getetag`]:{},[`${"caldav"===m.accountType?i.CALDAV:i.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{},[`${i.DAV}:displayname`]:{}},syncLevel:1,syncToken:v.syncToken,headers:g}),t=e.filter((e=>{var t;const r="caldav"===m.accountType?".ics":".vcf";return(null===(t=e.href)||void 0===t?void 0:t.slice(-4))===r})),l=t.filter((e=>404!==e.status)).map((e=>e.href)),u=t.filter((e=>404===e.status)).map((e=>e.href)),p=(l.length&&null!==(o=yield null===(r=null==v?void 0:v.objectMultiGet)||void 0===r?void 0:r.call(v,{url:v.url,props:{[`${i.DAV}:getetag`]:{},[`${"caldav"===m.accountType?i.CALDAV:i.CARDDAV}:${"caldav"===m.accountType?"calendar-data":"address-data"}`]:{}},objectUrls:l,depth:"1",headers:g}))&&void 0!==o?o:[]).map((e=>{var t,r,o,a,n,s,d,i,c,l;return{url:null!==(t=e.href)&&void 0!==t?t:"",etag:null===(r=e.props)||void 0===r?void 0:r.getetag,data:"caldav"===(null==m?void 0:m.accountType)?null!==(n=null===(a=null===(o=e.props)||void 0===o?void 0:o.calendarData)||void 0===a?void 0:a._cdata)&&void 0!==n?n:null===(s=e.props)||void 0===s?void 0:s.calendarData:null!==(c=null===(i=null===(d=e.props)||void 0===d?void 0:d.addressData)||void 0===i?void 0:i._cdata)&&void 0!==c?c:null===(l=e.props)||void 0===l?void 0:l.addressData}})),f=null!==(a=v.objects)&&void 0!==a?a:[],b=p.filter((e=>f.every((t=>!h(t.url,e.url))))),A=f.reduce(((e,t)=>{const r=p.find((e=>h(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),O=u.map((e=>({url:e,etag:""}))),D=f.filter((e=>p.some((t=>h(e.url,t.url)&&t.etag===e.etag))));return Object.assign(Object.assign({},v),{objects:y?{created:b,updated:A,deleted:O}:[...D,...b,...A],syncToken:null!==(c=null===(d=null===(s=null===(n=e[0])||void 0===n?void 0:n.raw)||void 0===s?void 0:s.multistatus)||void 0===d?void 0:d.syncToken)&&void 0!==c?c:v.syncToken})}if("basic"===A){const{isDirty:e,newCtag:t}=yield R({collection:v,headers:g}),r=null!==(l=v.objects)&&void 0!==l?l:[],o=null!==(p=yield null===(u=v.fetchObjects)||void 0===u?void 0:u.call(v,{collection:v,headers:g}))&&void 0!==p?p:[],a=o.filter((e=>r.every((t=>!h(t.url,e.url))))),n=r.reduce(((e,t)=>{const r=o.find((e=>h(e.url,t.url)));return r&&r.etag&&r.etag!==t.etag?[...e,r]:e}),[]),s=r.filter((e=>o.every((t=>!h(t.url,e.url))))),d=r.filter((e=>o.some((t=>h(e.url,t.url)&&t.etag===e.etag))));if(e)return Object.assign(Object.assign({},v),{objects:y?{created:a,updated:n,deleted:s}:[...d,...a,...n],ctag:t})}return y?Object.assign(Object.assign({},v),{objects:{created:[],updated:[],deleted:[]}}):v}));var L=Object.freeze({__proto__:null,collectionQuery:w,isCollectionDirty:R,makeCollection:k,smartCollectionSync:E,supportedReportSet:_,syncCollection:U});const T=t("tsdav:addressBook"),S=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:o,depth:a,headers:n}=e;return w({url:t,body:{"addressbook-query":{_attributes:p([s.CARDDAV,s.DAV]),[`${i.DAV}:prop`]:r,filter:null!=o?o:{"prop-filter":{_attributes:{name:"FN"}}}}},defaultNamespace:i.CARDDAV,depth:a,headers:n})})),x=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:o,depth:a,headers:n}=e;return w({url:t,body:{"addressbook-multiget":{_attributes:p([s.DAV,s.CARDDAV]),[`${i.DAV}:prop`]:r,[`${i.DAV}:href`]:o}},defaultNamespace:i.CARDDAV,depth:a,headers:n})})),N=e=>n(void 0,void 0,void 0,(function*(){const{account:t,headers:r,props:o}=null!=e?e:{},a=["homeUrl","rootUrl"];if(!t||!C(t,a)){if(!t)throw new Error("no account for fetchAddressBooks");throw new Error(`account must have ${V(t,a)} before fetchAddressBooks`)}const s=yield b({url:t.homeUrl,props:null!=o?o:{[`${i.DAV}:displayname`]:{},[`${i.CALENDAR_SERVER}:getctag`]:{},[`${i.DAV}:resourcetype`]:{},[`${i.DAV}:sync-token`]:{}},depth:"1",headers:r});return Promise.all(s.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("addressbook")})).map((e=>{var r,o,a,n,s,d,i,c,l;const u=null!==(a=null===(o=null===(r=e.props)||void 0===r?void 0:r.displayname)||void 0===o?void 0:o._cdata)&&void 0!==a?a:null===(n=e.props)||void 0===n?void 0:n.displayname;return T(`Found address book named ${"string"==typeof u?u:""},\n props: ${JSON.stringify(e.props)}`),{url:new URL(null!==(s=e.href)&&void 0!==s?s:"",null!==(d=t.rootUrl)&&void 0!==d?d:"").href,ctag:null===(i=e.props)||void 0===i?void 0:i.getctag,displayName:"string"==typeof u?u:"",resourcetype:Object.keys(null===(c=e.props)||void 0===c?void 0:c.resourcetype),syncToken:null===(l=e.props)||void 0===l?void 0:l.syncToken}})).map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield _({collection:e,headers:r})})})))))})),P=e=>n(void 0,void 0,void 0,(function*(){const{addressBook:t,headers:r,objectUrls:o,urlFilter:a=(e=>e),useMultiGet:n=!0}=e;T(`Fetching vcards from ${null==t?void 0:t.url}`);const s=["url"];if(!t||!C(t,s)){if(!t)throw new Error("cannot fetchVCards for undefined addressBook");throw new Error(`addressBook must have ${V(t,s)} before fetchVCards`)}const d=(null!=o?o:(yield S({url:t.url,props:{[`${i.DAV}:getetag`]:{}},depth:"1",headers:r})).map((e=>{var t;return e.ok&&null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(a).map((e=>new URL(e).pathname));let c=[];return d.length>0&&(c=n?yield x({url:t.url,props:{[`${i.DAV}:getetag`]:{},[`${i.CARDDAV}:address-data`]:{}},objectUrls:d,depth:"1",headers:r}):yield S({url:t.url,props:{[`${i.DAV}:getetag`]:{},[`${i.CARDDAV}:address-data`]:{}},depth:"1",headers:r})),c.map((e=>{var r,o,a,n,s,d;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:null===(o=e.props)||void 0===o?void 0:o.getetag,data:null!==(s=null===(n=null===(a=e.props)||void 0===a?void 0:a.addressData)||void 0===n?void 0:n._cdata)&&void 0!==s?s:null===(d=e.props)||void 0===d?void 0:d.addressData}}))})),H=e=>n(void 0,void 0,void 0,(function*(){const{addressBook:t,vCardString:r,filename:o,headers:a}=e;return A({url:new URL(o,t.url).href,data:r,headers:Object.assign({"content-type":"text/vcard; charset=utf-8","If-None-Match":"*"},a)})})),B=e=>n(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return O({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/vcard; charset=utf-8"},r)})})),I=e=>n(void 0,void 0,void 0,(function*(){const{vCard:t,headers:r}=e;return D({url:t.url,etag:t.etag,headers:r})}));var M=Object.freeze({__proto__:null,addressBookMultiGet:x,addressBookQuery:S,createVCard:H,deleteVCard:I,fetchAddressBooks:N,fetchVCards:P,updateVCard:B});const F=t("tsdav:calendar"),z=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,filters:o,timezone:a,depth:n,headers:d}=e;return w({url:t,body:{"calendar-query":v({_attributes:p([s.CALDAV,s.CALENDAR_SERVER,s.CALDAV_APPLE,s.DAV]),[`${i.DAV}:prop`]:r,filter:o,timezone:a})},defaultNamespace:i.CALDAV,depth:n,headers:d})})),Z=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,objectUrls:o,filters:a,timezone:n,depth:d,headers:c}=e;return w({url:t,body:{"calendar-multiget":Object.assign(Object.assign({_attributes:p([s.DAV,s.CALDAV]),[`${i.DAV}:prop`]:r,[`${i.DAV}:href`]:o},f("filter",a)),{timezone:n})},defaultNamespace:i.CALDAV,depth:d,headers:c})})),G=e=>n(void 0,void 0,void 0,(function*(){const{url:t,props:r,depth:o,headers:a}=e;return y({url:t,init:{method:"MKCALENDAR",headers:v(Object.assign({depth:o},a)),namespace:i.DAV,body:{[`${i.CALDAV}:mkcalendar`]:{_attributes:p([s.DAV,s.CALDAV,s.CALDAV_APPLE]),set:{prop:r}}}}})})),Q=e=>n(void 0,void 0,void 0,(function*(){const{headers:t,account:r,props:o,projectedProps:a}=null!=e?e:{},s=["homeUrl","rootUrl"];if(!r||!C(r,s)){if(!r)throw new Error("no account for fetchCalendars");throw new Error(`account must have ${V(r,s)} before fetchCalendars`)}const d=yield b({url:r.homeUrl,props:null!=o?o:{[`${i.CALDAV}:calendar-description`]:{},[`${i.CALDAV}:calendar-timezone`]:{},[`${i.DAV}:displayname`]:{},[`${i.CALDAV_APPLE}:calendar-color`]:{},[`${i.CALENDAR_SERVER}:getctag`]:{},[`${i.DAV}:resourcetype`]:{},[`${i.CALDAV}:supported-calendar-component-set`]:{},[`${i.DAV}:sync-token`]:{}},depth:"1",headers:t});return Promise.all(d.filter((e=>{var t,r;return Object.keys(null!==(r=null===(t=e.props)||void 0===t?void 0:t.resourcetype)&&void 0!==r?r:{}).includes("calendar")})).filter((e=>{var t,r,o;return(Array.isArray(null===(t=e.props)||void 0===t?void 0:t.supportedCalendarComponentSet.comp)?null===(r=e.props)||void 0===r?void 0:r.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(o=e.props)||void 0===o?void 0:o.supportedCalendarComponentSet.comp._attributes.name]||[]).some((e=>Object.values(c).includes(e)))})).map((e=>{var t,o,n,s,d,i,c,l,u,h,p,v,g,m,y;const b=null===(t=e.props)||void 0===t?void 0:t.calendarDescription,A=null===(o=e.props)||void 0===o?void 0:o.calendarTimezone;return Object.assign({description:"string"==typeof b?b:"",timezone:"string"==typeof A?A:"",url:new URL(null!==(n=e.href)&&void 0!==n?n:"",null!==(s=r.rootUrl)&&void 0!==s?s:"").href,ctag:null===(d=e.props)||void 0===d?void 0:d.getctag,calendarColor:null===(i=e.props)||void 0===i?void 0:i.calendarColor,displayName:null!==(l=null===(c=e.props)||void 0===c?void 0:c.displayname._cdata)&&void 0!==l?l:null===(u=e.props)||void 0===u?void 0:u.displayname,components:Array.isArray(null===(h=e.props)||void 0===h?void 0:h.supportedCalendarComponentSet.comp)?null===(p=e.props)||void 0===p?void 0:p.supportedCalendarComponentSet.comp.map((e=>e._attributes.name)):[null===(v=e.props)||void 0===v?void 0:v.supportedCalendarComponentSet.comp._attributes.name],resourcetype:Object.keys(null===(g=e.props)||void 0===g?void 0:g.resourcetype),syncToken:null===(m=e.props)||void 0===m?void 0:m.syncToken},f("projectedProps",Object.fromEntries(Object.entries(null!==(y=e.props)&&void 0!==y?y:{}).filter((([e])=>null==a?void 0:a[e])))))})).map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{reports:yield _({collection:e,headers:t})})})))))})),q=e=>n(void 0,void 0,void 0,(function*(){const{calendar:t,objectUrls:r,filters:o,timeRange:a,headers:n,expand:s,urlFilter:d=(e=>Boolean(null==e?void 0:e.includes(".ics"))),useMultiGet:c=!0}=e;if(a){const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(a.start)&&e.test(a.end)||t.test(a.start)&&t.test(a.end)))throw new Error("invalid timeRange format, not in ISO8601")}F(`Fetching calendar objects from ${null==t?void 0:t.url}`);const l=["url"];if(!t||!C(t,l)){if(!t)throw new Error("cannot fetchCalendarObjects for undefined calendar");throw new Error(`calendar must have ${V(t,l)} before fetchCalendarObjects`)}const u=null!=o?o:[{"comp-filter":{_attributes:{name:"VCALENDAR"},"comp-filter":Object.assign({_attributes:{name:"VEVENT"}},a?{"time-range":{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})}}],h=(null!=r?r:(yield z({url:t.url,props:{[`${i.DAV}:getetag`]:Object.assign({},s&&a?{[`${i.CALDAV}:expand`]:{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:u,depth:"1",headers:n})).map((e=>{var t;return null!==(t=e.href)&&void 0!==t?t:""}))).map((e=>e.startsWith("http")||!e?e:new URL(e,t.url).href)).filter(d).map((e=>new URL(e).pathname));let p=[];return h.length>0&&(p=!c||s?yield z({url:t.url,props:{[`${i.DAV}:getetag`]:{},[`${i.CALDAV}:calendar-data`]:Object.assign({},s&&a?{[`${i.CALDAV}:expand`]:{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},filters:u,depth:"1",headers:n}):yield Z({url:t.url,props:{[`${i.DAV}:getetag`]:{},[`${i.CALDAV}:calendar-data`]:Object.assign({},s&&a?{[`${i.CALDAV}:expand`]:{_attributes:{start:`${new Date(a.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(a.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}}:{})},objectUrls:h,depth:"1",headers:n})),p.map((e=>{var r,o,a,n,s,d;return{url:new URL(null!==(r=e.href)&&void 0!==r?r:"",t.url).href,etag:`${null===(o=e.props)||void 0===o?void 0:o.getetag}`,data:null!==(s=null===(n=null===(a=e.props)||void 0===a?void 0:a.calendarData)||void 0===n?void 0:n._cdata)&&void 0!==s?s:null===(d=e.props)||void 0===d?void 0:d.calendarData}}))})),J=e=>n(void 0,void 0,void 0,(function*(){const{calendar:t,iCalString:r,filename:o,headers:a}=e;return A({url:new URL(o,t.url).href,data:r,headers:Object.assign({"content-type":"text/calendar; charset=utf-8","If-None-Match":"*"},a)})})),K=e=>n(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return O({url:t.url,data:t.data,etag:t.etag,headers:Object.assign({"content-type":"text/calendar; charset=utf-8"},r)})})),W=e=>n(void 0,void 0,void 0,(function*(){const{calendarObject:t,headers:r}=e;return D({url:t.url,etag:t.etag,headers:r})})),Y=e=>n(void 0,void 0,void 0,(function*(){var t;const{oldCalendars:r,account:o,detailedResult:a,headers:s}=e;if(!o)throw new Error("Must have account before syncCalendars");const d=null!==(t=null!=r?r:o.calendars)&&void 0!==t?t:[],i=yield Q({account:o,headers:s}),c=i.filter((e=>d.every((t=>!h(t.url,e.url)))));F(`new calendars: ${c.map((e=>e.displayName))}`);const l=d.reduce(((e,t)=>{const r=i.find((e=>h(e.url,t.url)));return r&&(r.syncToken&&r.syncToken!==t.syncToken||r.ctag&&r.ctag!==t.ctag)?[...e,r]:e}),[]);F(`updated calendars: ${l.map((e=>e.displayName))}`);const u=yield Promise.all(l.map((e=>n(void 0,void 0,void 0,(function*(){return yield E({collection:Object.assign(Object.assign({},e),{objectMultiGet:Z}),method:"webdav",headers:s,account:o})}))))),p=d.filter((e=>i.every((t=>!h(t.url,e.url)))));F(`deleted calendars: ${p.map((e=>e.displayName))}`);const v=d.filter((e=>i.some((t=>h(t.url,e.url)&&(t.syncToken&&t.syncToken!==e.syncToken||t.ctag&&t.ctag!==e.ctag)))));return a?{created:c,updated:l,deleted:p}:[...v,...c,...u]})),X=e=>n(void 0,void 0,void 0,(function*(){const{url:t,timeRange:r,depth:o,headers:a}=e;if(!r)throw new Error("timeRange is required");{const e=/^\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?$/i,t=/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?(([+-]\d\d:\d\d)|Z)?$/i;if(!(e.test(r.start)&&e.test(r.end)||t.test(r.start)&&t.test(r.end)))throw new Error("invalid timeRange format, not in ISO8601")}return(yield w({url:t,body:{"free-busy-query":v({_attributes:p([s.CALDAV]),[`${i.CALDAV}:time-range`]:{_attributes:{start:`${new Date(r.start).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`,end:`${new Date(r.end).toISOString().slice(0,19).replace(/[-:.]/g,"")}Z`}}})},defaultNamespace:i.CALDAV,depth:o,headers:a}))[0]}));var ee=Object.freeze({__proto__:null,calendarMultiGet:Z,calendarQuery:z,createCalendarObject:J,deleteCalendarObject:W,fetchCalendarObjects:q,fetchCalendars:Q,freeBusyQuery:X,makeCalendar:G,syncCalendars:Y,updateCalendarObject:K});const te=t("tsdav:account"),re=t=>n(void 0,void 0,void 0,(function*(){var r,o;te("Service discovery...");const{account:a,headers:n}=t,s=new URL(a.serverUrl),d=new URL(`/.well-known/${a.accountType}`,s);d.protocol=null!==(r=s.protocol)&&void 0!==r?r:"http";try{const t=yield e(d.href,{headers:n,method:"PROPFIND",redirect:"manual"});if(t.status>=300&&t.status<400){const e=t.headers.get("Location");if("string"==typeof e&&e.length){te(`Service discovery redirected to ${e}`);const t=new URL(e,s);return t.hostname===d.hostname&&d.port&&!t.port&&(t.port=d.port),t.protocol=null!==(o=s.protocol)&&void 0!==o?o:"http",t.href}}}catch(e){te(`Service discovery failed: ${e.stack}`)}return s.href})),oe=e=>n(void 0,void 0,void 0,(function*(){var t,r,o,a,n;const{account:s,headers:d}=e,c=["rootUrl"];if(!C(s,c))throw new Error(`account must have ${V(s,c)} before fetchPrincipalUrl`);te(`Fetching principal url from path ${s.rootUrl}`);const[l]=yield b({url:s.rootUrl,props:{[`${i.DAV}:current-user-principal`]:{}},depth:"0",headers:d});if(!l.ok&&(te(`Fetch principal url failed: ${l.statusText}`),401===l.status))throw new Error("Invalid credentials");return te(`Fetched principal url ${null===(r=null===(t=l.props)||void 0===t?void 0:t.currentUserPrincipal)||void 0===r?void 0:r.href}`),new URL(null!==(n=null===(a=null===(o=l.props)||void 0===o?void 0:o.currentUserPrincipal)||void 0===a?void 0:a.href)&&void 0!==n?n:"",s.rootUrl).href})),ae=e=>n(void 0,void 0,void 0,(function*(){var t,r;const{account:o,headers:a}=e,n=["principalUrl","rootUrl"];if(!C(o,n))throw new Error(`account must have ${V(o,n)} before fetchHomeUrl`);te(`Fetch home url from ${o.principalUrl}`);const s=(yield b({url:o.principalUrl,props:"caldav"===o.accountType?{[`${i.CALDAV}:calendar-home-set`]:{}}:{[`${i.CARDDAV}:addressbook-home-set`]:{}},depth:"0",headers:a})).find((e=>h(o.principalUrl,e.href)));if(!s||!s.ok)throw new Error("cannot find homeUrl");const d=new URL("caldav"===o.accountType?null===(t=null==s?void 0:s.props)||void 0===t?void 0:t.calendarHomeSet.href:null===(r=null==s?void 0:s.props)||void 0===r?void 0:r.addressbookHomeSet.href,o.rootUrl).href;return te(`Fetched home url ${d}`),d})),ne=e=>n(void 0,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:o=!1,loadObjects:a=!1}=e,s=Object.assign({},t);return s.rootUrl=yield re({account:t,headers:r}),s.principalUrl=yield oe({account:s,headers:r}),s.homeUrl=yield ae({account:s,headers:r}),(o||a)&&("caldav"===t.accountType?s.calendars=yield Q({headers:r,account:s}):"carddav"===t.accountType&&(s.addressBooks=yield N({headers:r,account:s}))),a&&("caldav"===t.accountType&&s.calendars?s.calendars=yield Promise.all(s.calendars.map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield q({calendar:e,headers:r})})}))))):"carddav"===t.accountType&&s.addressBooks&&(s.addressBooks=yield Promise.all(s.addressBooks.map((e=>n(void 0,void 0,void 0,(function*(){return Object.assign(Object.assign({},e),{objects:yield P({addressBook:e,headers:r})})}))))))),s}));var se=Object.freeze({__proto__:null,createAccount:ne,fetchHomeUrl:ae,fetchPrincipalUrl:oe,serviceDiscovery:re});const de=t("tsdav:authHelper"),ie=(e,t)=>(...r)=>e(Object.assign(Object.assign({},t),r[0])),ce=e=>(de(`Basic auth token generated: ${o(`${e.username}:${e.password}`)}`),{authorization:`Basic ${o(`${e.username}:${e.password}`)}`}),le=t=>n(void 0,void 0,void 0,(function*(){const r=["authorizationCode","redirectUrl","clientId","clientSecret","tokenUrl"];if(!C(t,r))throw new Error(`Oauth credentials missing: ${V(t,r)}`);const o=new URLSearchParams({grant_type:"authorization_code",code:t.authorizationCode,redirect_uri:t.redirectUrl,client_id:t.clientId,client_secret:t.clientSecret});de(t.tokenUrl),de(o.toString());const a=yield e(t.tokenUrl,{method:"POST",body:o.toString(),headers:{"content-length":`${o.toString().length}`,"content-type":"application/x-www-form-urlencoded"}});if(a.ok){return yield a.json()}return de(`Fetch Oauth tokens failed: ${yield a.text()}`),{}})),ue=t=>n(void 0,void 0,void 0,(function*(){const r=["refreshToken","clientId","clientSecret","tokenUrl"];if(!C(t,r))throw new Error(`Oauth credentials missing: ${V(t,r)}`);const o=new URLSearchParams({client_id:t.clientId,client_secret:t.clientSecret,refresh_token:t.refreshToken,grant_type:"refresh_token"}),a=yield e(t.tokenUrl,{method:"POST",body:o.toString(),headers:{"Content-Type":"application/x-www-form-urlencoded"}});if(a.ok){return yield a.json()}return de(`Refresh access token failed: ${yield a.text()}`),{}})),he=e=>n(void 0,void 0,void 0,(function*(){var t;de("Fetching oauth headers");let r={};return e.refreshToken?(e.refreshToken&&!e.accessToken||Date.now()>(null!==(t=e.expiration)&&void 0!==t?t:0))&&(r=yield ue(e)):r=yield le(e),de(`Oauth tokens fetched: ${r.access_token}`),{tokens:r,headers:{authorization:`Bearer ${r.access_token}`}}}));var pe=Object.freeze({__proto__:null,defaultParam:ie,fetchOauthTokens:le,getBasicAuthHeaders:ce,getOauthHeaders:he,refreshAccessToken:ue});const ve=e=>n(void 0,void 0,void 0,(function*(){var t;const{serverUrl:r,credentials:o,authMethod:s,defaultAccountType:d,authFunction:i}=e;let c={};switch(s){case"Basic":c=ce(o);break;case"Oauth":c=(yield he(o)).headers;break;case"Digest":c={Authorization:`Digest ${o.digestString}`};break;case"Custom":c=null!==(t=yield null==i?void 0:i(o))&&void 0!==t?t:{};break;default:throw new Error("Invalid auth method")}const l=d?yield ne({account:{serverUrl:r,credentials:o,accountType:d},headers:c}):void 0,u=ie(A,{url:r,headers:c}),h=ie(O,{headers:c,url:r}),p=ie(D,{headers:c,url:r}),v=ie(b,{headers:c}),f=ie(w,{headers:c}),g=ie(k,{headers:c}),m=ie(U,{headers:c}),j=ie(_,{headers:c}),C=ie(R,{headers:c}),V=ie(E,{headers:c,account:l}),$=ie(z,{headers:c}),L=ie(Z,{headers:c}),T=ie(G,{headers:c}),M=ie(Q,{headers:c,account:l}),F=ie(q,{headers:c}),X=ie(J,{headers:c}),ee=ie(K,{headers:c}),te=ie(W,{headers:c}),re=ie(Y,{account:l,headers:c}),oe=ie(S,{headers:c}),ae=ie(x,{headers:c});return{davRequest:e=>n(void 0,void 0,void 0,(function*(){const{init:t}=e,r=a(e,["init"]),{headers:o}=t,n=a(t,["headers"]);return y(Object.assign(Object.assign({},r),{init:Object.assign(Object.assign({},n),{headers:Object.assign(Object.assign({},c),o)})}))})),propfind:v,createAccount:e=>n(void 0,void 0,void 0,(function*(){const{account:t,headers:a,loadCollections:n,loadObjects:s}=e;return ne({account:Object.assign({serverUrl:r,credentials:o},t),headers:Object.assign(Object.assign({},c),a),loadCollections:n,loadObjects:s})})),createObject:u,updateObject:h,deleteObject:p,calendarQuery:$,addressBookQuery:oe,collectionQuery:f,makeCollection:g,calendarMultiGet:L,makeCalendar:T,syncCollection:m,supportedReportSet:j,isCollectionDirty:C,smartCollectionSync:V,fetchCalendars:M,fetchCalendarObjects:F,createCalendarObject:X,updateCalendarObject:ee,deleteCalendarObject:te,syncCalendars:re,fetchAddressBooks:ie(N,{account:l,headers:c}),addressBookMultiGet:ae,fetchVCards:ie(P,{headers:c}),createVCard:ie(H,{headers:c}),updateVCard:ie(B,{headers:c}),deleteVCard:ie(I,{headers:c})}}));class fe{constructor(e){var t,r;this.serverUrl=e.serverUrl,this.credentials=e.credentials,this.authMethod=null!==(t=e.authMethod)&&void 0!==t?t:"Basic",this.accountType=null!==(r=e.defaultAccountType)&&void 0!==r?r:"caldav"}login(){var e;return n(this,void 0,void 0,(function*(){switch(this.authMethod){case"Basic":this.authHeaders=ce(this.credentials);break;case"Oauth":this.authHeaders=(yield he(this.credentials)).headers;break;case"Digest":this.authHeaders={Authorization:`Digest ${this.credentials.digestString}`};break;case"Custom":this.authHeaders=yield null===(e=this.authFunction)||void 0===e?void 0:e.call(this,this.credentials);break;default:throw new Error("Invalid auth method")}this.account=this.accountType?yield ne({account:{serverUrl:this.serverUrl,credentials:this.credentials,accountType:this.accountType},headers:this.authHeaders}):void 0}))}davRequest(e){return n(this,void 0,void 0,(function*(){const{init:t}=e,r=a(e,["init"]),{headers:o}=t,n=a(t,["headers"]);return y(Object.assign(Object.assign({},r),{init:Object.assign(Object.assign({},n),{headers:Object.assign(Object.assign({},this.authHeaders),o)})}))}))}createObject(...e){return n(this,void 0,void 0,(function*(){return ie(A,{url:this.serverUrl,headers:this.authHeaders})(e[0])}))}updateObject(...e){return n(this,void 0,void 0,(function*(){return ie(O,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}deleteObject(...e){return n(this,void 0,void 0,(function*(){return ie(D,{headers:this.authHeaders,url:this.serverUrl})(e[0])}))}propfind(...e){return n(this,void 0,void 0,(function*(){return ie(b,{headers:this.authHeaders})(e[0])}))}createAccount(e){return n(this,void 0,void 0,(function*(){const{account:t,headers:r,loadCollections:o,loadObjects:a}=e;return ne({account:Object.assign({serverUrl:this.serverUrl,credentials:this.credentials},t),headers:Object.assign(Object.assign({},this.authHeaders),r),loadCollections:o,loadObjects:a})}))}collectionQuery(...e){return n(this,void 0,void 0,(function*(){return ie(w,{headers:this.authHeaders})(e[0])}))}makeCollection(...e){return n(this,void 0,void 0,(function*(){return ie(k,{headers:this.authHeaders})(e[0])}))}syncCollection(...e){return n(this,void 0,void 0,(function*(){return ie(U,{headers:this.authHeaders})(e[0])}))}supportedReportSet(...e){return n(this,void 0,void 0,(function*(){return ie(_,{headers:this.authHeaders})(e[0])}))}isCollectionDirty(...e){return n(this,void 0,void 0,(function*(){return ie(R,{headers:this.authHeaders})(e[0])}))}smartCollectionSync(...e){return n(this,void 0,void 0,(function*(){return ie(E,{headers:this.authHeaders,account:this.account})(e[0])}))}calendarQuery(...e){return n(this,void 0,void 0,(function*(){return ie(z,{headers:this.authHeaders})(e[0])}))}makeCalendar(...e){return n(this,void 0,void 0,(function*(){return ie(G,{headers:this.authHeaders})(e[0])}))}calendarMultiGet(...e){return n(this,void 0,void 0,(function*(){return ie(Z,{headers:this.authHeaders})(e[0])}))}fetchCalendars(...e){return n(this,void 0,void 0,(function*(){return ie(Q,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchCalendarObjects(...e){return n(this,void 0,void 0,(function*(){return ie(q,{headers:this.authHeaders})(e[0])}))}createCalendarObject(...e){return n(this,void 0,void 0,(function*(){return ie(J,{headers:this.authHeaders})(e[0])}))}updateCalendarObject(...e){return n(this,void 0,void 0,(function*(){return ie(K,{headers:this.authHeaders})(e[0])}))}deleteCalendarObject(...e){return n(this,void 0,void 0,(function*(){return ie(W,{headers:this.authHeaders})(e[0])}))}syncCalendars(...e){return n(this,void 0,void 0,(function*(){return ie(Y,{headers:this.authHeaders,account:this.account})(e[0])}))}addressBookQuery(...e){return n(this,void 0,void 0,(function*(){return ie(S,{headers:this.authHeaders})(e[0])}))}addressBookMultiGet(...e){return n(this,void 0,void 0,(function*(){return ie(x,{headers:this.authHeaders})(e[0])}))}fetchAddressBooks(...e){return n(this,void 0,void 0,(function*(){return ie(N,{headers:this.authHeaders,account:this.account})(null==e?void 0:e[0])}))}fetchVCards(...e){return n(this,void 0,void 0,(function*(){return ie(P,{headers:this.authHeaders})(e[0])}))}createVCard(...e){return n(this,void 0,void 0,(function*(){return ie(H,{headers:this.authHeaders})(e[0])}))}updateVCard(...e){return n(this,void 0,void 0,(function*(){return ie(B,{headers:this.authHeaders})(e[0])}))}deleteVCard(...e){return n(this,void 0,void 0,(function*(){return ie(I,{headers:this.authHeaders})(e[0])}))}}var ge=Object.freeze({__proto__:null,DAVClient:fe,createDAVClient:ve}),me=Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({DAVNamespace:s,DAVNamespaceShort:i,DAVAttributeMap:d},ge),j),L),se),M),ee),pe),g);export{d as DAVAttributeMap,fe as DAVClient,s as DAVNamespace,i as DAVNamespaceShort,S as addressBookQuery,Z as calendarMultiGet,z as calendarQuery,v as cleanupFalsy,w as collectionQuery,ne as createAccount,J as createCalendarObject,ve as createDAVClient,A as createObject,H as createVCard,y as davRequest,me as default,W as deleteCalendarObject,D as deleteObject,I as deleteVCard,N as fetchAddressBooks,q as fetchCalendarObjects,Q as fetchCalendars,le as fetchOauthTokens,P as fetchVCards,X as freeBusyQuery,ce as getBasicAuthHeaders,p as getDAVAttribute,he as getOauthHeaders,R as isCollectionDirty,G as makeCalendar,b as propfind,ue as refreshAccessToken,E as smartCollectionSync,_ as supportedReportSet,Y as syncCalendars,U as syncCollection,K as updateCalendarObject,O as updateObject,B as updateVCard,h as urlContains,u as urlEquals}; diff --git a/dist/tsdav.mjs b/dist/tsdav.mjs index fe7b905..aacac24 100644 --- a/dist/tsdav.mjs +++ b/dist/tsdav.mjs @@ -127,10 +127,19 @@ const cleanupFalsy = (obj) => Object.entries(obj).reduce((prev, [key, value]) => return Object.assign(Object.assign({}, prev), { [key]: value }); return prev; }, {}); +const conditionalParam = (key, param) => { + if (param) { + return { + [key]: param, + }; + } + return {}; +}; var requestHelpers = /*#__PURE__*/Object.freeze({ __proto__: null, cleanupFalsy: cleanupFalsy, + conditionalParam: conditionalParam, getDAVAttribute: getDAVAttribute, urlContains: urlContains, urlEquals: urlEquals @@ -740,13 +749,7 @@ const calendarMultiGet = (params) => __awaiter(void 0, void 0, void 0, function* return collectionQuery({ url, body: { - 'calendar-multiget': { - _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), - [`${DAVNamespaceShort.DAV}:prop`]: props, - [`${DAVNamespaceShort.DAV}:href`]: objectUrls, - filter: filters, - timezone, - }, + 'calendar-multiget': Object.assign(Object.assign({ _attributes: getDAVAttribute([DAVNamespace.DAV, DAVNamespace.CALDAV]), [`${DAVNamespaceShort.DAV}:prop`]: props, [`${DAVNamespaceShort.DAV}:href`]: objectUrls }, conditionalParam('filter', filters)), { timezone }), }, defaultNamespace: DAVNamespaceShort.CALDAV, depth, @@ -777,7 +780,7 @@ const makeCalendar = (params) => __awaiter(void 0, void 0, void 0, function* () }); }); const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { headers, account, props: customProps } = params !== null && params !== void 0 ? params : {}; + const { headers, account, props: customProps, projectedProps } = params !== null && params !== void 0 ? params : {}; const requiredFields = ['homeUrl', 'rootUrl']; if (!account || !hasFields(account, requiredFields)) { if (!account) { @@ -811,23 +814,13 @@ const fetchCalendars = (params) => __awaiter(void 0, void 0, void 0, function* ( return components.some((c) => Object.values(ICALObjects).includes(c)); }) .map((rs) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p; + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q; // debug(`Found calendar ${rs.props?.displayname}`); const description = (_a = rs.props) === null || _a === void 0 ? void 0 : _a.calendarDescription; const timezone = (_b = rs.props) === null || _b === void 0 ? void 0 : _b.calendarTimezone; - return { - description: typeof description === 'string' ? description : '', - timezone: typeof timezone === 'string' ? timezone : '', - url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, - ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, - calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, - displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, - components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) + return Object.assign({ description: typeof description === 'string' ? description : '', timezone: typeof timezone === 'string' ? timezone : '', url: new URL((_c = rs.href) !== null && _c !== void 0 ? _c : '', (_d = account.rootUrl) !== null && _d !== void 0 ? _d : '').href, ctag: (_e = rs.props) === null || _e === void 0 ? void 0 : _e.getctag, calendarColor: (_f = rs.props) === null || _f === void 0 ? void 0 : _f.calendarColor, displayName: (_h = (_g = rs.props) === null || _g === void 0 ? void 0 : _g.displayname._cdata) !== null && _h !== void 0 ? _h : (_j = rs.props) === null || _j === void 0 ? void 0 : _j.displayname, components: Array.isArray((_k = rs.props) === null || _k === void 0 ? void 0 : _k.supportedCalendarComponentSet.comp) ? (_l = rs.props) === null || _l === void 0 ? void 0 : _l.supportedCalendarComponentSet.comp.map((sc) => sc._attributes.name) - : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], - resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), - syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken, - }; + : [(_m = rs.props) === null || _m === void 0 ? void 0 : _m.supportedCalendarComponentSet.comp._attributes.name], resourcetype: Object.keys((_o = rs.props) === null || _o === void 0 ? void 0 : _o.resourcetype), syncToken: (_p = rs.props) === null || _p === void 0 ? void 0 : _p.syncToken }, conditionalParam('projectedProps', Object.fromEntries(Object.entries((_q = rs.props) !== null && _q !== void 0 ? _q : {}).filter(([key]) => projectedProps === null || projectedProps === void 0 ? void 0 : projectedProps[key])))); }) .map((cal) => __awaiter(void 0, void 0, void 0, function* () { return (Object.assign(Object.assign({}, cal), { reports: yield supportedReportSet({ collection: cal, headers }) })); @@ -1330,14 +1323,27 @@ var authHelpers = /*#__PURE__*/Object.freeze({ // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types const createDAVClient = (params) => __awaiter(void 0, void 0, void 0, function* () { - const { serverUrl, credentials, authMethod, defaultAccountType } = params; - const authHeaders = - // eslint-disable-next-line no-nested-ternary - authMethod === 'Basic' - ? getBasicAuthHeaders(credentials) - : authMethod === 'Oauth' - ? (yield getOauthHeaders(credentials)).headers - : {}; + var _a; + const { serverUrl, credentials, authMethod, defaultAccountType, authFunction } = params; + let authHeaders = {}; + switch (authMethod) { + case 'Basic': + authHeaders = getBasicAuthHeaders(credentials); + break; + case 'Oauth': + authHeaders = (yield getOauthHeaders(credentials)).headers; + break; + case 'Digest': + authHeaders = { + Authorization: `Digest ${credentials.digestString}`, + }; + break; + case 'Custom': + authHeaders = (_a = (yield (authFunction === null || authFunction === void 0 ? void 0 : authFunction(credentials)))) !== null && _a !== void 0 ? _a : {}; + break; + default: + throw new Error('Invalid auth method'); + } const defaultAccount = defaultAccountType ? yield createAccount({ account: { serverUrl, credentials, accountType: defaultAccountType }, @@ -1455,14 +1461,26 @@ class DAVClient { this.accountType = (_b = params.defaultAccountType) !== null && _b !== void 0 ? _b : 'caldav'; } login() { + var _a; return __awaiter(this, void 0, void 0, function* () { - this.authHeaders = - // eslint-disable-next-line no-nested-ternary - this.authMethod === 'Basic' - ? getBasicAuthHeaders(this.credentials) - : this.authMethod === 'Oauth' - ? (yield getOauthHeaders(this.credentials)).headers - : {}; + switch (this.authMethod) { + case 'Basic': + this.authHeaders = getBasicAuthHeaders(this.credentials); + break; + case 'Oauth': + this.authHeaders = (yield getOauthHeaders(this.credentials)).headers; + break; + case 'Digest': + this.authHeaders = { + Authorization: `Digest ${this.credentials.digestString}`, + }; + break; + case 'Custom': + this.authHeaders = yield ((_a = this.authFunction) === null || _a === void 0 ? void 0 : _a.call(this, this.credentials)); + break; + default: + throw new Error('Invalid auth method'); + } this.account = this.accountType ? yield createAccount({ account: {