Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -0,0 +1,115 @@
// AK-P16a · provider-agnostic CalendarAdapter contract (M25 Block G).
//
// v1 ships only the Google implementation (GoogleCalendarAdapter.server.ts);
// Outlook/Microsoft is a v2 adapter against this SAME interface. The adapter is a
// thin PROVIDER BOUNDARY: given decrypted creds it performs one network op and
// returns provider-neutral data. The per-user orchestration (cursor persistence,
// mapping upserts, Last-Write-Wins) lives in the sync services, not here.
//
// Neutral types deliberately avoid any Google naming so a second provider drops in
// without leaking provider shapes into the domain layer.
/** A connection's decrypted OAuth credentials (the engine handles envelope crypto). */
export interface CalendarCreds {
readonly accessToken: string;
readonly refreshToken: string;
readonly expiresAt?: Date | null;
}
export interface CalendarTokens {
readonly accessToken: string;
/** Present on the initial code exchange; absent on a refresh. */
readonly refreshToken?: string;
readonly expiresAt: Date;
readonly scopes: readonly string[];
}
export interface CalendarAccount {
readonly email: string;
readonly accountId: string;
}
export interface NeutralCalendar {
readonly id: string;
readonly name: string;
readonly isPrimary: boolean;
}
export interface NeutralEvent {
readonly externalId: string;
/** false when the provider reports the event as cancelled/deleted. */
readonly isActive: boolean;
readonly title: string | null;
readonly description: string | null;
readonly location: string | null;
readonly startsAt: Date;
readonly endsAt: Date;
readonly isAllDay: boolean;
readonly timeZone: string | null;
readonly recurrenceRule: string | null;
readonly attendees: ReadonlyArray<{ email: string; status: string | null }>;
readonly etag: string | null;
readonly lastModifiedExternal: Date | null;
/** Whether this event blocks availability (false = provider "Free"). */
readonly isBusy: boolean;
}
export interface NeutralEventInput {
readonly title: string;
readonly description?: string;
readonly location?: string;
readonly startsAt: Date;
readonly endsAt: Date;
readonly isAllDay?: boolean;
readonly timeZone?: string;
readonly attendees?: ReadonlyArray<{ email: string }>;
}
export interface DeltaResult {
readonly events: readonly NeutralEvent[];
/** Persist as the next cursor when present (page complete). */
readonly nextSyncToken?: string;
/** Continue paging within the same sync when present. */
readonly nextPageToken?: string;
/** True when the cursor expired (HTTP 410) → caller must full-resync. */
readonly fullResyncRequired?: boolean;
}
export interface WebhookSubscription {
readonly subscriptionId: string;
readonly resourceId: string;
readonly expiresAt: Date | null;
}
export interface WriteResult {
readonly externalId: string;
readonly etag: string | null;
}
/** Thrown by updateEvent when the provider reports a concurrent external edit. */
export class CalendarConflictError extends Error {
constructor(message = "external_concurrent_edit") {
super(message);
this.name = "CalendarConflictError";
}
}
export interface CalendarAdapter {
readonly provider: "google";
/** True only when the provider OAuth config is present (EXT-10 env). */
isConfigured(): boolean;
buildAuthorizationUrl(state: string): string;
exchangeCode(code: string): Promise<{ tokens: CalendarTokens; account: CalendarAccount }>;
refreshTokens(refreshToken: string): Promise<CalendarTokens>;
listCalendars(creds: CalendarCreds): Promise<NeutralCalendar[]>;
subscribeWebhook(creds: CalendarCreds, calendarId: string, channelId: string, address: string, token: string): Promise<WebhookSubscription>;
unsubscribeWebhook(creds: CalendarCreds, subscriptionId: string, resourceId: string): Promise<void>;
fetchEvents(
creds: CalendarCreds,
calendarId: string,
opts: { syncToken?: string; pageToken?: string; timeMin?: Date; timeMax?: Date },
): Promise<DeltaResult>;
createEvent(creds: CalendarCreds, calendarId: string, input: NeutralEventInput): Promise<WriteResult>;
updateEvent(creds: CalendarCreds, calendarId: string, externalId: string, input: NeutralEventInput, ifMatchEtag?: string | null): Promise<WriteResult>;
deleteEvent(creds: CalendarCreds, calendarId: string, externalId: string): Promise<void>;
}
@@ -0,0 +1,180 @@
// AK-P16a · Google implementation of the provider-agnostic CalendarAdapter.
//
// Maps the neutral domain shapes to/from the shared @hivegrid/integrations Google
// REST client. No Prisma here — the adapter only does network I/O against Google
// and provider↔neutral mapping. Token storage/crypto + orchestration live in the
// sync services.
import {
buildAuthorizationUrl,
deleteEvent as gDeleteEvent,
exchangeCodeForTokens,
fetchUserInfo,
GoogleCalendarError,
insertEvent,
listCalendars as gListCalendars,
listEvents,
patchEvent,
refreshAccessToken,
resolveGoogleOAuthConfig,
stopChannel,
watchCalendar,
type GoogleEvent,
type GoogleEventInput,
type GoogleOAuthConfig,
} from "@hivegrid/integrations";
import {
CalendarConflictError,
type CalendarAccount,
type CalendarAdapter,
type CalendarCreds,
type CalendarTokens,
type DeltaResult,
type NeutralCalendar,
type NeutralEvent,
type NeutralEventInput,
type WebhookSubscription,
type WriteResult,
} from "./CalendarAdapter";
/** Thrown when the OAuth config (EXT-10 env) is absent — surfaced as Klartext. */
export class CalendarNotConfiguredError extends Error {
constructor() {
super("calendar_not_configured");
this.name = "CalendarNotConfiguredError";
}
}
function requireConfig(): GoogleOAuthConfig {
const config = resolveGoogleOAuthConfig();
if (!config) {
throw new CalendarNotConfiguredError();
}
return config;
}
function parseBoundary(b: { dateTime?: string; date?: string } | undefined): { at: Date; isAllDay: boolean } {
if (b?.dateTime) {
return { at: new Date(b.dateTime), isAllDay: false };
}
if (b?.date) {
return { at: new Date(`${b.date}T00:00:00.000Z`), isAllDay: true };
}
return { at: new Date(0), isAllDay: false };
}
function toNeutralEvent(g: GoogleEvent): NeutralEvent {
const start = parseBoundary(g.start);
const end = parseBoundary(g.end);
return {
externalId: g.id,
isActive: g.status !== "cancelled",
title: g.summary ?? null,
description: g.description ?? null,
location: g.location ?? null,
startsAt: start.at,
endsAt: end.at,
isAllDay: start.isAllDay || end.isAllDay,
timeZone: g.start?.timeZone ?? null,
recurrenceRule: g.recurrence && g.recurrence.length > 0 ? g.recurrence[0] : null,
attendees: (g.attendees ?? []).map((a) => ({ email: a.email ?? "", status: a.responseStatus ?? null })),
etag: g.etag ?? null,
lastModifiedExternal: g.updated ? new Date(g.updated) : null,
// Google "transparent" == Free → not busy. Default (opaque/undefined) = busy.
isBusy: g.transparency !== "transparent",
};
}
function toGoogleInput(input: NeutralEventInput): GoogleEventInput {
const tz = input.timeZone ?? "UTC";
const boundary = (d: Date): GoogleEventInput["start"] =>
input.isAllDay ? { date: d.toISOString().slice(0, 10) } : { dateTime: d.toISOString(), timeZone: tz };
return {
summary: input.title,
description: input.description,
location: input.location,
start: boundary(input.startsAt),
end: boundary(input.endsAt),
attendees: input.attendees ? input.attendees.map((a) => ({ email: a.email })) : undefined,
};
}
export const googleCalendarAdapter: CalendarAdapter = {
provider: "google",
isConfigured(): boolean {
return resolveGoogleOAuthConfig() !== null;
},
buildAuthorizationUrl(state: string): string {
return buildAuthorizationUrl(requireConfig(), state);
},
async exchangeCode(code: string): Promise<{ tokens: CalendarTokens; account: CalendarAccount }> {
const config = requireConfig();
const tokenSet = await exchangeCodeForTokens(config, code);
const info = await fetchUserInfo(tokenSet.accessToken);
return {
tokens: { accessToken: tokenSet.accessToken, refreshToken: tokenSet.refreshToken, expiresAt: tokenSet.expiresAt, scopes: tokenSet.scopes },
account: { email: info.email, accountId: info.sub },
};
},
async refreshTokens(refreshToken: string): Promise<CalendarTokens> {
const set = await refreshAccessToken(requireConfig(), refreshToken);
return { accessToken: set.accessToken, refreshToken: set.refreshToken, expiresAt: set.expiresAt, scopes: set.scopes };
},
async listCalendars(creds: CalendarCreds): Promise<NeutralCalendar[]> {
const cals = await gListCalendars(creds.accessToken);
return cals.map((c) => ({ id: c.id, name: c.summary, isPrimary: c.primary }));
},
async subscribeWebhook(creds: CalendarCreds, calendarId: string, channelId: string, address: string, token: string): Promise<WebhookSubscription> {
const channel = await watchCalendar(creds.accessToken, calendarId, channelId, address, token);
return { subscriptionId: channel.channelId, resourceId: channel.resourceId, expiresAt: channel.expiresAt };
},
async unsubscribeWebhook(creds: CalendarCreds, subscriptionId: string, resourceId: string): Promise<void> {
await stopChannel(creds.accessToken, subscriptionId, resourceId);
},
async fetchEvents(creds: CalendarCreds, calendarId: string, opts): Promise<DeltaResult> {
try {
const page = await listEvents(creds.accessToken, calendarId, {
syncToken: opts.syncToken,
pageToken: opts.pageToken,
timeMin: opts.timeMin?.toISOString(),
timeMax: opts.timeMax?.toISOString(),
});
return { events: page.events.map(toNeutralEvent), nextSyncToken: page.nextSyncToken, nextPageToken: page.nextPageToken };
} catch (error) {
if (error instanceof GoogleCalendarError && error.fullResyncRequired) {
return { events: [], fullResyncRequired: true };
}
throw error;
}
},
async createEvent(creds: CalendarCreds, calendarId: string, input: NeutralEventInput): Promise<WriteResult> {
const result = await insertEvent(creds.accessToken, calendarId, toGoogleInput(input));
return { externalId: result.id, etag: result.etag ?? null };
},
async updateEvent(creds: CalendarCreds, calendarId: string, externalId: string, input: NeutralEventInput, ifMatchEtag?: string | null): Promise<WriteResult> {
try {
const result = await patchEvent(creds.accessToken, calendarId, externalId, toGoogleInput(input), ifMatchEtag ?? undefined);
return { externalId: result.id, etag: result.etag ?? null };
} catch (error) {
// 412 precondition-failed = a concurrent external edit (M25 Block F).
if (error instanceof GoogleCalendarError && error.httpStatus === 412) {
throw new CalendarConflictError();
}
throw error;
}
},
async deleteEvent(creds: CalendarCreds, calendarId: string, externalId: string): Promise<void> {
await gDeleteEvent(creds.accessToken, calendarId, externalId);
},
};