### Setup Environment Variables for Testing Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/contributing.md Copy the example environment file to start configuring your local testing environment. Fill in the necessary values. ```bash mv .env.example .env ``` -------------------------------- ### Google CALDAV Quickstart with DAVClient Source: https://github.com/natelindev/tsdav/blob/main/README.md Quickstart example for connecting to Google CALDAV using the DAVClient constructor. This method requires explicit login after client creation. ```typescript import { DAVClient } from 'tsdav'; const client = new DAVClient({ serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/', credentials: { tokenUrl: 'https://accounts.google.com/o/oauth2/token', username: 'YOUR_EMAIL_ADDRESS', refreshToken: 'YOUR_REFRESH_TOKEN_WITH_CALDAV_PERMISSION', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, authMethod: 'Oauth', defaultAccountType: 'caldav', }); (async () => { await client.login(); const calendars = await client.fetchCalendars(); const calendarObjects = await client.fetchCalendarObjects({ calendar: calendars[0], }); })(); ``` -------------------------------- ### Google CALDAV Quickstart with createDAVClient Source: https://github.com/natelindev/tsdav/blob/main/README.md Quickstart example for connecting to Google CALDAV using the createDAVClient function. Requires OAuth credentials and CALDAV permission. ```typescript import { createDAVClient } from 'tsdav'; (async () => { const client = await createDAVClient({ serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/', credentials: { tokenUrl: 'https://accounts.google.com/o/oauth2/token', username: 'YOUR_EMAIL_ADDRESS', refreshToken: 'YOUR_REFRESH_TOKEN_WITH_CALDAV_PERMISSION', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, authMethod: 'Oauth', defaultAccountType: 'caldav', }); const calendars = await client.fetchCalendars(); const calendarObjects = await client.fetchCalendarObjects({ calendar: calendars[0], }); })(); ``` -------------------------------- ### Apple CARDDAV Quickstart with DAVClient Source: https://github.com/natelindev/tsdav/blob/main/README.md Quickstart example for connecting to Apple CARDDAV using the DAVClient constructor. This method requires explicit login after client creation. ```typescript import { DAVClient } from 'tsdav'; const client = new DAVClient({ serverUrl: 'https://contacts.icloud.com', credentials: { username: 'YOUR_APPLE_ID', password: 'YOUR_APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'carddav', }); (async () => { await client.login(); const addressBooks = await client.fetchAddressBooks(); const vcards = await client.fetchVCards({ addressBook: addressBooks[0], }); })(); ``` -------------------------------- ### Apple CARDDAV Quickstart with createDAVClient Source: https://github.com/natelindev/tsdav/blob/main/README.md Quickstart example for connecting to Apple CARDDAV using the createDAVClient function. Requires Apple ID and an app-specific password. ```typescript import { createDAVClient } from 'tsdav'; (async () => { const client = await createDAVClient({ serverUrl: 'https://contacts.icloud.com', credentials: { username: 'YOUR_APPLE_ID', password: 'YOUR_APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'carddav', }); const addressBooks = await client.fetchAddressBooks(); const vcards = await client.fetchVCards({ addressBook: addressBooks[0], }); })(); ``` -------------------------------- ### DAVClient - Google CALDAV Quickstart (v1.1.0+) Source: https://github.com/natelindev/tsdav/blob/main/dist/README.md Example of creating a DAV client for Google CALDAV using the DAVClient class and fetching calendars and calendar objects. ```APIDOC ## DAVClient - Google CALDAV Quickstart (v1.1.0+) ### Description This example demonstrates how to initialize a DAV client for Google Calendar (CalDAV) using OAuth2 authentication with the `DAVClient` class and fetch calendars and their associated objects. ### Method `DAVClient` constructor and `login` method. ### Parameters - `serverUrl` (string): The base URL for the CalDAV service. - `credentials` (object): Authentication credentials. - `tokenUrl` (string): The OAuth2 token endpoint. - `username` (string): The user's email address. - `refreshToken` (string): The OAuth2 refresh token with CalDAV permissions. - `clientId` (string): The OAuth2 client ID. - `clientSecret` (string): The OAuth2 client secret. - `authMethod` (string): The authentication method, set to 'Oauth'. - `defaultAccountType` (string): The default account type, set to 'caldav'. ### Usage ```ts import { DAVClient } from 'tsdav'; const client = new DAVClient({ serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/', credentials: { tokenUrl: 'https://accounts.google.com/o/oauth2/token', username: 'YOUR_EMAIL_ADDRESS', refreshToken: 'YOUR_REFRESH_TOKEN_WITH_CALDAV_PERMISSION', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, authMethod: 'Oauth', defaultAccountType: 'caldav', }); (async () => { await client.login(); const calendars = await client.fetchCalendars(); const calendarObjects = await client.fetchCalendarObjects({ calendar: calendars[0], }); })(); ``` ``` -------------------------------- ### DAVClient - Apple CARDDAV Quickstart (v1.1.0+) Source: https://github.com/natelindev/tsdav/blob/main/dist/README.md Example of creating a DAV client for Apple CARDDAV using the DAVClient class and fetching address books and vCards. ```APIDOC ## DAVClient - Apple CARDDAV Quickstart (v1.1.0+) ### Description This example demonstrates how to initialize a DAV client for Apple CardDAV using Basic authentication with the `DAVClient` class and fetch address books and vCards. ### Method `DAVClient` constructor and `login` method. ### Parameters - `serverUrl` (string): The base URL for the CardDAV service. - `credentials` (object): Authentication credentials. - `username` (string): The user's Apple ID. - `password` (string): The user's app-specific password. - `authMethod` (string): The authentication method, set to 'Basic'. - `defaultAccountType` (string): The default account type, set to 'carddav'. ### Usage ```ts import { DAVClient } from 'tsdav'; const client = new DAVClient({ serverUrl: 'https://contacts.icloud.com', credentials: { username: 'YOUR_APPLE_ID', password: 'YOUR_APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'carddav', }); (async () => { await client.login(); const addressBooks = await client.fetchAddressBooks(); const vcards = await client.fetchVCards({ addressBook: addressBooks[0], }); })(); ``` ``` -------------------------------- ### Start Local Development Server Source: https://github.com/natelindev/tsdav/blob/main/docs/README.md Starts a local development server for live preview. Changes are reflected without server restart. ```bash yarn start ``` -------------------------------- ### createDAVClient - Apple CARDDAV Quickstart Source: https://github.com/natelindev/tsdav/blob/main/dist/README.md Example of creating a DAV client for Apple CARDDAV using the createDAVClient function and fetching address books and vCards. ```APIDOC ## createDAVClient - Apple CARDDAV Quickstart ### Description This example demonstrates how to initialize a DAV client for Apple CardDAV using Basic authentication and fetch address books and vCards. ### Method `createDAVClient` ### Parameters - `serverUrl` (string): The base URL for the CardDAV service. - `credentials` (object): Authentication credentials. - `username` (string): The user's Apple ID. - `password` (string): The user's app-specific password. - `authMethod` (string): The authentication method, set to 'Basic'. - `defaultAccountType` (string): The default account type, set to 'carddav'. ### Usage ```ts import { createDAVClient } from 'tsdav'; (async () => { const client = await createDAVClient({ serverUrl: 'https://contacts.icloud.com', credentials: { username: 'YOUR_APPLE_ID', password: 'YOUR_APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'carddav', }); const addressBooks = await client.fetchAddressBooks(); const vcards = await client.fetchVCards({ addressBook: addressBooks[0], }); })(); ``` ``` -------------------------------- ### createDAVClient - Google CALDAV Quickstart Source: https://github.com/natelindev/tsdav/blob/main/dist/README.md Example of creating a DAV client for Google CALDAV using the createDAVClient function and fetching calendars and calendar objects. ```APIDOC ## createDAVClient - Google CALDAV Quickstart ### Description This example demonstrates how to initialize a DAV client for Google Calendar (CalDAV) using OAuth2 authentication and fetch calendars and their associated objects. ### Method `createDAVClient` ### Parameters - `serverUrl` (string): The base URL for the CalDAV service. - `credentials` (object): Authentication credentials. - `tokenUrl` (string): The OAuth2 token endpoint. - `username` (string): The user's email address. - `refreshToken` (string): The OAuth2 refresh token with CalDAV permissions. - `clientId` (string): The OAuth2 client ID. - `clientSecret` (string): The OAuth2 client secret. - `authMethod` (string): The authentication method, set to 'Oauth'. - `defaultAccountType` (string): The default account type, set to 'caldav'. ### Usage ```ts import { createDAVClient } from 'tsdav'; (async () => { const client = await createDAVClient({ serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/', credentials: { tokenUrl: 'https://accounts.google.com/o/oauth2/token', username: 'YOUR_EMAIL_ADDRESS', refreshToken: 'YOUR_REFRESH_TOKEN_WITH_CALDAV_PERMISSION', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, authMethod: 'Oauth', defaultAccountType: 'caldav', }); const calendars = await client.fetchCalendars(); const calendarObjects = await client.fetchCalendarObjects({ calendar: calendars[0], }); })(); ``` ``` -------------------------------- ### Install tsdav with npm Source: https://github.com/natelindev/tsdav/blob/main/README.md Install the tsdav package using npm. This is the first step to using the library in your project. ```bash npm install tsdav ``` -------------------------------- ### Install tsdav with Bun Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/intro.md Add tsdav to your project when using Bun. Bun automatically uses its built-in fetch. ```bash bun add tsdav ``` -------------------------------- ### Build Project with npm Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/contributing.md Use this command to build the project using npm. Ensure you have npm installed. ```bash npm run build ``` -------------------------------- ### Fetch Home URL Example Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/account/fetchHomeUrl.md Demonstrates how to use the fetchHomeUrl function with account and header details. Ensure the account object contains principalUrl, serverUrl, rootUrl, and accountType. ```typescript const url = await fetchHomeUrl({ account: { principalUrl, serverUrl: 'https://caldav.icloud.com/', rootUrl: 'https://caldav.icloud.com/', accountType: 'caldav', }, headers: { authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj', }, }); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/natelindev/tsdav/blob/main/docs/README.md Installs project dependencies using Yarn. ```bash yarn install ``` -------------------------------- ### Install tsdav with yarn Source: https://github.com/natelindev/tsdav/blob/main/README.md Install the tsdav package using yarn. This is an alternative to npm for package management. ```bash yarn add tsdav ``` -------------------------------- ### WebDAV vs. REST: Get Entity Attributes Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/contributing.md Compares the WebDAV PROPFIND operation for retrieving specific entity attributes with the RESTful GET method. WebDAV uses XML for attribute requests. ```bash PROPFIND /entities/$id with XML body of attributes to fetch ``` ```bash GET /entities/$id ``` -------------------------------- ### Create vCard Example Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/carddav/createVCard.md Use this snippet to create a new vCard. Ensure you provide a valid address book, filename ending in `.vcf`, and the vCard data as a string. Optional headers can be included for authentication or other purposes. ```typescript const result = await createVCard({ addressBook: addressBooks[0], filename: 'test.vcf' vCardString: 'BEGIN:VCARD\nVERSION:3.0\nN:;Test BBB;;;\nFN:Test BBB\nUID:0976cf06-a0e8-44bd-9217-327f6907242c\nPRODID:-//Apple Inc.//iCloud Web Address Book 2109B35//EN\nREV:2021-06-16T01:28:23Z\nEND:VCARD', headers: { authorization: 'Basic x0C9ueWd9Vz8OwS0DEAtkAlj', }, }); ``` -------------------------------- ### WebDAV vs. REST: Get Entity Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/contributing.md Compares the WebDAV GET operation for retrieving an entity with the RESTful GET method. Both retrieve the entity body. ```bash GET /entities/$id ``` ```bash GET /entities/$id ``` -------------------------------- ### WebDAV vs. REST: List Entities Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/contributing.md Compares the WebDAV PROPFIND operation for listing entities with the RESTful GET method. WebDAV uses XML for attribute fetching and returns a multi-status response. ```bash PROPFIND /entities with XML body of attributes to fetch ``` ```bash GET /entities ``` -------------------------------- ### Perform Address Book Query Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/carddav/addressBookQuery.md Example of how to query for address books, specifying the URL, desired properties (like getetag), depth, and authorization headers. ```typescript const addressbooks = await addressBookQuery({ url: 'https://contacts.icloud.com/123456/carddavhome/card/', props: { [`${DAVNamespaceShort.DAV}:getetag`]: {}, }, depth: '1', headers: { authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj', }, }); ``` -------------------------------- ### Sample DAVResponse Object Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/types/DAVResponse.md An example of a DAVResponse object, illustrating the structure for a Multi-Status response. ```json { "raw": { "multistatus": { "response": { "href": "/", "propstat": { "prop": { "currentUserPrincipal": { "href": "/123456/principal/" } }, "status": "HTTP/1.1 200 OK" } } } }, "href": "/", "status": 207, "statusText": "Multi-Status", "ok": true, "props": { "currentUserPrincipal": { "href": "/123456/principal/" } } } ``` -------------------------------- ### DAVClient - Nextcloud Token-based Auth (OIDC) Source: https://github.com/natelindev/tsdav/blob/main/dist/README.md Example of creating a DAV client for Nextcloud using token-based authentication (OIDC) with the DAVClient class. ```APIDOC ## DAVClient - Nextcloud Token-based Auth (OIDC) ### Description This example shows how to configure the `DAVClient` for Nextcloud instances that support token-based authentication (e.g., via the `user_oidc` app) using an access token. ### Method `DAVClient` constructor. ### Parameters - `serverUrl` (string): The base URL for the Nextcloud DAV endpoint. - `credentials` (object): Authentication credentials. - `accessToken` (string): The OIDC access token. - `authMethod` (string): The authentication method, set to 'Bearer'. - `defaultAccountType` (string): The default account type (e.g., 'caldav'). ### Usage ```ts import { DAVClient } from 'tsdav'; const client = new DAVClient({ serverUrl: 'https:///remote.php/dav', credentials: { accessToken: 'YOUR_OIDC_ACCESS_TOKEN', }, authMethod: 'Bearer', defaultAccountType: 'caldav', }); ``` **Note:** Some Nextcloud configurations might still require Basic auth (username + app password) if OIDC is not fully integrated with the DAV subsystem. ``` -------------------------------- ### Cloudflare Workers Example Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/intro.md Integrate tsdav into a Cloudflare Worker. The library automatically uses the native fetch provided by the Workers runtime. Ensure environment variables for credentials are set. ```typescript import { createDAVClient } from 'tsdav'; export default { async fetch(request, env) { const client = await createDAVClient({ serverUrl: 'https://caldav.icloud.com', credentials: { username: env.APPLE_ID, password: env.APPLE_PASSWORD, }, authMethod: 'Basic', defaultAccountType: 'caldav', }); const calendars = await client.fetchCalendars(); return new Response(JSON.stringify(calendars), { headers: { 'Content-Type': 'application/json' }, }); }, }; ``` -------------------------------- ### Detailed Smart Collection Sync Example Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/collection/smartCollectionSync.md Use `smartCollectionSyncDetailed` to get a detailed breakdown of created, updated, and deleted objects during a collection sync. This function is recommended over `smartCollectionSync` for more granular control. ```typescript const { created, updated, deleted } = ( await smartCollectionSyncDetailed({ collection: { url: 'https://caldav.icloud.com/12345676/calendars/c623f6be-a2d4-4c60-932a-043e67025dde/', ctag: 'eWd9Vz8OwS0DE==', syncToken: 'eWdLSfo8439Vz8OwS0DE==', objects: [ { etag: '"63758758580"', id: '0003ffbe-cb71-49f5-bc7b-9fafdd756784', data: 'BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//ZContent.net//Zap Calendar 1.0//EN\nCALSCALE:GREGORIAN\nMETHOD:PUBLISH\nBEGIN:VEVENT\nSUMMARY:Abraham Lincoln\nUID:c7614cff-3549-4a00-9152-d25cc1fe077d\nSEQUENCE:0\nSTATUS:CONFIRMED\nTRANSP:TRANSPARENT\nRRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=2;BYMONTHDAY=12\nDTSTART:20080212\nDTEND:20080213\nDTSTAMP:20150421T141403\nCATEGORIES:U.S. Presidents,Civil War People\nLOCATION:Hodgenville, Kentucky\nGEO:37.5739497;-85.7399606\nDESCRIPTION:Born February 12, 1809\nSixteenth President (1861-1865)\n\n\n\n \nhttp://AmericanHistoryCalendar.com\nURL:http://americanhistorycalendar.com/peoplecalendar/1,328-abraham-lincol\n n\nEND:VEVENT\nEND:VCALENDAR', url: 'https://caldav.icloud.com/123456/calendars/A5639426-B73B-4F90-86AB-D70F7F603E75/test.ics', }, ], objectMultiGet: calendarMultiGet, }, method: 'webdav', account: { accountType: 'caldav', homeUrl: 'https://caldav.icloud.com/123456/calendars/', }, headers: { authorization: 'Basic x0C9ueWd9Vz8OwS0DEAtkAlj', }, }) ).objects; ``` -------------------------------- ### Instantiate DAVClient Class and Login Source: https://context7.com/natelindev/tsdav/llms.txt Instantiate the `DAVClient` class synchronously and then call `await client.login()` to initialize authentication and the default account. Optionally load collections and objects during login. ```typescript import { DAVClient } from 'tsdav'; const client = new DAVClient({ serverUrl: 'https://contacts.icloud.com', credentials: { username: 'user@icloud.com', password: 'APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'carddav', }); // Login: resolves auth headers and creates the default account. // Pass loadCollections/loadObjects to eagerly fetch data during login. await client.login({ loadCollections: true }); // client.account is now populated console.log(client.account?.homeUrl); // => 'https://contacts.icloud.com/123456789/carddavhome/' // All methods are available after login const books = await client.fetchAddressBooks(); ``` -------------------------------- ### Build Static Website Source: https://github.com/natelindev/tsdav/blob/main/docs/README.md Generates static content for deployment. The output is placed in the 'build' directory. ```bash yarn build ``` -------------------------------- ### Making a PROPFIND Request with davRequest Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/davRequest.md Use this snippet to perform a PROPFIND request to a CalDAV server. It demonstrates how to structure the `init` object with the method, namespace, request body, and authorization headers. ```typescript const [result] = await davRequest({ url: 'https://caldav.icloud.com/', init: { method: 'PROPFIND', namespace: 'd', body: { propfind: { _attributes: { 'xmlns:d': 'DAV:', }, prop: { 'd:current-user-principal': {} }, }, }, headers: { authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj', }, }, }); ``` -------------------------------- ### Create a Generic WebDAV Collection (MKCOL) Source: https://context7.com/natelindev/tsdav/llms.txt Creates a generic WebDAV collection (folder). Check the status of the first response for success. ```typescript import { makeCollection } from 'tsdav'; const responses = await client.makeCollection({ url: 'https://dav.example.com/user/files/new-folder/', }); console.log(responses[0].status); // => 201 ``` -------------------------------- ### Deploy Website to GitHub Pages Source: https://github.com/natelindev/tsdav/blob/main/docs/README.md Builds the website and pushes it to the 'gh-pages' branch, suitable for GitHub Pages hosting. Replace '' with your actual username. ```bash GIT_USER= USE_SSH=true yarn deploy ``` -------------------------------- ### Create Google DAVClient Class Instance Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/intro.md This demonstrates creating a DAVClient instance for Google services using the class-based approach. Note that `client.login()` must be called before using other functions. ```typescript const client = new DAVClient({ serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/', credentials: { tokenUrl: 'https://accounts.google.com/o/oauth2/token', username: 'YOUR_EMAIL_ADDRESS', refreshToken: 'YOUR_REFRESH_TOKEN_WITH_CALDAV_PERMISSION', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, authMethod: 'Oauth', defaultAccountType: 'caldav', }); ``` -------------------------------- ### Get Supported Reports Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/collection/supportedReportSet.md Use this to retrieve a list of supported REPORT names for a given collection. Ensure the collection object is properly initialized. ```typescript const reports = await supportedReportSet({ collection, headers: { authorization: 'Basic x0C9ueWd9Vz8OwS0DEAtkAlj', }, }); ``` -------------------------------- ### makeCollection Source: https://context7.com/natelindev/tsdav/llms.txt Creates a generic WebDAV collection (MKCOL). ```APIDOC ## makeCollection ### Description Creates a generic WebDAV collection using the MKCOL method. ### Method (Implicitly part of the SDK) ### Parameters - **options** (object) - Required - Options for creating the collection. - **url** (string) - Required - The URL of the collection to create. ### Returns - **responses** (array) - An array of response objects from the server. ### Request Example ```ts import { makeCollection } from 'tsdav'; const responses = await client.makeCollection({ url: 'https://dav.example.com/user/files/new-folder/', }); console.log(responses[0].status); // => 201 ``` ``` -------------------------------- ### Nextcloud Token-Based Auth with Bearer Source: https://github.com/natelindev/tsdav/blob/main/README.md Example of creating a DAVClient for Nextcloud using token-based authentication (OIDC) with the 'Bearer' auth method. Ensure your Nextcloud instance is configured for OIDC. ```typescript const client = new DAVClient({ serverUrl: 'https:///remote.php/dav', credentials: { accessToken: 'YOUR_OIDC_ACCESS_TOKEN', }, authMethod: 'Bearer', defaultAccountType: 'caldav', }); ``` -------------------------------- ### Create DAV Client (Class-based) Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/intro.md Creates a DAV client instance using the `DAVClient` class constructor. This method is available after v1.1.0 and requires calling `client.login()` before using other functions. ```APIDOC ## Create DAV Client (Class-based) ### Description Creates a DAV client instance using the `DAVClient` class constructor. This method is available after v1.1.0 and requires calling `client.login()` before using other functions. It supports authentication via OAuth for Google and Basic authentication for Apple. ### Method `new DAVClient(options)` ### Parameters #### `options` (object) - **serverUrl** (string) - Required - The base URL for the CalDAV server. - **credentials** (object) - Required - Authentication credentials. - For Google OAuth: - **tokenUrl** (string) - Required - The OAuth token URL. - **username** (string) - Required - The user's email address. - **refreshToken** (string) - Required - The refresh token with CalDAV permission. - **clientId** (string) - Required - The OAuth client ID. - **clientSecret** (string) - Required - The OAuth client secret. - For Apple Basic Auth: - **username** (string) - Required - The Apple ID. - **password** (string) - Required - The app-specific password. - **authMethod** (string) - Required - The authentication method ('Oauth' or 'Basic'). - **defaultAccountType** (string) - Required - The default account type ('caldav'). ### Request Example (Google OAuth) ```ts const client = new DAVClient({ serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/', credentials: { tokenUrl: 'https://accounts.google.com/o/oauth2/token', username: 'YOUR_EMAIL_ADDRESS', refreshToken: 'YOUR_REFRESH_TOKEN_WITH_CALDAV_PERMISSION', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, authMethod: 'Oauth', defaultAccountType: 'caldav', }); ``` ### Request Example (Apple Basic Auth) ```ts const client = new DAVClient({ serverUrl: 'https://caldav.icloud.com', credentials: { username: 'YOUR_APPLE_ID', password: 'YOUR_APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'caldav', }); ``` ``` -------------------------------- ### Detailed Calendar Synchronization Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/caldav/syncCalendars.md Use `syncCalendarsDetailed` to get a breakdown of created, updated, and deleted calendars. The `oldCalendars` argument should include calendar objects when using the older `syncCalendars` function, but not for `syncCalendarsDetailed`. ```typescript const { created, updated, deleted } = await syncCalendarsDetailed({ oldCalendars: [ { displayName: 'personal calendar', syncToken: 'HwoQEgwAAAAAAAAAAAAAAAAYARgAIhsI4pnF4erDm4CsARDdl6K9rqa9/pYBKAA=', ctag: '63758742166', url: 'https://caldav.icloud.com/123456/calendars/A5639426-B73B-4F90-86AB-D70F7F603E75/', objects: [ { etag: '"63758758580"', id: '0003ffbe-cb71-49f5-bc7b-9fafdd756784', data: 'BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//ZContent.net//Zap Calendar 1.0//EN\nCALSCALE:GREGORIAN\nMETHOD:PUBLISH\nBEGIN:VEVENT\nSUMMARY:Abraham Lincoln\nUID:c7614cff-3549-4a00-9152-d25cc1fe077d\nSEQUENCE:0\nSTATUS:CONFIRMED\nTRANSP:TRANSPARENT\nRRULE:FREQ=YEARLY;INTERVAL=1;BYMONTH=2;BYMONTHDAY=12\nDTSTART:20080212\nDTEND:20080213\nDTSTAMP:20150421T141403\nCATEGORIES:U.S. Presidents,Civil War People\nLOCATION:Hodgenville, Kentucky\nGEO:37.5739497;-85.7399606\nDESCRIPTION:Born February 12, 1809\nSixteenth President (1861-1865)\n\n\n\n \nhttp://AmericanHistoryCalendar.com\nURL:http://americanhistorycalendar.com/peoplecalendar/1,328-abraham-lincol\n n\nEND:VEVENT\nEND:VCALENDAR', url: 'https://caldav.icloud.com/123456/calendars/A5639426-B73B-4F90-86AB-D70F7F603E75/test.ics', }, ], }, ], headers: { authorization: 'Basic x0C9ueWd9Vz8OwS0DEAtkAlj', }, }); ``` -------------------------------- ### WebDAV vs. REST: Create Collection Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/contributing.md Compares the WebDAV MKCOL operation for creating collections with its RESTful equivalent. Note that WebDAV requires a predefined ID for collection creation, while REST allows it to be generated. ```bash MKCOL /entities/$predefined_id ``` ```bash POST /entities with JSON body with attributes, response contains new id ``` -------------------------------- ### Create a New Collection with Properties Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/collection/makeCollection.md Use this snippet to create a new collection on the server. Provide the URL, desired properties like `displayname` and custom calendar descriptions, and any necessary authorization headers. ```typescript const response = await makeCollection({ url: 'https://caldav.icloud.com/12345676/calendars/c623f6be-a2d4-4c60-932a-043e67025dde/', props: { displayname: 'my-calendar', [`${DAVNamespaceShort.CALDAV}:calendar-description`]: 'calendar description', }, headers: { authorization: 'Basic x0C9ueWd9Vz8OwS0DEAtkAlj', }, }); ``` -------------------------------- ### Fetch Principal URL using fetchPrincipalUrl Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/account/fetchPrincipalUrl.md Call fetchPrincipalUrl with account details and headers to get the principal collection URL. Requires account information including server and root URLs, and account type. ```typescript const url = await fetchPrincipalUrl({ account: { serverUrl: 'https://caldav.icloud.com/', rootUrl: 'https://caldav.icloud.com/', accountType: 'caldav', }, headers: { authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj', }, }); ``` -------------------------------- ### Initialize CalDAV Client Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/smart calendar sync.md Creates a new CalDAV client instance using server URL, credentials, authentication method, and account type. Ensure you use valid credentials, such as an app-specific password for Apple. ```typescript const client = new DAVClient({ serverUrl: 'https://caldav.icloud.com', credentials: { username: 'YOUR_APPLE_ID', password: 'YOUR_APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'caldav', }); ``` -------------------------------- ### Fetch Full Documentation for RAG Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/llms.md Use this to fetch the entire tsdav documentation as plain text for Retrieval-Augmented Generation (RAG) or context injection into LLMs. It provides comprehensive knowledge of the library. ```typescript const response = await fetch('https://tsdav.vercel.app/llms-full.txt'); const docs = await response.text(); ``` -------------------------------- ### Get OAuth2 Headers with Auto-Refresh Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/helpers/authHelpers.md Combines fetching and refreshing OAuth2 tokens to provide authorization headers. It automatically renews the access token using the refresh token when it expires. This function handles the complete OAuth2 token lifecycle for requests. ```typescript const result = await getOauthHeaders({ authorizationCode: '123', clientId: 'clientId', clientSecret: 'clientSecret', tokenUrl: 'https://oauth.example.com/tokens', redirectUrl: 'https://yourdomain.com/oauth-callback', }); ``` ```typescript { tokens: { access_token: 'kTKGQ2TBEqn03KJMM9AqIA'; refresh_token: 'iHwWwqytfW3AfOjNbM1HLg'; expires_in: 12800; id_token: 'TKfsafGQ2JMM9AqIA'; token_type: 'bearer'; scope: 'openid email'; }, headers: { authorization: `Bearer q-2OCH2g3RctZOJOG9T2Q`, }, } ``` -------------------------------- ### Import External iCal Feed to CalDAV Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/caldav/import-ical-feed.md This example demonstrates fetching an iCal feed, parsing its events, and uploading them to a CalDAV calendar using node-ical and tsdav. Ensure you handle potential duplicates and errors, and consider using `updateCalendarObject` for synchronization. ```typescript import ical from 'node-ical'; import { createCalendarObject, DAVCalendar } from 'tsdav'; async function importExternalFeed( feedUrl: string, targetCalendar: DAVCalendar, authHeader: string, ) { // 1. Fetch and parse the feed const events = await ical.async.fromURL(feedUrl); for (const event of Object.values(events)) { if (event.type !== 'VEVENT') continue; // 2. Convert the event back to an iCal string (if needed) or use the raw source // Note: You should wrap each event in its own VCALENDAR/VEVENT structure for CalDAV const iCalString = `BEGIN:VCALENDAR VERSION:2.0 PRODID:-//tsdav//Import Helper//EN BEGIN:VEVENT UID:${event.uid} SUMMARY:${event.summary} DTSTART:${event.start.toISOString().replace(/[-:]/g, '').split('.')[0]}Z DTEND:${event.end.toISOString().replace(/[-:]/g, '').split('.')[0]}Z DESCRIPTION:${event.description || ''} END:VEVENT END:VCALENDAR`; // 3. Upload to CalDAV try { await createCalendarObject({ calendar: targetCalendar, filename: `${event.uid}.ics`, iCalString, headers: { authorization: authHeader, }, }); console.log(`Imported event: ${event.summary}`); } catch (error) { // In a real application, you'd handle 412 Precondition Failed (If-None-Match) // if the event already exists, or use updateCalendarObject if you want to sync. console.error(`Failed to import event ${event.uid}:`, error); } } } ``` -------------------------------- ### Create DAV Client (Legacy) Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/intro.md Creates a DAV client instance using the `createDAVClient` function. This method is suitable for older versions of the library. It supports authentication via OAuth for Google and Basic authentication for Apple. ```APIDOC ## Create DAV Client (Legacy) ### Description Creates a DAV client instance using the `createDAVClient` function. This method is suitable for older versions of the library. It supports authentication via OAuth for Google and Basic authentication for Apple. ### Method `createDAVClient(options)` ### Parameters #### `options` (object) - **serverUrl** (string) - Required - The base URL for the CalDAV server. - **credentials** (object) - Required - Authentication credentials. - For Google OAuth: - **tokenUrl** (string) - Required - The OAuth token URL. - **username** (string) - Required - The user's email address. - **refreshToken** (string) - Required - The refresh token with CalDAV permission. - **clientId** (string) - Required - The OAuth client ID. - **clientSecret** (string) - Required - The OAuth client secret. - For Google OAuth (Authorization Code): - **authorizationCode** (string) - Required - The authorization code obtained from OAuth callback. - **tokenUrl** (string) - Required - The OAuth token URL. - **clientId** (string) - Required - The OAuth client ID. - **clientSecret** (string) - Required - The OAuth client secret. - For Apple Basic Auth: - **username** (string) - Required - The Apple ID. - **password** (string) - Required - The app-specific password. - **authMethod** (string) - Required - The authentication method ('Oauth' or 'Basic'). - **defaultAccountType** (string) - Required - The default account type ('caldav'). ### Request Example (Google OAuth) ```ts const client = await createDAVClient({ serverUrl: 'https://apidata.googleusercontent.com/caldav/v2/', credentials: { tokenUrl: 'https://accounts.google.com/o/oauth2/token', username: 'YOUR_EMAIL_ADDRESS', refreshToken: 'YOUR_REFRESH_TOKEN_WITH_CALDAV_PERMISSION', clientId: 'YOUR_CLIENT_ID', clientSecret: 'YOUR_CLIENT_SECRET', }, authMethod: 'Oauth', defaultAccountType: 'caldav', }); ``` ### Request Example (Apple Basic Auth) ```ts const client = await createDAVClient({ serverUrl: 'https://caldav.icloud.com', credentials: { username: 'YOUR_APPLE_ID', password: 'YOUR_APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'caldav', }); ``` ``` -------------------------------- ### fetchHomeUrl Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/account/fetchHomeUrl.md Fetches the resource home set URL for a given account. It sends a PROPFIND request to determine the correct home URL based on the account type. ```APIDOC ## `fetchHomeUrl` fetch resource home set url ```ts const url = await fetchHomeUrl({ account: { principalUrl, serverUrl: 'https://caldav.icloud.com/', rootUrl: 'https://caldav.icloud.com/', accountType: 'caldav', }, headers: { authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj', }, }); ``` ### Arguments - `account` **required**, account with `principalUrl` and `accountType` - `headers` request headers - `headersToExclude` array of keys of the headers you want to exclude - `fetchOptions` options to pass to underlying fetch function - `fetch` custom fetch implementation ### Return Value resource home set url ### Behavior send calendar-home-set or addressbook-home-set (based on accountType) PROPFIND request and extract resource home set url from xml response ``` -------------------------------- ### WebDAV vs. REST: Create Entity Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/contributing.md Compares the WebDAV operations for creating entities (with or without a predefined ID) with the RESTful POST method. WebDAV may require a subsequent PROPPATCH for attributes. ```bash PUT /entities/$predefined_id with body, empty response ``` ```bash POST /entities, receive id as part of Content-Location header ``` ```bash POST /entities with JSON body with attributes, response contains new id ``` -------------------------------- ### Create WebDAV Account Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/account/createAccount.md Use this function to construct WebDAV account information needed for requests. It performs service discovery and fetches necessary URLs. ```typescript const account = await createAccount({ account: { serverUrl: 'https://caldav.icloud.com/', accountType: 'caldav', }, headers: { authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj', }, }); ``` -------------------------------- ### Create DAV Client with Apple CalDAV (Basic Auth) Source: https://context7.com/natelindev/tsdav/llms.txt Use `createDAVClient` for Apple CalDAV with Basic authentication. Requires a username and an app-specific password. ```typescript // --- Apple CalDAV (Basic auth with app-specific password) --- const appleClient = await createDAVClient({ serverUrl: 'https://caldav.icloud.com', credentials: { username: 'user@icloud.com', password: 'APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'caldav', }); ``` -------------------------------- ### createAccount Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/account/createAccount.md Constructs WebDAV account information needed for requests. ```APIDOC ## `createAccount` ### Description Constructs WebDAV account information needed for requests. ### Method `createAccount` ### Arguments - `account` (object) - Required. Account with `serverUrl` and `accountType`. - `headers` (object) - Request headers. - `headersToExclude` (array) - Array of keys of the headers you want to exclude. - `fetchOptions` (object) - Options to pass to underlying fetch function. - `fetch` (function) - Custom fetch implementation. - `loadCollections` (boolean) - Defaults to `false`. Whether to load all collections of the account. - `loadObjects` (boolean) - Defaults to `false`. Whether to load all objects of collections as well, must be used with `loadCollections` set to `true`. ### Return Value `DAVAccount` - Created account information. ### Behavior Performs `serviceDiscovery`, `fetchHomeUrl`, and `fetchPrincipalUrl` for account information gathering. Makes fetch collections & fetch objects requests depend on options. ``` -------------------------------- ### Enable Verbose Debug Logs Source: https://context7.com/natelindev/tsdav/llms.txt Enable verbose debug logs by setting the DEBUG environment variable. Available namespaces include request, calendar, addressBook, collection, account, and authHelper. ```bash DEBUG=tsdav:* node my-script.js ``` -------------------------------- ### Create Apple DAV Client Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/intro.md Instantiate a DAV client for Apple services using basic authentication. You will need your Apple ID and an app-specific password. ```typescript const client = await createDAVClient({ serverUrl: 'https://caldav.icloud.com', credentials: { username: 'YOUR_APPLE_ID', password: 'YOUR_APP_SPECIFIC_PASSWORD', }, authMethod: 'Basic', defaultAccountType: 'caldav', }); ``` -------------------------------- ### Create DAV Client with Custom Fetch Override Source: https://context7.com/natelindev/tsdav/llms.txt Use `createDAVClient` with a custom `fetch` override for environments like Electron or to use a CORS proxy. The provided `fetch` function will be used for all network requests. ```typescript // --- Custom fetch override (Electron / CORS proxy) --- const electronClient = await createDAVClient({ serverUrl: 'https://caldav.icloud.com', credentials: { username: 'user@icloud.com', password: 'APP_PASS' }, authMethod: 'Basic', defaultAccountType: 'caldav', fetch: async (url, options) => window.electronAPI.makeRequest(url, options), }); ``` -------------------------------- ### PROPFIND Method Source: https://github.com/natelindev/tsdav/blob/main/docs/docs/webdav/propfind.md The PROPFIND method retrieves properties defined on the resource identified by the Request-URI. It allows clients to request specific properties of a resource. ```APIDOC ## PROPFIND The [PROPFIND](https://datatracker.ietf.org/doc/html/rfc4918#section-9.1) method retrieves properties defined on the resource identified by the Request-URI. ```ts const [result] = await propfind({ url: 'https://caldav.icloud.com/', props: [{ name: 'current-user-principal', namespace: DAVNamespace.DAV }], headers: { authorization: 'Basic x0C9uFWd9Vz8OwS0DEAtkAlj', }, }); ``` ### Arguments - `url` **required**, request url - `props` **required**, [ElementCompact](../types/ElementCompact.md) props to find - `depth` [DAVDepth](../types/DAVDepth.md) - `headers` request headers - `headersToExclude` array of keys of the headers you want to exclude - `fetchOptions` options to pass to underlying fetch function ### Return Value array of [DAVResponse](../types/DAVResponse.md) ### Behavior send a prop find request, parse the response xml to an array of [DAVResponse](../types/DAVResponse.md). ```