diff --git a/docs/docs/intro.md b/docs/docs/intro.md index 48274338..dd8e9a86 100644 --- a/docs/docs/intro.md +++ b/docs/docs/intro.md @@ -280,7 +280,7 @@ const calendarObjects = await client.fetchCalendarObjects({ ```ts const calendarObjects = await client.fetchCalendarObjects({ calendar: myCalendar, - calendarObjectUrls: urlArray, + objectUrls: urlArray, }); ``` diff --git a/docs/package.json b/docs/package.json index 0814778a..3da75347 100644 --- a/docs/package.json +++ b/docs/package.json @@ -55,15 +55,5 @@ "docusaurus-plugin-llms": "^0.6.0", "typescript": "7.0.2" }, - "packageManager": "pnpm@10.34.4", - "pnpm": { - "overrides": { - "docusaurus-plugin-llms>minimatch": "9.0.7", - "docusaurus-plugin-llms>yaml": "2.8.3", - "qs@>=6.14.2 <6.16.0": "6.16.0", - "sockjs>uuid": "11.1.1", - "serialize-javascript@<7.0.5": "7.0.5", - "image-size": "npm:image-size-next@2.1.1" - } - } + "packageManager": "pnpm@10.34.4" } diff --git a/docs/pnpm-lock.yaml b/docs/pnpm-lock.yaml index 60c7344f..d081a9a1 100644 --- a/docs/pnpm-lock.yaml +++ b/docs/pnpm-lock.yaml @@ -5,6 +5,8 @@ settings: excludeLinksFromLockfile: false overrides: + serialize-javascript: 7.0.6 + uuid@<11.1.1: 11.1.1 docusaurus-plugin-llms>minimatch: 9.0.7 docusaurus-plugin-llms>yaml: 2.8.3 qs@>=6.14.2 <6.16.0: 6.16.0 diff --git a/docs/pnpm-workspace.yaml b/docs/pnpm-workspace.yaml index cc114fdf..1d58f34d 100644 --- a/docs/pnpm-workspace.yaml +++ b/docs/pnpm-workspace.yaml @@ -4,3 +4,9 @@ packages: overrides: serialize-javascript: 7.0.6 'uuid@<11.1.1': 11.1.1 + docusaurus-plugin-llms>minimatch: "9.0.7" + docusaurus-plugin-llms>yaml: "2.8.3" + qs@>=6.14.2 <6.16.0: "6.16.0" + sockjs>uuid: "11.1.1" + serialize-javascript@<7.0.5: "7.0.5" + image-size: "npm:image-size-next@2.1.1" diff --git a/package.json b/package.json index 1dd158eb..a89f4e1e 100644 --- a/package.json +++ b/package.json @@ -82,10 +82,5 @@ "packageManager": "pnpm@10.34.4", "engines": { "node": ">=18" - }, - "pnpm": { - "overrides": { - "vite>postcss": "8.5.28" - } } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bd716450..7d0dc4de 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5,6 +5,10 @@ settings: excludeLinksFromLockfile: false overrides: + picomatch: 4.0.4 + postcss: 8.5.15 + serialize-javascript: 7.0.6 + vite: 6.4.3 vite>postcss: 8.5.28 importers: @@ -710,7 +714,7 @@ packages: resolution: {integrity: sha512-66PGTMIiVJP3t4a5yxU9qPtf7MdTBs8jmToMvy+HVflB3Yy13WJZTtPePdvU+wjRV02SKK5doLbSA6o9pwOmiA==} peerDependencies: msw: ^2.4.9 - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + vite: 6.4.3 peerDependenciesMeta: msw: optional: true @@ -795,7 +799,7 @@ packages: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} peerDependencies: - picomatch: ^3 || ^4 + picomatch: 4.0.4 peerDependenciesMeta: picomatch: optional: true @@ -921,10 +925,6 @@ packages: resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} engines: {node: '>=12'} - picomatch@4.0.7: - resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} - engines: {node: '>=12'} - postcss@8.5.28: resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} engines: {node: ^10 || ^12 || >=14} @@ -1069,7 +1069,7 @@ packages: '@vitest/ui': 5.0.0 happy-dom: '*' jsdom: '*' - vite: ^6.4.0 || ^7.0.0 || ^8.0.0 + vite: 6.4.3 peerDependenciesMeta: '@edge-runtime/vm': optional: true @@ -1663,8 +1663,6 @@ snapshots: picomatch@4.0.4: {} - picomatch@4.0.7: {} - postcss@8.5.28: dependencies: nanoid: 3.3.18 @@ -1830,7 +1828,7 @@ snapshots: expect-type: 1.4.0 magic-string: 1.2.3 obug: 2.1.4 - picomatch: 4.0.7 + picomatch: 4.0.4 std-env: 4.2.0 tinybench: 6.1.4 tinyexec: 1.3.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 4b6aec23..0db48195 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -9,3 +9,4 @@ overrides: postcss: 8.5.15 serialize-javascript: 7.0.6 vite: 6.4.3 + vite>postcss: "8.5.28" diff --git a/src/__tests__/unit/account.test.ts b/src/__tests__/unit/account.test.ts index 7a695f32..fd43476a 100644 --- a/src/__tests__/unit/account.test.ts +++ b/src/__tests__/unit/account.test.ts @@ -606,4 +606,40 @@ describe('fetchHomeUrl', () => { }), ).rejects.toThrow('cannot find homeUrl'); }); + + it('should handle calendar-home-set with multiple hrefs by selecting the first', async () => { + const mockFetch = vi.fn().mockResolvedValue( + buildResponse({ + status: 207, + body: ` + + + /principals/user1/ + + + + /calendars/user1/ + /calendars/shared/ + + + HTTP/1.1 200 OK + + +`, + headers: { 'content-type': 'application/xml' }, + }), + ); + + const result = await fetchHomeUrl({ + account: { + serverUrl: 'https://example.com/', + rootUrl: 'https://example.com/', + principalUrl: 'https://example.com/principals/user1/', + accountType: 'caldav', + }, + fetch: mockFetch, + }); + + expect(result).toBe('https://example.com/calendars/user1/'); + }); }); diff --git a/src/__tests__/unit/client.test.ts b/src/__tests__/unit/client.test.ts index de137fca..d7b43e75 100644 --- a/src/__tests__/unit/client.test.ts +++ b/src/__tests__/unit/client.test.ts @@ -852,3 +852,68 @@ describe('DAVClient empty sync response', () => { expect(await client.calendarQuery({ url: 'http://example.com/col/', props: {} })).toEqual([]); }); }); + +describe('client freeBusyQuery', () => { + it('should expose freeBusyQuery on DAVClient', async () => { + const mockFetch = buildMockFetch( + ` + + + /cal/ + + BEGIN:VCALENDAR...END:VCALENDAR + HTTP/1.1 200 OK + + +`, + 207, + ); + const client = new DAVClient({ + serverUrl: 'http://example.com/', + credentials: { username: 'u', password: 'p' }, + fetch: mockFetch, + }); + client.authHeaders = { authorization: 'Basic dTpw' }; + + const res = await client.freeBusyQuery({ + url: 'http://example.com/cal/', + timeRange: { start: '2026-01-01T00:00:00Z', end: '2026-01-02T00:00:00Z' }, + }); + + expect(res).toBeDefined(); + expect(mockFetch).toHaveBeenCalled(); + const lastCall = mockFetch.mock.calls[mockFetch.mock.calls.length - 1]; + expect(lastCall[1].body).toContain('free-busy-query'); + }); + + it('should expose freeBusyQuery on createDAVClient', async () => { + const mockFetch = buildMockFetch( + ` + + + /cal/ + + BEGIN:VCALENDAR...END:VCALENDAR + HTTP/1.1 200 OK + + +`, + 207, + ); + const client = await createDAVClient({ + serverUrl: 'http://example.com/', + credentials: { username: 'u', password: 'p' }, + fetch: mockFetch, + }); + + const res = await client.freeBusyQuery({ + url: 'http://example.com/cal/', + timeRange: { start: '2026-01-01T00:00:00Z', end: '2026-01-02T00:00:00Z' }, + }); + + expect(res).toBeDefined(); + expect(mockFetch).toHaveBeenCalled(); + const lastCall = mockFetch.mock.calls[mockFetch.mock.calls.length - 1]; + expect(lastCall[1].body).toContain('free-busy-query'); + }); +}); diff --git a/src/__tests__/unit/collection.test.ts b/src/__tests__/unit/collection.test.ts index b8bcc672..d238b572 100644 --- a/src/__tests__/unit/collection.test.ts +++ b/src/__tests__/unit/collection.test.ts @@ -231,6 +231,7 @@ describe('makeCollection', () => { expect(mockedDavRequest.mock.calls[0][0].init.method).toBe('MKCOL'); const body = mockedDavRequest.mock.calls[0][0].init.body as any; expect(body.mkcol.set.prop).toEqual({ 'd:displayname': 'New Collection' }); + expect(body.mkcol._attributes).toHaveProperty('xmlns:d', 'DAV:'); expect(result).toHaveLength(1); }); diff --git a/src/__tests__/unit/index.test.ts b/src/__tests__/unit/index.test.ts new file mode 100644 index 00000000..dda1a79d --- /dev/null +++ b/src/__tests__/unit/index.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect } from 'vitest'; +import * as tsdav from '../../index'; + +describe('tsdav public exports', () => { + it('should export all public client, request, and collection functions', () => { + expect(typeof tsdav.DAVClient).toBe('function'); + expect(typeof tsdav.createDAVClient).toBe('function'); + expect(typeof tsdav.davRequest).toBe('function'); + expect(typeof tsdav.propfind).toBe('function'); + expect(typeof tsdav.createObject).toBe('function'); + expect(typeof tsdav.updateObject).toBe('function'); + expect(typeof tsdav.deleteObject).toBe('function'); + expect(typeof tsdav.collectionQuery).toBe('function'); + expect(typeof tsdav.supportedReportSet).toBe('function'); + expect(typeof tsdav.isCollectionDirty).toBe('function'); + expect(typeof tsdav.syncCollection).toBe('function'); + expect(typeof tsdav.smartCollectionSync).toBe('function'); + expect(typeof tsdav.smartCollectionSyncDetailed).toBe('function'); + }); + + it('should export all public account functions including discovery', () => { + expect(typeof tsdav.createAccount).toBe('function'); + expect(typeof tsdav.serviceDiscovery).toBe('function'); + expect(typeof tsdav.fetchPrincipalUrl).toBe('function'); + expect(typeof tsdav.fetchHomeUrl).toBe('function'); + }); + + it('should export all public calendar and addressbook functions', () => { + expect(typeof tsdav.calendarQuery).toBe('function'); + expect(typeof tsdav.calendarMultiGet).toBe('function'); + expect(typeof tsdav.makeCalendar).toBe('function'); + expect(typeof tsdav.fetchCalendars).toBe('function'); + expect(typeof tsdav.fetchCalendarUserAddresses).toBe('function'); + expect(typeof tsdav.fetchCalendarObjects).toBe('function'); + expect(typeof tsdav.createCalendarObject).toBe('function'); + expect(typeof tsdav.updateCalendarObject).toBe('function'); + expect(typeof tsdav.deleteCalendarObject).toBe('function'); + expect(typeof tsdav.syncCalendars).toBe('function'); + expect(typeof tsdav.syncCalendarsDetailed).toBe('function'); + expect(typeof tsdav.freeBusyQuery).toBe('function'); + + expect(typeof tsdav.addressBookQuery).toBe('function'); + expect(typeof tsdav.addressBookMultiGet).toBe('function'); + expect(typeof tsdav.fetchAddressBooks).toBe('function'); + expect(typeof tsdav.fetchVCards).toBe('function'); + expect(typeof tsdav.createVCard).toBe('function'); + expect(typeof tsdav.updateVCard).toBe('function'); + expect(typeof tsdav.deleteVCard).toBe('function'); + }); + + it('should export auth and request helpers', () => { + expect(typeof tsdav.getBasicAuthHeaders).toBe('function'); + expect(typeof tsdav.getBearerAuthHeaders).toBe('function'); + expect(typeof tsdav.getOauthHeaders).toBe('function'); + expect(typeof tsdav.fetchOauthTokens).toBe('function'); + expect(typeof tsdav.refreshAccessToken).toBe('function'); + + expect(typeof tsdav.urlContains).toBe('function'); + expect(typeof tsdav.urlEquals).toBe('function'); + expect(typeof tsdav.urlMatches).toBe('function'); + expect(typeof tsdav.ensureTrailingSlash).toBe('function'); + expect(typeof tsdav.getDAVAttribute).toBe('function'); + expect(typeof tsdav.cleanupFalsy).toBe('function'); + expect(typeof tsdav.excludeHeaders).toBe('function'); + expect(typeof tsdav.mergeHeaders).toBe('function'); + }); + + it('should export constants', () => { + expect(tsdav.DAVNamespace).toBeDefined(); + expect(tsdav.DAVAttributeMap).toBeDefined(); + expect(tsdav.DAVNamespaceShort).toBeDefined(); + expect(tsdav.ICALObjects).toBeDefined(); + expect(tsdav.ICALObjects.VEVENT).toBe('VEVENT'); + }); +}); diff --git a/src/__tests__/unit/request.test.ts b/src/__tests__/unit/request.test.ts index 564bcf48..d02eb036 100644 --- a/src/__tests__/unit/request.test.ts +++ b/src/__tests__/unit/request.test.ts @@ -542,6 +542,43 @@ describe('davRequest', () => { expect(callArgs.credentials).toBe('include'); expect(callArgs.headers['X-Extra']).toBe('yes'); }); + + it.each([null, undefined])( + 'should send a %s body with attributes without conversion', + async (body) => { + const mockFetch = buildMockFetch({ text: '' }); + await davRequest({ + url: 'http://example.com/', + init: { method: 'OPTIONS', body, attributes: { 'xmlns:d': 'DAV:' } }, + fetch: mockFetch, + }); + expect(mockFetch).toHaveBeenCalledOnce(); + expect(mockFetch.mock.calls[0][1].body).toBe(body); + }, + ); + + it('should propagate init.attributes to the root XML element', async () => { + const mockFetch = buildMockFetch({ text: '' }); + + await davRequest({ + url: 'http://example.com/', + init: { + method: 'REPORT', + body: { + 'custom-report': { + prop: {}, + }, + }, + attributes: { + 'xmlns:custom': 'http://example.com/ns', + }, + }, + fetch: mockFetch, + }); + + const callArgs = mockFetch.mock.calls[0][1]; + expect(callArgs.body).toContain('xmlns:custom="http://example.com/ns"'); + }); }); describe('propfind', () => { diff --git a/src/__tests__/unit/requestHelpers.test.ts b/src/__tests__/unit/requestHelpers.test.ts index 7d0d029f..4e25ff6f 100644 --- a/src/__tests__/unit/requestHelpers.test.ts +++ b/src/__tests__/unit/requestHelpers.test.ts @@ -2,6 +2,7 @@ import { describe, it, test, expect } from 'vitest'; import { cleanupFalsy, conditionalParam, + ensureTrailingSlash, excludeHeaders, getDAVAttribute, urlContains, @@ -156,3 +157,29 @@ describe('conditionalParam', () => { expect(conditionalParam('foo', false)).toEqual({}); }); }); + +describe('ensureTrailingSlash', () => { + it.each([ + ['https://example.com/cal?token=x', 'https://example.com/cal/?token=x'], + ['https://example.com/cal#section', 'https://example.com/cal/#section'], + ['https://example.com/cal?token=x/#section', 'https://example.com/cal/?token=x/#section'], + ['https://example.com/cal/?token=x', 'https://example.com/cal/?token=x'], + ['/cal?token=x', '/cal/?token=x'], + ])('should preserve URL suffixes when normalizing %s', (input, expected) => { + expect(ensureTrailingSlash(input)).toBe(expected); + expect( + new URL('event.ics', new URL(ensureTrailingSlash(input), 'https://example.com')).href, + ).toBe('https://example.com/cal/event.ics'); + }); + + it('should append a trailing slash if not present', () => { + expect(ensureTrailingSlash('https://example.com/cal')).toBe('https://example.com/cal/'); + expect(ensureTrailingSlash('/cal/user')).toBe('/cal/user/'); + }); + + it('should preserve existing trailing slash and trim whitespace', () => { + expect(ensureTrailingSlash('https://example.com/cal/')).toBe('https://example.com/cal/'); + expect(ensureTrailingSlash(' https://example.com/cal/ ')).toBe('https://example.com/cal/'); + expect(ensureTrailingSlash(' https://example.com/cal ')).toBe('https://example.com/cal/'); + }); +}); diff --git a/src/account.ts b/src/account.ts index de8397b0..c486a72d 100644 --- a/src/account.ts +++ b/src/account.ts @@ -6,7 +6,12 @@ import { DAVNamespaceShort } from './consts'; import { propfind } from './request'; import { DAVAccount } from './types/models'; import { fetch } from './util/fetch'; -import { excludeHeaders, mergeHeaders, urlMatches } from './util/requestHelpers'; +import { + excludeHeaders, + mergeHeaders, + urlMatches, + ensureTrailingSlash, +} from './util/requestHelpers'; import { findMissingFieldNames, hasFields } from './util/typeHelpers'; const debug = getLogger('tsdav:account'); @@ -108,6 +113,30 @@ export const serviceDiscovery = async (params: { return endpoint.href; }; +const extractHref = (raw: unknown): string | undefined => { + if (typeof raw === 'string' && raw.trim().length > 0) { + return raw.trim(); + } + if (Array.isArray(raw)) { + for (const item of raw) { + const found = extractHref(item); + if (found) return found; + } + return undefined; + } + if (raw && typeof raw === 'object') { + if ('_cdata' in raw && typeof (raw as { _cdata: unknown })._cdata === 'string') { + const cdata = (raw as { _cdata: string })._cdata.trim(); + if (cdata.length > 0) return cdata; + } + if ('_text' in raw && typeof (raw as { _text: unknown })._text === 'string') { + const text = (raw as { _text: string })._text.trim(); + if (text.length > 0) return text; + } + } + return undefined; +}; + export const fetchPrincipalUrl = async (params: { account: DAVAccount; headers?: Record; @@ -144,14 +173,14 @@ export const fetchPrincipalUrl = async (params: { throw new Error('cannot find principalUrl'); } - const principalHref = response.props?.currentUserPrincipal?.href; - if (typeof principalHref !== 'string' || !principalHref.length) { + const principalHref = extractHref(response.props?.currentUserPrincipal?.href); + if (!principalHref) { debug('Fetch principal url failed: missing current-user-principal href'); throw new Error('cannot find principalUrl'); } debug(`Fetched principal url ${principalHref}`); - return new URL(principalHref, account.rootUrl).href; + return new URL(principalHref, ensureTrailingSlash(account.rootUrl)).href; }; export const fetchHomeUrl = async (params: { @@ -190,11 +219,12 @@ export const fetchHomeUrl = async (params: { throw new Error('cannot find homeUrl'); } - const homeHref = + const homeHref = extractHref( account.accountType === 'caldav' ? matched.props?.calendarHomeSet?.href - : matched.props?.addressbookHomeSet?.href; - if (typeof homeHref !== 'string' || homeHref.length === 0) { + : matched.props?.addressbookHomeSet?.href, + ); + if (!homeHref) { debug( `Fetch home url failed: server did not return a ${ account.accountType === 'caldav' ? 'calendar-home-set' : 'addressbook-home-set' @@ -203,7 +233,7 @@ export const fetchHomeUrl = async (params: { throw new Error('cannot find homeUrl'); } - const result = new URL(homeHref, account.rootUrl).href; + const result = new URL(homeHref, ensureTrailingSlash(account.rootUrl)).href; debug(`Fetched home url ${result}`); return result; }; diff --git a/src/addressBook.ts b/src/addressBook.ts index 2a75e977..515d72cc 100644 --- a/src/addressBook.ts +++ b/src/addressBook.ts @@ -7,7 +7,13 @@ import { DAVNamespace, DAVNamespaceShort } from './consts'; import { createObject, deleteObject, propfind, updateObject } from './request'; import { DAVDepth, DAVResponse } from './types/DAVTypes'; import { DAVAccount, DAVAddressBook, DAVVCard } from './types/models'; -import { cleanupFalsy, excludeHeaders, getDAVAttribute, urlEquals } from './util/requestHelpers'; +import { + cleanupFalsy, + excludeHeaders, + getDAVAttribute, + urlEquals, + ensureTrailingSlash, +} from './util/requestHelpers'; import { findMissingFieldNames, hasFields } from './util/typeHelpers'; const debug = getLogger('tsdav:addressBook'); @@ -141,7 +147,7 @@ export const fetchAddressBooks = async (params?: { debug(`Found address book named ${typeof displayName === 'string' ? displayName : ''}, props: ${JSON.stringify(rs.props)}`); return { - url: new URL(rs.href ?? '', account.rootUrl ?? '').href, + url: new URL(rs.href ?? '', ensureTrailingSlash(account.rootUrl ?? '')).href, ctag: rs.props?.getctag, displayName: typeof displayName === 'string' ? displayName : '', resourcetype: Object.keys(rs.props?.resourcetype ?? {}), @@ -208,8 +214,11 @@ export const fetchVCards = async (params: { }) ).map((res) => res.href ?? '') ) - .map((url) => (url.startsWith('http') || !url ? url : new URL(url, addressBook.url).href)) - .filter((url) => url && !urlEquals(url, addressBook.url)) + .filter((url): url is string => typeof url === 'string' && url.trim().length > 0) + .map((url) => + url.startsWith('http') ? url : new URL(url, ensureTrailingSlash(addressBook.url)).href, + ) + .filter((url) => !urlEquals(url, addressBook.url)) .filter(urlFilter) .map((url) => { const parsedUrl = new URL(url); @@ -247,7 +256,7 @@ export const fetchVCards = async (params: { } return vCardResults.map((res) => ({ - url: new URL(res.href ?? '', addressBook.url).href, + url: new URL(res.href ?? '', ensureTrailingSlash(addressBook.url)).href, etag: res.props?.getetag == null ? undefined : String(res.props.getetag), data: res.props?.addressData?._cdata ?? res.props?.addressData, })); @@ -272,7 +281,7 @@ export const createVCard = async (params: { fetch: fetchOverride, } = params; return createObject({ - url: new URL(filename, addressBook.url).href, + url: new URL(filename, ensureTrailingSlash(addressBook.url)).href, data: vCardString, headers: excludeHeaders( { diff --git a/src/calendar.ts b/src/calendar.ts index 16f89c13..b00396ef 100644 --- a/src/calendar.ts +++ b/src/calendar.ts @@ -12,7 +12,13 @@ import { SyncCalendarsDetailedResult, } from './types/functionsOverloads'; import { DAVAccount, DAVCalendar, DAVCalendarObject } from './types/models'; -import { cleanupFalsy, excludeHeaders, getDAVAttribute, urlMatches } from './util/requestHelpers'; +import { + cleanupFalsy, + excludeHeaders, + getDAVAttribute, + urlMatches, + ensureTrailingSlash, +} from './util/requestHelpers'; import { findMissingFieldNames, hasFields } from './util/typeHelpers'; const debug = getLogger('tsdav:calendar'); @@ -297,7 +303,7 @@ export const fetchCalendars = async (params?: { return { description: typeof description === 'string' ? description : '', timezone: typeof timezone === 'string' ? timezone : '', - url: new URL(rs.href ?? '', account.rootUrl ?? '').href, + url: new URL(rs.href ?? '', ensureTrailingSlash(account.rootUrl ?? '')).href, ctag: rs.props?.getctag, calendarColor: rs.props?.calendarColor, displayName: rs.props?.displayname?._cdata ?? rs.props?.displayname, @@ -432,7 +438,10 @@ export const fetchCalendarObjects = async (params: { } const calendarObjectUrls = (objectUrls ?? initialResponses.map((res) => res.href ?? '')) - .map((url) => (url.startsWith('http') || !url ? url : new URL(url, calendar.url).href)) // patch up to full url if url is not full + .filter((url): url is string => typeof url === 'string' && url.trim().length > 0) + .map((url) => + url.startsWith('http') ? url : new URL(url, ensureTrailingSlash(calendar.url)).href, + ) // patch up to full url if url is not full .filter(urlFilter) // custom filter function on calendar objects .map((url) => { const parsedUrl = new URL(url); @@ -446,7 +455,7 @@ export const fetchCalendarObjects = async (params: { calendarObjectResults = initialResponses.filter((res) => { const fullUrl = (res.href ?? '').startsWith('http') ? res.href - : new URL(res.href ?? '', calendar.url).href; + : new URL(res.href ?? '', ensureTrailingSlash(calendar.url)).href; return urlFilter(fullUrl ?? ''); }); } else if (!useMultiGet) { @@ -479,6 +488,14 @@ export const fetchCalendarObjects = async (params: { fetchOptions, fetch: fetchOverride, }); + if (objectUrls && objectUrls.length > 0) { + calendarObjectResults = calendarObjectResults.filter((res) => { + const fullUrl = (res.href ?? '').startsWith('http') + ? (res.href ?? '') + : new URL(res.href ?? '', ensureTrailingSlash(calendar.url)).href; + return calendarObjectUrls.some((target) => urlMatches(fullUrl, target, calendar.url)); + }); + } } else { calendarObjectResults = await calendarMultiGet({ url: calendar.url, @@ -513,7 +530,7 @@ export const fetchCalendarObjects = async (params: { } return calendarObjectResults.map((res) => ({ - url: new URL(res.href ?? '', calendar.url).href, + url: new URL(res.href ?? '', ensureTrailingSlash(calendar.url)).href, etag: res.props?.getetag == null ? undefined : String(res.props.getetag), data: res.props?.calendarData?._cdata ?? res.props?.calendarData, })); @@ -539,7 +556,7 @@ export const createCalendarObject = async (params: { } = params; return createObject({ - url: new URL(filename, calendar.url).href, + url: new URL(filename, ensureTrailingSlash(calendar.url)).href, data: iCalString, headers: excludeHeaders( { diff --git a/src/client.ts b/src/client.ts index 7421eea5..4e433e05 100644 --- a/src/client.ts +++ b/src/client.ts @@ -20,6 +20,7 @@ import { syncCalendarsDetailed as rawSyncCalendarsDetailed, updateCalendarObject as rawUpdateCalendarObject, fetchCalendarUserAddresses as rawFetchCalendarUserAddresses, + freeBusyQuery as rawFreeBusyQuery, } from './calendar'; import { collectionQuery as rawCollectionQuery, @@ -237,6 +238,8 @@ export const createDAVClient = async (params: { commonDefaultsWithAccount, ) as SyncCalendarsDetailed; + const freeBusyQuery = defaultParam(rawFreeBusyQuery, commonDefaults); + // addressBook const addressBookQuery = defaultParam(rawAddressBookQuery, commonDefaults); const addressBookMultiGet = defaultParam(rawAddressBookMultiGet, commonDefaults); @@ -260,6 +263,7 @@ export const createDAVClient = async (params: { makeCollection, calendarMultiGet, makeCalendar, + freeBusyQuery, syncCollection, supportedReportSet, isCollectionDirty, @@ -579,6 +583,14 @@ export class DAVClient { })(params[0]); } + async freeBusyQuery(...params: Parameters): Promise { + return defaultParam(rawFreeBusyQuery, { + headers: this.authHeaders, + fetchOptions: this.fetchOptions, + fetch: this.fetchOverride, + })(params[0]); + } + async calendarMultiGet( ...params: Parameters ): Promise { diff --git a/src/collection.ts b/src/collection.ts index a810670e..ac8f1f4a 100644 --- a/src/collection.ts +++ b/src/collection.ts @@ -11,14 +11,20 @@ import { SmartCollectionSyncDetailedResult, } from './types/functionsOverloads'; import { DAVAccount, DAVCollection, DAVObject } from './types/models'; -import { cleanupFalsy, excludeHeaders, getDAVAttribute, urlMatches } from './util/requestHelpers'; +import { + cleanupFalsy, + excludeHeaders, + getDAVAttribute, + urlMatches, + ensureTrailingSlash, +} from './util/requestHelpers'; import { findMissingFieldNames, hasFields, RequireAndNotNullSome } from './util/typeHelpers'; const debug = getLogger('tsdav:collection'); const resolveDAVHref = (href: string, baseUrl: string): string => { try { - return new URL(href, baseUrl).href; + return new URL(href, ensureTrailingSlash(baseUrl)).href; } catch { return href; } @@ -26,7 +32,7 @@ const resolveDAVHref = (href: string, baseUrl: string): string => { const hrefHasExtension = (href: string, extension: string, baseUrl: string): boolean => { try { - return new URL(href, baseUrl).pathname.toLowerCase().endsWith(extension); + return new URL(href, ensureTrailingSlash(baseUrl)).pathname.toLowerCase().endsWith(extension); } catch { return (href.split(/[?#]/, 1)[0] ?? '').toLowerCase().endsWith(extension); } @@ -138,6 +144,13 @@ export const makeCollection = async (params: { body: props ? { mkcol: { + _attributes: getDAVAttribute([ + DAVNamespace.DAV, + DAVNamespace.CALDAV, + DAVNamespace.CARDDAV, + DAVNamespace.CALENDAR_SERVER, + DAVNamespace.CALDAV_APPLE, + ]), set: { prop: props, }, diff --git a/src/index.ts b/src/index.ts index 64f906bd..d7e0b07f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,7 +3,7 @@ import * as addressBook from './addressBook'; import * as calendar from './calendar'; import * as client from './client'; import * as collection from './collection'; -import { DAVAttributeMap, DAVNamespace, DAVNamespaceShort } from './consts'; +import { DAVAttributeMap, DAVNamespace, DAVNamespaceShort, ICALObjects } from './consts'; import * as request from './request'; import * as authHelpers from './util/authHelpers'; import * as requestHelpers from './util/requestHelpers'; @@ -19,11 +19,24 @@ export type { DAVObject, DAVVCard, } from './types/models'; +export type { + SmartCollectionSync, + SmartCollectionSyncDetailed, + SmartCollectionSyncDetailedResult, + SyncCalendars, + SyncCalendarsDetailed, + SyncCalendarsDetailedResult, +} from './types/functionsOverloads'; export { DAVClient } from './client'; export { createDAVClient } from './client'; -export { createAccount } from './account'; +export { + createAccount, + serviceDiscovery, + fetchPrincipalUrl, + fetchHomeUrl, +} from './account'; export { davRequest, propfind, createObject, updateObject, deleteObject } from './request'; export { @@ -67,12 +80,22 @@ export { fetchOauthTokens, refreshAccessToken, } from './util/authHelpers'; -export { urlContains, urlEquals, getDAVAttribute, cleanupFalsy } from './util/requestHelpers'; -export { DAVNamespace, DAVAttributeMap, DAVNamespaceShort } from './consts'; +export { + urlContains, + urlEquals, + urlMatches, + ensureTrailingSlash, + getDAVAttribute, + cleanupFalsy, + excludeHeaders, + mergeHeaders, +} from './util/requestHelpers'; +export { DAVNamespace, DAVAttributeMap, DAVNamespaceShort, ICALObjects } from './consts'; export default { DAVNamespace, DAVNamespaceShort, DAVAttributeMap, + ICALObjects, ...client, ...request, ...collection, diff --git a/src/request.ts b/src/request.ts index 2f0efd5e..9710be33 100644 --- a/src/request.ts +++ b/src/request.ts @@ -47,15 +47,34 @@ export const davRequest = async (params: { } = params; const requestFetch = fetchOverride ?? fetch; const { headers = {}, body, namespace, method, attributes } = init; + let processedBody = body; + if (attributes && body != null && typeof body === 'object' && !Array.isArray(body)) { + processedBody = Object.fromEntries( + Object.entries(body).map(([key, value]) => { + if (value && typeof value === 'object' && !Array.isArray(value)) { + const element = value as Record; + return [ + key, + { + ...element, + _attributes: { + ...attributes, + ...(element._attributes as Record | undefined), + }, + }, + ]; + } + return [key, value]; + }), + ); + } + const xmlBody = convertIncoming && body != null ? convert.js2xml( { _declaration: { _attributes: { version: '1.0', encoding: 'utf-8' } }, - // body is spread AFTER _attributes so a body-level `_attributes` - // set by the caller wins over the implicit `attributes` param. - _attributes: attributes, - ...body, + ...processedBody, }, { compact: true, diff --git a/src/util/requestHelpers.ts b/src/util/requestHelpers.ts index c3591c2c..a3c46df5 100644 --- a/src/util/requestHelpers.ts +++ b/src/util/requestHelpers.ts @@ -7,6 +7,15 @@ const normalizeUrl = (url: string): string => { return trimmed.endsWith('/') ? trimmed.slice(0, -1) : trimmed; }; +/** Ensure a directory or collection URL ends with a trailing slash for relative resolution. */ +export const ensureTrailingSlash = (url: string): string => { + const trimmed = url.trim(); + const suffixIndex = trimmed.search(/[?#]/); + const pathname = suffixIndex === -1 ? trimmed : trimmed.slice(0, suffixIndex); + const suffix = suffixIndex === -1 ? '' : trimmed.slice(suffixIndex); + return `${pathname.endsWith('/') ? pathname : `${pathname}/`}${suffix}`; +}; + /** * Strict URL equality after trimming whitespace and a single trailing slash. * Two URLs are equal if and only if their normalized forms are identical. diff --git a/src/util/typeHelpers.ts b/src/util/typeHelpers.ts index 3b46a69e..2cf8170a 100644 --- a/src/util/typeHelpers.ts +++ b/src/util/typeHelpers.ts @@ -22,17 +22,24 @@ export function hasFields( fields: K[], ): obj is RequireAndNotNullSome; export function hasFields(obj: T | Array, fields: K[]): boolean { + if (!obj) { + return false; + } const inObj: { (obj: T | RequireAndNotNullSome): boolean } = (object) => - fields.every((f) => object[f]); + object != null && fields.every((f) => (object as any)[f]); if (Array.isArray(obj)) { - return obj.every((o) => inObj(o)); + return obj.length > 0 && obj.every((o) => inObj(o)); } return inObj(obj); } -export const findMissingFieldNames = (obj: T, fields: Array): string => - fields.reduce( +export const findMissingFieldNames = (obj: T, fields: Array): string => { + if (!obj || typeof obj !== 'object') { + return fields.map((f) => f.toString()).join(','); + } + return fields.reduce( (prev, curr) => (obj[curr] ? prev : `${prev.length ? `${prev},` : ''}${curr.toString()}`), '', ); +};