Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(sdk): add calendar client backed by calendar_service (#6754)

gbirman4f162d2fd1cd
diff --git a/packages/sdk/generated/calendar/client.gen.ts b/packages/sdk/generated/calendar/client.gen.ts
new file mode 100644
index 0000000000..47828b746c
--- /dev/null
+++ b/packages/sdk/generated/calendar/client.gen.ts
@@ -0,0 +1,16 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+import { type Client, type ClientOptions, type Config, createClient, createConfig } from './client';
+import type { ClientOptions as ClientOptions2 } from './types.gen';
+
+/**
+ * The `createClientConfig()` function will be called on client initialization
+ * and the returned object will become the client's initial configuration.
+ *
+ * You may want to initialize your client this way instead of calling
+ * `setConfig()`. This is useful for example if you're using Next.js
+ * to ensure your client always has the correct values.
+ */
+export type CreateClientConfig<T extends ClientOptions = ClientOptions2> = (override?: Config<ClientOptions & T>) => Config<Required<ClientOptions> & T>;
+
+export const client: Client = createClient(createConfig<ClientOptions2>());
diff --git a/packages/sdk/generated/calendar/client/client.gen.ts b/packages/sdk/generated/calendar/client/client.gen.ts
new file mode 100644
index 0000000000..fc3f037f16
--- /dev/null
+++ b/packages/sdk/generated/calendar/client/client.gen.ts
@@ -0,0 +1,277 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+import { createSseClient } from '../core/serverSentEvents.gen';
+import type { HttpMethod } from '../core/types.gen';
+import { getValidRequestBody } from '../core/utils.gen';
+import type { Client, Config, RequestOptions, ResolvedRequestOptions } from './types.gen';
+import {
+ buildUrl,
+ createConfig,
+ createInterceptors,
+ getParseAs,
+ mergeConfigs,
+ mergeHeaders,
+ setAuthParams,
+} from './utils.gen';
+
+type ReqInit = Omit<RequestInit, 'body' | 'headers'> & {
+ body?: any;
+ headers: ReturnType<typeof mergeHeaders>;
+};
+
+export const createClient = (config: Config = {}): Client => {
+ let _config = mergeConfigs(createConfig(), config);
+
+ const getConfig = (): Config => ({ ..._config });
+
+ const setConfig = (config: Config): Config => {
+ _config = mergeConfigs(_config, config);
+ return getConfig();
+ };
+
+ const interceptors = createInterceptors<Request, Response, unknown, ResolvedRequestOptions>();
+
+ const beforeRequest = async <
+ TData = unknown,
+ TResponseStyle extends 'data' | 'fields' = 'fields',
+ ThrowOnError extends boolean = boolean,
+ Url extends string = string,
+ >(
+ options: RequestOptions<TData, TResponseStyle, ThrowOnError, Url>,
+ ) => {
+ const opts = {
+ ..._config,
+ ...options,
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
+ headers: mergeHeaders(_config.headers, options.headers),
+ serializedBody: undefined as string | undefined,
+ };
+
+ if (opts.security) {
+ await setAuthParams(opts);
+ }
+
+ if (opts.requestValidator) {
+ await opts.requestValidator(opts);
+ }
+
+ if (opts.body !== undefined && opts.bodySerializer) {
+ opts.serializedBody = opts.bodySerializer(opts.body) as string | undefined;
+ }
+
+ // remove Content-Type header if body is empty to avoid sending invalid requests
+ if (opts.body === undefined || opts.serializedBody === '') {
+ opts.headers.delete('Content-Type');
+ }
+
+ const resolvedOpts = opts as typeof opts &
+ ResolvedRequestOptions<TResponseStyle, ThrowOnError, Url>;
+ const url = buildUrl(resolvedOpts);
+
+ return { opts: resolvedOpts, url };
+ };
+
+ const request: Client['request'] = async (options) => {
+ const throwOnError = options.throwOnError ?? _config.throwOnError;
+ const responseStyle = options.responseStyle ?? _config.responseStyle;
+
+ let request: Request | undefined;
+ let response: Response | undefined;
+
+ try {
+ const { opts, url } = await beforeRequest(options);
+ const requestInit: ReqInit = {
+ redirect: 'follow',
+ ...opts,
+ body: getValidRequestBody(opts),
+ };
+
+ request = new Request(url, requestInit);
+
+ for (const fn of interceptors.request.fns) {
+ if (fn) {
+ request = await fn(request, opts);
+ }
+ }
+
+ // fetch must be assigned here, otherwise it would throw the error:
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
+ const _fetch = opts.fetch!;
+
+ response = await _fetch(request);
+
+ for (const fn of interceptors.response.fns) {
+ if (fn) {
+ response = await fn(response, request, opts);
+ }
+ }
+
+ const result = {
+ request,
+ response,
+ };
+
+ if (response.ok) {
+ const parseAs =
+ (opts.parseAs === 'auto'
+ ? getParseAs(response.headers.get('Content-Type'))
+ : opts.parseAs) ?? 'json';
+
+ if (response.status === 204 || response.headers.get('Content-Length') === '0') {
+ let emptyData: any;
+ switch (parseAs) {
+ case 'arrayBuffer':
+ case 'blob':
+ case 'text':
+ emptyData = await response[parseAs]();
+ break;
+ case 'formData':
+ emptyData = new FormData();
+ break;
+ case 'stream':
+ emptyData = response.body;
+ break;
+ case 'json':
+ default:
+ emptyData = {};
+ break;
+ }
+ return opts.responseStyle === 'data'
+ ? emptyData
+ : {
+ data: emptyData,
+ ...result,
+ };
+ }
+
+ let data: any;
+ switch (parseAs) {
+ case 'arrayBuffer':
+ case 'blob':
+ case 'formData':
+ case 'text':
+ data = await response[parseAs]();
+ break;
+ case 'json': {
+ // Some servers return 200 with no Content-Length and empty body.
+ // response.json() would throw; read as text and parse if non-empty.
+ const text = await response.text();
+ data = text ? JSON.parse(text) : {};
+ break;
+ }
+ case 'stream':
+ return opts.responseStyle === 'data'
+ ? response.body
+ : {
+ data: response.body,
+ ...result,
+ };
+ }
+
+ if (parseAs === 'json') {
+ if (opts.responseValidator) {
+ await opts.responseValidator(data);
+ }
+
+ if (opts.responseTransformer) {
+ data = await opts.responseTransformer(data);
+ }
+ }
+
+ return opts.responseStyle === 'data'
+ ? data
+ : {
+ data,
+ ...result,
+ };
+ }
+
+ const textError = await response.text();
+ let jsonError: unknown;
+
+ try {
+ jsonError = JSON.parse(textError);
+ } catch {
+ // noop
+ }
+
+ throw jsonError ?? textError;
+ } catch (error) {
+ let finalError = error;
+
+ for (const fn of interceptors.error.fns) {
+ if (fn) {
+ finalError = await fn(finalError, response, request, options as ResolvedRequestOptions);
+ }
+ }
+
+ finalError = finalError || {};
+
+ if (throwOnError) {
+ throw finalError;
+ }
+
+ // TODO: we probably want to return error and improve types
+ return responseStyle === 'data'
+ ? undefined
+ : {
+ error: finalError,
+ request,
+ response,
+ };
+ }
+ };
+
+ const makeMethodFn = (method: Uppercase<HttpMethod>) => (options: RequestOptions) =>
+ request({ ...options, method });
+
+ const makeSseFn = (method: Uppercase<HttpMethod>) => async (options: RequestOptions) => {
+ const { opts, url } = await beforeRequest(options);
+ return createSseClient({
+ ...opts,
+ body: opts.body as BodyInit | null | undefined,
+ method,
+ onRequest: async (url, init) => {
+ let request = new Request(url, init);
+ for (const fn of interceptors.request.fns) {
+ if (fn) {
+ request = await fn(request, opts);
+ }
+ }
+ return request;
+ },
+ serializedBody: getValidRequestBody(opts) as BodyInit | null | undefined,
+ url,
+ });
+ };
+
+ const _buildUrl: Client['buildUrl'] = (options) => buildUrl({ ..._config, ...options });
+
+ return {
+ buildUrl: _buildUrl,
+ connect: makeMethodFn('CONNECT'),
+ delete: makeMethodFn('DELETE'),
+ get: makeMethodFn('GET'),
+ getConfig,
+ head: makeMethodFn('HEAD'),
+ interceptors,
+ options: makeMethodFn('OPTIONS'),
+ patch: makeMethodFn('PATCH'),
+ post: makeMethodFn('POST'),
+ put: makeMethodFn('PUT'),
+ request,
+ setConfig,
+ sse: {
+ connect: makeSseFn('CONNECT'),
+ delete: makeSseFn('DELETE'),
+ get: makeSseFn('GET'),
+ head: makeSseFn('HEAD'),
+ options: makeSseFn('OPTIONS'),
+ patch: makeSseFn('PATCH'),
+ post: makeSseFn('POST'),
+ put: makeSseFn('PUT'),
+ trace: makeSseFn('TRACE'),
+ },
+ trace: makeMethodFn('TRACE'),
+ } as Client;
+};
diff --git a/packages/sdk/generated/calendar/client/index.ts b/packages/sdk/generated/calendar/client/index.ts
new file mode 100644
index 0000000000..8c693310d9
--- /dev/null
+++ b/packages/sdk/generated/calendar/client/index.ts
@@ -0,0 +1,27 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+export type { Auth } from '../core/auth.gen';
+export type { QuerySerializerOptions } from '../core/bodySerializer.gen';
+export {
+ formDataBodySerializer,
+ jsonBodySerializer,
+ urlSearchParamsBodySerializer,
+} from '../core/bodySerializer.gen';
+export { buildClientParams } from '../core/params.gen';
+export { serializeQueryKeyValue } from '../core/queryKeySerializer.gen';
+export type { ServerSentEventsResult } from '../core/serverSentEvents.gen';
+export type { ClientMeta } from '../core/types.gen';
+export { createClient } from './client.gen';
+export type {
+ Client,
+ ClientOptions,
+ Config,
+ CreateClientConfig,
+ Options,
+ RequestOptions,
+ RequestResult,
+ ResolvedRequestOptions,
+ ResponseStyle,
+ TDataShape,
+} from './types.gen';
+export { createConfig, mergeHeaders } from './utils.gen';
diff --git a/packages/sdk/generated/calendar/client/types.gen.ts b/packages/sdk/generated/calendar/client/types.gen.ts
new file mode 100644
index 0000000000..193646cddf
--- /dev/null
+++ b/packages/sdk/generated/calendar/client/types.gen.ts
@@ -0,0 +1,218 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+import type { Auth } from '../core/auth.gen';
+import type {
+ ServerSentEventsOptions,
+ ServerSentEventsResult,
+} from '../core/serverSentEvents.gen';
+import type { Client as CoreClient, Config as CoreConfig } from '../core/types.gen';
+import type { Middleware } from './utils.gen';
+
+export type ResponseStyle = 'data' | 'fields';
+
+export interface Config<T extends ClientOptions = ClientOptions>
+ extends Omit<RequestInit, 'body' | 'headers' | 'method'>, CoreConfig {
+ /**
+ * Base URL for all requests made by this client.
+ */
+ baseUrl?: T['baseUrl'];
+ /**
+ * Fetch API implementation. You can use this option to provide a custom
+ * fetch instance.
+ *
+ * @default globalThis.fetch
+ */
+ fetch?: typeof fetch;
+ /**
+ * Please don't use the Fetch client for Next.js applications. The `next`
+ * options won't have any effect.
+ *
+ * Install {@link https://www.npmjs.com/package/@hey-api/client-next `@hey-api/client-next`} instead.
+ */
+ next?: never;
+ /**
+ * Return the response data parsed in a specified format. By default, `auto`
+ * will infer the appropriate method from the `Content-Type` response header.
+ * You can override this behavior with any of the {@link Body} methods.
+ * Select `stream` if you don't want to parse response data at all.
+ *
+ * @default 'auto'
+ */
+ parseAs?: 'arrayBuffer' | 'auto' | 'blob' | 'formData' | 'json' | 'stream' | 'text';
+ /**
+ * Should we return only data or multiple fields (data, error, response, etc.)?
+ *
+ * @default 'fields'
+ */
+ responseStyle?: ResponseStyle;
+ /**
+ * Throw an error instead of returning it in the response?
+ *
+ * @default false
+ */
+ throwOnError?: T['throwOnError'];
+}
+
+export interface RequestOptions<
+ TData = unknown,
+ TResponseStyle extends ResponseStyle = 'fields',
+ ThrowOnError extends boolean = boolean,
+ Url extends string = string,
+>
+ extends
+ Config<{
+ responseStyle: TResponseStyle;
+ throwOnError: ThrowOnError;
+ }>,
+ Pick<
+ ServerSentEventsOptions<TData>,
+ | 'onRequest'
+ | 'onSseError'
+ | 'onSseEvent'
+ | 'sseDefaultRetryDelay'
+ | 'sseMaxRetryAttempts'
+ | 'sseMaxRetryDelay'
+ > {
+ /**
+ * Any body that you want to add to your request.
+ *
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#body}
+ */
+ body?: unknown;
+ path?: Record<string, unknown>;
+ query?: Record<string, unknown>;
+ /**
+ * Security mechanism(s) to use for the request.
+ */
+ security?: ReadonlyArray<Auth>;
+ url: Url;
+}
+
+export interface ResolvedRequestOptions<
+ TResponseStyle extends ResponseStyle = 'fields',
+ ThrowOnError extends boolean = boolean,
+ Url extends string = string,
+> extends RequestOptions<unknown, TResponseStyle, ThrowOnError, Url> {
+ headers: Headers;
+ serializedBody?: string;
+}
+
+export type RequestResult<
+ TData = unknown,
+ TError = unknown,
+ ThrowOnError extends boolean = boolean,
+ TResponseStyle extends ResponseStyle = 'fields',
+> = ThrowOnError extends true
+ ? Promise<
+ TResponseStyle extends 'data'
+ ? TData extends Record<string, unknown>
+ ? TData[keyof TData]
+ : TData
+ : {
+ data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
+ request: Request;
+ response: Response;
+ }
+ >
+ : Promise<
+ TResponseStyle extends 'data'
+ ? (TData extends Record<string, unknown> ? TData[keyof TData] : TData) | undefined
+ : (
+ | {
+ data: TData extends Record<string, unknown> ? TData[keyof TData] : TData;
+ error: undefined;
+ }
+ | {
+ data: undefined;
+ error: TError extends Record<string, unknown> ? TError[keyof TError] : TError;
+ }
+ ) & {
+ /** request may be undefined, because error may be from building the request object itself */
+ request?: Request;
+ /** response may be undefined, because error may be from building the request object itself or from a network error */
+ response?: Response;
+ }
+ >;
+
+export interface ClientOptions {
+ baseUrl?: string;
+ responseStyle?: ResponseStyle;
+ throwOnError?: boolean;
+}
+
+type MethodFn = <
+ TData = unknown,
+ TError = unknown,
+ ThrowOnError extends boolean = false,
+ TResponseStyle extends ResponseStyle = 'fields',
+>(
+ options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'>,
+) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
+
+type SseFn = <
+ TData = unknown,
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ _TError = unknown,
+ ThrowOnError extends boolean = false,
+ TResponseStyle extends ResponseStyle = 'fields',
+>(
+ options: Omit<RequestOptions<never, TResponseStyle, ThrowOnError>, 'method'>,
+) => Promise<ServerSentEventsResult<TData>>;
+
+type RequestFn = <
+ TData = unknown,
+ TError = unknown,
+ ThrowOnError extends boolean = false,
+ TResponseStyle extends ResponseStyle = 'fields',
+>(
+ options: Omit<RequestOptions<TData, TResponseStyle, ThrowOnError>, 'method'> &
+ Pick<Required<RequestOptions<TData, TResponseStyle, ThrowOnError>>, 'method'>,
+) => RequestResult<TData, TError, ThrowOnError, TResponseStyle>;
+
+type BuildUrlFn = <
+ TData extends {
+ body?: unknown;
+ path?: Record<string, unknown>;
+ query?: Record<string, unknown>;
+ url: string;
+ },
+>(
+ options: TData & Options<TData>,
+) => string;
+
+export type Client = CoreClient<RequestFn, Config, MethodFn, BuildUrlFn, SseFn> & {
+ interceptors: Middleware<Request, Response, unknown, ResolvedRequestOptions>;
+};
+
+/**
+ * The `createClientConfig()` function will be called on client initialization
+ * and the returned object will become the client's initial configuration.
+ *
+ * You may want to initialize your client this way instead of calling
+ * `setConfig()`. This is useful for example if you're using Next.js
+ * to ensure your client always has the correct values.
+ */
+export type CreateClientConfig<T extends ClientOptions = ClientOptions> = (
+ override?: Config<ClientOptions & T>,
+) => Config<Required<ClientOptions> & T>;
+
+export interface TDataShape {
+ body?: unknown;
+ headers?: unknown;
+ path?: unknown;
+ query?: unknown;
+ url: string;
+}
+
+type OmitKeys<T, K> = Pick<T, Exclude<keyof T, K>>;
+
+export type Options<
+ TData extends TDataShape = TDataShape,
+ ThrowOnError extends boolean = boolean,
+ TResponse = unknown,
+ TResponseStyle extends ResponseStyle = 'fields',
+> = OmitKeys<
+ RequestOptions<TResponse, TResponseStyle, ThrowOnError>,
+ 'body' | 'path' | 'query' | 'url'
+> &
+ ([TData] extends [never] ? unknown : Omit<TData, 'url'>);
diff --git a/packages/sdk/generated/calendar/client/utils.gen.ts b/packages/sdk/generated/calendar/client/utils.gen.ts
new file mode 100644
index 0000000000..d4a728438a
--- /dev/null
+++ b/packages/sdk/generated/calendar/client/utils.gen.ts
@@ -0,0 +1,316 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+import { getAuthToken } from '../core/auth.gen';
+import type { QuerySerializerOptions } from '../core/bodySerializer.gen';
+import { jsonBodySerializer } from '../core/bodySerializer.gen';
+import {
+ serializeArrayParam,
+ serializeObjectParam,
+ serializePrimitiveParam,
+} from '../core/pathSerializer.gen';
+import { getUrl } from '../core/utils.gen';
+import type { Client, ClientOptions, Config, RequestOptions } from './types.gen';
+
+export const createQuerySerializer = <T = unknown>({
+ parameters = {},
+ ...args
+}: QuerySerializerOptions = {}): ((queryParams: T) => string) => {
+ const querySerializer = (queryParams: T): string => {
+ const search: string[] = [];
+ if (queryParams && typeof queryParams === 'object') {
+ for (const name in queryParams) {
+ const value = queryParams[name];
+
+ if (value === undefined || value === null) {
+ continue;
+ }
+
+ const options = parameters[name] || args;
+
+ if (Array.isArray(value)) {
+ const serializedArray = serializeArrayParam({
+ allowReserved: options.allowReserved,
+ explode: true,
+ name,
+ style: 'form',
+ value,
+ ...options.array,
+ });
+ if (serializedArray) search.push(serializedArray);
+ } else if (typeof value === 'object') {
+ const serializedObject = serializeObjectParam({
+ allowReserved: options.allowReserved,
+ explode: true,
+ name,
+ style: 'deepObject',
+ value: value as Record<string, unknown>,
+ ...options.object,
+ });
+ if (serializedObject) search.push(serializedObject);
+ } else {
+ const serializedPrimitive = serializePrimitiveParam({
+ allowReserved: options.allowReserved,
+ name,
+ value: value as string,
+ });
+ if (serializedPrimitive) search.push(serializedPrimitive);
+ }
+ }
+ }
+ return search.join('&');
+ };
+ return querySerializer;
+};
+
+/**
+ * Infers parseAs value from provided Content-Type header.
+ */
+export const getParseAs = (contentType: string | null): Exclude<Config['parseAs'], 'auto'> => {
+ if (!contentType) {
+ // If no Content-Type header is provided, the best we can do is return the raw response body,
+ // which is effectively the same as the 'stream' option.
+ return 'stream';
+ }
+
+ const cleanContent = contentType.split(';')[0]?.trim();
+
+ if (!cleanContent) {
+ return;
+ }
+
+ if (cleanContent.startsWith('application/json') || cleanContent.endsWith('+json')) {
+ return 'json';
+ }
+
+ if (cleanContent === 'multipart/form-data') {
+ return 'formData';
+ }
+
+ if (
+ ['application/', 'audio/', 'image/', 'video/'].some((type) => cleanContent.startsWith(type))
+ ) {
+ return 'blob';
+ }
+
+ if (cleanContent.startsWith('text/')) {
+ return 'text';
+ }
+
+ return;
+};
+
+const checkForExistence = (
+ options: Pick<RequestOptions, 'auth' | 'query'> & {
+ headers: Headers;
+ },
+ name?: string,
+): boolean => {
+ if (!name) {
+ return false;
+ }
+ if (
+ options.headers.has(name) ||
+ options.query?.[name] ||
+ options.headers.get('Cookie')?.includes(`${name}=`)
+ ) {
+ return true;
+ }
+ return false;
+};
+
+export async function setAuthParams(
+ options: Pick<RequestOptions, 'auth' | 'query' | 'security'> & {
+ headers: Headers;
+ },
+): Promise<void> {
+ for (const auth of options.security ?? []) {
+ if (checkForExistence(options, auth.name)) {
+ continue;
+ }
+
+ const token = await getAuthToken(auth, options.auth);
+
+ if (!token) {
+ continue;
+ }
+
+ const name = auth.name ?? 'Authorization';
+
+ switch (auth.in) {
+ case 'query':
+ if (!options.query) {
+ options.query = {};
+ }
+ options.query[name] = token;
+ break;
+ case 'cookie':
+ options.headers.append('Cookie', `${name}=${token}`);
+ break;
+ case 'header':
+ default:
+ options.headers.set(name, token);
+ break;
+ }
+ }
+}
+
+export const buildUrl: Client['buildUrl'] = (options) =>
+ getUrl({
+ baseUrl: options.baseUrl as string,
+ path: options.path,
+ query: options.query,
+ querySerializer:
+ typeof options.querySerializer === 'function'
+ ? options.querySerializer
+ : createQuerySerializer(options.querySerializer),
+ url: options.url,
+ });
+
+export const mergeConfigs = (a: Config, b: Config): Config => {
+ const config = { ...a, ...b };
+ if (config.baseUrl?.endsWith('/')) {
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
+ }
+ config.headers = mergeHeaders(a.headers, b.headers);
+ return config;
+};
+
+const headersEntries = (headers: Headers): Array<[string, string]> => {
+ const entries: Array<[string, string]> = [];
+ headers.forEach((value, key) => {
+ entries.push([key, value]);
+ });
+ return entries;
+};
+
+export const mergeHeaders = (
+ ...headers: Array<Required<Config>['headers'] | undefined>
+): Headers => {
+ const mergedHeaders = new Headers();
+ for (const header of headers) {
+ if (!header) {
+ continue;
+ }
+
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
+
+ for (const [key, value] of iterator) {
+ if (value === null) {
+ mergedHeaders.delete(key);
+ } else if (Array.isArray(value)) {
+ for (const v of value) {
+ mergedHeaders.append(key, v as string);
+ }
+ } else if (value !== undefined) {
+ // assume object headers are meant to be JSON stringified, i.e., their
+ // content value in OpenAPI specification is 'application/json'
+ mergedHeaders.set(
+ key,
+ typeof value === 'object' ? JSON.stringify(value) : (value as string),
+ );
+ }
+ }
+ }
+ return mergedHeaders;
+};
+
+type ErrInterceptor<Err, Res, Req, Options> = (
+ error: Err,
+ /** response may be undefined due to a network error where no response object is produced */
+ response: Res | undefined,
+ /** request may be undefined, because error may be from building the request object itself */
+ request: Req | undefined,
+ options: Options,
+) => Err | Promise<Err>;
+
+type ReqInterceptor<Req, Options> = (request: Req, options: Options) => Req | Promise<Req>;
+
+type ResInterceptor<Res, Req, Options> = (
+ response: Res,
+ request: Req,
+ options: Options,
+) => Res | Promise<Res>;
+
+class Interceptors<Interceptor> {
+ fns: Array<Interceptor | null> = [];
+
+ clear(): void {
+ this.fns = [];
+ }
+
+ eject(id: number | Interceptor): void {
+ const index = this.getInterceptorIndex(id);
+ if (this.fns[index]) {
+ this.fns[index] = null;
+ }
+ }
+
+ exists(id: number | Interceptor): boolean {
+ const index = this.getInterceptorIndex(id);
+ return Boolean(this.fns[index]);
+ }
+
+ getInterceptorIndex(id: number | Interceptor): number {
+ if (typeof id === 'number') {
+ return this.fns[id] ? id : -1;
+ }
+ return this.fns.indexOf(id);
+ }
+
+ update(id: number | Interceptor, fn: Interceptor): number | Interceptor | false {
+ const index = this.getInterceptorIndex(id);
+ if (this.fns[index]) {
+ this.fns[index] = fn;
+ return id;
+ }
+ return false;
+ }
+
+ use(fn: Interceptor): number {
+ this.fns.push(fn);
+ return this.fns.length - 1;
+ }
+}
+
+export interface Middleware<Req, Res, Err, Options> {
+ error: Interceptors<ErrInterceptor<Err, Res, Req, Options>>;
+ request: Interceptors<ReqInterceptor<Req, Options>>;
+ response: Interceptors<ResInterceptor<Res, Req, Options>>;
+}
+
+export const createInterceptors = <Req, Res, Err, Options>(): Middleware<
+ Req,
+ Res,
+ Err,
+ Options
+> => ({
+ error: new Interceptors<ErrInterceptor<Err, Res, Req, Options>>(),
+ request: new Interceptors<ReqInterceptor<Req, Options>>(),
+ response: new Interceptors<ResInterceptor<Res, Req, Options>>(),
+});
+
+const defaultQuerySerializer = createQuerySerializer({
+ allowReserved: false,
+ array: {
+ explode: true,
+ style: 'form',
+ },
+ object: {
+ explode: true,
+ style: 'deepObject',
+ },
+});
+
+const defaultHeaders = {
+ 'Content-Type': 'application/json',
+};
+
+export const createConfig = <T extends ClientOptions = ClientOptions>(
+ override: Config<Omit<ClientOptions, keyof T> & T> = {},
+): Config<Omit<ClientOptions, keyof T> & T> => ({
+ ...jsonBodySerializer,
+ headers: defaultHeaders,
+ parseAs: 'auto',
+ querySerializer: defaultQuerySerializer,
+ ...override,
+});
diff --git a/packages/sdk/generated/calendar/core/auth.gen.ts b/packages/sdk/generated/calendar/core/auth.gen.ts
new file mode 100644
index 0000000000..c663664487
--- /dev/null
+++ b/packages/sdk/generated/calendar/core/auth.gen.ts
@@ -0,0 +1,48 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+export type AuthToken = string | undefined;
+
+export interface Auth {
+ /**
+ * Which part of the request do we use to send the auth?
+ *
+ * @default 'header'
+ */
+ in?: 'header' | 'query' | 'cookie';
+ /**
+ * A unique identifier for the security scheme.
+ *
+ * Defined only when there are multiple security schemes whose `Auth`
+ * shape would otherwise be identical.
+ */
+ key?: string;
+ /**
+ * Header or query parameter name.
+ *
+ * @default 'Authorization'
+ */
+ name?: string;
+ scheme?: 'basic' | 'bearer';
+ type: 'apiKey' | 'http';
+}
+
+export const getAuthToken = async (
+ auth: Auth,
+ callback: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken,
+): Promise<string | undefined> => {
+ const token = typeof callback === 'function' ? await callback(auth) : callback;
+
+ if (!token) {
+ return;
+ }
+
+ if (auth.scheme === 'bearer') {
+ return `Bearer ${token}`;
+ }
+
+ if (auth.scheme === 'basic') {
+ return `Basic ${btoa(token)}`;
+ }
+
+ return token;
+};
diff --git a/packages/sdk/generated/calendar/core/bodySerializer.gen.ts b/packages/sdk/generated/calendar/core/bodySerializer.gen.ts
new file mode 100644
index 0000000000..67daca60f8
--- /dev/null
+++ b/packages/sdk/generated/calendar/core/bodySerializer.gen.ts
@@ -0,0 +1,82 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+import type { ArrayStyle, ObjectStyle, SerializerOptions } from './pathSerializer.gen';
+
+export type QuerySerializer = (query: Record<string, unknown>) => string;
+
+export type BodySerializer = (body: unknown) => unknown;
+
+type QuerySerializerOptionsObject = {
+ allowReserved?: boolean;
+ array?: Partial<SerializerOptions<ArrayStyle>>;
+ object?: Partial<SerializerOptions<ObjectStyle>>;
+};
+
+export type QuerySerializerOptions = QuerySerializerOptionsObject & {
+ /**
+ * Per-parameter serialization overrides. When provided, these settings
+ * override the global array/object settings for specific parameter names.
+ */
+ parameters?: Record<string, QuerySerializerOptionsObject>;
+};
+
+const serializeFormDataPair = (data: FormData, key: string, value: unknown): void => {
+ if (typeof value === 'string' || value instanceof Blob) {
+ data.append(key, value);
+ } else if (value instanceof Date) {
+ data.append(key, value.toISOString());
+ } else {
+ data.append(key, JSON.stringify(value));
+ }
+};
+
+const serializeUrlSearchParamsPair = (data: URLSearchParams, key: string, value: unknown): void => {
+ if (typeof value === 'string') {
+ data.append(key, value);
+ } else {
+ data.append(key, JSON.stringify(value));
+ }
+};
+
+export const formDataBodySerializer = {
+ bodySerializer: (body: unknown): FormData => {
+ const data = new FormData();
+
+ Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {
+ if (value === undefined || value === null) {
+ return;
+ }
+ if (Array.isArray(value)) {
+ value.forEach((v) => serializeFormDataPair(data, key, v));
+ } else {
+ serializeFormDataPair(data, key, value);
+ }
+ });
+
+ return data;
+ },
+};
+
+export const jsonBodySerializer = {
+ bodySerializer: (body: unknown): string =>
+ JSON.stringify(body, (_key, value) => (typeof value === 'bigint' ? value.toString() : value)),
+};
+
+export const urlSearchParamsBodySerializer = {
+ bodySerializer: (body: unknown): string => {
+ const data = new URLSearchParams();
+
+ Object.entries(body as Record<string, unknown>).forEach(([key, value]) => {
+ if (value === undefined || value === null) {
+ return;
+ }
+ if (Array.isArray(value)) {
+ value.forEach((v) => serializeUrlSearchParamsPair(data, key, v));
+ } else {
+ serializeUrlSearchParamsPair(data, key, value);
+ }
+ });
+
+ return data.toString();
+ },
+};
diff --git a/packages/sdk/generated/calendar/core/params.gen.ts b/packages/sdk/generated/calendar/core/params.gen.ts
new file mode 100644
index 0000000000..5e8908f205
--- /dev/null
+++ b/packages/sdk/generated/calendar/core/params.gen.ts
@@ -0,0 +1,178 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+type Slot = 'body' | 'headers' | 'path' | 'query';
+
+export type Field =
+ | {
+ in: Exclude<Slot, 'body'>;
+ /**
+ * Field name. This is the name we want the user to see and use.
+ */
+ key: string;
+ /**
+ * Field mapped name. This is the name we want to use in the request.
+ * If omitted, we use the same value as `key`.
+ */
+ map?: string;
+ }
+ | {
+ in: Extract<Slot, 'body'>;
+ /**
+ * Key isn't required for bodies.
+ */
+ key?: string;
+ map?: string;
+ }
+ | {
+ /**
+ * Field name. This is the name we want the user to see and use.
+ */
+ key: string;
+ /**
+ * Field mapped name. This is the name we want to use in the request.
+ * If `in` is omitted, `map` aliases `key` to the transport layer.
+ */
+ map: Slot;
+ };
+
+export interface Fields {
+ allowExtra?: Partial<Record<Slot, boolean>>;
+ args?: ReadonlyArray<Field>;
+}
+
+export type FieldsConfig = ReadonlyArray<Field | Fields>;
+
+const extraPrefixesMap: Record<string, Slot> = {
+ $body_: 'body',
+ $headers_: 'headers',
+ $path_: 'path',
+ $query_: 'query',
+};
+const extraPrefixes = Object.entries(extraPrefixesMap);
+
+type KeyMap = Map<
+ string,
+ | {
+ in: Slot;
+ map?: string;
+ }
+ | {
+ in?: never;
+ map: Slot;
+ }
+>;
+
+function buildKeyMap(fields: FieldsConfig, map?: KeyMap): KeyMap {
+ if (!map) {
+ map = new Map();
+ }
+
+ for (const config of fields) {
+ if ('in' in config) {
+ if (config.key) {
+ map.set(config.key, {
+ in: config.in,
+ map: config.map,
+ });
+ }
+ } else if ('key' in config) {
+ map.set(config.key, {
+ map: config.map,
+ });
+ } else if (config.args) {
+ buildKeyMap(config.args, map);
+ }
+ }
+
+ return map;
+}
+
+interface Params {
+ body?: unknown;
+ headers: Record<string, unknown>;
+ path: Record<string, unknown>;
+ query: Record<string, unknown>;
+}
+
+function stripEmptySlots(params: Params): void {
+ for (const [slot, value] of Object.entries(params)) {
+ if (slot === 'body') continue;
+ if (value && typeof value === 'object' && !Array.isArray(value) && !Object.keys(value).length) {
+ delete params[slot as Slot];
+ }
+ }
+}
+
+export function buildClientParams(args: ReadonlyArray<unknown>, fields: FieldsConfig): Params {
+ const params: Params = {
+ headers: Object.create(null),
+ path: Object.create(null),
+ query: Object.create(null),
+ };
+
+ const map = buildKeyMap(fields);
+
+ function writeSlot(slot: Slot, key: string, value: unknown): void {
+ let record = params[slot] as Record<string, unknown> | undefined;
+ if (record === undefined) {
+ record = Object.create(null) as Record<string, unknown>;
+ params[slot] = record;
+ }
+ record[key] = value;
+ }
+
+ let config: FieldsConfig[number] | undefined;
+
+ for (const [index, arg] of args.entries()) {
+ if (fields[index]) {
+ config = fields[index];
+ }
+
+ if (!config) {
+ continue;
+ }
+
+ if ('in' in config) {
+ if (config.key) {
+ const field = map.get(config.key)!;
+ const name = field.map || config.key;
+ if (field.in) {
+ writeSlot(field.in, name, arg);
+ }
+ } else {
+ params.body = arg;
+ }
+ } else {
+ for (const [key, value] of Object.entries(arg ?? {})) {
+ const field = map.get(key);
+
+ if (field) {
+ if (field.in) {
+ const name = field.map || key;
+ writeSlot(field.in, name, value);
+ } else {
+ params[field.map] = value;
+ }
+ } else {
+ const extra = extraPrefixes.find(([prefix]) => key.startsWith(prefix));
+
+ if (extra) {
+ const [prefix, slot] = extra;
+ writeSlot(slot, key.slice(prefix.length), value);
+ } else if ('allowExtra' in config && config.allowExtra) {
+ for (const [slot, allowed] of Object.entries(config.allowExtra)) {
+ if (allowed) {
+ writeSlot(slot as Slot, key, value);
+ break;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ stripEmptySlots(params);
+
+ return params;
+}
diff --git a/packages/sdk/generated/calendar/core/pathSerializer.gen.ts b/packages/sdk/generated/calendar/core/pathSerializer.gen.ts
new file mode 100644
index 0000000000..fab1ed4b98
--- /dev/null
+++ b/packages/sdk/generated/calendar/core/pathSerializer.gen.ts
@@ -0,0 +1,171 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+interface SerializeOptions<T> extends SerializePrimitiveOptions, SerializerOptions<T> {}
+
+interface SerializePrimitiveOptions {
+ allowReserved?: boolean;
+ name: string;
+}
+
+export interface SerializerOptions<T> {
+ /**
+ * @default true
+ */
+ explode: boolean;
+ style: T;
+}
+
+export type ArrayStyle = 'form' | 'spaceDelimited' | 'pipeDelimited';
+export type ArraySeparatorStyle = ArrayStyle | MatrixStyle;
+type MatrixStyle = 'label' | 'matrix' | 'simple';
+export type ObjectStyle = 'form' | 'deepObject';
+type ObjectSeparatorStyle = ObjectStyle | MatrixStyle;
+
+interface SerializePrimitiveParam extends SerializePrimitiveOptions {
+ value: string;
+}
+
+export const separatorArrayExplode = (style: ArraySeparatorStyle): '.' | ';' | ',' | '&' => {
+ switch (style) {
+ case 'label':
+ return '.';
+ case 'matrix':
+ return ';';
+ case 'simple':
+ return ',';
+ default:
+ return '&';
+ }
+};
+
+export const separatorArrayNoExplode = (style: ArraySeparatorStyle): ',' | '|' | '%20' => {
+ switch (style) {
+ case 'form':
+ return ',';
+ case 'pipeDelimited':
+ return '|';
+ case 'spaceDelimited':
+ return '%20';
+ default:
+ return ',';
+ }
+};
+
+export const separatorObjectExplode = (style: ObjectSeparatorStyle): '.' | ';' | ',' | '&' => {
+ switch (style) {
+ case 'label':
+ return '.';
+ case 'matrix':
+ return ';';
+ case 'simple':
+ return ',';
+ default:
+ return '&';
+ }
+};
+
+export const serializeArrayParam = ({
+ allowReserved,
+ explode,
+ name,
+ style,
+ value,
+}: SerializeOptions<ArraySeparatorStyle> & {
+ value: unknown[];
+}): string => {
+ if (!explode) {
+ const joinedValues = (
+ allowReserved ? value : value.map((v) => encodeURIComponent(v as string))
+ ).join(separatorArrayNoExplode(style));
+ switch (style) {
+ case 'label':
+ return `.${joinedValues}`;
+ case 'matrix':
+ return `;${name}=${joinedValues}`;
+ case 'simple':
+ return joinedValues;
+ default:
+ return `${name}=${joinedValues}`;
+ }
+ }
+
+ const separator = separatorArrayExplode(style);
+ const joinedValues = value
+ .map((v) => {
+ if (style === 'label' || style === 'simple') {
+ return allowReserved ? v : encodeURIComponent(v as string);
+ }
+
+ return serializePrimitiveParam({
+ allowReserved,
+ name,
+ value: v as string,
+ });
+ })
+ .join(separator);
+ return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
+};
+
+export const serializePrimitiveParam = ({
+ allowReserved,
+ name,
+ value,
+}: SerializePrimitiveParam): string => {
+ if (value === undefined || value === null) {
+ return '';
+ }
+
+ if (typeof value === 'object') {
+ throw new Error(
+ 'Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.',
+ );
+ }
+
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
+};
+
+export const serializeObjectParam = ({
+ allowReserved,
+ explode,
+ name,
+ style,
+ value,
+ valueOnly,
+}: SerializeOptions<ObjectSeparatorStyle> & {
+ value: Record<string, unknown> | Date;
+ valueOnly?: boolean;
+}): string => {
+ if (value instanceof Date) {
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
+ }
+
+ if (style !== 'deepObject' && !explode) {
+ let values: string[] = [];
+ Object.entries(value).forEach(([key, v]) => {
+ values = [...values, key, allowReserved ? (v as string) : encodeURIComponent(v as string)];
+ });
+ const joinedValues = values.join(',');
+ switch (style) {
+ case 'form':
+ return `${name}=${joinedValues}`;
+ case 'label':
+ return `.${joinedValues}`;
+ case 'matrix':
+ return `;${name}=${joinedValues}`;
+ default:
+ return joinedValues;
+ }
+ }
+
+ const separator = separatorObjectExplode(style);
+ const joinedValues = Object.entries(value)
+ .map(([key, v]) =>
+ serializePrimitiveParam({
+ allowReserved,
+ name: style === 'deepObject' ? `${name}[${key}]` : key,
+ value: v as string,
+ }),
+ )
+ .join(separator);
+ return style === 'label' || style === 'matrix' ? separator + joinedValues : joinedValues;
+};
diff --git a/packages/sdk/generated/calendar/core/queryKeySerializer.gen.ts b/packages/sdk/generated/calendar/core/queryKeySerializer.gen.ts
new file mode 100644
index 0000000000..773b0650b1
--- /dev/null
+++ b/packages/sdk/generated/calendar/core/queryKeySerializer.gen.ts
@@ -0,0 +1,117 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+/**
+ * JSON-friendly union that mirrors what Pinia Colada can hash.
+ */
+export type JsonValue =
+ | null
+ | string
+ | number
+ | boolean
+ | JsonValue[]
+ | { [key: string]: JsonValue };
+
+/**
+ * Replacer that converts non-JSON values (bigint, Date, etc.) to safe substitutes.
+ */
+export const queryKeyJsonReplacer = (_key: string, value: unknown): unknown | undefined => {
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
+ return undefined;
+ }
+ if (typeof value === 'bigint') {
+ return value.toString();
+ }
+ if (value instanceof Date) {
+ return value.toISOString();
+ }
+ return value;
+};
+
+/**
+ * Safely stringifies a value and parses it back into a JsonValue.
+ */
+export const stringifyToJsonValue = (input: unknown): JsonValue | undefined => {
+ try {
+ const json = JSON.stringify(input, queryKeyJsonReplacer);
+ if (json === undefined) {
+ return undefined;
+ }
+ return JSON.parse(json) as JsonValue;
+ } catch {
+ return undefined;
+ }
+};
+
+/**
+ * Detects plain objects (including objects with a null prototype).
+ */
+const isPlainObject = (value: unknown): value is Record<string, unknown> => {
+ if (value === null || typeof value !== 'object') {
+ return false;
+ }
+ const prototype = Object.getPrototypeOf(value as object);
+ return prototype === Object.prototype || prototype === null;
+};
+
+/**
+ * Turns URLSearchParams into a sorted JSON object for deterministic keys.
+ */
+const serializeSearchParams = (params: URLSearchParams): JsonValue => {
+ const entries = Array.from(params.entries()).sort(([a], [b]) => a.localeCompare(b));
+ const result: Record<string, JsonValue> = {};
+
+ for (const [key, value] of entries) {
+ const existing = result[key];
+ if (existing === undefined) {
+ result[key] = value;
+ continue;
+ }
+
+ if (Array.isArray(existing)) {
+ (existing as string[]).push(value);
+ } else {
+ result[key] = [existing, value];
+ }
+ }
+
+ return result;
+};
+
+/**
+ * Normalizes any accepted value into a JSON-friendly shape for query keys.
+ */
+export const serializeQueryKeyValue = (value: unknown): JsonValue | undefined => {
+ if (value === null) {
+ return null;
+ }
+
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
+ return value;
+ }
+
+ if (value === undefined || typeof value === 'function' || typeof value === 'symbol') {
+ return undefined;
+ }
+
+ if (typeof value === 'bigint') {
+ return value.toString();
+ }
+
+ if (value instanceof Date) {
+ return value.toISOString();
+ }
+
+ if (Array.isArray(value)) {
+ return stringifyToJsonValue(value);
+ }
+
+ if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
+ return serializeSearchParams(value);
+ }
+
+ if (isPlainObject(value)) {
+ return stringifyToJsonValue(value);
+ }
+
+ return undefined;
+};
diff --git a/packages/sdk/generated/calendar/core/serverSentEvents.gen.ts b/packages/sdk/generated/calendar/core/serverSentEvents.gen.ts
new file mode 100644
index 0000000000..ddf3c4d13a
--- /dev/null
+++ b/packages/sdk/generated/calendar/core/serverSentEvents.gen.ts
@@ -0,0 +1,242 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+import type { Config } from './types.gen';
+
+export type ServerSentEventsOptions<TData = unknown> = Omit<RequestInit, 'method'> &
+ Pick<Config, 'method' | 'responseTransformer' | 'responseValidator'> & {
+ /**
+ * Fetch API implementation. You can use this option to provide a custom
+ * fetch instance.
+ *
+ * @default globalThis.fetch
+ */
+ fetch?: typeof fetch;
+ /**
+ * Implementing clients can call request interceptors inside this hook.
+ */
+ onRequest?: (url: string, init: RequestInit) => Promise<Request>;
+ /**
+ * Callback invoked when a network or parsing error occurs during streaming.
+ *
+ * This option applies only if the endpoint returns a stream of events.
+ *
+ * @param error The error that occurred.
+ */
+ onSseError?: (error: unknown) => void;
+ /**
+ * Callback invoked when an event is streamed from the server.
+ *
+ * This option applies only if the endpoint returns a stream of events.
+ *
+ * @param event Event streamed from the server.
+ * @returns Nothing (void).
+ */
+ onSseEvent?: (event: StreamEvent<TData>) => void;
+ serializedBody?: RequestInit['body'];
+ /**
+ * Default retry delay in milliseconds.
+ *
+ * This option applies only if the endpoint returns a stream of events.
+ *
+ * @default 3000
+ */
+ sseDefaultRetryDelay?: number;
+ /**
+ * Maximum number of retry attempts before giving up.
+ */
+ sseMaxRetryAttempts?: number;
+ /**
+ * Maximum retry delay in milliseconds.
+ *
+ * Applies only when exponential backoff is used.
+ *
+ * This option applies only if the endpoint returns a stream of events.
+ *
+ * @default 30000
+ */
+ sseMaxRetryDelay?: number;
+ /**
+ * Optional sleep function for retry backoff.
+ *
+ * Defaults to using `setTimeout`.
+ */
+ sseSleepFn?: (ms: number) => Promise<void>;
+ url: string;
+ };
+
+export interface StreamEvent<TData = unknown> {
+ data: TData;
+ event?: string;
+ id?: string;
+ retry?: number;
+}
+
+export type ServerSentEventsResult<TData = unknown, TReturn = void, TNext = unknown> = {
+ stream: AsyncGenerator<
+ TData extends Record<string, unknown> ? TData[keyof TData] : TData,
+ TReturn,
+ TNext
+ >;
+};
+
+export function createSseClient<TData = unknown>({
+ onRequest,
+ onSseError,
+ onSseEvent,
+ responseTransformer,
+ responseValidator,
+ sseDefaultRetryDelay,
+ sseMaxRetryAttempts,
+ sseMaxRetryDelay,
+ sseSleepFn,
+ url,
+ ...options
+}: ServerSentEventsOptions): ServerSentEventsResult<TData> {
+ let lastEventId: string | undefined;
+
+ const sleep = sseSleepFn ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms)));
+
+ const createStream = async function* () {
+ let retryDelay: number = sseDefaultRetryDelay ?? 3000;
+ let attempt = 0;
+ const signal = options.signal ?? new AbortController().signal;
+
+ while (true) {
+ if (signal.aborted) break;
+
+ attempt++;
+
+ const headers =
+ options.headers instanceof Headers
+ ? options.headers
+ : new Headers(options.headers as Record<string, string> | undefined);
+
+ if (lastEventId !== undefined) {
+ headers.set('Last-Event-ID', lastEventId);
+ }
+
+ try {
+ const requestInit: RequestInit = {
+ redirect: 'follow',
+ ...options,
+ body: options.serializedBody,
+ headers,
+ signal,
+ };
+ let request = new Request(url, requestInit);
+ if (onRequest) {
+ request = await onRequest(url, requestInit);
+ }
+ // fetch must be assigned here, otherwise it would throw the error:
+ // TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
+ const _fetch = options.fetch ?? globalThis.fetch;
+ const response = await _fetch(request);
+
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
+
+ if (!response.body) throw new Error('No body in SSE response');
+
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
+
+ let buffer = '';
+
+ const abortHandler = () => {
+ try {
+ reader.cancel();
+ } catch {
+ // noop
+ }
+ };
+
+ signal.addEventListener('abort', abortHandler);
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += value;
+ buffer = buffer.replace(/\r\n?/g, '\n'); // normalize line endings
+
+ const chunks = buffer.split('\n\n');
+ buffer = chunks.pop() ?? '';
+
+ for (const chunk of chunks) {
+ const lines = chunk.split('\n');
+ const dataLines: Array<string> = [];
+ let eventName: string | undefined;
+
+ for (const line of lines) {
+ if (line.startsWith('data:')) {
+ dataLines.push(line.replace(/^data:\s*/, ''));
+ } else if (line.startsWith('event:')) {
+ eventName = line.replace(/^event:\s*/, '');
+ } else if (line.startsWith('id:')) {
+ lastEventId = line.replace(/^id:\s*/, '');
+ } else if (line.startsWith('retry:')) {
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ''), 10);
+ if (!Number.isNaN(parsed)) {
+ retryDelay = parsed;
+ }
+ }
+ }
+
+ let data: unknown;
+ let parsedJson = false;
+
+ if (dataLines.length) {
+ const rawData = dataLines.join('\n');
+ try {
+ data = JSON.parse(rawData);
+ parsedJson = true;
+ } catch {
+ data = rawData;
+ }
+ }
+
+ if (parsedJson) {
+ if (responseValidator) {
+ await responseValidator(data);
+ }
+
+ if (responseTransformer) {
+ data = await responseTransformer(data);
+ }
+ }
+
+ onSseEvent?.({
+ data,
+ event: eventName,
+ id: lastEventId,
+ retry: retryDelay,
+ });
+
+ if (dataLines.length) {
+ yield data as any;
+ }
+ }
+ }
+ } finally {
+ signal.removeEventListener('abort', abortHandler);
+ reader.releaseLock();
+ }
+
+ break; // exit loop on normal completion
+ } catch (error) {
+ // connection failed or aborted; retry after delay
+ onSseError?.(error);
+
+ if (sseMaxRetryAttempts !== undefined && attempt >= sseMaxRetryAttempts) {
+ break; // stop after firing error
+ }
+
+ // exponential backoff: double retry each attempt, cap at 30s
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 30000);
+ await sleep(backoff);
+ }
+ }
+ };
+
+ const stream = createStream();
+
+ return { stream };
+}
diff --git a/packages/sdk/generated/calendar/core/types.gen.ts b/packages/sdk/generated/calendar/core/types.gen.ts
new file mode 100644
index 0000000000..c657c8599b
--- /dev/null
+++ b/packages/sdk/generated/calendar/core/types.gen.ts
@@ -0,0 +1,110 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+import type { Auth, AuthToken } from './auth.gen';
+import type { BodySerializer, QuerySerializer, QuerySerializerOptions } from './bodySerializer.gen';
+
+export type HttpMethod =
+ | 'connect'
+ | 'delete'
+ | 'get'
+ | 'head'
+ | 'options'
+ | 'patch'
+ | 'post'
+ | 'put'
+ | 'trace';
+
+export type Client<
+ RequestFn = never,
+ Config = unknown,
+ MethodFn = never,
+ BuildUrlFn = never,
+ SseFn = never,
+> = {
+ /**
+ * Returns the final request URL.
+ */
+ buildUrl: BuildUrlFn;
+ getConfig: () => Config;
+ request: RequestFn;
+ setConfig: (config: Config) => Config;
+} & {
+ [K in HttpMethod]: MethodFn;
+} & ([SseFn] extends [never] ? { sse?: never } : { sse: { [K in HttpMethod]: SseFn } });
+
+export interface Config {
+ /**
+ * Auth token or a function returning auth token. The resolved value will be
+ * added to the request payload as defined by its `security` array.
+ */
+ auth?: ((auth: Auth) => Promise<AuthToken> | AuthToken) | AuthToken;
+ /**
+ * A function for serializing request body parameter. By default,
+ * {@link JSON.stringify()} will be used.
+ */
+ bodySerializer?: BodySerializer | null;
+ /**
+ * An object containing any HTTP headers that you want to pre-populate your
+ * `Headers` object with.
+ *
+ * {@link https://developer.mozilla.org/docs/Web/API/Headers/Headers#init See more}
+ */
+ headers?:
+ | RequestInit['headers']
+ | Record<
+ string,
+ string | number | boolean | (string | number | boolean)[] | null | undefined | unknown
+ >;
+ /**
+ * The request method.
+ *
+ * {@link https://developer.mozilla.org/docs/Web/API/fetch#method See more}
+ */
+ method?: Uppercase<HttpMethod>;
+ /**
+ * A function for serializing request query parameters. By default, arrays
+ * will be exploded in form style, objects will be exploded in deepObject
+ * style, and reserved characters are percent-encoded.
+ *
+ * This method will have no effect if the native `paramsSerializer()` Axios
+ * API function is used.
+ *
+ * {@link https://swagger.io/docs/specification/serialization/#query View examples}
+ */
+ querySerializer?: QuerySerializer | QuerySerializerOptions;
+ /**
+ * A function validating request data. This is useful if you want to ensure
+ * the request conforms to the desired shape, so it can be safely sent to
+ * the server.
+ */
+ requestValidator?: (data: unknown) => Promise<unknown>;
+ /**
+ * A function transforming response data before it's returned. This is useful
+ * for post-processing data, e.g., converting ISO strings into Date objects.
+ */
+ responseTransformer?: (data: unknown) => Promise<unknown>;
+ /**
+ * A function validating response data. This is useful if you want to ensure
+ * the response conforms to the desired shape, so it can be safely passed to
+ * the transformers and returned to the user.
+ */
+ responseValidator?: (data: unknown) => Promise<unknown>;
+}
+
+/**
+ * Arbitrary metadata passed through the `meta` request option.
+ */
+// eslint-disable-next-line @typescript-eslint/no-empty-object-type
+export interface ClientMeta {}
+
+type IsExactlyNeverOrNeverUndefined<T> = [T] extends [never]
+ ? true
+ : [T] extends [never | undefined]
+ ? [undefined] extends [T]
+ ? false
+ : true
+ : false;
+
+export type OmitNever<T extends Record<string, unknown>> = {
+ [K in keyof T as IsExactlyNeverOrNeverUndefined<T[K]> extends true ? never : K]: T[K];
+};
diff --git a/packages/sdk/generated/calendar/core/utils.gen.ts b/packages/sdk/generated/calendar/core/utils.gen.ts
new file mode 100644
index 0000000000..af56e0711e
--- /dev/null
+++ b/packages/sdk/generated/calendar/core/utils.gen.ts
@@ -0,0 +1,140 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+import type { BodySerializer, QuerySerializer } from './bodySerializer.gen';
+import {
+ type ArraySeparatorStyle,
+ serializeArrayParam,
+ serializeObjectParam,
+ serializePrimitiveParam,
+} from './pathSerializer.gen';
+
+export interface PathSerializer {
+ path: Record<string, unknown>;
+ url: string;
+}
+
+export const PATH_PARAM_RE: RegExp = /\{[^{}]+\}/g;
+
+export const defaultPathSerializer = ({ path, url: _url }: PathSerializer): string => {
+ let url = _url;
+ const matches = _url.match(PATH_PARAM_RE);
+ if (matches) {
+ for (const match of matches) {
+ let explode = false;
+ let name = match.substring(1, match.length - 1);
+ let style: ArraySeparatorStyle = 'simple';
+
+ if (name.endsWith('*')) {
+ explode = true;
+ name = name.substring(0, name.length - 1);
+ }
+
+ if (name.startsWith('.')) {
+ name = name.substring(1);
+ style = 'label';
+ } else if (name.startsWith(';')) {
+ name = name.substring(1);
+ style = 'matrix';
+ }
+
+ const value = path[name];
+
+ if (value === undefined || value === null) {
+ continue;
+ }
+
+ if (Array.isArray(value)) {
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
+ continue;
+ }
+
+ if (typeof value === 'object') {
+ url = url.replace(
+ match,
+ serializeObjectParam({
+ explode,
+ name,
+ style,
+ value: value as Record<string, unknown>,
+ valueOnly: true,
+ }),
+ );
+ continue;
+ }
+
+ if (style === 'matrix') {
+ url = url.replace(
+ match,
+ `;${serializePrimitiveParam({
+ name,
+ value: value as string,
+ })}`,
+ );
+ continue;
+ }
+
+ const replaceValue = encodeURIComponent(
+ style === 'label' ? `.${value as string}` : (value as string),
+ );
+ url = url.replace(match, replaceValue);
+ }
+ }
+ return url;
+};
+
+export const getUrl = ({
+ baseUrl,
+ path,
+ query,
+ querySerializer,
+ url: _url,
+}: {
+ baseUrl?: string;
+ path?: Record<string, unknown>;
+ query?: Record<string, unknown>;
+ querySerializer: QuerySerializer;
+ url: string;
+}): string => {
+ const pathUrl = _url.startsWith('/') ? _url : `/${_url}`;
+ let url = (baseUrl ?? '') + pathUrl;
+ if (path) {
+ url = defaultPathSerializer({ path, url });
+ }
+ let search = query ? querySerializer(query) : '';
+ if (search.startsWith('?')) {
+ search = search.substring(1);
+ }
+ if (search) {
+ url += `?${search}`;
+ }
+ return url;
+};
+
+export function getValidRequestBody(options: {
+ body?: unknown;
+ bodySerializer?: BodySerializer | null;
+ serializedBody?: unknown;
+}): unknown {
+ const hasBody = options.body !== undefined;
+ const isSerializedBody = hasBody && options.bodySerializer;
+
+ if (isSerializedBody) {
+ if ('serializedBody' in options) {
+ const hasSerializedBody =
+ options.serializedBody !== undefined && options.serializedBody !== '';
+
+ return hasSerializedBody ? options.serializedBody : null;
+ }
+
+ // not all clients implement a serializedBody property (i.e., client-axios)
+ return options.body !== '' ? options.body : null;
+ }
+
+ // plain/text body
+ if (hasBody) {
+ return options.body;
+ }
+
+ // no body was provided
+ return undefined;
+}
diff --git a/packages/sdk/generated/calendar/index.ts b/packages/sdk/generated/calendar/index.ts
new file mode 100644
index 0000000000..99fc9c7e6c
--- /dev/null
+++ b/packages/sdk/generated/calendar/index.ts
@@ -0,0 +1,4 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+export { type Options, Sdk } from './sdk.gen';
+export type { AttendeeResponseStatus, CalendarAttendee, CalendarAttendeeInputBody, CalendarDeletionScopeParam, CalendarEvent, CalendarEventSourceContent, CalendarMutationApiError, CalendarMutationErrorCode, CalendarRsvpScopeParam, CalendarUpdateScopeParam, ClientOptions, ConferenceChange, ConferenceProvider, CreateCalendarEventData, CreateCalendarEventError, CreateCalendarEventErrors, CreateCalendarEventRequest, CreateCalendarEventResponse, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventError, DeleteCalendarEventErrors, DeleteCalendarEventResponse, DeleteCalendarEventResponses, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, ListCalendarsData, ListCalendarsError, ListCalendarsErrors, ListCalendarsResponse, ListCalendarsResponse2, ListCalendarsResponses, OutOfOfficeAutoDeclineMode, OutOfOfficeProperties, RefreshCalendarEvent, RsvpCalendarEventData, RsvpCalendarEventError, RsvpCalendarEventErrors, RsvpCalendarEventRequest, RsvpCalendarEventResponse, RsvpCalendarEventResponses, UpdateCalendarEventData, UpdateCalendarEventError, UpdateCalendarEventErrors, UpdateCalendarEventRequest, UpdateCalendarEventResponse, UpdateCalendarEventResponses, VisibleCalendar } from './types.gen';
diff --git a/packages/sdk/generated/calendar/sdk.gen.ts b/packages/sdk/generated/calendar/sdk.gen.ts
new file mode 100644
index 0000000000..2f2ea091dd
--- /dev/null
+++ b/packages/sdk/generated/calendar/sdk.gen.ts
@@ -0,0 +1,122 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
+import { client } from './client.gen';
+import type { CreateCalendarEventData, CreateCalendarEventErrors, CreateCalendarEventResponses, DeleteCalendarEventData, DeleteCalendarEventErrors, DeleteCalendarEventResponses, HealthHandlerData, HealthHandlerResponses, ListCalendarsData, ListCalendarsErrors, ListCalendarsResponses, RsvpCalendarEventData, RsvpCalendarEventErrors, RsvpCalendarEventResponses, UpdateCalendarEventData, UpdateCalendarEventErrors, UpdateCalendarEventResponses } from './types.gen';
+
+export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
+ /**
+ * You can provide a client instance returned by `createClient()` instead of
+ * individual options. This might be also useful if you want to implement a
+ * custom client.
+ */
+ client?: Client;
+ /**
+ * You can pass arbitrary values through the `meta` object. This can be
+ * used to access values that aren't defined as part of the SDK function.
+ */
+ meta?: keyof ClientMeta extends never ? Record<string, unknown> : ClientMeta;
+};
+
+class HeyApiClient {
+ protected client: Client;
+
+ constructor(args?: {
+ client?: Client;
+ }) {
+ this.client = args?.client ?? client;
+ }
+}
+
+class HeyApiRegistry<T> {
+ private readonly defaultKey = 'default';
+
+ private readonly instances: Map<string, T> = new Map();
+
+ get(key?: string): T {
+ const instance = this.instances.get(key ?? this.defaultKey);
+ if (!instance) {
+ throw new Error(`No SDK client found. Create one with "new Sdk()" to fix this error.`);
+ }
+ return instance;
+ }
+
+ set(value: T, key?: string): void {
+ this.instances.set(key ?? this.defaultKey, value);
+ }
+}
+
+export class Sdk extends HeyApiClient {
+ public static readonly __registry: HeyApiRegistry<Sdk> = new HeyApiRegistry<Sdk>();
+
+ constructor(args?: {
+ client?: Client;
+ key?: string;
+ }) {
+ super(args);
+ Sdk.__registry.set(this, args?.key);
+ }
+
+ /**
+ * List the requester's visible calendars for pickers and filters.
+ */
+ public listCalendars<ThrowOnError extends boolean = false>(options?: Options<ListCalendarsData, ThrowOnError>): RequestResult<ListCalendarsResponses, ListCalendarsErrors, ThrowOnError> {
+ return (options?.client ?? this.client).get<ListCalendarsResponses, ListCalendarsErrors, ThrowOnError>({ url: '/calendars', ...options });
+ }
+
+ /**
+ * Create a calendar event and return its synced entity.
+ */
+ public createCalendarEvent<ThrowOnError extends boolean = false>(options: Options<CreateCalendarEventData, ThrowOnError>): RequestResult<CreateCalendarEventResponses, CreateCalendarEventErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<CreateCalendarEventResponses, CreateCalendarEventErrors, ThrowOnError>({
+ url: '/events',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Delete a calendar event at its provider.
+ */
+ public deleteCalendarEvent<ThrowOnError extends boolean = false>(options: Options<DeleteCalendarEventData, ThrowOnError>): RequestResult<DeleteCalendarEventResponses, DeleteCalendarEventErrors, ThrowOnError> {
+ return (options.client ?? this.client).delete<DeleteCalendarEventResponses, DeleteCalendarEventErrors, ThrowOnError>({ url: '/events/{event_id}', ...options });
+ }
+
+ /**
+ * Update fields of a calendar event and return its synced entity.
+ */
+ public updateCalendarEvent<ThrowOnError extends boolean = false>(options: Options<UpdateCalendarEventData, ThrowOnError>): RequestResult<UpdateCalendarEventResponses, UpdateCalendarEventErrors, ThrowOnError> {
+ return (options.client ?? this.client).patch<UpdateCalendarEventResponses, UpdateCalendarEventErrors, ThrowOnError>({
+ url: '/events/{event_id}',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Set the requester's RSVP on a calendar event and return its synced entity.
+ */
+ public rsvpCalendarEvent<ThrowOnError extends boolean = false>(options: Options<RsvpCalendarEventData, ThrowOnError>): RequestResult<RsvpCalendarEventResponses, RsvpCalendarEventErrors, ThrowOnError> {
+ return (options.client ?? this.client).put<RsvpCalendarEventResponses, RsvpCalendarEventErrors, ThrowOnError>({
+ url: '/events/{event_id}/rsvp',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Health check
+ */
+ public healthHandler<ThrowOnError extends boolean = false>(options?: Options<HealthHandlerData, ThrowOnError>): RequestResult<HealthHandlerResponses, unknown, ThrowOnError> {
+ return (options?.client ?? this.client).get<HealthHandlerResponses, unknown, ThrowOnError>({ url: '/health', ...options });
+ }
+}
diff --git a/packages/sdk/generated/calendar/types.gen.ts b/packages/sdk/generated/calendar/types.gen.ts
new file mode 100644
index 0000000000..997e2345a6
--- /dev/null
+++ b/packages/sdk/generated/calendar/types.gen.ts
@@ -0,0 +1,829 @@
+// This file is auto-generated by @hey-api/openapi-ts
+
+export type ClientOptions = {
+ baseUrl: `${string}://${string}` | (string & {});
+};
+
+/**
+ * RSVP state for an attendee.
+ */
+export type AttendeeResponseStatus = 'needs_action' | 'accepted' | 'declined' | 'tentative';
+
+/**
+ * An attendee on a calendar event.
+ */
+export type CalendarAttendee = {
+ /**
+ * Optional attendee comment.
+ */
+ comment?: string | null;
+ /**
+ * Provider display name.
+ */
+ displayName?: string | null;
+ /**
+ * Normalized email address.
+ */
+ email: string;
+ /**
+ * Whether attendance is optional.
+ */
+ isOptional: boolean;
+ /**
+ * Whether this attendee is the organizer.
+ */
+ isOrganizer: boolean;
+ /**
+ * Whether this attendee is one of the viewing requester's inboxes.
+ */
+ isSelf: boolean;
+ /**
+ * RSVP state.
+ */
+ responseStatus: AttendeeResponseStatus;
+};
+
+/**
+ * An attendee supplied to a calendar mutation.
+ */
+export type CalendarAttendeeInputBody = {
+ /**
+ * Attendee email address.
+ */
+ email: string;
+ /**
+ * Whether attendance is optional.
+ */
+ isOptional?: boolean;
+};
+
+/**
+ * How much of a recurring series a deletion removes.
+ */
+export type CalendarDeletionScopeParam = 'all' | 'this_event' | 'this_and_following';
+
+/**
+ * A stable, first-class Macro calendar event entity.
+ *
+ * Content fields hold the canonical source's values: the account's primary
+ * calendar copy when one is synced, else the freshest remaining copy.
+ */
+export type CalendarEvent = {
+ /**
+ * Attendees, keyed by email during persistence.
+ */
+ attendees: Array<CalendarAttendee>;
+ /**
+ * Calendar the canonical source belongs to, when known. Absent only in
+ * projections stored before calendars were attributed.
+ */
+ calendarId?: string | null;
+ conferenceProvider?: null | ConferenceProvider;
+ /**
+ * Direct join URL when known.
+ */
+ conferenceUrl?: string | null;
+ /**
+ * Entity creation time.
+ */
+ createdAt: string;
+ /**
+ * Provider-reported creator email. Distinct from the organizer when
+ * someone writes onto a calendar they do not own. Omitted from stored
+ * projections when unknown so events ingested before this field still
+ * compare equal.
+ */
+ creatorEmail?: string | null;
+ /**
+ * Provider-reported creator display name.
+ */
+ creatorName?: string | null;
+ /**
+ * Optional event body.
+ */
+ description?: string | null;
+ /**
+ * Provider event type. Skipped when it is the regular type so
+ * projections stored before event types were modeled still compare
+ * equal.
+ */
+ eventType?: EventType;
+ /**
+ * RFC 5545 UID used to reconcile provider and email sources.
+ */
+ icalUid: string;
+ /**
+ * Macro entity identifier.
+ */
+ id: string;
+ /**
+ * Whether the canonical source's calendar prohibits editing it.
+ */
+ isReadOnly: boolean;
+ /**
+ * Optional physical or virtual location label.
+ */
+ location?: string | null;
+ /**
+ * Organizer email.
+ */
+ organizerEmail?: string | null;
+ /**
+ * Organizer display name.
+ */
+ organizerName?: string | null;
+ /**
+ * Macro user who owns this event entity.
+ */
+ ownerId: string;
+ /**
+ * Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).
+ */
+ recurrenceLines: Array<string>;
+ /**
+ * Per-user reminder configuration. Skipped when it is the provider
+ * default so projections stored before reminders were modeled still
+ * compare equal.
+ */
+ reminders?: EventReminders;
+ /**
+ * Provider/iCalendar sequence number.
+ */
+ sequence: number;
+ /**
+ * Content of every active copy of this event, canonical first: the
+ * primary calendar's copy, then the freshest. A client picks the copy
+ * whose calendar it is showing and falls back to the first. Populated
+ * only on the read path, so stored projections omit it.
+ */
+ sources?: Array<CalendarEventSourceContent>;
+ /**
+ * Event status.
+ */
+ status: EventStatus;
+ /**
+ * Timed or all-day shape.
+ */
+ time: EventTime;
+ /**
+ * Display title.
+ */
+ title: string;
+ /**
+ * Availability behavior.
+ */
+ transparency: EventTransparency;
+ /**
+ * Entity update time.
+ */
+ updatedAt: string;
+ /**
+ * Event visibility.
+ */
+ visibility: EventVisibility;
+};
+
+/**
+ * The content one provider copy of an event carries.
+ *
+ * Google keeps these fields per calendar copy: a shared calendar's copy of a
+ * member's event can have its own title, type, reminders, and access role.
+ * The entity holds its canonical source's values. Every other copy's values
+ * are read from here so a client can show the copy that belongs to the
+ * calendar being viewed.
+ */
+export type CalendarEventSourceContent = {
+ /**
+ * Calendar this copy lives on.
+ */
+ calendarId: string;
+ /**
+ * Provider-reported creator email.
+ */
+ creatorEmail?: string | null;
+ /**
+ * Provider-reported creator display name.
+ */
+ creatorName?: string | null;
+ /**
+ * Optional event body.
+ */
+ description?: string | null;
+ /**
+ * Provider event type.
+ */
+ eventType: EventType;
+ /**
+ * Whether the calendar's access role prohibits editing this copy.
+ */
+ isReadOnly: boolean;
+ /**
+ * Optional physical or virtual location label.
+ */
+ location?: string | null;
+ /**
+ * Reminder configuration of this copy.
+ */
+ reminders: EventReminders;
+ /**
+ * Display title.
+ */
+ title: string;
+ /**
+ * Availability behavior.
+ */
+ transparency: EventTransparency;
+ /**
+ * Event visibility.
+ */
+ visibility: EventVisibility;
+};
+
+/**
+ * HTTP error body returned by calendar mutation endpoints.
+ */
+export type CalendarMutationApiError = {
+ /**
+ * Machine-readable failure category.
+ */
+ code: CalendarMutationErrorCode;
+ /**
+ * Human-readable failure description.
+ */
+ message: string;
+};
+
+/**
+ * Machine-readable failure category for calendar mutations.
+ */
+export type CalendarMutationErrorCode = 'not_found' | 'occurrence_not_found' | 'read_only' | 'no_writable_calendar' | 'not_attendee' | 'invalid_input' | 'reauth_required' | 'provider_rejected' | 'retryable' | 'persist_failed';
+
+/**
+ * How much of a recurring series an RSVP applies to.
+ *
+ * Unlike deletion there is no this-and-following variant: the provider
+ * cannot express a forward-scoped response, so offering one would be a
+ * promise sync could not keep.
+ */
+export type CalendarRsvpScopeParam = 'all' | 'this_event';
+
+/**
+ * How much of a recurring series an update applies to.
+ *
+ * Like RSVPs there is no this-and-following variant: the provider cannot
+ * express a forward-scoped edit as one write, and emulating it (truncate
+ * the series, insert an edited clone) is non-atomic and re-invites the
+ * attendees of the clone. Compose it from a this-and-following deletion
+ * and a create when that shape is wanted.
+ */
+export type CalendarUpdateScopeParam = 'all' | 'this_event';
+
+/**
+ * A requested change to an event's conferencing. Omitting the field leaves
+ * the existing conference untouched; only these values change it.
+ */
+export type ConferenceChange = 'google_meet' | 'none';
+
+/**
+ * The conferencing system backing an event's join URL.
+ *
+ * Macro generates only Google Meet conferences, so this distinguishes one it
+ * created from a third party's — Zoom and friends arriving as `addOn`
+ * conference data, or a legacy classic Hangout. Clients use it to label the
+ * conference and to tell whether the Meet toggle reflects a Macro-managed
+ * conference.
+ *
+ * It does not gate mutation. An explicit request replaces or detaches any
+ * conference, third-party included, exactly as deleting the event would;
+ * what protects a conference is that omitting the field leaves it untouched,
+ * so an unrelated edit never disturbs it.
+ */
+export type ConferenceProvider = 'google_meet' | 'other';
+
+/**
+ * Request body creating a calendar event on the requester's calendar.
+ */
+export type CreateCalendarEventRequest = {
+ /**
+ * Invited attendees.
+ */
+ attendees?: Array<CalendarAttendeeInputBody>;
+ /**
+ * Exact calendar to create the event on; takes precedence over the
+ * inbox default.
+ */
+ calendarId?: string | null;
+ conference?: null | ConferenceChange;
+ /**
+ * Optional event body.
+ */
+ description?: string | null;
+ /**
+ * Connected inbox whose primary calendar receives the event; defaults
+ * to the requester's primary inbox.
+ */
+ emailLinkId?: string | null;
+ /**
+ * Optional location label.
+ */
+ location?: string | null;
+ outOfOffice?: null | OutOfOfficeProperties;
+ /**
+ * Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`).
+ */
+ recurrenceLines?: Array<string>;
+ reminders?: null | EventReminders;
+ /**
+ * Timed or all-day shape.
+ */
+ time: EventTime;
+ /**
+ * Display title.
+ */
+ title: string;
+ transparency?: null | EventTransparency;
+ visibility?: null | EventVisibility;
+};
+
+/**
+ * One reminder: how it alerts and how many minutes before the event start
+ * (before midnight in the calendar's zone for all-day events) it fires.
+ */
+export type EventReminderOverride = {
+ /**
+ * Provider method, stored verbatim; only `popup` fires Macro
+ * notifications.
+ */
+ method: string;
+ /**
+ * Minutes before the event start.
+ */
+ minutes: number;
+};
+
+/**
+ * Per-user reminder configuration for an event, mirroring Google's model:
+ * either the calendar's default reminders apply, or the explicit overrides
+ * replace them entirely.
+ */
+export type EventReminders = {
+ /**
+ * Explicit reminders replacing the defaults when `use_default` is off.
+ */
+ overrides?: Array<EventReminderOverride>;
+ /**
+ * Whether the calendar's default reminders apply.
+ */
+ useDefault: boolean;
+};
+
+/**
+ * Canonical event status.
+ */
+export type EventStatus = 'confirmed' | 'tentative' | 'cancelled';
+
+/**
+ * The mutually exclusive time shape of a calendar event.
+ *
+ * Fields are renamed per variant rather than with `rename_all_fields`
+ * because utoipa only honors variant-level serde renames when it
+ * derives the OpenAPI schema.
+ */
+export type EventTime = {
+ /**
+ * Exclusive end instant.
+ */
+ endsAt: string;
+ kind: 'timed';
+ /**
+ * Inclusive start instant.
+ */
+ startsAt: string;
+ /**
+ * Original IANA time-zone identifier, when supplied.
+ */
+ timeZone?: string | null;
+} | {
+ /**
+ * Exclusive local end date.
+ */
+ endDate: string;
+ kind: 'allDay';
+ /**
+ * Inclusive local start date.
+ */
+ startDate: string;
+};
+
+/**
+ * Whether an event blocks availability.
+ */
+export type EventTransparency = 'opaque' | 'transparent';
+
+/**
+ * Google's event type: ordinary meetings versus the status-style entries
+ * (working location, out of office, focus time, birthdays) Google renders
+ * and notifies differently. Immutable at the provider after creation.
+ */
+export type EventType = 'default' | 'out_of_office' | 'focus_time' | 'working_location' | 'birthday' | 'from_gmail';
+
+/**
+ * Visibility of event details.
+ */
+export type EventVisibility = 'default' | 'public' | 'private' | 'confidential';
+
+/**
+ * Calendars visible to the requester across connected and delegated inboxes.
+ */
+export type ListCalendarsResponse = {
+ /**
+ * Primaries and writable calendars first.
+ */
+ calendars: Array<VisibleCalendar>;
+};
+
+/**
+ * How an out-of-office event responds to conflicting invitations, mirroring
+ * Google's `autoDeclineMode`.
+ */
+export type OutOfOfficeAutoDeclineMode = 'decline_none' | 'decline_all_conflicting_invitations' | 'decline_only_new_conflicting_invitations';
+
+/**
+ * The extra properties Google requires on an out-of-office event, mirroring
+ * its `outOfOfficeProperties` block. Their presence on a draft or patch is
+ * what marks the mutation as out-of-office.
+ */
+export type OutOfOfficeProperties = {
+ /**
+ * How conflicting invitations are handled while the user is out.
+ */
+ autoDeclineMode?: OutOfOfficeAutoDeclineMode;
+ /**
+ * Message returned to organizers whose invitations are auto-declined.
+ */
+ declineMessage?: string | null;
+};
+
+/**
+ * A sync run committed changes for `link_id`; viewers should refetch.
+ */
+export type RefreshCalendarEvent = {
+ event: 'synced';
+ /**
+ * Connected inbox whose calendars changed.
+ */
+ link_id: string;
+};
+
+/**
+ * Request body setting the requester's RSVP on an event.
+ */
+export type RsvpCalendarEventRequest = {
+ /**
+ * Calendar whose copy of the event is answered, for an event synced
+ * from more than one calendar. Omit to answer on the canonical copy.
+ */
+ calendarId?: string | null;
+ /**
+ * Original-start key of the occurrence the response targets.
+ */
+ recurrenceId?: string | null;
+ /**
+ * The response to record for the connected account.
+ */
+ response: AttendeeResponseStatus;
+ scope?: null | CalendarRsvpScopeParam;
+};
+
+/**
+ * Request body patching an event; omitted fields are left untouched.
+ */
+export type UpdateCalendarEventRequest = {
+ /**
+ * Replacement attendee list.
+ */
+ attendees?: Array<CalendarAttendeeInputBody> | null;
+ /**
+ * Calendar whose copy of the event is patched, for an event synced from
+ * more than one calendar. Omit to patch the canonical copy.
+ */
+ calendarId?: string | null;
+ conference?: null | ConferenceChange;
+ /**
+ * Replacement description; an empty string clears it.
+ */
+ description?: string | null;
+ /**
+ * Replacement location; an empty string clears it.
+ */
+ location?: string | null;
+ outOfOffice?: null | OutOfOfficeProperties;
+ /**
+ * Original-start key of the occurrence the update targets.
+ */
+ recurrenceId?: string | null;
+ /**
+ * Replacement recurrence properties; an empty list clears them.
+ */
+ recurrenceLines?: Array<string> | null;
+ reminders?: null | EventReminders;
+ scope?: null | CalendarUpdateScopeParam;
+ time?: null | EventTime;
+ /**
+ * Replacement title; an empty string clears it.
+ */
+ title?: string | null;
+ transparency?: null | EventTransparency;
+ visibility?: null | EventVisibility;
+};
+
+/**
+ * A calendar visible to a requester, listed for pickers and filters.
+ */
+export type VisibleCalendar = {
+ /**
+ * Provider color.
+ */
+ color?: string | null;
+ /**
+ * Default reminders applied to events that keep `useDefault`.
+ */
+ defaultReminders: Array<EventReminderOverride>;
+ /**
+ * Connected inbox address, for grouping in multi-inbox pickers.
+ */
+ emailAddress: string;
+ /**
+ * Connected inbox that syncs this calendar.
+ */
+ emailLinkId: string;
+ /**
+ * Persisted Macro calendar identifier.
+ */
+ id: string;
+ /**
+ * Whether this is its account's primary calendar.
+ */
+ isPrimary: boolean;
+ /**
+ * Whether this is one of Google's shared system calendars (holidays,
+ * birthdays) the account subscribes to rather than one a person maintains.
+ */
+ isSubscription: boolean;
+ /**
+ * Whether the grant can create and modify events on this calendar.
+ */
+ isWritable: boolean;
+ /**
+ * Provider display name.
+ */
+ name: string;
+ /**
+ * A persistent sync failure isolated to this calendar, surfaced so the
+ * settings row can badge it. `None` while the calendar is syncing
+ * normally or a failure has not yet crossed the persistence threshold.
+ */
+ syncError?: string | null;
+};
+
+export type ListCalendarsData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/calendars';
+};
+
+export type ListCalendarsErrors = {
+ /**
+ * Authentication required
+ */
+ 401: unknown;
+ /**
+ * Transient failure
+ */
+ 503: CalendarMutationApiError;
+};
+
+export type ListCalendarsError = ListCalendarsErrors[keyof ListCalendarsErrors];
+
+export type ListCalendarsResponses = {
+ /**
+ * Calendars visible to the requester
+ */
+ 200: ListCalendarsResponse;
+};
+
+export type ListCalendarsResponse2 = ListCalendarsResponses[keyof ListCalendarsResponses];
+
+export type CreateCalendarEventData = {
+ body: CreateCalendarEventRequest;
+ path?: never;
+ query?: never;
+ url: '/events';
+};
+
+export type CreateCalendarEventErrors = {
+ /**
+ * Invalid event fields
+ */
+ 400: CalendarMutationApiError;
+ /**
+ * Authentication required
+ */
+ 401: unknown;
+ /**
+ * Calendar is read-only or needs reauthorization
+ */
+ 403: CalendarMutationApiError;
+ /**
+ * No writable calendar or the provider rejected the event
+ */
+ 409: CalendarMutationApiError;
+ /**
+ * Transient provider failure
+ */
+ 503: CalendarMutationApiError;
+};
+
+export type CreateCalendarEventError = CreateCalendarEventErrors[keyof CreateCalendarEventErrors];
+
+export type CreateCalendarEventResponses = {
+ /**
+ * The created calendar event
+ */
+ 201: CalendarEvent;
+};
+
+export type CreateCalendarEventResponse = CreateCalendarEventResponses[keyof CreateCalendarEventResponses];
+
+export type DeleteCalendarEventData = {
+ body?: never;
+ path: {
+ /**
+ * Calendar event entity id
+ */
+ event_id: string;
+ };
+ query?: {
+ /**
+ * Calendar whose copy of the event is deleted, for an event synced from
+ * more than one calendar. Omit to delete the canonical copy.
+ */
+ calendarId?: string;
+ /**
+ * Deletion scope; defaults to the entire event or series.
+ */
+ scope?: CalendarDeletionScopeParam;
+ /**
+ * Original-start key of the occurrence a scoped deletion targets.
+ */
+ recurrenceId?: string;
+ };
+ url: '/events/{event_id}';
+};
+
+export type DeleteCalendarEventErrors = {
+ /**
+ * Authentication required
+ */
+ 401: unknown;
+ /**
+ * Calendar is read-only or needs reauthorization
+ */
+ 403: CalendarMutationApiError;
+ /**
+ * Event not found
+ */
+ 404: CalendarMutationApiError;
+ /**
+ * The provider rejected the deletion
+ */
+ 409: CalendarMutationApiError;
+ /**
+ * Transient provider failure
+ */
+ 503: CalendarMutationApiError;
+};
+
+export type DeleteCalendarEventError = DeleteCalendarEventErrors[keyof DeleteCalendarEventErrors];
+
+export type DeleteCalendarEventResponses = {
+ /**
+ * The event was deleted
+ */
+ 204: void;
+};
+
+export type DeleteCalendarEventResponse = DeleteCalendarEventResponses[keyof DeleteCalendarEventResponses];
+
+export type UpdateCalendarEventData = {
+ body: UpdateCalendarEventRequest;
+ path: {
+ /**
+ * Calendar event entity id
+ */
+ event_id: string;
+ };
+ query?: never;
+ url: '/events/{event_id}';
+};
+
+export type UpdateCalendarEventErrors = {
+ /**
+ * Invalid event fields
+ */
+ 400: CalendarMutationApiError;
+ /**
+ * Authentication required
+ */
+ 401: unknown;
+ /**
+ * Calendar is read-only or needs reauthorization
+ */
+ 403: CalendarMutationApiError;
+ /**
+ * Event or targeted occurrence not found
+ */
+ 404: CalendarMutationApiError;
+ /**
+ * The provider rejected the update
+ */
+ 409: CalendarMutationApiError;
+ /**
+ * Transient provider failure
+ */
+ 503: CalendarMutationApiError;
+};
+
+export type UpdateCalendarEventError = UpdateCalendarEventErrors[keyof UpdateCalendarEventErrors];
+
+export type UpdateCalendarEventResponses = {
+ /**
+ * The updated calendar event
+ */
+ 200: CalendarEvent;
+};
+
+export type UpdateCalendarEventResponse = UpdateCalendarEventResponses[keyof UpdateCalendarEventResponses];
+
+export type RsvpCalendarEventData = {
+ body: RsvpCalendarEventRequest;
+ path: {
+ /**
+ * Calendar event entity id
+ */
+ event_id: string;
+ };
+ query?: never;
+ url: '/events/{event_id}/rsvp';
+};
+
+export type RsvpCalendarEventErrors = {
+ /**
+ * Authentication required
+ */
+ 401: unknown;
+ /**
+ * Calendar is read-only or needs reauthorization
+ */
+ 403: CalendarMutationApiError;
+ /**
+ * Event not found
+ */
+ 404: CalendarMutationApiError;
+ /**
+ * The connected account is not an attendee
+ */
+ 409: CalendarMutationApiError;
+ /**
+ * Transient provider failure
+ */
+ 503: CalendarMutationApiError;
+};
+
+export type RsvpCalendarEventError = RsvpCalendarEventErrors[keyof RsvpCalendarEventErrors];
+
+export type RsvpCalendarEventResponses = {
+ /**
+ * The updated calendar event
+ */
+ 200: CalendarEvent;
+};
+
+export type RsvpCalendarEventResponse = RsvpCalendarEventResponses[keyof RsvpCalendarEventResponses];
+
+export type HealthHandlerData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/health';
+};
+
+export type HealthHandlerResponses = {
+ /**
+ * health
+ */
+ 200: string;
+};
+
+export type HealthHandlerResponse = HealthHandlerResponses[keyof HealthHandlerResponses];
diff --git a/packages/sdk/package.json b/packages/sdk/package.json
index c94514d0b9..ef20c9ce5e 100644
--- a/packages/sdk/package.json
+++ b/packages/sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@macro-inc/sdk",
- "version": "0.0.2",
+ "version": "0.1.0",
"repository": {
"type": "git",
"url": "git+https://github.com/macro-inc/macro.git",
diff --git a/packages/sdk/scripts/sync-specs.ts b/packages/sdk/scripts/sync-specs.ts
index 347da17734..7dee8e368d 100644
--- a/packages/sdk/scripts/sync-specs.ts
+++ b/packages/sdk/scripts/sync-specs.ts
@@ -1,6 +1,12 @@
import * as path from 'node:path';
+import { $ } from 'bun';
import { services } from '../services';
+// Services whose OpenAPI spec is copied from apps/web's service-clients package,
+// where `apps/web`'s `gen-api` writes each Rust service's spec. `calendar` is not
+// among them: it has no service-client in apps/web (the web app reaches calendar
+// through the hand-written email client), so its spec is generated here directly
+// from the Rust `calendar_service_openapi` binary. See `syncCalendarSpec`.
const serviceClientDirectories = {
'agent-harness': 'service-agent-harness',
auth: 'service-auth',
@@ -15,22 +21,66 @@ const serviceClientDirectories = {
'static-files': 'service-static-files',
storage: 'service-storage',
unfurl: 'service-unfurl',
-} satisfies Record<(typeof services)[number], string>;
+} satisfies Record<Exclude<(typeof services)[number], 'calendar'>, string>;
const serviceClientsDirectory = path.resolve(
import.meta.dirname,
'../../../apps/web/src/lib/service-clients',
);
const specsDirectory = path.resolve(import.meta.dirname, '../specs');
+const rustWorkspaceDirectory = path.resolve(import.meta.dirname, '../../..');
+
+/**
+ * Rewrite calendar_service's OpenAPI so its paths are root-relative.
+ *
+ * The calendar mutation handlers are shared with email-service, whose spec must
+ * keep serving them under `/calendar/*` (email base is `/email`). Their
+ * `utoipa::path` annotations therefore carry a `/calendar` prefix. The SDK's
+ * calendar client instead carries `/calendar` in its base URL (dev/prod
+ * `<gateway>/calendar`), so the generated paths must drop it. Stripping here
+ * keeps the annotations untouched — and so keeps email-service's spec, and the
+ * apps/web spec generated from it, byte-for-byte unchanged.
+ *
+ * Temporary: once email-service stops serving `/calendar/*` (cutover cleanup),
+ * the shared annotations can become router-relative and this transform goes away.
+ */
+function stripCalendarPrefix(spec: string): string {
+ const doc = JSON.parse(spec) as { paths?: Record<string, unknown> };
+ if (doc.paths) {
+ const rewritten: Record<string, unknown> = {};
+ for (const [route, item] of Object.entries(doc.paths)) {
+ const stripped = route.startsWith('/calendar/')
+ ? route.slice('/calendar'.length)
+ : route;
+ rewritten[stripped] = item;
+ }
+ doc.paths = rewritten;
+ }
+ return `${JSON.stringify(doc, null, 2)}\n`;
+}
+
+async function syncCalendarSpec(destination: string): Promise<void> {
+ const spec = await $`cargo run --quiet --bin calendar_service_openapi`
+ .cwd(rustWorkspaceDirectory)
+ .env({ ...process.env, SQLX_OFFLINE: 'true' })
+ .text();
+ await Bun.write(destination, stripCalendarPrefix(spec));
+ console.log('Synced calendar (from calendar_service_openapi)');
+}
for (const service of services) {
+ const destination = path.join(specsDirectory, `${service}.json`);
+
+ if (service === 'calendar') {
+ await syncCalendarSpec(destination);
+ continue;
+ }
+
const source = path.join(
serviceClientsDirectory,
serviceClientDirectories[service],
'openapi.json',
);
- const destination = path.join(specsDirectory, `${service}.json`);
-
await Bun.write(destination, Bun.file(source));
console.log(`Synced ${service}`);
}
diff --git a/packages/sdk/services.ts b/packages/sdk/services.ts
index ba05f494f0..af34d9d37d 100644
--- a/packages/sdk/services.ts
+++ b/packages/sdk/services.ts
@@ -7,6 +7,7 @@
export const services = [
'agent-harness',
'auth',
+ 'calendar',
'cognition',
'connection',
'contacts',
diff --git a/packages/sdk/specs/calendar.json b/packages/sdk/specs/calendar.json
new file mode 100644
index 0000000000..0733e16abc
--- /dev/null
+++ b/packages/sdk/specs/calendar.json
@@ -0,0 +1,1397 @@
+{
+ "openapi": "3.1.0",
+ "info": {
+ "title": "calendar_service",
+ "description": "",
+ "license": {
+ "name": ""
+ },
+ "version": "0.1.0"
+ },
+ "paths": {
+ "/calendars": {
+ "get": {
+ "tags": [
+ "calendar_events"
+ ],
+ "summary": "List the requester's visible calendars for pickers and filters.",
+ "operationId": "list_calendars",
+ "responses": {
+ "200": {
+ "description": "Calendars visible to the requester",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListCalendarsResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required"
+ },
+ "503": {
+ "description": "Transient failure",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/events": {
+ "post": {
+ "tags": [
+ "calendar_events"
+ ],
+ "summary": "Create a calendar event and return its synced entity.",
+ "operationId": "create_calendar_event",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CreateCalendarEventRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "201": {
+ "description": "The created calendar event",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarEvent"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid event fields",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required"
+ },
+ "403": {
+ "description": "Calendar is read-only or needs reauthorization",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "No writable calendar or the provider rejected the event",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Transient provider failure",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/events/{event_id}": {
+ "delete": {
+ "tags": [
+ "calendar_events"
+ ],
+ "summary": "Delete a calendar event at its provider.",
+ "operationId": "delete_calendar_event",
+ "parameters": [
+ {
+ "name": "event_id",
+ "in": "path",
+ "description": "Calendar event entity id",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "calendarId",
+ "in": "query",
+ "description": "Calendar whose copy of the event is deleted, for an event synced from\nmore than one calendar. Omit to delete the canonical copy.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ },
+ {
+ "name": "scope",
+ "in": "query",
+ "description": "Deletion scope; defaults to the entire event or series.",
+ "required": false,
+ "schema": {
+ "$ref": "#/components/schemas/CalendarDeletionScopeParam"
+ }
+ },
+ {
+ "name": "recurrenceId",
+ "in": "query",
+ "description": "Original-start key of the occurrence a scoped deletion targets.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": "The event was deleted"
+ },
+ "401": {
+ "description": "Authentication required"
+ },
+ "403": {
+ "description": "Calendar is read-only or needs reauthorization",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Event not found",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "The provider rejected the deletion",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Transient provider failure",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ }
+ }
+ },
+ "patch": {
+ "tags": [
+ "calendar_events"
+ ],
+ "summary": "Update fields of a calendar event and return its synced entity.",
+ "operationId": "update_calendar_event",
+ "parameters": [
+ {
+ "name": "event_id",
+ "in": "path",
+ "description": "Calendar event entity id",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/UpdateCalendarEventRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "The updated calendar event",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarEvent"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "Invalid event fields",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required"
+ },
+ "403": {
+ "description": "Calendar is read-only or needs reauthorization",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Event or targeted occurrence not found",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "The provider rejected the update",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Transient provider failure",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/events/{event_id}/rsvp": {
+ "put": {
+ "tags": [
+ "calendar_events"
+ ],
+ "summary": "Set the requester's RSVP on a calendar event and return its synced entity.",
+ "operationId": "rsvp_calendar_event",
+ "parameters": [
+ {
+ "name": "event_id",
+ "in": "path",
+ "description": "Calendar event entity id",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RsvpCalendarEventRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "The updated calendar event",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarEvent"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "Authentication required"
+ },
+ "403": {
+ "description": "Calendar is read-only or needs reauthorization",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Event not found",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "409": {
+ "description": "The connected account is not an attendee",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ },
+ "503": {
+ "description": "Transient provider failure",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/CalendarMutationApiError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/health": {
+ "get": {
+ "tags": [
+ "crate::health"
+ ],
+ "summary": "Health check",
+ "operationId": "health_handler",
+ "responses": {
+ "200": {
+ "description": "health",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "components": {
+ "schemas": {
+ "AttendeeResponseStatus": {
+ "type": "string",
+ "description": "RSVP state for an attendee.",
+ "enum": [
+ "needs_action",
+ "accepted",
+ "declined",
+ "tentative"
+ ]
+ },
+ "CalendarAttendee": {
+ "type": "object",
+ "description": "An attendee on a calendar event.",
+ "required": [
+ "email",
+ "responseStatus",
+ "isOrganizer",
+ "isOptional",
+ "isSelf"
+ ],
+ "properties": {
+ "comment": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Optional attendee comment."
+ },
+ "displayName": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Provider display name."
+ },
+ "email": {
+ "type": "string",
+ "description": "Normalized email address."
+ },
+ "isOptional": {
+ "type": "boolean",
+ "description": "Whether attendance is optional."
+ },
+ "isOrganizer": {
+ "type": "boolean",
+ "description": "Whether this attendee is the organizer."
+ },
+ "isSelf": {
+ "type": "boolean",
+ "description": "Whether this attendee is one of the viewing requester's inboxes."
+ },
+ "responseStatus": {
+ "$ref": "#/components/schemas/AttendeeResponseStatus",
+ "description": "RSVP state."
+ }
+ }
+ },
+ "CalendarAttendeeInputBody": {
+ "type": "object",
+ "description": "An attendee supplied to a calendar mutation.",
+ "required": [
+ "email"
+ ],
+ "properties": {
+ "email": {
+ "type": "string",
+ "description": "Attendee email address."
+ },
+ "isOptional": {
+ "type": "boolean",
+ "description": "Whether attendance is optional."
+ }
+ }
+ },
+ "CalendarDeletionScopeParam": {
+ "type": "string",
+ "description": "How much of a recurring series a deletion removes.",
+ "enum": [
+ "all",
+ "this_event",
+ "this_and_following"
+ ]
+ },
+ "CalendarEvent": {
+ "type": "object",
+ "description": "A stable, first-class Macro calendar event entity.\n\nContent fields hold the canonical source's values: the account's primary\ncalendar copy when one is synced, else the freshest remaining copy.",
+ "required": [
+ "id",
+ "ownerId",
+ "icalUid",
+ "title",
+ "status",
+ "visibility",
+ "transparency",
+ "time",
+ "recurrenceLines",
+ "sequence",
+ "isReadOnly",
+ "attendees",
+ "createdAt",
+ "updatedAt"
+ ],
+ "properties": {
+ "attendees": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CalendarAttendee"
+ },
+ "description": "Attendees, keyed by email during persistence."
+ },
+ "calendarId": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "uuid",
+ "description": "Calendar the canonical source belongs to, when known. Absent only in\nprojections stored before calendars were attributed."
+ },
+ "conferenceProvider": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ConferenceProvider",
+ "description": "Which conferencing system backs `conference_url`. `None` whenever no\nconference is attached."
+ }
+ ]
+ },
+ "conferenceUrl": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Direct join URL when known."
+ },
+ "createdAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Entity creation time."
+ },
+ "creatorEmail": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Provider-reported creator email. Distinct from the organizer when\nsomeone writes onto a calendar they do not own. Omitted from stored\nprojections when unknown so events ingested before this field still\ncompare equal."
+ },
+ "creatorName": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Provider-reported creator display name."
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Optional event body."
+ },
+ "eventType": {
+ "$ref": "#/components/schemas/EventType",
+ "description": "Provider event type. Skipped when it is the regular type so\nprojections stored before event types were modeled still compare\nequal."
+ },
+ "icalUid": {
+ "type": "string",
+ "description": "RFC 5545 UID used to reconcile provider and email sources."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Macro entity identifier."
+ },
+ "isReadOnly": {
+ "type": "boolean",
+ "description": "Whether the canonical source's calendar prohibits editing it."
+ },
+ "location": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Optional physical or virtual location label."
+ },
+ "organizerEmail": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Organizer email."
+ },
+ "organizerName": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Organizer display name."
+ },
+ "ownerId": {
+ "type": "string",
+ "description": "Macro user who owns this event entity."
+ },
+ "recurrenceLines": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`)."
+ },
+ "reminders": {
+ "$ref": "#/components/schemas/EventReminders",
+ "description": "Per-user reminder configuration. Skipped when it is the provider\ndefault so projections stored before reminders were modeled still\ncompare equal."
+ },
+ "sequence": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Provider/iCalendar sequence number.",
+ "minimum": 0
+ },
+ "sources": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CalendarEventSourceContent"
+ },
+ "description": "Content of every active copy of this event, canonical first: the\nprimary calendar's copy, then the freshest. A client picks the copy\nwhose calendar it is showing and falls back to the first. Populated\nonly on the read path, so stored projections omit it."
+ },
+ "status": {
+ "$ref": "#/components/schemas/EventStatus",
+ "description": "Event status."
+ },
+ "time": {
+ "$ref": "#/components/schemas/EventTime",
+ "description": "Timed or all-day shape."
+ },
+ "title": {
+ "type": "string",
+ "description": "Display title."
+ },
+ "transparency": {
+ "$ref": "#/components/schemas/EventTransparency",
+ "description": "Availability behavior."
+ },
+ "updatedAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Entity update time."
+ },
+ "visibility": {
+ "$ref": "#/components/schemas/EventVisibility",
+ "description": "Event visibility."
+ }
+ }
+ },
+ "CalendarEventSourceContent": {
+ "type": "object",
+ "description": "The content one provider copy of an event carries.\n\nGoogle keeps these fields per calendar copy: a shared calendar's copy of a\nmember's event can have its own title, type, reminders, and access role.\nThe entity holds its canonical source's values. Every other copy's values\nare read from here so a client can show the copy that belongs to the\ncalendar being viewed.",
+ "required": [
+ "calendarId",
+ "title",
+ "eventType",
+ "visibility",
+ "transparency",
+ "isReadOnly",
+ "reminders"
+ ],
+ "properties": {
+ "calendarId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Calendar this copy lives on."
+ },
+ "creatorEmail": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Provider-reported creator email."
+ },
+ "creatorName": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Provider-reported creator display name."
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Optional event body."
+ },
+ "eventType": {
+ "$ref": "#/components/schemas/EventType",
+ "description": "Provider event type."
+ },
+ "isReadOnly": {
+ "type": "boolean",
+ "description": "Whether the calendar's access role prohibits editing this copy."
+ },
+ "location": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Optional physical or virtual location label."
+ },
+ "reminders": {
+ "$ref": "#/components/schemas/EventReminders",
+ "description": "Reminder configuration of this copy."
+ },
+ "title": {
+ "type": "string",
+ "description": "Display title."
+ },
+ "transparency": {
+ "$ref": "#/components/schemas/EventTransparency",
+ "description": "Availability behavior."
+ },
+ "visibility": {
+ "$ref": "#/components/schemas/EventVisibility",
+ "description": "Event visibility."
+ }
+ }
+ },
+ "CalendarMutationApiError": {
+ "type": "object",
+ "description": "HTTP error body returned by calendar mutation endpoints.",
+ "required": [
+ "code",
+ "message"
+ ],
+ "properties": {
+ "code": {
+ "$ref": "#/components/schemas/CalendarMutationErrorCode",
+ "description": "Machine-readable failure category."
+ },
+ "message": {
+ "type": "string",
+ "description": "Human-readable failure description."
+ }
+ }
+ },
+ "CalendarMutationErrorCode": {
+ "type": "string",
+ "description": "Machine-readable failure category for calendar mutations.",
+ "enum": [
+ "not_found",
+ "occurrence_not_found",
+ "read_only",
+ "no_writable_calendar",
+ "not_attendee",
+ "invalid_input",
+ "reauth_required",
+ "provider_rejected",
+ "retryable",
+ "persist_failed"
+ ]
+ },
+ "CalendarRsvpScopeParam": {
+ "type": "string",
+ "description": "How much of a recurring series an RSVP applies to.\n\nUnlike deletion there is no this-and-following variant: the provider\ncannot express a forward-scoped response, so offering one would be a\npromise sync could not keep.",
+ "enum": [
+ "all",
+ "this_event"
+ ]
+ },
+ "CalendarUpdateScopeParam": {
+ "type": "string",
+ "description": "How much of a recurring series an update applies to.\n\nLike RSVPs there is no this-and-following variant: the provider cannot\nexpress a forward-scoped edit as one write, and emulating it (truncate\nthe series, insert an edited clone) is non-atomic and re-invites the\nattendees of the clone. Compose it from a this-and-following deletion\nand a create when that shape is wanted.",
+ "enum": [
+ "all",
+ "this_event"
+ ]
+ },
+ "ConferenceChange": {
+ "type": "string",
+ "description": "A requested change to an event's conferencing. Omitting the field leaves\nthe existing conference untouched; only these values change it.",
+ "enum": [
+ "google_meet",
+ "none"
+ ]
+ },
+ "ConferenceProvider": {
+ "type": "string",
+ "description": "The conferencing system backing an event's join URL.\n\nMacro generates only Google Meet conferences, so this distinguishes one it\ncreated from a third party's — Zoom and friends arriving as `addOn`\nconference data, or a legacy classic Hangout. Clients use it to label the\nconference and to tell whether the Meet toggle reflects a Macro-managed\nconference.\n\nIt does not gate mutation. An explicit request replaces or detaches any\nconference, third-party included, exactly as deleting the event would;\nwhat protects a conference is that omitting the field leaves it untouched,\nso an unrelated edit never disturbs it.",
+ "enum": [
+ "google_meet",
+ "other"
+ ]
+ },
+ "CreateCalendarEventRequest": {
+ "type": "object",
+ "description": "Request body creating a calendar event on the requester's calendar.",
+ "required": [
+ "title",
+ "time"
+ ],
+ "properties": {
+ "attendees": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/CalendarAttendeeInputBody"
+ },
+ "description": "Invited attendees."
+ },
+ "calendarId": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "uuid",
+ "description": "Exact calendar to create the event on; takes precedence over the\ninbox default."
+ },
+ "conference": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ConferenceChange",
+ "description": "Conference to attach to the new event; omit to create it without one."
+ }
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Optional event body."
+ },
+ "emailLinkId": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "uuid",
+ "description": "Connected inbox whose primary calendar receives the event; defaults\nto the requester's primary inbox."
+ },
+ "location": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Optional location label."
+ },
+ "outOfOffice": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/OutOfOfficeProperties",
+ "description": "Out-of-office properties; present to create the event as a Google\nout-of-office status event (primary calendar only, timed, no\nattendees), omitted for a regular event."
+ }
+ ]
+ },
+ "recurrenceLines": {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "description": "Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`)."
+ },
+ "reminders": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EventReminders",
+ "description": "Reminder configuration; omit to keep the calendar defaults."
+ }
+ ]
+ },
+ "time": {
+ "$ref": "#/components/schemas/EventTime",
+ "description": "Timed or all-day shape."
+ },
+ "title": {
+ "type": "string",
+ "description": "Display title."
+ },
+ "transparency": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EventTransparency",
+ "description": "Availability behavior."
+ }
+ ]
+ },
+ "visibility": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EventVisibility",
+ "description": "Event visibility."
+ }
+ ]
+ }
+ }
+ },
+ "EventReminderOverride": {
+ "type": "object",
+ "description": "One reminder: how it alerts and how many minutes before the event start\n(before midnight in the calendar's zone for all-day events) it fires.",
+ "required": [
+ "method",
+ "minutes"
+ ],
+ "properties": {
+ "method": {
+ "type": "string",
+ "description": "Provider method, stored verbatim; only `popup` fires Macro\nnotifications."
+ },
+ "minutes": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Minutes before the event start.",
+ "minimum": 0
+ }
+ }
+ },
+ "EventReminders": {
+ "type": "object",
+ "description": "Per-user reminder configuration for an event, mirroring Google's model:\neither the calendar's default reminders apply, or the explicit overrides\nreplace them entirely.",
+ "required": [
+ "useDefault"
+ ],
+ "properties": {
+ "overrides": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/EventReminderOverride"
+ },
+ "description": "Explicit reminders replacing the defaults when `use_default` is off."
+ },
+ "useDefault": {
+ "type": "boolean",
+ "description": "Whether the calendar's default reminders apply."
+ }
+ }
+ },
+ "EventStatus": {
+ "type": "string",
+ "description": "Canonical event status.",
+ "enum": [
+ "confirmed",
+ "tentative",
+ "cancelled"
+ ]
+ },
+ "EventTime": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "An event with absolute instants.",
+ "required": [
+ "startsAt",
+ "endsAt",
+ "kind"
+ ],
+ "properties": {
+ "endsAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Exclusive end instant."
+ },
+ "kind": {
+ "type": "string",
+ "enum": [
+ "timed"
+ ]
+ },
+ "startsAt": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Inclusive start instant."
+ },
+ "timeZone": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Original IANA time-zone identifier, when supplied."
+ }
+ }
+ },
+ {
+ "type": "object",
+ "description": "An all-day event using RFC 5545's exclusive end date.",
+ "required": [
+ "startDate",
+ "endDate",
+ "kind"
+ ],
+ "properties": {
+ "endDate": {
+ "type": "string",
+ "format": "date",
+ "description": "Exclusive local end date."
+ },
+ "kind": {
+ "type": "string",
+ "enum": [
+ "allDay"
+ ]
+ },
+ "startDate": {
+ "type": "string",
+ "format": "date",
+ "description": "Inclusive local start date."
+ }
+ }
+ }
+ ],
+ "description": "The mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema."
+ },
+ "EventTransparency": {
+ "type": "string",
+ "description": "Whether an event blocks availability.",
+ "enum": [
+ "opaque",
+ "transparent"
+ ]
+ },
+ "EventType": {
+ "type": "string",
+ "description": "Google's event type: ordinary meetings versus the status-style entries\n(working location, out of office, focus time, birthdays) Google renders\nand notifies differently. Immutable at the provider after creation.",
+ "enum": [
+ "default",
+ "out_of_office",
+ "focus_time",
+ "working_location",
+ "birthday",
+ "from_gmail"
+ ]
+ },
+ "EventVisibility": {
+ "type": "string",
+ "description": "Visibility of event details.",
+ "enum": [
+ "default",
+ "public",
+ "private",
+ "confidential"
+ ]
+ },
+ "ListCalendarsResponse": {
+ "type": "object",
+ "description": "Calendars visible to the requester across connected and delegated inboxes.",
+ "required": [
+ "calendars"
+ ],
+ "properties": {
+ "calendars": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/VisibleCalendar"
+ },
+ "description": "Primaries and writable calendars first."
+ }
+ }
+ },
+ "OutOfOfficeAutoDeclineMode": {
+ "type": "string",
+ "description": "How an out-of-office event responds to conflicting invitations, mirroring\nGoogle's `autoDeclineMode`.",
+ "enum": [
+ "decline_none",
+ "decline_all_conflicting_invitations",
+ "decline_only_new_conflicting_invitations"
+ ]
+ },
+ "OutOfOfficeProperties": {
+ "type": "object",
+ "description": "The extra properties Google requires on an out-of-office event, mirroring\nits `outOfOfficeProperties` block. Their presence on a draft or patch is\nwhat marks the mutation as out-of-office.",
+ "properties": {
+ "autoDeclineMode": {
+ "$ref": "#/components/schemas/OutOfOfficeAutoDeclineMode",
+ "description": "How conflicting invitations are handled while the user is out."
+ },
+ "declineMessage": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Message returned to organizers whose invitations are auto-declined."
+ }
+ }
+ },
+ "RefreshCalendarEvent": {
+ "oneOf": [
+ {
+ "type": "object",
+ "description": "A sync run committed changes for `link_id`; viewers should refetch.",
+ "required": [
+ "link_id",
+ "event"
+ ],
+ "properties": {
+ "event": {
+ "type": "string",
+ "enum": [
+ "synced"
+ ]
+ },
+ "link_id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Connected inbox whose calendars changed."
+ }
+ }
+ }
+ ],
+ "description": "Realtime signal that a connected inbox's calendar projection changed."
+ },
+ "RsvpCalendarEventRequest": {
+ "type": "object",
+ "description": "Request body setting the requester's RSVP on an event.",
+ "required": [
+ "response"
+ ],
+ "properties": {
+ "calendarId": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "uuid",
+ "description": "Calendar whose copy of the event is answered, for an event synced\nfrom more than one calendar. Omit to answer on the canonical copy."
+ },
+ "recurrenceId": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Original-start key of the occurrence the response targets."
+ },
+ "response": {
+ "$ref": "#/components/schemas/AttendeeResponseStatus",
+ "description": "The response to record for the connected account."
+ },
+ "scope": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/CalendarRsvpScopeParam",
+ "description": "How much of a recurring series the response covers. Omit to let\n`recurrenceId` decide: the identified occurrence alone when one is\nsupplied, otherwise the whole series. An explicit `this_event` scope\nrequires `recurrenceId`, so a scoped request is never silently\nwidened to the series."
+ }
+ ]
+ }
+ }
+ },
+ "UpdateCalendarEventRequest": {
+ "type": "object",
+ "description": "Request body patching an event; omitted fields are left untouched.",
+ "properties": {
+ "attendees": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/components/schemas/CalendarAttendeeInputBody"
+ },
+ "description": "Replacement attendee list."
+ },
+ "calendarId": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "uuid",
+ "description": "Calendar whose copy of the event is patched, for an event synced from\nmore than one calendar. Omit to patch the canonical copy."
+ },
+ "conference": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/ConferenceChange",
+ "description": "Conference change: `google_meet` attaches a freshly generated Meet,\n`none` detaches the current conference, and omitting it leaves the\nconference untouched.\n\nA third-party conference is replaced or detached like any other, since\nthe request is explicit. Omit the field to leave it alone."
+ }
+ ]
+ },
+ "description": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Replacement description; an empty string clears it."
+ },
+ "location": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Replacement location; an empty string clears it."
+ },
+ "outOfOffice": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/OutOfOfficeProperties",
+ "description": "Replacement out-of-office properties, applied only to an event that is\nalready out-of-office — the provider event type is immutable. Omit to\nleave them untouched."
+ }
+ ]
+ },
+ "recurrenceId": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Original-start key of the occurrence the update targets."
+ },
+ "recurrenceLines": {
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "type": "string"
+ },
+ "description": "Replacement recurrence properties; an empty list clears them."
+ },
+ "reminders": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EventReminders",
+ "description": "Replacement reminder configuration."
+ }
+ ]
+ },
+ "scope": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/CalendarUpdateScopeParam",
+ "description": "How much of a recurring series the update covers. Omit to let\n`recurrenceId` decide: the identified occurrence alone when one is\nsupplied, otherwise the whole event or series. An explicit\n`this_event` scope requires `recurrenceId`, so a scoped request is\nnever silently widened to the series."
+ }
+ ]
+ },
+ "time": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EventTime",
+ "description": "Replacement time."
+ }
+ ]
+ },
+ "title": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Replacement title; an empty string clears it."
+ },
+ "transparency": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EventTransparency",
+ "description": "Replacement transparency."
+ }
+ ]
+ },
+ "visibility": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/EventVisibility",
+ "description": "Replacement visibility."
+ }
+ ]
+ }
+ }
+ },
+ "VisibleCalendar": {
+ "type": "object",
+ "description": "A calendar visible to a requester, listed for pickers and filters.",
+ "required": [
+ "id",
+ "emailLinkId",
+ "emailAddress",
+ "name",
+ "isPrimary",
+ "isWritable",
+ "isSubscription",
+ "defaultReminders"
+ ],
+ "properties": {
+ "color": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Provider color."
+ },
+ "defaultReminders": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/EventReminderOverride"
+ },
+ "description": "Default reminders applied to events that keep `useDefault`."
+ },
+ "emailAddress": {
+ "type": "string",
+ "description": "Connected inbox address, for grouping in multi-inbox pickers."
+ },
+ "emailLinkId": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Connected inbox that syncs this calendar."
+ },
+ "id": {
+ "type": "string",
+ "format": "uuid",
+ "description": "Persisted Macro calendar identifier."
+ },
+ "isPrimary": {
+ "type": "boolean",
+ "description": "Whether this is its account's primary calendar."
+ },
+ "isSubscription": {
+ "type": "boolean",
+ "description": "Whether this is one of Google's shared system calendars (holidays,\nbirthdays) the account subscribes to rather than one a person maintains."
+ },
+ "isWritable": {
+ "type": "boolean",
+ "description": "Whether the grant can create and modify events on this calendar."
+ },
+ "name": {
+ "type": "string",
+ "description": "Provider display name."
+ },
+ "syncError": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "A persistent sync failure isolated to this calendar, surfaced so the\nsettings row can badge it. `None` while the calendar is syncing\nnormally or a failure has not yet crossed the persistence threshold."
+ }
+ }
+ }
+ }
+ },
+ "tags": [
+ {
+ "name": "calendar_events",
+ "description": "Macro Calendar Service"
+ }
+ ]
+}
diff --git a/packages/sdk/src/config.ts b/packages/sdk/src/config.ts
index a90d9f543a..26648cb629 100644
--- a/packages/sdk/src/config.ts
+++ b/packages/sdk/src/config.ts
@@ -7,6 +7,7 @@ export type ServiceName =
| 'storage'
| 'auth'
| 'email'
+ | 'calendar'
| 'cognition'
| 'notification'
| 'properties'
@@ -29,6 +30,7 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {
storage: 'https://dev-gateway.macro.com/dss',
auth: 'https://dev-gateway.macro.com/auth',
email: 'https://dev-gateway.macro.com/email',
+ calendar: 'https://dev-gateway.macro.com/calendar',
cognition: 'https://dev-gateway.macro.com/cognition',
notification: 'https://dev-gateway.macro.com/notification',
properties: 'https://dev-gateway.macro.com/dss',
@@ -44,6 +46,7 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {
storage: 'https://gateway.macro.com/dss',
auth: 'https://gateway.macro.com/auth',
email: 'https://gateway.macro.com/email',
+ calendar: 'https://gateway.macro.com/calendar',
cognition: 'https://gateway.macro.com/cognition',
notification: 'https://gateway.macro.com/notification',
properties: 'https://gateway.macro.com/dss',
@@ -59,6 +62,12 @@ export const HOSTS: Record<Env, Record<ServiceName, string>> = {
storage: 'http://localhost:8086',
auth: 'http://localhost:8080',
email: 'http://localhost:8087',
+ // No gateway locally, and calendar_service is not in the local stack yet.
+ // email-service still serves /calendar/* on 8087, so the `/calendar` segment
+ // is carried in the base here (the client's paths are root-relative). Point
+ // this at calendar_service once it joins the local stack. Mirrors
+ // apps/web servers.ts (PR #6752).
+ calendar: 'http://localhost:8087/calendar',
cognition: 'http://localhost:8085',
notification: 'http://localhost:8089',
properties: 'http://localhost:8086',
diff --git a/packages/sdk/src/coverage/check.ts b/packages/sdk/src/coverage/check.ts
index 646810b2dd..cf7e2f58bb 100644
--- a/packages/sdk/src/coverage/check.ts
+++ b/packages/sdk/src/coverage/check.ts
@@ -19,6 +19,7 @@ const ROOT = join(import.meta.dir, '..', '..');
const ACCESSORS: Partial<Record<(typeof services)[number], string>> = {
'agent-harness': 'agentHarness',
auth: 'auth',
+ calendar: 'calendar',
cognition: 'cognition',
contacts: 'contacts',
email: 'email',
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index 1f62d7f039..89e6564d85 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -11,6 +11,7 @@
import type { Sdk as AgentHarnessSdk } from '../../generated/agent-harness/sdk.gen';
import type { Sdk as AuthSdk } from '../../generated/auth/sdk.gen';
+import type { Sdk as CalendarSdk } from '../../generated/calendar/sdk.gen';
import type { Sdk as CognitionSdk } from '../../generated/cognition/sdk.gen';
import type { Sdk as ConnectionSdk } from '../../generated/connection/sdk.gen';
import type { Sdk as ContactsSdk } from '../../generated/contacts/sdk.gen';
@@ -123,6 +124,14 @@ export const authBacklog = [
'macroApiToken',
] as const satisfies readonly (keyof AuthSdk)[];
+export const calendarExcluded = [
+ // Health probe is infra, not SDK surface.
+ 'healthHandler',
+] as const satisfies readonly (keyof CalendarSdk)[];
+
+export const calendarBacklog =
+ [] as const satisfies readonly (keyof CalendarSdk)[];
+
export const cognitionExcluded = [
'addMcpServer',
'browsePipedreamMcpCatalog',
diff --git a/packages/sdk/src/entities/calendar/calendar.ts b/packages/sdk/src/entities/calendar/calendar.ts
new file mode 100644
index 0000000000..9cab85772f
--- /dev/null
+++ b/packages/sdk/src/entities/calendar/calendar.ts
@@ -0,0 +1,59 @@
+import type { VisibleCalendar } from '../../../generated/calendar/types.gen';
+import { MacroNotFoundError, unwrap } from '../../utils';
+import type { MacroClient } from '../../utils/client';
+import { Link } from '../email/link';
+import { MacroEntity } from '../entity';
+
+/**
+ * A calendar visible to the requester across their connected inboxes: a
+ * free-to-construct handle whose detail resolves from the caller's calendar
+ * list. There is no fetch-by-id endpoint, so a bare {@link Calendar.byId}
+ * handle loads its detail by listing the caller's calendars and matching on id.
+ */
+export class Calendar extends MacroEntity<VisibleCalendar> {
+ protected async fetch(): Promise<VisibleCalendar> {
+ const { calendars } = unwrap(await this.client.calendar.listCalendars());
+ const found = calendars.find((calendar) => calendar.id === this.id);
+ if (!found) throw new MacroNotFoundError(`calendar ${this.id} not found`);
+ return found;
+ }
+
+ /** A handle to a calendar by id. Detail loads on first access. */
+ static byId(client: MacroClient, id: string): Calendar {
+ return new Calendar(client, id);
+ }
+
+ /** The caller's visible calendars, primaries and writable first. */
+ static async list(client: MacroClient): Promise<Calendar[]> {
+ const { calendars } = unwrap(await client.calendar.listCalendars());
+ return calendars.map(
+ (calendar) => new Calendar(client, calendar.id, calendar),
+ );
+ }
+
+ /** Provider display name. */
+ readonly name = this.field('name');
+
+ /** Connected inbox address that syncs this calendar. */
+ readonly emailAddress = this.field('emailAddress');
+
+ /** Whether this is its account's primary calendar. */
+ readonly isPrimary = this.field('isPrimary');
+
+ /** Whether the grant can create and modify events on this calendar. */
+ readonly isWritable = this.field('isWritable');
+
+ /** Whether this is a subscribed system calendar (holidays, birthdays). */
+ readonly isSubscription = this.field('isSubscription');
+
+ /** Provider color, when set. */
+ readonly color = this.field('color');
+
+ /** A persistent per-calendar sync failure, surfaced for settings badges. */
+ readonly syncError = this.field('syncError');
+
+ /** The connected inbox (email link) that syncs this calendar. */
+ readonly emailLink = this.mappedField('emailLinkId', (id) =>
+ Link.byId(this.client, id),
+ );
+}
diff --git a/packages/sdk/src/entities/calendar/event.test.ts b/packages/sdk/src/entities/calendar/event.test.ts
new file mode 100644
index 0000000000..270fe0cb26
--- /dev/null
+++ b/packages/sdk/src/entities/calendar/event.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, test } from 'bun:test';
+import type { CalendarEvent as CalendarEventRecord } from '../../../generated/calendar/types.gen';
+import { MacroError } from '../../utils';
+import type { MacroClient } from '../../utils/client';
+import { CalendarEvent } from './event';
+
+const client = new Proxy({} as MacroClient, {
+ get() {
+ throw new Error('Seeded state access must not fetch');
+ },
+});
+
+const record: CalendarEventRecord = {
+ id: 'event-1',
+ ownerId: 'macro|[email protected]',
+ calendarId: 'calendar-1',
+ icalUid: 'ical-1',
+ title: 'Standup',
+ description: 'Daily sync',
+ location: 'Room 1',
+ attendees: [],
+ recurrenceLines: [],
+ sequence: 0,
+ status: 'confirmed',
+ isReadOnly: false,
+ time: {
+ kind: 'timed',
+ startsAt: '2026-01-01T09:00:00Z',
+ endsAt: '2026-01-01T09:15:00Z',
+ },
+ transparency: 'opaque',
+ visibility: 'default',
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+};
+
+describe('CalendarEvent', () => {
+ test('a seeded handle reads fields without fetching', async () => {
+ const event = CalendarEvent.fromRecord(client, record);
+ expect(event.id).toBe('event-1');
+ expect(await event.title()).toBe('Standup');
+ expect(await event.description()).toBe('Daily sync');
+ expect(await event.isReadOnly()).toBe(false);
+ expect(await event.status()).toBe('confirmed');
+ expect(await event.record()).toEqual(record);
+ });
+
+ test('calendarId is exposed as a Calendar handle', async () => {
+ const event = CalendarEvent.fromRecord(client, record);
+ const calendar = await event.calendar();
+ expect(calendar?.id).toBe('calendar-1');
+ });
+
+ test('a bare byId handle has no fetch endpoint', async () => {
+ const event = CalendarEvent.byId(client, 'event-2');
+ expect(event.id).toBe('event-2');
+ await expect(event.title()).rejects.toBeInstanceOf(MacroError);
+ });
+});
diff --git a/packages/sdk/src/entities/calendar/event.ts b/packages/sdk/src/entities/calendar/event.ts
new file mode 100644
index 0000000000..fb5c4fbe2a
--- /dev/null
+++ b/packages/sdk/src/entities/calendar/event.ts
@@ -0,0 +1,212 @@
+import type {
+ AttendeeResponseStatus,
+ CalendarAttendeeInputBody,
+ CalendarDeletionScopeParam,
+ CalendarEvent as CalendarEventRecord,
+ CalendarRsvpScopeParam,
+ CalendarUpdateScopeParam,
+ ConferenceChange,
+ EventReminders,
+ EventTime,
+ EventTransparency,
+ EventVisibility,
+ OutOfOfficeProperties,
+ UpdateCalendarEventRequest,
+} from '../../../generated/calendar/types.gen';
+import { MacroError } from '../../utils';
+import type { MacroClient } from '../../utils/client';
+import { MacroEntity } from '../entity';
+import { Calendar } from './calendar';
+
+/** Fields to change on an event; omitted fields are left untouched. */
+export interface UpdateEventOptions {
+ /** Replacement title; an empty string clears it. */
+ title?: string;
+ /** Replacement description; an empty string clears it. */
+ description?: string;
+ /** Replacement location; an empty string clears it. */
+ location?: string;
+ /** Replacement time. */
+ time?: EventTime;
+ /** Replacement attendee list. */
+ attendees?: CalendarAttendeeInputBody[];
+ /** Replacement recurrence properties; an empty list clears them. */
+ recurrenceLines?: string[];
+ /** Replacement visibility. */
+ visibility?: EventVisibility;
+ /** Replacement availability behavior. */
+ transparency?: EventTransparency;
+ /** Replacement reminder configuration. */
+ reminders?: EventReminders;
+ /** `google_meet` attaches a fresh Meet, `none` detaches; omit to leave the
+ * conference untouched. */
+ conference?: ConferenceChange;
+ /** Replacement out-of-office properties, applied only to an event that is
+ * already out-of-office. */
+ outOfOffice?: OutOfOfficeProperties;
+ /** How much of a recurring series the update covers. Omit to let
+ * `recurrenceId` decide. */
+ scope?: CalendarUpdateScopeParam;
+ /** Original-start key of the occurrence the update targets. */
+ recurrenceId?: string;
+ /** Calendar whose copy of the event is patched, for a multi-calendar event.
+ * Omit to patch the canonical copy. */
+ calendar?: Calendar;
+}
+
+/** How a deletion is scoped across a recurring series. */
+export interface DeleteEventOptions {
+ /** Deletion scope; defaults to the entire event or series. */
+ scope?: CalendarDeletionScopeParam;
+ /** Original-start key of the occurrence a scoped deletion targets. */
+ recurrenceId?: string;
+ /** Calendar whose copy of the event is deleted, for a multi-calendar event.
+ * Omit to delete the canonical copy. */
+ calendar?: Calendar;
+}
+
+/** The RSVP to record and how it is scoped across a recurring series. */
+export interface RsvpEventOptions {
+ /** The response to record for the connected account. */
+ response: AttendeeResponseStatus;
+ /** How much of a recurring series the response covers. Omit to let
+ * `recurrenceId` decide. */
+ scope?: CalendarRsvpScopeParam;
+ /** Original-start key of the occurrence the response targets. */
+ recurrenceId?: string;
+ /** Calendar whose copy of the event is answered, for a multi-calendar event.
+ * Omit to answer on the canonical copy. */
+ calendar?: Calendar;
+}
+
+/**
+ * A Macro calendar event: a handle exposing the event's synced fields and the
+ * mutations that act on it ({@link CalendarEvent.update},
+ * {@link CalendarEvent.delete}, {@link CalendarEvent.rsvp}).
+ *
+ * The calendar service has no fetch-by-id endpoint, so a handle reads its
+ * fields only when seeded with a record — as returned by
+ * {@link CalendarEvent.update}, {@link CalendarEvent.rsvp}, or
+ * `calendar.createEvent`. A bare {@link CalendarEvent.byId} handle can drive
+ * mutations, but reading a field on it throws.
+ */
+export class CalendarEvent extends MacroEntity<CalendarEventRecord> {
+ protected async fetch(): Promise<CalendarEventRecord> {
+ throw new MacroError(
+ `calendar event ${this.id} has no fetch-by-id endpoint; read the record ` +
+ `returned by calendar.createEvent / event.update / event.rsvp instead`,
+ );
+ }
+
+ /** A handle to a calendar event by id, for driving mutations. Reading a
+ * field on it throws (there is no fetch-by-id endpoint). */
+ static byId(client: MacroClient, id: string): CalendarEvent {
+ return new CalendarEvent(client, id);
+ }
+
+ /** A handle seeded with a synced event record; reads resolve without a fetch. */
+ static fromRecord(
+ client: MacroClient,
+ record: CalendarEventRecord,
+ ): CalendarEvent {
+ return new CalendarEvent(client, record.id, record);
+ }
+
+ /** Display title. */
+ readonly title = this.field('title');
+
+ /** Optional event body. */
+ readonly description = this.field('description');
+
+ /** Optional physical or virtual location label. */
+ readonly location = this.field('location');
+
+ /** Timed or all-day shape. */
+ readonly time = this.field('time');
+
+ /** Event status. */
+ readonly status = this.field('status');
+
+ /** Attendees on the canonical copy. */
+ readonly attendees = this.field('attendees');
+
+ /** Availability behavior. */
+ readonly transparency = this.field('transparency');
+
+ /** Whether the canonical source's calendar prohibits editing. */
+ readonly isReadOnly = this.field('isReadOnly');
+
+ /** Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). */
+ readonly recurrenceLines = this.field('recurrenceLines');
+
+ /** The calendar the canonical source belongs to, when known. */
+ readonly calendar = this.mappedField('calendarId', (id) =>
+ id ? Calendar.byId(this.client, id) : undefined,
+ );
+
+ /** The full synced event record. Available on a seeded handle (from create /
+ * update / rsvp); a bare `byId` handle throws (no fetch-by-id endpoint). */
+ record(): Promise<CalendarEventRecord> {
+ return this.detail.get();
+ }
+
+ /** Update the event and return a handle to its synced record. */
+ async update(options: UpdateEventOptions): Promise<CalendarEvent> {
+ const record = await this.mutate((client) =>
+ client.calendar.updateCalendarEvent({
+ path: { event_id: this.id },
+ body: toUpdateBody(options),
+ }),
+ );
+ return CalendarEvent.fromRecord(this.client, record);
+ }
+
+ /** Delete the event (or a scoped part of a recurring series) at its provider. */
+ async delete(options: DeleteEventOptions = {}): Promise<void> {
+ await this.mutate((client) =>
+ client.calendar.deleteCalendarEvent({
+ path: { event_id: this.id },
+ query: {
+ calendarId: options.calendar?.id,
+ scope: options.scope,
+ recurrenceId: options.recurrenceId,
+ },
+ }),
+ );
+ }
+
+ /** Record the requester's RSVP and return a handle to the synced record. */
+ async rsvp(options: RsvpEventOptions): Promise<CalendarEvent> {
+ const record = await this.mutate((client) =>
+ client.calendar.rsvpCalendarEvent({
+ path: { event_id: this.id },
+ body: {
+ response: options.response,
+ scope: options.scope,
+ recurrenceId: options.recurrenceId,
+ calendarId: options.calendar?.id,
+ },
+ }),
+ );
+ return CalendarEvent.fromRecord(this.client, record);
+ }
+}
+
+function toUpdateBody(options: UpdateEventOptions): UpdateCalendarEventRequest {
+ return {
+ title: options.title,
+ description: options.description,
+ location: options.location,
+ time: options.time,
+ attendees: options.attendees,
+ recurrenceLines: options.recurrenceLines,
+ visibility: options.visibility,
+ transparency: options.transparency,
+ reminders: options.reminders,
+ conference: options.conference,
+ outOfOffice: options.outOfOffice,
+ scope: options.scope,
+ recurrenceId: options.recurrenceId,
+ calendarId: options.calendar?.id,
+ };
+}
diff --git a/packages/sdk/src/entities/calendar/namespace.ts b/packages/sdk/src/entities/calendar/namespace.ts
new file mode 100644
index 0000000000..2304ea589a
--- /dev/null
+++ b/packages/sdk/src/entities/calendar/namespace.ts
@@ -0,0 +1,99 @@
+import type {
+ CalendarAttendeeInputBody,
+ ConferenceChange,
+ CreateCalendarEventRequest,
+ EventReminders,
+ EventTime,
+ EventTransparency,
+ EventVisibility,
+ OutOfOfficeProperties,
+} from '../../../generated/calendar/types.gen';
+import { unwrap } from '../../utils';
+import type { MacroClient } from '../../utils/client';
+import type { Link } from '../email/link';
+import { Calendar } from './calendar';
+import { CalendarEvent } from './event';
+
+/** Fields for a new calendar event. */
+export interface CreateEventOptions {
+ /** Display title. */
+ title: string;
+ /** Timed or all-day shape. */
+ time: EventTime;
+ /** Optional event body. */
+ description?: string;
+ /** Optional location label. */
+ location?: string;
+ /** Invited attendees. */
+ attendees?: CalendarAttendeeInputBody[];
+ /** Raw RFC 5545 recurrence properties (`RRULE`, `RDATE`, `EXDATE`). */
+ recurrenceLines?: string[];
+ /** Event visibility. */
+ visibility?: EventVisibility;
+ /** Availability behavior. */
+ transparency?: EventTransparency;
+ /** Reminder configuration; omit to keep the calendar defaults. */
+ reminders?: EventReminders;
+ /** Conference to attach; omit to create the event without one. */
+ conference?: ConferenceChange;
+ /** Out-of-office properties; present to create a Google out-of-office event. */
+ outOfOffice?: OutOfOfficeProperties;
+ /** Exact calendar to create the event on; takes precedence over the inbox
+ * default. */
+ calendar?: Calendar;
+ /** Connected inbox whose primary calendar receives the event; defaults to the
+ * requester's primary inbox. */
+ emailLink?: Link;
+}
+
+/**
+ * The calendar surface: the caller's visible calendars, event creation, and
+ * handles to individual events and calendars. Backed by calendar_service (the
+ * SDK reaches it on the gateway's `/calendar` route).
+ */
+export class CalendarNamespace {
+ constructor(private readonly client: MacroClient) {}
+
+ /** The caller's visible calendars, primaries and writable first. */
+ calendars(): Promise<Calendar[]> {
+ return Calendar.list(this.client);
+ }
+
+ /** A handle to a calendar by id. Detail loads on first access. */
+ calendar(id: string): Calendar {
+ return Calendar.byId(this.client, id);
+ }
+
+ /** A handle to a calendar event by id, for driving mutations. */
+ event(id: string): CalendarEvent {
+ return CalendarEvent.byId(this.client, id);
+ }
+
+ /** Create a calendar event and return a handle to its synced record. */
+ async createEvent(options: CreateEventOptions): Promise<CalendarEvent> {
+ const record = unwrap(
+ await this.client.calendar.createCalendarEvent({
+ body: toCreateBody(options),
+ }),
+ );
+ return CalendarEvent.fromRecord(this.client, record);
+ }
+}
+
+function toCreateBody(options: CreateEventOptions): CreateCalendarEventRequest {
+ return {
+ title: options.title,
+ time: options.time,
+ description: options.description,
+ location: options.location,
+ attendees: options.attendees,
+ recurrenceLines: options.recurrenceLines,
+ visibility: options.visibility,
+ transparency: options.transparency,
+ reminders: options.reminders,
+ conference: options.conference,
+ outOfOffice: options.outOfOffice,
+ calendarId: options.calendar?.id,
+ emailLinkId: options.emailLink?.id,
+ };
+}
diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.ts
index 6da9c25a54..a8424269ad 100644
--- a/packages/sdk/src/macro.ts
+++ b/packages/sdk/src/macro.ts
@@ -1,6 +1,7 @@
import type { MacroOpts } from './config';
import { AgentSessionNamespace } from './entities/agent-sessions/namespace';
import { BotsNamespace } from './entities/bots/namespace';
+import { CalendarNamespace } from './entities/calendar/namespace';
import { CallRecordNamespace } from './entities/calls/namespace';
import { ChannelNamespace } from './entities/channels/namespace';
import { ChatNamespace } from './entities/chats/namespace';
@@ -38,6 +39,7 @@ export {
export class Macro<T extends MacroOpts = MacroOpts> {
readonly agentSessions: AgentSessionNamespace;
readonly bots: BotsNamespace;
+ readonly calendar: CalendarNamespace;
readonly calls: CallRecordNamespace;
readonly channels: ChannelNamespace;
readonly chats: ChatNamespace;
@@ -67,6 +69,7 @@ export class Macro<T extends MacroOpts = MacroOpts> {
this._client = client;
this.agentSessions = new AgentSessionNamespace(client);
this.bots = new BotsNamespace(client);
+ this.calendar = new CalendarNamespace(client);
this.calls = new CallRecordNamespace(client);
this.channels = new ChannelNamespace(client);
this.chats = new ChatNamespace(client);
diff --git a/packages/sdk/src/utils/client.ts b/packages/sdk/src/utils/client.ts
index 8df507a8b6..7102f1d93d 100644
--- a/packages/sdk/src/utils/client.ts
+++ b/packages/sdk/src/utils/client.ts
@@ -1,6 +1,7 @@
import { match, P } from 'ts-pattern';
import { Sdk as AgentHarnessSdk } from '../../generated/agent-harness/sdk.gen';
import { Sdk as AuthSdk } from '../../generated/auth/sdk.gen';
+import { Sdk as CalendarSdk } from '../../generated/calendar/sdk.gen';
import { Sdk as CognitionSdk } from '../../generated/cognition/sdk.gen';
import { Sdk as ContactsSdk } from '../../generated/contacts/sdk.gen';
import { Sdk as EmailSdk } from '../../generated/email/sdk.gen';
@@ -95,6 +96,7 @@ export async function requestAuthHeaders(
export class MacroClient {
readonly agentHarness: AgentHarnessSdk;
readonly auth: AuthSdk;
+ readonly calendar: CalendarSdk;
readonly cognition: CognitionSdk;
readonly contacts: ContactsSdk;
readonly email: EmailSdk;
@@ -142,6 +144,9 @@ export class MacroClient {
client: this.makeClient(hosts['agent-harness']),
});
this.auth = new AuthSdk({ client: this.makeClient(hosts.auth) });
+ this.calendar = new CalendarSdk({
+ client: this.makeClient(hosts.calendar),
+ });
this.cognition = new CognitionSdk({
client: this.makeClient(hosts.cognition),
});
diff --git a/services/calendar_service/src/api/swagger.rs b/services/calendar_service/src/api/swagger.rs
index 566f0830df..bddff411d3 100644
--- a/services/calendar_service/src/api/swagger.rs
+++ b/services/calendar_service/src/api/swagger.rs
@@ -1,6 +1,42 @@
use utoipa::OpenApi;
/// OpenAPI document for the calendar service.
+///
+/// The calendar mutation operations live in the shared `calendar_events` crate
+/// and are served here (and, for cutover, also under `/calendar`). Their
+/// `utoipa::path` annotations carry the `/calendar` prefix because email-service
+/// serves the same handlers under `/email/calendar/*`; the SDK's spec sync
+/// strips that prefix so a calendar client can carry `/calendar` in its base.
#[derive(OpenApi)]
-#[openapi(paths(crate::health::health_handler))]
+#[openapi(
+ paths(
+ crate::health::health_handler,
+ calendar_events::inbound::mutation_router::list_calendars,
+ calendar_events::inbound::mutation_router::create_calendar_event,
+ calendar_events::inbound::mutation_router::update_calendar_event,
+ calendar_events::inbound::mutation_router::delete_calendar_event,
+ calendar_events::inbound::mutation_router::rsvp_calendar_event,
+ ),
+ components(schemas(
+ calendar_events::inbound::mutation_router::CreateCalendarEventRequest,
+ calendar_events::inbound::mutation_router::ListCalendarsResponse,
+ calendar_events::domain::models::VisibleCalendar,
+ calendar_events::inbound::mutation_router::UpdateCalendarEventRequest,
+ calendar_events::inbound::mutation_router::RsvpCalendarEventRequest,
+ calendar_events::inbound::mutation_router::CalendarAttendeeInputBody,
+ calendar_events::inbound::mutation_router::CalendarMutationApiError,
+ calendar_events::inbound::mutation_router::CalendarMutationErrorCode,
+ calendar_events::inbound::mutation_router::CalendarDeletionScopeParam,
+ calendar_events::inbound::mutation_router::CalendarUpdateScopeParam,
+ calendar_events::domain::models::CalendarEvent,
+ calendar_events::domain::models::CalendarAttendee,
+ calendar_events::domain::models::AttendeeResponseStatus,
+ calendar_events::domain::models::EventTime,
+ calendar_events::domain::models::EventStatus,
+ calendar_events::domain::models::EventVisibility,
+ calendar_events::domain::models::EventTransparency,
+ calendar_events::domain::models::RefreshCalendarEvent,
+ )),
+ tags((name = "calendar_events", description = "Macro Calendar Service"))
+)]
pub struct ApiDoc;