@gravity-rail/sdk 0.18.1 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/{chunk-2YLKG4TT.js → chunk-3HAV5XUJ.js} +1 -1
  2. package/dist/chunk-3HAV5XUJ.js.map +1 -0
  3. package/dist/{chunk-PJFEGUHM.js → chunk-7OLBLLV7.js} +6 -2
  4. package/dist/{chunk-PJFEGUHM.js.map → chunk-7OLBLLV7.js.map} +1 -1
  5. package/dist/{chunk-PUIYXJSZ.js → chunk-WMA6YCAS.js} +496 -41
  6. package/dist/chunk-WMA6YCAS.js.map +1 -0
  7. package/dist/{client-B-jmQ4UA.d.cts → client-C10qSd6b.d.ts} +1678 -285
  8. package/dist/{client-CatNn6FD.d.ts → client-Ct0soeip.d.cts} +1678 -285
  9. package/dist/helpers.cjs +141 -0
  10. package/dist/helpers.cjs.map +1 -1
  11. package/dist/helpers.d.cts +17 -3
  12. package/dist/helpers.d.ts +17 -3
  13. package/dist/helpers.js +127 -1
  14. package/dist/helpers.js.map +1 -1
  15. package/dist/index.cjs +595 -41
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +28 -5
  18. package/dist/index.d.ts +28 -5
  19. package/dist/index.js +123 -5
  20. package/dist/index.js.map +1 -1
  21. package/dist/internal.cjs +502 -41
  22. package/dist/internal.cjs.map +1 -1
  23. package/dist/internal.d.cts +630 -551
  24. package/dist/internal.d.ts +630 -551
  25. package/dist/internal.js +9 -5
  26. package/dist/internal.js.map +1 -1
  27. package/dist/{revision-state-Fw1jsQOa.d.ts → revision-state-C6aM-PHu.d.ts} +53 -172
  28. package/dist/{revision-state-CuESPYpi.d.cts → revision-state-CCPTiW-i.d.cts} +53 -172
  29. package/dist/schemas.cjs +31 -5
  30. package/dist/schemas.cjs.map +1 -1
  31. package/dist/schemas.d.cts +37 -14
  32. package/dist/schemas.d.ts +37 -14
  33. package/dist/schemas.js +31 -6
  34. package/dist/schemas.js.map +1 -1
  35. package/dist/{tasks-GVbVa_Lj.d.cts → tasks-WH_VfzMv.d.cts} +351 -16
  36. package/dist/{tasks-GVbVa_Lj.d.ts → tasks-WH_VfzMv.d.ts} +351 -16
  37. package/package.json +6 -6
  38. package/dist/chunk-2YLKG4TT.js.map +0 -1
  39. package/dist/chunk-PUIYXJSZ.js.map +0 -1
@@ -120,4 +120,4 @@ export {
120
120
  AttendeeStatus,
121
121
  AttendeeResponseStatus
122
122
  };
123
- //# sourceMappingURL=chunk-2YLKG4TT.js.map
123
+ //# sourceMappingURL=chunk-3HAV5XUJ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types/generated/data.ts","../src/types/data-types.ts","../src/types/calendar-types.ts"],"sourcesContent":["/**\n * Generated by Orval, grouped by scripts/types-codegen/group_generated.ts\n * (group map from emit_openapi.py). Do not edit manually.\n * Group: data\n */\n\nimport type { EventRuleResponse } from './event_rule';\nimport type { EnumOption } from './schema_field';\n\n/**\n * Response for bulk create data records operation.\n */\nexport interface BulkCreateDataRecordResponse {\n importedCount: number;\n totalCount: number;\n success: boolean;\n results: BulkRecordResult[];\n errors?: string[] | null;\n}\n\n/**\n * Result for a single record in a bulk import operation.\n */\nexport interface BulkRecordResult {\n index: number;\n status: BulkRecordResultStatus;\n recordId?: number | null;\n externalId?: string | null;\n error?: string | null;\n}\n\nexport type BulkRecordResultStatus = typeof BulkRecordResultStatus[keyof typeof BulkRecordResultStatus];\n\n\nexport const BulkRecordResultStatus = {\n created: 'created',\n updated: 'updated',\n failed: 'failed',\n} as const;\n\nexport type DataFieldType = typeof DataFieldType[keyof typeof DataFieldType];\n\n\nexport const DataFieldType = {\n enum: 'enum',\n email: 'email',\n phone: 'phone',\n text: 'text',\n longtext: 'longtext',\n number: 'number',\n integer: 'integer',\n boolean: 'boolean',\n date: 'date',\n datetime: 'datetime',\n time_of_day: 'time_of_day',\n us_zip_code: 'us_zip_code',\n array: 'array',\n object: 'object',\n function: 'function',\n} as const;\n\nexport interface DataRecordResponse {\n id: number;\n dataTypeId: number;\n memberId: number | null;\n memberName?: string | null;\n fieldValues: DataRecordResponseFieldValues;\n createdAt: string;\n updatedAt: string;\n externalId?: string | null;\n accessMode?: number | null;\n retirement?: DataRecordRetirementResponse | null;\n}\n\nexport type DataRecordResponseFieldValues = { [key: string]: unknown };\n\n/**\n * Derived lifecycle-retirement status for a connector-backed record.\n *\n * Populated only on the human Forms/CRUD read responses (list + single GET)\n * so the UI can show an \"Archived in Monday\" / \"Deleted in Monday\" badge.\n * Derived at read time from ``ConnectionEntityExclusion`` + active-link\n * state — there is no stored retirement column on ``DataRecord``.\n *\n * PHI-safe: closed-vocabulary ``status`` / ``reason`` / ``source`` codes\n * only. No field values, no remote item/board IDs, no connection metadata.\n */\nexport interface DataRecordRetirementResponse {\n status?: 'retired';\n reason: DataRecordRetirementResponseReason;\n source?: 'monday';\n}\n\nexport type DataRecordRetirementResponseReason = typeof DataRecordRetirementResponseReason[keyof typeof DataRecordRetirementResponseReason];\n\n\nexport const DataRecordRetirementResponseReason = {\n monday_item_archived: 'monday_item_archived',\n monday_item_deleted: 'monday_item_deleted',\n} as const;\n\nexport interface DataRecordUpdateResponse {\n id: number;\n dataRecordId: number;\n actorMemberId?: number | null;\n recordMemberId?: number | null;\n fieldName: string;\n oldValue: string | null;\n newValue: string | null;\n createdAt: string;\n updatedAt: string;\n assignmentTaskId?: number | null;\n memberName?: string | null;\n source?: string | null;\n}\n\nexport interface DataTypeMemberRoleAccessResponse {\n memberRoleId: number;\n memberRoleName: string;\n accessMode: number;\n}\n\nexport interface DataTypeResponse {\n id: number;\n name: string;\n uuid: string;\n slug: string;\n accessMode?: number | null;\n description: string | null;\n prompt: string | null;\n isCollection: boolean;\n pinned?: boolean | null;\n archived?: boolean;\n ownerId?: number | null;\n recordScope: string;\n sensitivity: string;\n categories: string[];\n createdAt: string;\n updatedAt: string;\n eventRules: EventRuleResponse[];\n fields: SchemaField[];\n memberRoleAccess?: DataTypeMemberRoleAccessResponse[];\n recordCount?: number | null;\n}\n\nexport interface IndexStatusResponse {\n fieldId: string;\n fieldName: string;\n shouldIndex: string;\n indexStatus: string;\n message?: string | null;\n}\n\n/**\n * Strongly-typed field definition for DataType schemas.\n */\nexport interface SchemaField {\n /** Unique field identifier */\n slug: string;\n /** Display name for the field */\n name: string;\n /** Optional field description */\n description?: string | null;\n /** Field type (text, email, enum, etc.) */\n fieldType?: typeof SchemaFieldFieldType[keyof typeof SchemaFieldFieldType];\n /** Whether field is required */\n required?: boolean;\n /** Deprecated: Display order is now determined by array position */\n order?: number | null;\n /** Options for enum fields as {label, value} objects. */\n options?: EnumOption[] | null;\n /** Referenced DataType ID for reference fields */\n referencedTypeId?: number | null;\n /** Whether to index this field */\n shouldIndex?: boolean;\n /** Whether only admins can see this field */\n adminOnly?: boolean;\n /** Default value for the field */\n defaultValue?: unknown;\n /** CEL expression that computes this field's value. CONSTRAINT: Can ONLY reference regular fields (TEXT, NUMBER, DATE, etc.). Cannot reference other FUNCTION fields. Syntax: record.data.<field_slug>. Example: 'record.data.score1 + record.data.score2' */\n celFunction?: string | null;\n /** CEL expression for cross-field validation. Context: 'value' (current field value), 'record.data.<field_slug>' (other fields). Returns: true if valid, or a string error message if invalid. CONSTRAINT: Can only reference non-FUNCTION fields. Example: 'value >= record.data.min_score' or 'value < record.data.min_score ? \"Must be >= \" + string(record.data.min_score) : true' */\n validateCel?: string | null;\n /** Disclosure severity for audit and access policy */\n sensitivity?: SchemaFieldSensitivity;\n /** Regulatory or content categories for audit and policy */\n categories?: SchemaFieldCategoriesItem[];\n}\n\nexport type SchemaFieldCategoriesItem = typeof SchemaFieldCategoriesItem[keyof typeof SchemaFieldCategoriesItem];\n\n\nexport const SchemaFieldCategoriesItem = {\n personal: 'personal',\n identifier: 'identifier',\n phi: 'phi',\n credential: 'credential',\n} as const;\n\nexport const SchemaFieldFieldType = { enum: 'enum',\n email: 'email',\n phone: 'phone',\n text: 'text',\n longtext: 'longtext',\n number: 'number',\n integer: 'integer',\n boolean: 'boolean',\n date: 'date',\n datetime: 'datetime',\n time_of_day: 'time_of_day',\n us_zip_code: 'us_zip_code',\n array: 'array',\n object: 'object',\n function: 'function'} as const\n\n/**\n * Disclosure severity for audit and access policy\n */\nexport type SchemaFieldSensitivity = typeof SchemaFieldSensitivity[keyof typeof SchemaFieldSensitivity];\n\n\nexport const SchemaFieldSensitivity = {\n public: 'public',\n internal: 'internal',\n confidential: 'confidential',\n restricted: 'restricted',\n secret: 'secret',\n} as const;\n","// Data-related types.\n// Server response shapes are generated from Pydantic via emit_openapi.py → Orval.\n// Client-only shapes (enums, forms, report items) are defined below.\n\nimport type { SchemaField } from './generated/data';\n\n// ===== GENERATED SERVER TYPES =====\n\nexport type {\n DataRecordResponse,\n DataRecordResponse as DataRecord,\n DataRecordRetirementResponse,\n DataRecordUpdateResponse,\n DataRecordUpdateResponse as DataRecordUpdate,\n DataTypeMemberRoleAccessResponse,\n DataTypeResponse,\n DataTypeResponse as DataType,\n IndexStatusResponse,\n SchemaField,\n} from './generated/data';\n\nexport type {\n DataRecordFilterResponse,\n DataRecordFilterResponse as DataRecordFilter,\n CreateDataRecordFilterRequest,\n UpdateDataRecordFilterRequest,\n} from './generated/data_record_filter';\n\nexport { DataRecordRetirementResponseReason } from './generated/data';\n\n// Field-slug rename (preview + apply). Value-free by construction: counts, ids,\n// schema slugs and closed-vocabulary blocker codes only.\nexport type {\n FieldReferenceImpact,\n FieldSlugRenamePreview,\n FieldSlugRenameResult,\n} from './generated/data_type_field_rename_service';\n\nimport type { DataRecordFilterResponse as GeneratedDataRecordFilterResponse } from './generated/data_record_filter';\nimport type { QueryPredicate } from './query-engine-types';\n\n/** DataRecordFilter with the query-engine predicate column narrowed to IR. */\nexport type DataRecordFilterWithQuery = GeneratedDataRecordFilterResponse & {\n query?: QueryPredicate | null;\n};\n\nexport interface DataRecordFilterFormData {\n dataTypeId: number;\n name: string;\n description?: string;\n pinned?: boolean;\n /** Query-engine predicate (JSON IR). Pass null to author an empty filter. */\n query: QueryPredicate | null;\n}\n\n// Pagination wrapper for data records (the backend uses an inline shape, not\n// a top-level Pydantic generic, so there is no generated equivalent).\nexport interface DataRecordsPaginatedResponse {\n items: DataRecordResponse[];\n total: number;\n page: number;\n pageSize: number;\n totalPages: number;\n}\n\n// Local import for use in `extends` clauses\nimport type { DataRecordResponse } from './generated/data';\n\n// ===== CLIENT-ONLY SURFACE =====\n// Enums, form shapes, report items, and query helpers that have no direct\n// Pydantic counterpart (or that the frontend builds in a different shape).\n\nimport type { AccountReportItem } from './account-types';\nimport type { EventRuleInput } from './event-types';\nimport type { MemberReportItem } from './member-types';\n\n// Field type enum (kept as TypeScript enum; widely used for comparisons)\nexport enum DataFieldType {\n ENUM = 'enum',\n EMAIL = 'email',\n PHONE = 'phone',\n TEXT = 'text',\n LONGTEXT = 'longtext',\n NUMBER = 'number',\n INTEGER = 'integer',\n DATE = 'date',\n DATETIME = 'datetime',\n TIME_OF_DAY = 'time_of_day',\n BOOLEAN = 'boolean',\n FILE = 'file',\n REFERENCE = 'reference',\n FUNCTION = 'function',\n ARRAY = 'array',\n OBJECT = 'object',\n US_ZIP_CODE = 'us_zip_code',\n}\n\nexport enum IndexStatus {\n NOT_INDEXED = 'not_indexed',\n INDEXING = 'indexing',\n INDEXED = 'indexed',\n ERROR = 'error',\n}\n\nexport enum DataTypeRecordScope {\n WORKSPACE = 'workspace',\n MEMBER = 'member',\n}\n\nexport enum DataSensitivity {\n PUBLIC = 'public',\n INTERNAL = 'internal',\n CONFIDENTIAL = 'confidential',\n RESTRICTED = 'restricted',\n SECRET = 'secret',\n}\n\nexport enum DataCategory {\n PHI = 'phi',\n PII = 'pii',\n FINANCIAL = 'financial',\n OPERATIONAL = 'operational',\n CREDENTIAL = 'credential',\n PERSONAL = 'personal',\n IDENTIFIER = 'identifier',\n}\n\n// DataField — the legacy client-side shape used in forms and the data-type editor.\n// SchemaField (from generated) is the canonical server representation.\nexport interface DataField {\n id?: number;\n name: string;\n slug: string;\n description?: string;\n required: boolean;\n fieldType: DataFieldType;\n options?: EnumOption[];\n referencedTypeId?: number;\n shouldIndex?: boolean;\n indexStatus?: IndexStatus;\n adminOnly?: boolean;\n defaultValue?: any;\n order: number;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Label-value pair for enum field options.\n * Allows enum fields to have user-friendly labels while storing clean values\n * (e.g., numbers for scoring calculations in CEL expressions).\n */\nexport interface EnumOption {\n /** Display label shown to users */\n label: string;\n /** Stored value (can be string or number) */\n value: string | number;\n /**\n * CEL expression that must return true for this option to be visible.\n * Uses record.data.<field_slug> syntax to reference other field values.\n * CONSTRAINT: Can only reference non-FUNCTION fields.\n */\n visibleWhen?: string | null;\n}\n\nexport interface DataTypeFormData {\n name: string;\n slug?: string;\n description?: string;\n prompt?: string;\n isCollection?: boolean;\n recordScope?: DataTypeRecordScope;\n sensitivity?: DataSensitivity;\n categories?: DataCategory[];\n // The update/create endpoints accept full SchemaField payloads (including\n // celFunction / validateCel); a narrower \"form data\" type here forced\n // unsafe double-casts at every call site.\n fields?: SchemaField[];\n memberRoleAccess?: DataTypeMemberRoleAccessInput[];\n pinned?: boolean;\n ownerId?: number | null;\n /**\n * Inline Actions. The same flat list ``DataType.eventRules`` returns, so a\n * form round-trips one shape. (``createRules``/``updateRules`` used to sit\n * here too, marked as the preferred pair — but the API never read them:\n * ``UpdateDataTypeRequest`` accepts ``eventRules`` and nothing else.)\n */\n eventRules?: EventRuleInput[];\n}\n\nexport interface DataRecordFormData {\n dataTypeId: number;\n memberId?: number | null;\n externalId?: string;\n fieldValues: Record<string, unknown>;\n}\n\nexport interface DataTypeMemberRoleAccessInput {\n memberRoleId: number;\n accessMode: number;\n}\n\nexport interface DataRecordAssociationFormData {\n dataRecordId: number;\n accessMode?: number;\n}\n\nexport interface DataRecordWithAccessMode extends DataRecordResponse {\n accessMode?: number | null;\n}\n\nexport interface DataRecordReportItem {\n id: number;\n dataTypeId: number;\n dataTypeSlug: string;\n member?: MemberReportItem;\n account?: AccountReportItem;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface DataIntegrityReportItem {\n dataTypeId: number;\n dataTypeSlug: string;\n dataTypeName: string;\n totalRecords: number;\n invalidRecords: number;\n issues: string[];\n}\n\nexport interface DataTypeExportItem {\n id: number;\n slug: string;\n name: string;\n fields: DataField[];\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface TaskExportDataTypeRelation {\n dataTypeId: number;\n dataTypeSlug: string;\n accessMode: number;\n}\n\nexport interface BulkRecordResult {\n index: number;\n status: 'created' | 'updated' | 'failed';\n recordId?: number;\n error?: string;\n}\n\nexport interface BulkCreateDataRecordResponse {\n importedCount: number;\n totalCount: number;\n success: boolean;\n results: BulkRecordResult[];\n errors?: string[];\n}\n\nexport interface BulkCreateDataRecordRequest {\n dataTypeId: number;\n records: DataRecordFormData[];\n upsert?: boolean;\n}\n","/**\n * Calendar-related types for the Gravity Rail calendar and appointment booking system.\n * Server response shapes are generated from Pydantic via emit_openapi.py → Orval.\n * Client-only shapes (forms, enums, query params) are defined below.\n */\n\n// ===== GENERATED SERVER TYPES =====\n\nexport type {\n AttendeeResponse,\n AttendeeResponse as CalendarEventAttendee,\n AvailabilityResponse,\n AvailableSlotsResponse,\n CalendarResponse as GeneratedCalendarResponse,\n CalendarScheduleResponse as GeneratedCalendarScheduleResponse,\n EventResponse,\n EventResponse as CalendarEvent,\n EventTypeResponse,\n EventTypeResponse as CalendarEventType,\n ExternalAttendeeData,\n GoogleCalendarInfo,\n GoogleCalendarInsufficientScopesResponse,\n GoogleCalendarStatusResponse,\n ICalFeedGrantSummary,\n ICalFeedTokenResponse,\n ICalFeedUrlResponse,\n TimeSlot,\n} from './generated/calendar';\n\nimport type {\n CalendarResponse as GeneratedCalendarResponse,\n CalendarScheduleResponse as GeneratedCalendarScheduleResponse,\n ExternalAttendeeData as GeneratedExternalAttendeeData,\n} from './generated/calendar';\nimport type { EventRuleInput } from './event-types';\n\nexport type Calendar = Omit<GeneratedCalendarResponse, never> & {\n /** Present on detail responses; omitted from some list payloads. */\n eventTypeIds?: number[];\n};\nexport type CalendarResponse = Calendar;\n\nexport type CalendarSchedule = Omit<\n GeneratedCalendarScheduleResponse,\n 'availabilityType' | 'recurrenceType'\n> & {\n availabilityType: CalendarScheduleAvailabilityType | string;\n recurrenceType: CalendarScheduleRecurrence | string;\n};\nexport type CalendarScheduleResponse = CalendarSchedule;\n\n// ===== CLIENT-ONLY TYPES =====\n\nexport enum CalendarPermissionType {\n NONE = 'NONE',\n FREE_BUSY = 'FREE_BUSY',\n READ = 'READ',\n WRITE = 'WRITE',\n ADMIN = 'ADMIN',\n}\n\nexport enum CalendarSource {\n INTERNAL = 'internal',\n GOOGLE = 'google',\n OUTLOOK = 'outlook',\n}\n\nexport interface CalendarFormData {\n name: string;\n slug?: string;\n description?: string | null;\n timezone?: string;\n color?: string | null;\n isPublic?: boolean;\n eventTypeIds?: number[];\n /**\n * Ordered event rules to attach to the calendar in the same request.\n * Server syncs by UUID: same-UUID updates, new UUID creates, omitted\n * UUIDs are deleted. Omit (undefined) to leave existing rules unchanged.\n */\n eventRules?: EventRuleInput[];\n}\n\nexport interface CalendarScheduleFormData {\n name: string;\n description?: string | null;\n availabilityType: CalendarScheduleAvailabilityType;\n recurrenceType: CalendarScheduleRecurrence;\n startTime: string;\n endTime: string;\n recurrenceRule?: Record<string, any> | null;\n recurrenceEndDate?: string | null;\n daysOfWeek?: string[] | null;\n priority?: number;\n eventTypeIds?: number[] | null;\n}\n\nexport enum CalendarScheduleRecurrence {\n ONCE = 'ONCE',\n DAILY = 'DAILY',\n WEEKLY = 'WEEKLY',\n MONTHLY = 'MONTHLY',\n CUSTOM = 'CUSTOM',\n}\n\nexport enum CalendarScheduleAvailabilityType {\n AVAILABLE = 'AVAILABLE',\n UNAVAILABLE = 'UNAVAILABLE',\n}\n\nexport interface CalendarEventTypeFormData {\n name: string;\n slug?: string;\n description?: string | null;\n defaultDurationMinutes: number;\n bufferBeforeMinutes?: number;\n bufferAfterMinutes?: number;\n minAttendees?: number;\n maxAttendees?: number | null;\n color?: string | null;\n active?: boolean;\n /**\n * Ordered event rules scoped to this event type. Server syncs by UUID:\n * same-UUID updates, new UUID creates, omitted UUIDs are deleted.\n */\n eventRules?: EventRuleInput[];\n}\n\nexport interface CalendarEventFormData {\n calendarId: number;\n eventTypeId: number;\n title: string;\n description?: string | null;\n location?: string | null;\n startTime: string;\n attendeeIds: number[];\n externalAttendees?: GeneratedExternalAttendeeData[];\n workflowRevisionId?: number | null;\n workflowId?: number | null;\n taskId?: number | null;\n assignmentId?: number | null;\n}\n\nexport enum CalendarEventStatus {\n TENTATIVE = 'TENTATIVE',\n CONFIRMED = 'CONFIRMED',\n CANCELLED = 'CANCELLED',\n NO_SHOW = 'NO_SHOW',\n COMPLETED = 'COMPLETED',\n}\n\nexport enum AttendeeStatus {\n REQUIRED = 'REQUIRED',\n OPTIONAL = 'OPTIONAL',\n}\n\nexport enum AttendeeResponseStatus {\n PENDING = 'PENDING',\n ACCEPTED = 'ACCEPTED',\n DECLINED = 'DECLINED',\n TENTATIVE = 'TENTATIVE',\n}\n\nexport interface UpdateAttendeeRequest {\n responseStatus: AttendeeResponseStatus;\n note?: string | null;\n}\n\nexport interface AvailabilityCheck {\n eventTypeId: number;\n startTime: string;\n endTime?: string | null;\n}\n\nexport interface AvailableSlotsRequest {\n eventTypeId: number;\n startDate: string;\n endDate: string;\n slotIntervalMinutes?: number;\n}\n\nexport interface CalendarEventsQueryParams {\n calendarId?: number;\n startDate?: string;\n endDate?: string;\n status?: CalendarEventStatus;\n memberId?: number;\n limit?: number;\n offset?: number;\n}\n\nexport interface LinkCalendarRequest {\n googleCalendarId: string;\n}\n\nexport interface LinkCalendarResponse {\n status: string;\n message: string;\n googleCalendarId: string;\n googleCalendarName?: string;\n}\n\nexport interface UnlinkCalendarResponse {\n status: string;\n message: string;\n}\n\nexport interface SyncCalendarResponse {\n status: string;\n message: string;\n created: number;\n updated: number;\n errors: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Recurrence","CalendarScheduleAvailabilityType","CalendarEventStatus","AttendeeStatus","AttendeeResponseStatus"]}
@@ -304,7 +304,11 @@ ${formattedErrors}`, response.status);
304
304
  throw error;
305
305
  }
306
306
  const errorMessage = typeof errorData.detail === "string" ? errorData.detail : errorData.message || response.statusText;
307
- throw new ApiError(errorMessage, response.status);
307
+ const simpleError = new ApiError(errorMessage, response.status);
308
+ if (typeof errorData.code === "string") {
309
+ simpleError.errorData = errorData;
310
+ }
311
+ throw simpleError;
308
312
  }
309
313
  if (response.status === 204) {
310
314
  return void 0;
@@ -476,4 +480,4 @@ export {
476
480
  parseOrgAuthChallenge,
477
481
  BaseApiClient
478
482
  };
479
- //# sourceMappingURL=chunk-PJFEGUHM.js.map
483
+ //# sourceMappingURL=chunk-7OLBLLV7.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/api/base.ts"],"sourcesContent":["// Utility function to read a specific cookie value\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const trimmedCookie = cookie.trim();\n const eqIndex = trimmedCookie.indexOf('=');\n if (eqIndex === -1) continue;\n\n const cookieName = trimmedCookie.substring(0, eqIndex);\n const cookieValue = trimmedCookie.substring(eqIndex + 1);\n\n if (cookieName === name) {\n return cookieValue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Structured validation error returned by the backend's workflow-expression\n * validator (CEL / Jinja schema checks). See WorkflowValidationErrorResponse\n * in workflowValidationTypes.ts for the public-facing shape.\n */\nexport interface ApiValidationError {\n field: string;\n kind: 'cel_syntax' | 'cel_schema' | 'jinja_syntax' | 'jinja_schema';\n message: string;\n offendingPath: string | null;\n location: {\n start: number;\n end: number;\n line: number;\n column: number;\n length: number;\n } | null;\n suggestion: string | null;\n}\n\nfunction isApiValidationError(value: unknown): value is ApiValidationError {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.field === 'string' && typeof v.kind === 'string' && typeof v.message === 'string'\n );\n}\n\nexport class ApiError extends Error {\n statusCode: number;\n /** Legacy string-array errors — kept for non-validation callers. */\n errors?: string[];\n /**\n * Structured workflow-expression validation errors (CEL/Jinja).\n * Populated when the backend returns a WorkflowValidationErrorResponse.\n */\n validationErrors?: ApiValidationError[];\n /**\n * The raw structured `detail` object when the backend returned one (a body\n * with `error: true` or a `code`). Declared here rather than bolted on with\n * `as any` at the throw site so consumers can narrow it with a type guard —\n * see `isMemberContactConflict` in `types/member-types`.\n */\n errorData?: unknown;\n\n constructor(\n message: string,\n statusCode: number,\n errors?: string[],\n validationErrors?: ApiValidationError[]\n ) {\n super(message);\n this.statusCode = statusCode;\n this.errors = errors;\n this.validationErrors = validationErrors;\n }\n}\n\n/**\n * Handler for enhanced authentication requirement (RFC 9470 Step-Up Authentication).\n * Called when a 401 response includes WWW-Authenticate header with\n * error=\"insufficient_user_authentication\".\n * Should return a promise that resolves with the new auth token after re-auth.\n */\nexport type EnhancedAuthHandler = () => Promise<string>;\n\n/**\n * Info parsed from WWW-Authenticate header for org auth requirement.\n */\nexport interface OrgAuthInfo {\n orgUuid: string;\n cookieName: string;\n authUrl: string;\n}\n\n/**\n * Handler for organization authentication requirement.\n * Called when a 401 response includes WWW-Authenticate header with realm=\"org\".\n * The handler should redirect the user to the auth URL for consent/SSO.\n * Returns a promise that resolves when the user should retry (after page reload with cookie).\n */\nexport type OrgAuthHandler = (info: OrgAuthInfo) => Promise<void>;\n\n/**\n * Check if a WWW-Authenticate header indicates step-up authentication is required.\n * Per RFC 9470, this is indicated by error=\"insufficient_user_authentication\".\n */\nfunction requiresStepUpAuth(wwwAuthenticate: string | null): boolean {\n if (!wwwAuthenticate) return false;\n return wwwAuthenticate.includes('error=\"insufficient_user_authentication\"');\n}\n\n/**\n * Parse org auth info from WWW-Authenticate header.\n * Returns null if this is not an org auth challenge.\n * Expected format: Bearer realm=\"org\", org_uuid=\"...\", cookie_name=\"...\", auth_url=\"...\"\n *\n * Exported so non-SDK fetch paths (e.g. the app's same-origin file-content\n * proxy fetches) can detect the same challenge and trigger the shared org\n * step-up flow.\n */\nexport function parseOrgAuthChallenge(wwwAuthenticate: string | null): OrgAuthInfo | null {\n if (!wwwAuthenticate) return null;\n if (!wwwAuthenticate.includes('realm=\"org\"')) return null;\n\n // Parse the key-value pairs from the header\n const orgUuidMatch = wwwAuthenticate.match(/org_uuid=\"([^\"]+)\"/);\n const cookieNameMatch = wwwAuthenticate.match(/cookie_name=\"([^\"]+)\"/);\n const authUrlMatch = wwwAuthenticate.match(/auth_url=\"([^\"]+)\"/);\n\n if (!orgUuidMatch?.[1] || !cookieNameMatch?.[1] || !authUrlMatch?.[1]) {\n // Don't log the raw header value — it embeds org_uuid + auth_url.\n console.warn('Invalid org auth challenge header: missing required fields');\n return null;\n }\n\n return {\n orgUuid: orgUuidMatch[1],\n cookieName: cookieNameMatch[1],\n authUrl: authUrlMatch[1],\n };\n}\n\nfunction getRequestOrgCookieName(cookieName: string): string | null {\n if (cookieName.startsWith('orgToken')) {\n return cookieName.replace(/^orgToken/, 'requestOrgToken');\n }\n if (cookieName.startsWith('orgSession')) {\n return cookieName.replace(/^orgSession/, 'requestOrgSession');\n }\n return null;\n}\n\nfunction orgAuthHeaderName(token: string): 'X-Org-Token' | 'X-Org-Session' {\n return token.startsWith('gr_sess_') ? 'X-Org-Session' : 'X-Org-Token';\n}\n\nfunction setOrgAuthHeader(headers: Headers, token: string | undefined): void {\n if (!token) return;\n headers.set(orgAuthHeaderName(token), token);\n}\n\nexport class BaseApiClient {\n protected baseUrl: string;\n protected apiKey: string | undefined;\n protected isCrossDomain: boolean;\n protected fetchFunction: typeof fetch;\n private enhancedAuthHandler?: EnhancedAuthHandler;\n private enhancedAuthInProgress: Promise<string> | null = null;\n private orgAuthHandler?: OrgAuthHandler;\n private orgAuthInProgress: Promise<void> | null = null;\n private actingMemberUuid?: string;\n private orgSession?: string;\n /**\n * The org_uuid that issued the current org auth credential. Tracked so we can detect\n * a 401 challenge from a *different* org and re-fire the handler — the\n * credential is opaque to the client, so without this the original guard\n * `!this.orgSession` would prevent re-auth across orgs and surface as a silent\n * 401 in multi-org CLI workflows.\n */\n private orgSessionOrgUuid?: string;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n // console.log('[BaseApiClient] constructor - baseUrl:', baseUrl);\n // Bind fetch to its proper context (window in browser, global in Node)\n this.fetchFunction =\n customFetch || (typeof window !== 'undefined' ? fetch.bind(window) : fetch);\n\n // Determine if we're making cross-domain requests by comparing current origin to API origin\n const apiUrlParsed = new URL(baseUrl);\n const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';\n this.isCrossDomain = currentOrigin !== '' && currentOrigin !== apiUrlParsed.origin;\n // console.log('[BaseApiClient] isCrossDomain:', this.isCrossDomain, 'currentOrigin:', currentOrigin, 'apiOrigin:', apiUrlParsed.origin);\n }\n\n /**\n * Set the handler for enhanced authentication requirements (RFC 9470 Step-Up Auth).\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with error=\"insufficient_user_authentication\".\n */\n setEnhancedAuthHandler(handler: EnhancedAuthHandler | undefined) {\n this.enhancedAuthHandler = handler;\n }\n\n /**\n * Set the handler for organization authentication requirements.\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with realm=\"org\". The handler should redirect the user to complete org auth.\n */\n setOrgAuthHandler(handler: OrgAuthHandler | undefined) {\n this.orgAuthHandler = handler;\n }\n\n /**\n * Update the API key (used after successful re-authentication).\n */\n updateApiKey(newApiKey: string) {\n this.apiKey = newApiKey;\n }\n\n /**\n * Set the acting member UUID for member identity switching.\n * When set, all API requests will include the X-Acting-Member header.\n * The backend will validate that the authenticated account owns this member\n * and use it as the effective identity for the request.\n */\n setActingMember(memberUuid: string | undefined) {\n this.actingMemberUuid = memberUuid;\n }\n\n /**\n * Get the current acting member UUID.\n */\n getActingMember(): string | undefined {\n return this.actingMemberUuid;\n }\n\n /**\n * Set the opaque org session credential for cross-domain requests.\n * Opaque gr_sess_ values use X-Org-Session. Legacy orgToken JWE values still\n * use X-Org-Token through setOrgToken() during the migration window.\n *\n * `orgUuid` is the org that issued the credential; passing it lets the 401\n * handler detect a stale session when a subsequent request targets a\n * different org and re-fire the org-auth handler instead of silently\n * 401-ing. Callers without that context (legacy / unknown) may omit it.\n */\n setOrgSession(session: string | undefined, orgUuid?: string) {\n this.orgSession = session;\n this.orgSessionOrgUuid = session ? orgUuid : undefined;\n }\n\n /**\n * @deprecated Legacy compatibility for stateless orgToken JWE credentials.\n * Prefer setOrgSession() for opaque org browser sessions.\n */\n setOrgToken(token: string | undefined, orgUuid?: string) {\n this.setOrgSession(token, orgUuid);\n }\n\n protected async fetch<T>(endpoint: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n // Don't set Content-Type for FormData — the browser must set it\n // with the multipart boundary automatically.\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n // For cross-domain requests, try to use the requestToken cookie\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n // console.warn(\"Calling with apiKey:\", this.apiKey)\n const fullUrl = `${this.baseUrl}/api/v2/${endpoint}`;\n // console.log('[BaseApiClient] fetch - URL:', fullUrl, 'baseUrl:', this.baseUrl, 'endpoint:', endpoint);\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n // If the challenge targets a different org than our current\n // token, the token is stale (e.g. switching from Org A to Org\n // B mid-session). Clear it so the handler re-fires below.\n if (\n orgAuthInfo &&\n this.orgSession &&\n this.orgSessionOrgUuid &&\n this.orgSessionOrgUuid !== orgAuthInfo.orgUuid\n ) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n }\n if (orgAuthInfo && !this.orgSession) {\n const requestCookieName = getRequestOrgCookieName(orgAuthInfo.cookieName);\n const cachedOrgSession = requestCookieName\n ? getCookieValue(requestCookieName)\n : undefined;\n if (cachedOrgSession) {\n this.orgSession = cachedOrgSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (this.orgAuthHandler) {\n if (!this.orgAuthInProgress) {\n const handler = this.orgAuthHandler;\n this.orgAuthInProgress = (async () => {\n try {\n await handler(orgAuthInfo);\n } finally {\n this.orgAuthInProgress = null;\n }\n })();\n }\n await this.orgAuthInProgress;\n // Prefer cookie (browser). Fall back to this.orgSession which\n // non-browser handlers (e.g. CLI) set directly via setOrgSession().\n const postHandlerSession =\n (requestCookieName ? getCookieValue(requestCookieName) : undefined) ??\n this.orgSession;\n if (!postHandlerSession) {\n throw new ApiError(\n 'Organization authentication did not issue a session',\n 401\n );\n }\n this.orgSession = postHandlerSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n }\n }\n\n const errorData = await response.json().catch(() => ({}));\n\n // Handle unauthorized errors for account endpoint\n if (response.status === 401 && endpoint === 'account') {\n throw new Error('unauthorized');\n }\n\n // Handle structured validation errors (Pydantic array format)\n if (Array.isArray(errorData.detail)) {\n const formattedErrors = errorData.detail\n .map((error: any) => {\n const location = error.loc.join(' > ');\n return `${location}: ${error.msg}`;\n })\n .join('\\n');\n throw new ApiError(`Validation Error:\\n${formattedErrors}`, response.status);\n }\n\n // Handle validation errors with errors array (new format)\n if (errorData.errors && Array.isArray(errorData.errors)) {\n // Structured workflow-expression validation errors — objects with\n // { field, kind, message, offendingPath, location }. Build a\n // readable message and preserve the structured payload.\n if (errorData.errors.length > 0 && isApiValidationError(errorData.errors[0])) {\n const validationErrors: ApiValidationError[] =\n errorData.errors.filter(isApiValidationError);\n const [first] = validationErrors;\n if (first) {\n const extra =\n validationErrors.length > 1\n ? ` (+${validationErrors.length - 1} more)`\n : '';\n const readable = `${first.field}: ${first.message}${extra}`;\n throw new ApiError(\n readable,\n response.status,\n validationErrors.map((e) => `${e.field}: ${e.message}`),\n validationErrors\n );\n }\n }\n\n // Legacy string-array errors.\n const stringErrors: string[] = errorData.errors.filter(\n (e: unknown): e is string => typeof e === 'string'\n );\n const details = stringErrors.join('; ');\n const message = errorData.detail\n ? `${errorData.detail}: ${details}`\n : `Validation failed: ${details}`;\n throw new ApiError(message, response.status, stringErrors);\n }\n\n // Handle structured errors (with error: true or with code property)\n const structuredError = errorData.detail || errorData;\n if (\n structuredError &&\n typeof structuredError === 'object' &&\n (structuredError.error === true || structuredError.code)\n ) {\n const message = structuredError.message || structuredError.code || 'Unknown error';\n const error = new ApiError(message, response.status);\n // Attach the full error data for frontend handling\n error.errorData = structuredError;\n throw error;\n }\n\n // Handle simple error messages\n const errorMessage =\n typeof errorData.detail === 'string'\n ? errorData.detail\n : errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n // Handle 204 No Content - no JSON body to parse\n if (response.status === 204) {\n return undefined as any;\n }\n\n return response.json();\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n\n protected async fetchRaw(\n endpoint: string,\n options?: RequestInit,\n allowedErrorStatuses: number[] = []\n ): Promise<Response> {\n try {\n const headers = new Headers({\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n // For cross-domain requests, try to use the requestToken cookie\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const response = await this.fetchFunction(`${this.baseUrl}/api/v2/${endpoint}`, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n // Mirror of the org-auth branch in fetch() above; see comments there.\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (\n orgAuthInfo &&\n this.orgSession &&\n this.orgSessionOrgUuid &&\n this.orgSessionOrgUuid !== orgAuthInfo.orgUuid\n ) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n }\n if (orgAuthInfo && !this.orgSession) {\n const requestCookieName = getRequestOrgCookieName(orgAuthInfo.cookieName);\n const cachedOrgSession = requestCookieName\n ? getCookieValue(requestCookieName)\n : undefined;\n if (cachedOrgSession) {\n this.orgSession = cachedOrgSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (this.orgAuthHandler) {\n if (!this.orgAuthInProgress) {\n const handler = this.orgAuthHandler;\n this.orgAuthInProgress = (async () => {\n try {\n await handler(orgAuthInfo);\n } finally {\n this.orgAuthInProgress = null;\n }\n })();\n }\n await this.orgAuthInProgress;\n // Prefer cookie (browser). Fall back to this.orgSession which\n // non-browser handlers (e.g. CLI) set directly via setOrgSession().\n const postHandlerSession =\n (requestCookieName ? getCookieValue(requestCookieName) : undefined) ??\n this.orgSession;\n if (!postHandlerSession) {\n throw new ApiError(\n 'Organization authentication did not issue a session',\n 401\n );\n }\n this.orgSession = postHandlerSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n }\n }\n\n if (allowedErrorStatuses.includes(response.status)) {\n return response;\n }\n\n const errorText = await response.text().catch(() => '');\n throw new ApiError(errorText || response.statusText, response.status);\n }\n\n return response;\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n\n /**\n * Fetch from root path (not prefixed with /api/v2/)\n * Used for OAuth and other non-API endpoints\n */\n protected async fetchRoot<T>(path: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const fullUrl = `${this.baseUrl}/${path}`;\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null as T;\n }\n const errorData = await response.json().catch(() => ({}));\n const errorMessage = errorData.detail || errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n return response.json();\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n}\n"],"mappings":";AACO,SAAS,eAAe,MAAkC;AAC9D,MAAI,OAAO,aAAa,YAAa,QAAO;AAE5C,QAAM,UAAU,SAAS,OAAO,MAAM,GAAG;AACzC,aAAW,UAAU,SAAS;AAC3B,UAAM,gBAAgB,OAAO,KAAK;AAClC,UAAM,UAAU,cAAc,QAAQ,GAAG;AACzC,QAAI,YAAY,GAAI;AAEpB,UAAM,aAAa,cAAc,UAAU,GAAG,OAAO;AACrD,UAAM,cAAc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/api/base.ts"],"sourcesContent":["// Utility function to read a specific cookie value\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const trimmedCookie = cookie.trim();\n const eqIndex = trimmedCookie.indexOf('=');\n if (eqIndex === -1) continue;\n\n const cookieName = trimmedCookie.substring(0, eqIndex);\n const cookieValue = trimmedCookie.substring(eqIndex + 1);\n\n if (cookieName === name) {\n return cookieValue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Structured validation error returned by the backend's workflow-expression\n * validator (CEL / Jinja schema checks). See WorkflowValidationErrorResponse\n * in workflowValidationTypes.ts for the public-facing shape.\n */\nexport interface ApiValidationError {\n field: string;\n kind: 'cel_syntax' | 'cel_schema' | 'jinja_syntax' | 'jinja_schema';\n message: string;\n offendingPath: string | null;\n location: {\n start: number;\n end: number;\n line: number;\n column: number;\n length: number;\n } | null;\n suggestion: string | null;\n}\n\nfunction isApiValidationError(value: unknown): value is ApiValidationError {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.field === 'string' && typeof v.kind === 'string' && typeof v.message === 'string'\n );\n}\n\nexport class ApiError extends Error {\n statusCode: number;\n /** Legacy string-array errors — kept for non-validation callers. */\n errors?: string[];\n /**\n * Structured workflow-expression validation errors (CEL/Jinja).\n * Populated when the backend returns a WorkflowValidationErrorResponse.\n */\n validationErrors?: ApiValidationError[];\n /**\n * The raw structured `detail` object when the backend returned one (a body\n * with `error: true` or a `code`). Declared here rather than bolted on with\n * `as any` at the throw site so consumers can narrow it with a type guard —\n * see `isMemberContactConflict` in `types/member-types`.\n */\n errorData?: unknown;\n\n constructor(\n message: string,\n statusCode: number,\n errors?: string[],\n validationErrors?: ApiValidationError[]\n ) {\n super(message);\n this.statusCode = statusCode;\n this.errors = errors;\n this.validationErrors = validationErrors;\n }\n}\n\n/**\n * Handler for enhanced authentication requirement (RFC 9470 Step-Up Authentication).\n * Called when a 401 response includes WWW-Authenticate header with\n * error=\"insufficient_user_authentication\".\n * Should return a promise that resolves with the new auth token after re-auth.\n */\nexport type EnhancedAuthHandler = () => Promise<string>;\n\n/**\n * Info parsed from WWW-Authenticate header for org auth requirement.\n */\nexport interface OrgAuthInfo {\n orgUuid: string;\n cookieName: string;\n authUrl: string;\n}\n\n/**\n * Handler for organization authentication requirement.\n * Called when a 401 response includes WWW-Authenticate header with realm=\"org\".\n * The handler should redirect the user to the auth URL for consent/SSO.\n * Returns a promise that resolves when the user should retry (after page reload with cookie).\n */\nexport type OrgAuthHandler = (info: OrgAuthInfo) => Promise<void>;\n\n/**\n * Check if a WWW-Authenticate header indicates step-up authentication is required.\n * Per RFC 9470, this is indicated by error=\"insufficient_user_authentication\".\n */\nfunction requiresStepUpAuth(wwwAuthenticate: string | null): boolean {\n if (!wwwAuthenticate) return false;\n return wwwAuthenticate.includes('error=\"insufficient_user_authentication\"');\n}\n\n/**\n * Parse org auth info from WWW-Authenticate header.\n * Returns null if this is not an org auth challenge.\n * Expected format: Bearer realm=\"org\", org_uuid=\"...\", cookie_name=\"...\", auth_url=\"...\"\n *\n * Exported so non-SDK fetch paths (e.g. the app's same-origin file-content\n * proxy fetches) can detect the same challenge and trigger the shared org\n * step-up flow.\n */\nexport function parseOrgAuthChallenge(wwwAuthenticate: string | null): OrgAuthInfo | null {\n if (!wwwAuthenticate) return null;\n if (!wwwAuthenticate.includes('realm=\"org\"')) return null;\n\n // Parse the key-value pairs from the header\n const orgUuidMatch = wwwAuthenticate.match(/org_uuid=\"([^\"]+)\"/);\n const cookieNameMatch = wwwAuthenticate.match(/cookie_name=\"([^\"]+)\"/);\n const authUrlMatch = wwwAuthenticate.match(/auth_url=\"([^\"]+)\"/);\n\n if (!orgUuidMatch?.[1] || !cookieNameMatch?.[1] || !authUrlMatch?.[1]) {\n // Don't log the raw header value — it embeds org_uuid + auth_url.\n console.warn('Invalid org auth challenge header: missing required fields');\n return null;\n }\n\n return {\n orgUuid: orgUuidMatch[1],\n cookieName: cookieNameMatch[1],\n authUrl: authUrlMatch[1],\n };\n}\n\nfunction getRequestOrgCookieName(cookieName: string): string | null {\n if (cookieName.startsWith('orgToken')) {\n return cookieName.replace(/^orgToken/, 'requestOrgToken');\n }\n if (cookieName.startsWith('orgSession')) {\n return cookieName.replace(/^orgSession/, 'requestOrgSession');\n }\n return null;\n}\n\nfunction orgAuthHeaderName(token: string): 'X-Org-Token' | 'X-Org-Session' {\n return token.startsWith('gr_sess_') ? 'X-Org-Session' : 'X-Org-Token';\n}\n\nfunction setOrgAuthHeader(headers: Headers, token: string | undefined): void {\n if (!token) return;\n headers.set(orgAuthHeaderName(token), token);\n}\n\nexport class BaseApiClient {\n protected baseUrl: string;\n protected apiKey: string | undefined;\n protected isCrossDomain: boolean;\n protected fetchFunction: typeof fetch;\n private enhancedAuthHandler?: EnhancedAuthHandler;\n private enhancedAuthInProgress: Promise<string> | null = null;\n private orgAuthHandler?: OrgAuthHandler;\n private orgAuthInProgress: Promise<void> | null = null;\n private actingMemberUuid?: string;\n private orgSession?: string;\n /**\n * The org_uuid that issued the current org auth credential. Tracked so we can detect\n * a 401 challenge from a *different* org and re-fire the handler — the\n * credential is opaque to the client, so without this the original guard\n * `!this.orgSession` would prevent re-auth across orgs and surface as a silent\n * 401 in multi-org CLI workflows.\n */\n private orgSessionOrgUuid?: string;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n // console.log('[BaseApiClient] constructor - baseUrl:', baseUrl);\n // Bind fetch to its proper context (window in browser, global in Node)\n this.fetchFunction =\n customFetch || (typeof window !== 'undefined' ? fetch.bind(window) : fetch);\n\n // Determine if we're making cross-domain requests by comparing current origin to API origin\n const apiUrlParsed = new URL(baseUrl);\n const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';\n this.isCrossDomain = currentOrigin !== '' && currentOrigin !== apiUrlParsed.origin;\n // console.log('[BaseApiClient] isCrossDomain:', this.isCrossDomain, 'currentOrigin:', currentOrigin, 'apiOrigin:', apiUrlParsed.origin);\n }\n\n /**\n * Set the handler for enhanced authentication requirements (RFC 9470 Step-Up Auth).\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with error=\"insufficient_user_authentication\".\n */\n setEnhancedAuthHandler(handler: EnhancedAuthHandler | undefined) {\n this.enhancedAuthHandler = handler;\n }\n\n /**\n * Set the handler for organization authentication requirements.\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with realm=\"org\". The handler should redirect the user to complete org auth.\n */\n setOrgAuthHandler(handler: OrgAuthHandler | undefined) {\n this.orgAuthHandler = handler;\n }\n\n /**\n * Update the API key (used after successful re-authentication).\n */\n updateApiKey(newApiKey: string) {\n this.apiKey = newApiKey;\n }\n\n /**\n * Set the acting member UUID for member identity switching.\n * When set, all API requests will include the X-Acting-Member header.\n * The backend will validate that the authenticated account owns this member\n * and use it as the effective identity for the request.\n */\n setActingMember(memberUuid: string | undefined) {\n this.actingMemberUuid = memberUuid;\n }\n\n /**\n * Get the current acting member UUID.\n */\n getActingMember(): string | undefined {\n return this.actingMemberUuid;\n }\n\n /**\n * Set the opaque org session credential for cross-domain requests.\n * Opaque gr_sess_ values use X-Org-Session. Legacy orgToken JWE values still\n * use X-Org-Token through setOrgToken() during the migration window.\n *\n * `orgUuid` is the org that issued the credential; passing it lets the 401\n * handler detect a stale session when a subsequent request targets a\n * different org and re-fire the org-auth handler instead of silently\n * 401-ing. Callers without that context (legacy / unknown) may omit it.\n */\n setOrgSession(session: string | undefined, orgUuid?: string) {\n this.orgSession = session;\n this.orgSessionOrgUuid = session ? orgUuid : undefined;\n }\n\n /**\n * @deprecated Legacy compatibility for stateless orgToken JWE credentials.\n * Prefer setOrgSession() for opaque org browser sessions.\n */\n setOrgToken(token: string | undefined, orgUuid?: string) {\n this.setOrgSession(token, orgUuid);\n }\n\n protected async fetch<T>(endpoint: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n // Don't set Content-Type for FormData — the browser must set it\n // with the multipart boundary automatically.\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n // For cross-domain requests, try to use the requestToken cookie\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n // console.warn(\"Calling with apiKey:\", this.apiKey)\n const fullUrl = `${this.baseUrl}/api/v2/${endpoint}`;\n // console.log('[BaseApiClient] fetch - URL:', fullUrl, 'baseUrl:', this.baseUrl, 'endpoint:', endpoint);\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n // If the challenge targets a different org than our current\n // token, the token is stale (e.g. switching from Org A to Org\n // B mid-session). Clear it so the handler re-fires below.\n if (\n orgAuthInfo &&\n this.orgSession &&\n this.orgSessionOrgUuid &&\n this.orgSessionOrgUuid !== orgAuthInfo.orgUuid\n ) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n }\n if (orgAuthInfo && !this.orgSession) {\n const requestCookieName = getRequestOrgCookieName(orgAuthInfo.cookieName);\n const cachedOrgSession = requestCookieName\n ? getCookieValue(requestCookieName)\n : undefined;\n if (cachedOrgSession) {\n this.orgSession = cachedOrgSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (this.orgAuthHandler) {\n if (!this.orgAuthInProgress) {\n const handler = this.orgAuthHandler;\n this.orgAuthInProgress = (async () => {\n try {\n await handler(orgAuthInfo);\n } finally {\n this.orgAuthInProgress = null;\n }\n })();\n }\n await this.orgAuthInProgress;\n // Prefer cookie (browser). Fall back to this.orgSession which\n // non-browser handlers (e.g. CLI) set directly via setOrgSession().\n const postHandlerSession =\n (requestCookieName ? getCookieValue(requestCookieName) : undefined) ??\n this.orgSession;\n if (!postHandlerSession) {\n throw new ApiError(\n 'Organization authentication did not issue a session',\n 401\n );\n }\n this.orgSession = postHandlerSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n }\n }\n\n const errorData = await response.json().catch(() => ({}));\n\n // Handle unauthorized errors for account endpoint\n if (response.status === 401 && endpoint === 'account') {\n throw new Error('unauthorized');\n }\n\n // Handle structured validation errors (Pydantic array format)\n if (Array.isArray(errorData.detail)) {\n const formattedErrors = errorData.detail\n .map((error: any) => {\n const location = error.loc.join(' > ');\n return `${location}: ${error.msg}`;\n })\n .join('\\n');\n throw new ApiError(`Validation Error:\\n${formattedErrors}`, response.status);\n }\n\n // Handle validation errors with errors array (new format)\n if (errorData.errors && Array.isArray(errorData.errors)) {\n // Structured workflow-expression validation errors — objects with\n // { field, kind, message, offendingPath, location }. Build a\n // readable message and preserve the structured payload.\n if (errorData.errors.length > 0 && isApiValidationError(errorData.errors[0])) {\n const validationErrors: ApiValidationError[] =\n errorData.errors.filter(isApiValidationError);\n const [first] = validationErrors;\n if (first) {\n const extra =\n validationErrors.length > 1\n ? ` (+${validationErrors.length - 1} more)`\n : '';\n const readable = `${first.field}: ${first.message}${extra}`;\n throw new ApiError(\n readable,\n response.status,\n validationErrors.map((e) => `${e.field}: ${e.message}`),\n validationErrors\n );\n }\n }\n\n // Legacy string-array errors.\n const stringErrors: string[] = errorData.errors.filter(\n (e: unknown): e is string => typeof e === 'string'\n );\n const details = stringErrors.join('; ');\n const message = errorData.detail\n ? `${errorData.detail}: ${details}`\n : `Validation failed: ${details}`;\n throw new ApiError(message, response.status, stringErrors);\n }\n\n // Handle structured errors (with error: true or with code property)\n const structuredError = errorData.detail || errorData;\n if (\n structuredError &&\n typeof structuredError === 'object' &&\n (structuredError.error === true || structuredError.code)\n ) {\n const message = structuredError.message || structuredError.code || 'Unknown error';\n const error = new ApiError(message, response.status);\n // Attach the full error data for frontend handling\n error.errorData = structuredError;\n throw error;\n }\n\n // Handle simple error messages\n const errorMessage =\n typeof errorData.detail === 'string'\n ? errorData.detail\n : errorData.message || response.statusText;\n const simpleError = new ApiError(errorMessage, response.status);\n // A prose `detail` STRING alongside a top-level `code` is the shape\n // the backend's domain-validation handler produces: it merges an\n // exception's `payload` into the body and keeps `detail`\n // authoritative. That misses the structured branch above, because\n // `errorData.detail || errorData` resolves to the string. Carry the\n // body through so a caller can still branch on the token — the\n // alternative is parsing `detail`, which is deliberately\n // human-facing prose and not a stable contract.\n if (typeof errorData.code === 'string') {\n simpleError.errorData = errorData;\n }\n throw simpleError;\n }\n\n // Handle 204 No Content - no JSON body to parse\n if (response.status === 204) {\n return undefined as any;\n }\n\n return response.json();\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n\n protected async fetchRaw(\n endpoint: string,\n options?: RequestInit,\n allowedErrorStatuses: number[] = []\n ): Promise<Response> {\n try {\n const headers = new Headers({\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n // For cross-domain requests, try to use the requestToken cookie\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const response = await this.fetchFunction(`${this.baseUrl}/api/v2/${endpoint}`, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n // Mirror of the org-auth branch in fetch() above; see comments there.\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (\n orgAuthInfo &&\n this.orgSession &&\n this.orgSessionOrgUuid &&\n this.orgSessionOrgUuid !== orgAuthInfo.orgUuid\n ) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n }\n if (orgAuthInfo && !this.orgSession) {\n const requestCookieName = getRequestOrgCookieName(orgAuthInfo.cookieName);\n const cachedOrgSession = requestCookieName\n ? getCookieValue(requestCookieName)\n : undefined;\n if (cachedOrgSession) {\n this.orgSession = cachedOrgSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (this.orgAuthHandler) {\n if (!this.orgAuthInProgress) {\n const handler = this.orgAuthHandler;\n this.orgAuthInProgress = (async () => {\n try {\n await handler(orgAuthInfo);\n } finally {\n this.orgAuthInProgress = null;\n }\n })();\n }\n await this.orgAuthInProgress;\n // Prefer cookie (browser). Fall back to this.orgSession which\n // non-browser handlers (e.g. CLI) set directly via setOrgSession().\n const postHandlerSession =\n (requestCookieName ? getCookieValue(requestCookieName) : undefined) ??\n this.orgSession;\n if (!postHandlerSession) {\n throw new ApiError(\n 'Organization authentication did not issue a session',\n 401\n );\n }\n this.orgSession = postHandlerSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n }\n }\n\n if (allowedErrorStatuses.includes(response.status)) {\n return response;\n }\n\n const errorText = await response.text().catch(() => '');\n throw new ApiError(errorText || response.statusText, response.status);\n }\n\n return response;\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n\n /**\n * Fetch from root path (not prefixed with /api/v2/)\n * Used for OAuth and other non-API endpoints\n */\n protected async fetchRoot<T>(path: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const fullUrl = `${this.baseUrl}/${path}`;\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null as T;\n }\n const errorData = await response.json().catch(() => ({}));\n const errorMessage = errorData.detail || errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n return response.json();\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n}\n"],"mappings":";AACO,SAAS,eAAe,MAAkC;AAC9D,MAAI,OAAO,aAAa,YAAa,QAAO;AAE5C,QAAM,UAAU,SAAS,OAAO,MAAM,GAAG;AACzC,aAAW,UAAU,SAAS;AAC3B,UAAM,gBAAgB,OAAO,KAAK;AAClC,UAAM,UAAU,cAAc,QAAQ,GAAG;AACzC,QAAI,YAAY,GAAI;AAEpB,UAAM,aAAa,cAAc,UAAU,GAAG,OAAO;AACrD,UAAM,cAAc,cAAc,UAAU,UAAU,CAAC;AAEvD,QAAI,eAAe,MAAM;AACtB,aAAO;AAAA,IACV;AAAA,EACH;AAEA,SAAO;AACV;AAsBA,SAAS,qBAAqB,OAA6C;AACxE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,QAAM,IAAI;AACV,SACG,OAAO,EAAE,UAAU,YAAY,OAAO,EAAE,SAAS,YAAY,OAAO,EAAE,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