kaafil-js 0.6.2 → 0.7.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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/generated/security.ts","../src/generated/error-codes.ts","../src/http/errors.ts","../src/auth/credentials.ts","../src/config.ts","../src/http/retry.ts","../src/http/client.ts","../src/idempotency.ts","../src/datetime.ts","../src/pagination/paginator.ts","../src/resources/internal.ts","../src/resources/agencies.ts","../src/resources/agency-admins.ts","../src/resources/auth.ts","../src/resources/bookings.ts","../src/resources/checklists.ts","../src/resources/closeout.ts","../src/resources/collections.ts","../src/resources/comms.ts","../src/resources/events.ts","../src/resources/expenses.ts","../src/resources/feedback-nps.ts","../src/resources/files.ts","../src/resources/float.ts","../src/resources/forms.ts","../src/resources/itinerary.ts","../src/resources/journey.ts","../src/resources/manager-today.ts","../src/resources/pickups.ts","../src/resources/rooming.ts","../src/resources/seating.ts","../src/resources/share-tokens.ts","../src/resources/sync.ts","../src/resources/test.ts","../src/resources/travellers.ts","../src/resources/treks.ts","../src/resources/trips.ts","../src/resources/vendors.ts","../src/resources/webhooks.ts","../src/client.ts","../src/delta/cursor.ts","../src/generated/enums.ts","../src/rooming/vocabulary.ts"],"names":["createInitialState"],"mappings":";AAmBO,IAAM,gBAAA,GAAmB;AAAA,EAC9B,eAAA,EAAiB,iBAAA;AAAA,EACjB,UAAA,EAAY,YAAA;AAAA,EAEZ,WAAA,EAAa,aAAA;AAAA,EAEb,SAAA,EAAW;AACb,CAAA;AAGO,IAAM,wBAAA,GAAkF;AAAA,EAC7F,eAAA,EAAiB,EAAE,IAAA,EAAM,QAAA,EAAS;AAAA,EAClC,UAAA,EAAY,EAAE,IAAA,EAAM,QAAA,EAAU,YAAY,WAAA,EAAY;AAAA,EACtD,WAAA,EAAa,EAAE,IAAA,EAAM,QAAA,EAAU,YAAY,wBAAA,EAAyB;AAAA,EACpE,WAAA,EAAa,E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AA,IAAK,SAAA,KAAc,IAAA,CAAK,SAAS,CAAA,EAAG;AACnD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,CAAA,EAAG,SAAS,CAAA;AACtC,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,KAAA,CAAM,SAAA,GAAY,CAAC,CAAA;AAGzC,EAAA,MAAM,KAAA,GAAQ,OAAO,QAAQ,CAAA;AAC7B,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,KAAK,CAAA,IAAK,QAAQ,CAAA,EAAG;AACzC,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,EAAE,QAAQ,KAAA,EAAM;AACzB","file":"index.js","sourcesContent":["/**\n * This file was auto-generated by `scripts/gen-meta.mjs` from\n * `openapi/openapi.json`. Do not make direct changes to the file — re-run\n * `pnpm gen:types` instead.\n *\n * @generated src/generated/security.ts\n */\n\n// `security` on an operation is a list of alternatives (OR), never an AND —\n// enforced by `gen-meta.mjs`, which throws if any requirement names more\n// than one scheme. The order below is the order declared in the spec: the\n// transport must try schemes in this order and use the first one the client\n// is actually configured for.\n\nexport type CredentialCarrier =\n | { readonly kind: 'header'; readonly headerName: string }\n | { readonly kind: 'bearer' }\n | { readonly kind: 'cookie'; readonly cookieName: string };\n\nexport const SecuritySchemeId = {\n AgencyAdminAuth: 'agencyAdminAuth',\n ApiKeyAuth: 'apiKeyAuth',\n ConsoleAuth: 'consoleAuth',\n ManagerAuth: 'managerAuth',\n PlatformAdminAuth: 'platformAdminAuth',\n ShareAuth: 'shareAuth',\n} as const;\nexport type SecuritySchemeId = (typeof SecuritySchemeId)[keyof typeof SecuritySchemeId];\n\nexport const SECURITY_SCHEME_CARRIERS: Readonly<Record<SecuritySchemeId, CredentialCarrier>> = {\n agencyAdminAuth: { kind: 'bearer' },\n apiKeyAuth: { kind: 'header', headerName: 'X-API-Key' },\n consoleAuth: { kind: 'cookie', cookieName: 'kaafil_console_session' },\n managerAuth: { kind: 'bearer' },\n platformAdminAuth: { kind: 'bearer' },\n shareAuth: { kind: 'bearer' },\n};\n\nexport const OperationId = {\n AcceptConsoleInvite: 'acceptConsoleInvite',\n AcceptPlatformAdminInvite: 'acceptPlatformAdminInvite',\n AddChecklistItem: 'addChecklistItem',\n AddItineraryItem: 'addItineraryItem',\n AddPlatformIncidentUpdate: 'addPlatformIncidentUpdate',\n AddTravellerNote: 'addTravellerNote',\n AdjustFloat: 'adjustFloat',\n AdvanceTestTime: 'advanceTestTime',\n AdvanceTestTimeConsole: 'advanceTestTimeConsole',\n ArchiveForm: 'archiveForm',\n AssignManager: 'assignManager',\n AssignPickupTraveller: 'assignPickupTraveller',\n AssignRoomingBed: 'assignRoomingBed',\n AssignSeating: 'assignSeating',\n AutoAssignRooming: 'autoAssignRooming',\n AutoAssignSeating: 'autoAssignSeating',\n BoardPickupTraveller: 'boardPickupTraveller',\n BuildTestFixtures: 'buildTestFixtures',\n BuildTestFixturesConsole: 'buildTestFixturesConsole',\n BulkUpsertBookings: 'bulkUpsertBookings',\n CancelTrip: 'cancelTrip',\n ChangeMyConsolePassword: 'changeMyConsolePassword',\n ChangeOwnPlatformPassword: 'changeOwnPlatformPassword',\n ClaimStatusIngest: 'claimStatusIngest',\n CloneForm: 'cloneForm',\n CloseForm: 'closeForm',\n ClosePickupStop: 'closePickupStop',\n ConfirmFileUpload: 'confirmFileUpload',\n ConsoleLogin: 'consoleLogin',\n ConsoleLogout: 'consoleLogout',\n ConsoleSwitchPlane: 'consoleSwitchPlane',\n CopyAgencyEntitlement: 'copyAgencyEntitlement',\n CorrectPickupBoardStatus: 'correctPickupBoardStatus',\n CreateAgencyConsole: 'createAgencyConsole',\n CreateApiKey: 'createApiKey',\n CreateChecklistTemplate: 'createChecklistTemplate',\n CreateCommsProviderCredential: 'createCommsProviderCredential',\n CreateCommsProviderCredentialConsole: 'createCommsProviderCredentialConsole',\n CreateConsoleUser: 'createConsoleUser',\n CreateForm: 'createForm',\n CreateFormField: 'createFormField',\n CreateFormSection: 'createFormSection',\n CreateMessageTemplate: 'createMessageTemplate',\n CreateParty: 'createParty',\n CreatePickupStop: 'createPickupStop',\n CreatePlatformAdmin: 'createPlatformAdmin',\n CreatePlatformIncident: 'createPlatformIncident',\n CreatePlatformPartner: 'createPlatformPartner',\n CreatePlatformPartnerConsoleUser: 'createPlatformPartnerConsoleUser',\n CreateRoomingRoom: 'createRoomingRoom',\n CreateRoomingStayWindow: 'createRoomingStayWindow',\n CreateSeatingVehicle: 'createSeatingVehicle',\n CreateSupportGrant: 'createSupportGrant',\n CreateTraveller: 'createTraveller',\n CreateTrekWalkIn: 'createTrekWalkIn',\n CreateVendor: 'createVendor',\n DeleteBooking: 'deleteBooking',\n DeleteChecklistItem: 'deleteChecklistItem',\n DeleteChecklistTemplate: 'deleteChecklistTemplate',\n DeleteFile: 'deleteFile',\n DeleteForm: 'deleteForm',\n DeleteFormField: 'deleteFormField',\n DeleteFormSection: 'deleteFormSection',\n DeleteItineraryItem: 'deleteItineraryItem',\n DeleteParty: 'deleteParty',\n DeletePickupStop: 'deletePickupStop',\n DeletePlatformPartnerPlan: 'deletePlatformPartnerPlan',\n DeleteRoomingRoom: 'deleteRoomingRoom',\n DeleteRoomingStayWindow: 'deleteRoomingStayWindow',\n DeleteSeatingVehicle: 'deleteSeatingVehicle',\n DeleteVendor: 'deleteVendor',\n DispatchForm: 'dispatchForm',\n EditWebhookEndpoint: 'editWebhookEndpoint',\n EraseTraveller: 'eraseTraveller',\n ExportCloseoutPack: 'exportCloseoutPack',\n ExportFormResponses: 'exportFormResponses',\n ExportTraveller: 'exportTraveller',\n GetAgencyAdminMe: 'getAgencyAdminMe',\n GetAgencySettings: 'getAgencySettings',\n GetAgencySettingsSelf: 'getAgencySettingsSelf',\n GetAgencyTrip: 'getAgencyTrip',\n GetForm: 'getForm',\n GetFormAggregate: 'getFormAggregate',\n GetFormConsentReceipt: 'getFormConsentReceipt',\n GetFormResponse: 'getFormResponse',\n GetFormsCompletionMatrix: 'getFormsCompletionMatrix',\n GetFormsCrossModuleAnswers: 'getFormsCrossModuleAnswers',\n GetManagerAgencyProfile: 'getManagerAgencyProfile',\n GetManagerInbox: 'getManagerInbox',\n GetNotificationDetail: 'getNotificationDetail',\n GetShareManifest: 'getShareManifest',\n GetShareSnapshot: 'getShareSnapshot',\n GetTravellerAgencyProfile: 'getTravellerAgencyProfile',\n GetTravellerDetail: 'getTravellerDetail',\n GetTrip: 'getTrip',\n GetTripManifest: 'getTripManifest',\n Health: 'health',\n HealthV1: 'healthV1',\n InspectConsoleInvite: 'inspectConsoleInvite',\n InspectPlatformAdminInvite: 'inspectPlatformAdminInvite',\n IssueFloat: 'issueFloat',\n LinkExpenseReceipt: 'linkExpenseReceipt',\n LinkSeatingManager: 'linkSeatingManager',\n ListAgencies: 'listAgencies',\n ListAgencyManagers: 'listAgencyManagers',\n ListAgencyTrips: 'listAgencyTrips',\n ListApiKeys: 'listApiKeys',\n ListBookings: 'listBookings',\n ListChecklistTemplates: 'listChecklistTemplates',\n ListChecklistTemplatesAdmin: 'listChecklistTemplatesAdmin',\n ListCollections: 'listCollections',\n ListConsoleUsers: 'listConsoleUsers',\n ListEligibleCollections: 'listEligibleCollections',\n ListEvents: 'listEvents',\n ListExpenses: 'listExpenses',\n ListFiles: 'listFiles',\n ListFormBindings: 'listFormBindings',\n ListForms: 'listForms',\n ListJourneyTriggers: 'listJourneyTriggers',\n ListJourneyTriggersConsole: 'listJourneyTriggersConsole',\n ListManagerExpenses: 'listManagerExpenses',\n ListManagerNotifications: 'listManagerNotifications',\n ListMessages: 'listMessages',\n ListMessagesConsole: 'listMessagesConsole',\n ListMessageTemplates: 'listMessageTemplates',\n ListMyConsoleSessions: 'listMyConsoleSessions',\n ListOwnManagerTrips: 'listOwnManagerTrips',\n ListParties: 'listParties',\n ListPickupStops: 'listPickupStops',\n ListPlatformAdmins: 'listPlatformAdmins',\n ListPlatformAudit: 'listPlatformAudit',\n ListPlatformIncidents: 'listPlatformIncidents',\n ListPlatformPartnerApiKeys: 'listPlatformPartnerApiKeys',\n ListPlatformPartnerConsoleUsers: 'listPlatformPartnerConsoleUsers',\n ListPlatformPartners: 'listPlatformPartners',\n ListPlatformPlanTiers: 'listPlatformPlanTiers',\n ListRoomingStayWindows: 'listRoomingStayWindows',\n ListShareTokens: 'listShareTokens',\n ListSupportIngestLog: 'listSupportIngestLog',\n ListSupportWebhookDeliveries: 'listSupportWebhookDeliveries',\n ListTravellerFormResponses: 'listTravellerFormResponses',\n ListTrekWalkIns: 'listTrekWalkIns',\n ListTripFormResponses: 'listTripFormResponses',\n ListTripForms: 'listTripForms',\n ListTripManagers: 'listTripManagers',\n ListTripManifest: 'listTripManifest',\n ListTripVendors: 'listTripVendors',\n ListWebhookDeliveries: 'listWebhookDeliveries',\n ListWebhookDeliveriesConsole: 'listWebhookDeliveriesConsole',\n ListWebhookEndpoints: 'listWebhookEndpoints',\n LockCloseout: 'lockCloseout',\n LogExpense: 'logExpense',\n ManagerCreateFormResponse: 'managerCreateFormResponse',\n MarkNotificationRead: 'markNotificationRead',\n MintAgencyAdminTokens: 'mintAgencyAdminTokens',\n MintManagerTokens: 'mintManagerTokens',\n MintShareToken: 'mintShareToken',\n NudgeConsoleInvite: 'nudgeConsoleInvite',\n PatchAgencyEntitlement: 'patchAgencyEntitlement',\n PatchAgencySettings: 'patchAgencySettings',\n PatchAgencySettingsSelf: 'patchAgencySettingsSelf',\n PatchChecklistItem: 'patchChecklistItem',\n PatchChecklistTemplate: 'patchChecklistTemplate',\n PatchConsoleUser: 'patchConsoleUser',\n PatchForm: 'patchForm',\n PatchFormField: 'patchFormField',\n PatchFormSection: 'patchFormSection',\n PatchItineraryDay: 'patchItineraryDay',\n PatchItineraryItem: 'patchItineraryItem',\n PatchJourneyTrigger: 'patchJourneyTrigger',\n PatchJourneyTriggerConsole: 'patchJourneyTriggerConsole',\n PatchMessageTemplate: 'patchMessageTemplate',\n PatchParty: 'patchParty',\n PatchPickupStop: 'patchPickupStop',\n PatchPlatformAdmin: 'patchPlatformAdmin',\n PatchPlatformPartnerConsoleUser: 'patchPlatformPartnerConsoleUser',\n PatchRoomingRoom: 'patchRoomingRoom',\n PatchRoomingStayWindow: 'patchRoomingStayWindow',\n PatchSeatingVehicle: 'patchSeatingVehicle',\n PatchShareToken: 'patchShareToken',\n PatchTripManager: 'patchTripManager',\n PlatformHealth: 'platformHealth',\n PlatformLogin: 'platformLogin',\n PlatformLogout: 'platformLogout',\n PlatformMe: 'platformMe',\n PlatformRefreshTokens: 'platformRefreshTokens',\n PlatformWebhookHealth: 'platformWebhookHealth',\n PostponeTrek: 'postponeTrek',\n PublishChecklistTemplate: 'publishChecklistTemplate',\n PublishForm: 'publishForm',\n PullChecklistTemplate: 'pullChecklistTemplate',\n PushBulkTrips: 'pushBulkTrips',\n PushManifest: 'pushManifest',\n PushTripBalances: 'pushTripBalances',\n PutCommsConfig: 'putCommsConfig',\n PutCommsConfigConsole: 'putCommsConfigConsole',\n PutPlatformPartnerPlan: 'putPlatformPartnerPlan',\n ReadAgencyEntitlement: 'readAgencyEntitlement',\n ReadAgencyFeedbackSummary: 'readAgencyFeedbackSummary',\n ReadApiKey: 'readApiKey',\n ReadChecklistAggregate: 'readChecklistAggregate',\n ReadChecklistItem: 'readChecklistItem',\n ReadCloseout: 'readCloseout',\n ReadCommsConfig: 'readCommsConfig',\n ReadCommsConfigConsole: 'readCommsConfigConsole',\n ReadConsoleAudit: 'readConsoleAudit',\n ReadConsoleCertification: 'readConsoleCertification',\n ReadConsoleMe: 'readConsoleMe',\n ReadConsoleUserInvite: 'readConsoleUserInvite',\n ReadEndpointDeliveries: 'readEndpointDeliveries',\n ReadEndpointDelivery: 'readEndpointDelivery',\n ReadEntitlementCatalog: 'readEntitlementCatalog',\n ReadExpense: 'readExpense',\n ReadFile: 'readFile',\n ReadFileUrl: 'readFileUrl',\n ReadFloatLedger: 'readFloatLedger',\n ReadFloatSummary: 'readFloatSummary',\n ReadIngestLog: 'readIngestLog',\n ReadIngestLogSummary: 'readIngestLogSummary',\n ReadItinerary: 'readItinerary',\n ReadItineraryChangeLog: 'readItineraryChangeLog',\n ReadJourney: 'readJourney',\n ReadJourneyCapabilities: 'readJourneyCapabilities',\n ReadManagerExpense: 'readManagerExpense',\n ReadManagerExpenseLogMeta: 'readManagerExpenseLogMeta',\n ReadManagerFileView: 'readManagerFileView',\n ReadManagerToday: 'readManagerToday',\n ReadManifestByPickup: 'readManifestByPickup',\n ReadPlan: 'readPlan',\n ReadPlatformPartner: 'readPlatformPartner',\n ReadRoomingBoard: 'readRoomingBoard',\n ReadRoomingRoom: 'readRoomingRoom',\n ReadSeatingBoard: 'readSeatingBoard',\n ReadShareToken: 'readShareToken',\n ReadSupportJourneyState: 'readSupportJourneyState',\n ReadSupportWebhookDeliveryDetail: 'readSupportWebhookDeliveryDetail',\n ReadTenantDefaultCommsConfig: 'readTenantDefaultCommsConfig',\n ReadTenantDefaultCommsConfigConsole: 'readTenantDefaultCommsConfigConsole',\n ReadTestClock: 'readTestClock',\n ReadTestClockConsole: 'readTestClockConsole',\n ReadTestFixtures: 'readTestFixtures',\n ReadTestFixturesConsole: 'readTestFixturesConsole',\n ReadTestQuota: 'readTestQuota',\n ReadTestQuotaConsole: 'readTestQuotaConsole',\n ReadTrekBoard: 'readTrekBoard',\n ReadTrekWalkInMeta: 'readTrekWalkInMeta',\n ReadTripFeedbackSummary: 'readTripFeedbackSummary',\n ReadUsage: 'readUsage',\n ReadWebhookDelivery: 'readWebhookDelivery',\n ReadWebhookDeliveryConsole: 'readWebhookDeliveryConsole',\n ReadWebhookEndpoint: 'readWebhookEndpoint',\n ReadWebhookEventCatalog: 'readWebhookEventCatalog',\n ReassignPickupStopTravellers: 'reassignPickupStopTravellers',\n RebuildJourney: 'rebuildJourney',\n RecheckConsoleCertification: 'recheckConsoleCertification',\n ReconcileTrekWalkIn: 'reconcileTrekWalkIn',\n RecordCollection: 'recordCollection',\n RedeliverEndpointDelivery: 'redeliverEndpointDelivery',\n RedeliverWebhookDelivery: 'redeliverWebhookDelivery',\n RedeliverWebhookDeliveryConsole: 'redeliverWebhookDeliveryConsole',\n RedriveSupportWebhookDelivery: 'redriveSupportWebhookDelivery',\n RefreshAgencyAdminTokens: 'refreshAgencyAdminTokens',\n RefreshConsoleSession: 'refreshConsoleSession',\n RefreshManagerTokens: 'refreshManagerTokens',\n RegenerateShareToken: 'regenerateShareToken',\n RegisterWebhookEndpoint: 'registerWebhookEndpoint',\n ReissueConsoleUserInvite: 'reissueConsoleUserInvite',\n ReissuePlatformAdminInvite: 'reissuePlatformAdminInvite',\n ReissuePlatformPartnerConsoleUserInvite: 'reissuePlatformPartnerConsoleUserInvite',\n RemoveFromManifest: 'removeFromManifest',\n RenamePlatformPartner: 'renamePlatformPartner',\n ReopenForm: 'reopenForm',\n ReopenPickupStop: 'reopenPickupStop',\n ReorderForm: 'reorderForm',\n ReorderItineraryItem: 'reorderItineraryItem',\n ReorderPickupStops: 'reorderPickupStops',\n ReplaceBookingVouchers: 'replaceBookingVouchers',\n ReplaySupportWebhookRange: 'replaySupportWebhookRange',\n ReplayWebhookEndpoint: 'replayWebhookEndpoint',\n ReplayWebhookEndpointConsole: 'replayWebhookEndpointConsole',\n RequestFileUpload: 'requestFileUpload',\n ResetPlatformPartnerConsoleUser: 'resetPlatformPartnerConsoleUser',\n ResetTestClock: 'resetTestClock',\n ResetTestClockConsole: 'resetTestClockConsole',\n ResolvePlatformCredential: 'resolvePlatformCredential',\n ReturnFloat: 'returnFloat',\n RevealShareToken: 'revealShareToken',\n RevokeApiKey: 'revokeApiKey',\n RevokeMyConsoleSession: 'revokeMyConsoleSession',\n RevokePlatformPartnerApiKey: 'revokePlatformPartnerApiKey',\n RevokeShareToken: 'revokeShareToken',\n RotateApiKey: 'rotateApiKey',\n RotateWebhookEndpointSecret: 'rotateWebhookEndpointSecret',\n RunJourneyStep: 'runJourneyStep',\n SaveCloseoutHandover: 'saveCloseoutHandover',\n SearchTravellerDirectory: 'searchTravellerDirectory',\n SendCommsTestMessage: 'sendCommsTestMessage',\n SendCommsTestMessageConsole: 'sendCommsTestMessageConsole',\n SendMessage: 'sendMessage',\n SetPlatformPartnerStatus: 'setPlatformPartnerStatus',\n ShareListForms: 'shareListForms',\n ShareRenderForm: 'shareRenderForm',\n ShareSaveForm: 'shareSaveForm',\n ShareSubmitForm: 'shareSubmitForm',\n SubmitExpenseClaim: 'submitExpenseClaim',\n SyncDigest: 'syncDigest',\n SyncPullTrip: 'syncPullTrip',\n SyncPush: 'syncPush',\n SyncPushShare: 'syncPushShare',\n TestCommsProviderCredential: 'testCommsProviderCredential',\n TestCommsProviderCredentialConsole: 'testCommsProviderCredentialConsole',\n TestWebhookEndpoint: 'testWebhookEndpoint',\n TestWebhookEndpointApiKey: 'testWebhookEndpointApiKey',\n ToggleChecklistItem: 'toggleChecklistItem',\n UnarchiveForm: 'unarchiveForm',\n UnassignManager: 'unassignManager',\n UnlinkSeatingManager: 'unlinkSeatingManager',\n UnlockCloseout: 'unlockCloseout',\n UpsertAgency: 'upsertAgency',\n UpsertAgencyAdmin: 'upsertAgencyAdmin',\n UpsertManager: 'upsertManager',\n UpsertTravellerProfile: 'upsertTravellerProfile',\n UpsertTrip: 'upsertTrip',\n UpsertVendor: 'upsertVendor',\n VoidCollection: 'voidCollection',\n VoidExpense: 'voidExpense',\n WithdrawExpenseClaim: 'withdrawExpenseClaim',\n} as const;\nexport type OperationId = (typeof OperationId)[keyof typeof OperationId];\n\n// Ordered list of accepted credential schemes per operation. An empty array\n// means the operation is public (no security requirement in the spec).\nexport const OPERATION_SECURITY: Readonly<Record<OperationId, readonly SecuritySchemeId[]>> = {\n acceptConsoleInvite: [],\n acceptPlatformAdminInvite: [],\n addChecklistItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n addItineraryItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n addPlatformIncidentUpdate: ['platformAdminAuth'],\n addTravellerNote: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n adjustFloat: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n advanceTestTime: ['apiKeyAuth'],\n advanceTestTimeConsole: ['consoleAuth'],\n archiveForm: ['apiKeyAuth', 'agencyAdminAuth'],\n assignManager: ['apiKeyAuth', 'agencyAdminAuth'],\n assignPickupTraveller: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n assignRoomingBed: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n assignSeating: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n autoAssignRooming: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n autoAssignSeating: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n boardPickupTraveller: ['managerAuth'],\n buildTestFixtures: ['apiKeyAuth'],\n buildTestFixturesConsole: ['consoleAuth'],\n bulkUpsertBookings: ['apiKeyAuth'],\n cancelTrip: ['apiKeyAuth'],\n changeMyConsolePassword: ['consoleAuth'],\n changeOwnPlatformPassword: ['platformAdminAuth'],\n claimStatusIngest: ['apiKeyAuth'],\n cloneForm: ['apiKeyAuth', 'agencyAdminAuth'],\n closeForm: ['apiKeyAuth', 'agencyAdminAuth'],\n closePickupStop: ['managerAuth'],\n confirmFileUpload: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n consoleLogin: [],\n consoleLogout: ['consoleAuth'],\n consoleSwitchPlane: ['consoleAuth'],\n copyAgencyEntitlement: ['consoleAuth'],\n correctPickupBoardStatus: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createAgencyConsole: ['consoleAuth'],\n createApiKey: ['consoleAuth'],\n createChecklistTemplate: ['apiKeyAuth', 'agencyAdminAuth'],\n createCommsProviderCredential: ['apiKeyAuth'],\n createCommsProviderCredentialConsole: ['consoleAuth'],\n createConsoleUser: ['consoleAuth'],\n createForm: ['apiKeyAuth', 'agencyAdminAuth'],\n createFormField: ['apiKeyAuth', 'agencyAdminAuth'],\n createFormSection: ['apiKeyAuth', 'agencyAdminAuth'],\n createMessageTemplate: ['apiKeyAuth'],\n createParty: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createPickupStop: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createPlatformAdmin: ['platformAdminAuth'],\n createPlatformIncident: ['platformAdminAuth'],\n createPlatformPartner: ['platformAdminAuth'],\n createPlatformPartnerConsoleUser: ['platformAdminAuth'],\n createRoomingRoom: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createRoomingStayWindow: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createSeatingVehicle: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createSupportGrant: ['platformAdminAuth'],\n createTraveller: ['apiKeyAuth', 'agencyAdminAuth'],\n createTrekWalkIn: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createVendor: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteBooking: ['apiKeyAuth'],\n deleteChecklistItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteChecklistTemplate: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteFile: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteForm: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteFormField: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteFormSection: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteItineraryItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteParty: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deletePickupStop: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deletePlatformPartnerPlan: ['platformAdminAuth'],\n deleteRoomingRoom: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteRoomingStayWindow: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteSeatingVehicle: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteVendor: ['apiKeyAuth', 'agencyAdminAuth'],\n dispatchForm: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n editWebhookEndpoint: ['consoleAuth'],\n eraseTraveller: ['apiKeyAuth'],\n exportCloseoutPack: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n exportFormResponses: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n exportTraveller: ['apiKeyAuth'],\n getAgencyAdminMe: ['agencyAdminAuth'],\n getAgencySettings: ['consoleAuth'],\n getAgencySettingsSelf: ['apiKeyAuth', 'agencyAdminAuth'],\n getAgencyTrip: ['apiKeyAuth', 'agencyAdminAuth'],\n getForm: ['apiKeyAuth', 'agencyAdminAuth', 'managerAuth'],\n getFormAggregate: ['apiKeyAuth'],\n getFormConsentReceipt: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n getFormResponse: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n getFormsCompletionMatrix: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n getFormsCrossModuleAnswers: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n getManagerAgencyProfile: ['apiKeyAuth', 'agencyAdminAuth'],\n getManagerInbox: ['managerAuth'],\n getNotificationDetail: ['managerAuth'],\n getShareManifest: ['shareAuth'],\n getShareSnapshot: ['shareAuth'],\n getTravellerAgencyProfile: ['apiKeyAuth', 'agencyAdminAuth'],\n getTravellerDetail: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n getTrip: ['apiKeyAuth'],\n getTripManifest: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n health: [],\n healthV1: [],\n inspectConsoleInvite: [],\n inspectPlatformAdminInvite: [],\n issueFloat: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n linkExpenseReceipt: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n linkSeatingManager: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listAgencies: ['consoleAuth'],\n listAgencyManagers: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listAgencyTrips: ['apiKeyAuth', 'agencyAdminAuth'],\n listApiKeys: ['consoleAuth'],\n listBookings: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n listChecklistTemplates: ['managerAuth', 'apiKeyAuth'],\n listChecklistTemplatesAdmin: ['apiKeyAuth', 'agencyAdminAuth'],\n listCollections: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listConsoleUsers: ['consoleAuth'],\n listEligibleCollections: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listEvents: ['apiKeyAuth'],\n listExpenses: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listFiles: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listFormBindings: ['apiKeyAuth', 'agencyAdminAuth', 'managerAuth'],\n listForms: ['apiKeyAuth', 'agencyAdminAuth'],\n listJourneyTriggers: ['apiKeyAuth', 'agencyAdminAuth'],\n listJourneyTriggersConsole: ['consoleAuth'],\n listManagerExpenses: ['managerAuth'],\n listManagerNotifications: ['managerAuth'],\n listMessages: ['apiKeyAuth'],\n listMessagesConsole: ['consoleAuth'],\n listMessageTemplates: ['apiKeyAuth'],\n listMyConsoleSessions: ['consoleAuth'],\n listOwnManagerTrips: ['managerAuth'],\n listParties: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n listPickupStops: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n listPlatformAdmins: ['platformAdminAuth'],\n listPlatformAudit: ['platformAdminAuth'],\n listPlatformIncidents: ['platformAdminAuth'],\n listPlatformPartnerApiKeys: ['platformAdminAuth'],\n listPlatformPartnerConsoleUsers: ['platformAdminAuth'],\n listPlatformPartners: ['platformAdminAuth'],\n listPlatformPlanTiers: ['platformAdminAuth'],\n listRoomingStayWindows: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n listShareTokens: ['apiKeyAuth', 'agencyAdminAuth'],\n listSupportIngestLog: ['platformAdminAuth'],\n listSupportWebhookDeliveries: ['platformAdminAuth'],\n listTravellerFormResponses: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTrekWalkIns: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTripFormResponses: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTripForms: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTripManagers: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTripManifest: ['apiKeyAuth', 'agencyAdminAuth'],\n listTripVendors: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n listWebhookDeliveries: ['apiKeyAuth'],\n listWebhookDeliveriesConsole: ['consoleAuth'],\n listWebhookEndpoints: ['consoleAuth'],\n lockCloseout: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n logExpense: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n managerCreateFormResponse: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n markNotificationRead: ['managerAuth'],\n mintAgencyAdminTokens: ['apiKeyAuth'],\n mintManagerTokens: ['apiKeyAuth'],\n mintShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n nudgeConsoleInvite: [],\n patchAgencyEntitlement: ['consoleAuth'],\n patchAgencySettings: ['consoleAuth'],\n patchAgencySettingsSelf: ['agencyAdminAuth'],\n patchChecklistItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchChecklistTemplate: ['apiKeyAuth', 'agencyAdminAuth'],\n patchConsoleUser: ['consoleAuth'],\n patchForm: ['apiKeyAuth', 'agencyAdminAuth'],\n patchFormField: ['apiKeyAuth', 'agencyAdminAuth'],\n patchFormSection: ['apiKeyAuth', 'agencyAdminAuth'],\n patchItineraryDay: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchItineraryItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchJourneyTrigger: ['apiKeyAuth', 'agencyAdminAuth'],\n patchJourneyTriggerConsole: ['consoleAuth'],\n patchMessageTemplate: ['apiKeyAuth'],\n patchParty: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchPickupStop: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchPlatformAdmin: ['platformAdminAuth'],\n patchPlatformPartnerConsoleUser: ['platformAdminAuth'],\n patchRoomingRoom: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchRoomingStayWindow: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchSeatingVehicle: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n patchTripManager: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n platformHealth: ['platformAdminAuth'],\n platformLogin: [],\n platformLogout: ['platformAdminAuth'],\n platformMe: ['platformAdminAuth'],\n platformRefreshTokens: ['platformAdminAuth'],\n platformWebhookHealth: ['platformAdminAuth'],\n postponeTrek: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n publishChecklistTemplate: ['apiKeyAuth', 'agencyAdminAuth'],\n publishForm: ['apiKeyAuth', 'agencyAdminAuth'],\n pullChecklistTemplate: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n pushBulkTrips: ['apiKeyAuth'],\n pushManifest: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n pushTripBalances: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n putCommsConfig: ['apiKeyAuth'],\n putCommsConfigConsole: ['consoleAuth'],\n putPlatformPartnerPlan: ['platformAdminAuth'],\n readAgencyEntitlement: ['consoleAuth'],\n readAgencyFeedbackSummary: ['agencyAdminAuth', 'apiKeyAuth'],\n readApiKey: ['consoleAuth'],\n readChecklistAggregate: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readChecklistItem: ['managerAuth', 'apiKeyAuth'],\n readCloseout: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readCommsConfig: ['apiKeyAuth'],\n readCommsConfigConsole: ['consoleAuth'],\n readConsoleAudit: ['consoleAuth'],\n readConsoleCertification: ['consoleAuth'],\n readConsoleMe: ['consoleAuth'],\n readConsoleUserInvite: ['consoleAuth'],\n readEndpointDeliveries: ['consoleAuth'],\n readEndpointDelivery: ['consoleAuth'],\n readEntitlementCatalog: ['consoleAuth'],\n readExpense: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readFile: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readFileUrl: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readFloatLedger: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readFloatSummary: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readIngestLog: ['consoleAuth'],\n readIngestLogSummary: ['consoleAuth'],\n readItinerary: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readItineraryChangeLog: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readJourney: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readJourneyCapabilities: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readManagerExpense: ['managerAuth'],\n readManagerExpenseLogMeta: ['managerAuth'],\n readManagerFileView: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readManagerToday: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readManifestByPickup: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readPlan: ['consoleAuth'],\n readPlatformPartner: ['platformAdminAuth'],\n readRoomingBoard: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readRoomingRoom: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readSeatingBoard: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n readSupportJourneyState: ['platformAdminAuth'],\n readSupportWebhookDeliveryDetail: ['platformAdminAuth'],\n readTenantDefaultCommsConfig: ['apiKeyAuth'],\n readTenantDefaultCommsConfigConsole: ['consoleAuth'],\n readTestClock: ['apiKeyAuth'],\n readTestClockConsole: ['consoleAuth'],\n readTestFixtures: ['apiKeyAuth'],\n readTestFixturesConsole: ['consoleAuth'],\n readTestQuota: ['apiKeyAuth'],\n readTestQuotaConsole: ['consoleAuth'],\n readTrekBoard: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readTrekWalkInMeta: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readTripFeedbackSummary: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readUsage: ['consoleAuth'],\n readWebhookDelivery: ['apiKeyAuth'],\n readWebhookDeliveryConsole: ['consoleAuth'],\n readWebhookEndpoint: ['consoleAuth'],\n readWebhookEventCatalog: ['consoleAuth'],\n reassignPickupStopTravellers: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n rebuildJourney: ['apiKeyAuth'],\n recheckConsoleCertification: ['consoleAuth'],\n reconcileTrekWalkIn: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n recordCollection: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n redeliverEndpointDelivery: ['consoleAuth'],\n redeliverWebhookDelivery: ['apiKeyAuth'],\n redeliverWebhookDeliveryConsole: ['consoleAuth'],\n redriveSupportWebhookDelivery: ['platformAdminAuth'],\n refreshAgencyAdminTokens: ['agencyAdminAuth'],\n refreshConsoleSession: ['consoleAuth'],\n refreshManagerTokens: ['managerAuth'],\n regenerateShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n registerWebhookEndpoint: ['consoleAuth'],\n reissueConsoleUserInvite: ['consoleAuth'],\n reissuePlatformAdminInvite: ['platformAdminAuth'],\n reissuePlatformPartnerConsoleUserInvite: ['platformAdminAuth'],\n removeFromManifest: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n renamePlatformPartner: ['platformAdminAuth'],\n reopenForm: ['apiKeyAuth', 'agencyAdminAuth'],\n reopenPickupStop: ['managerAuth'],\n reorderForm: ['apiKeyAuth', 'agencyAdminAuth'],\n reorderItineraryItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n reorderPickupStops: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n replaceBookingVouchers: ['apiKeyAuth', 'agencyAdminAuth'],\n replaySupportWebhookRange: ['platformAdminAuth'],\n replayWebhookEndpoint: ['apiKeyAuth'],\n replayWebhookEndpointConsole: ['consoleAuth'],\n requestFileUpload: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n resetPlatformPartnerConsoleUser: ['platformAdminAuth'],\n resetTestClock: ['apiKeyAuth'],\n resetTestClockConsole: ['consoleAuth'],\n resolvePlatformCredential: ['platformAdminAuth'],\n returnFloat: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n revealShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n revokeApiKey: ['consoleAuth'],\n revokeMyConsoleSession: ['consoleAuth'],\n revokePlatformPartnerApiKey: ['platformAdminAuth'],\n revokeShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n rotateApiKey: ['consoleAuth'],\n rotateWebhookEndpointSecret: ['consoleAuth'],\n runJourneyStep: ['apiKeyAuth'],\n saveCloseoutHandover: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n searchTravellerDirectory: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n sendCommsTestMessage: ['apiKeyAuth'],\n sendCommsTestMessageConsole: ['consoleAuth'],\n sendMessage: ['apiKeyAuth'],\n setPlatformPartnerStatus: ['platformAdminAuth'],\n shareListForms: ['shareAuth'],\n shareRenderForm: ['shareAuth'],\n shareSaveForm: ['shareAuth'],\n shareSubmitForm: ['shareAuth'],\n submitExpenseClaim: ['managerAuth', 'apiKeyAuth'],\n syncDigest: ['apiKeyAuth'],\n syncPullTrip: ['managerAuth', 'apiKeyAuth'],\n syncPush: ['managerAuth', 'apiKeyAuth'],\n syncPushShare: [],\n testCommsProviderCredential: ['apiKeyAuth'],\n testCommsProviderCredentialConsole: ['consoleAuth'],\n testWebhookEndpoint: ['consoleAuth'],\n testWebhookEndpointApiKey: ['apiKeyAuth'],\n toggleChecklistItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n unarchiveForm: ['apiKeyAuth', 'agencyAdminAuth'],\n unassignManager: ['apiKeyAuth', 'agencyAdminAuth'],\n unlinkSeatingManager: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n unlockCloseout: ['apiKeyAuth'],\n upsertAgency: ['apiKeyAuth'],\n upsertAgencyAdmin: ['apiKeyAuth'],\n upsertManager: ['apiKeyAuth'],\n upsertTravellerProfile: ['apiKeyAuth'],\n upsertTrip: ['apiKeyAuth'],\n upsertVendor: ['apiKeyAuth', 'agencyAdminAuth'],\n voidCollection: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n voidExpense: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n withdrawExpenseClaim: ['managerAuth', 'apiKeyAuth'],\n};\n\n// 110 of 327 operations accept an `Idempotency-Key` header, per each\n// operation's `parameters` in the vendored spec.\nexport const OPERATION_ACCEPTS_IDEMPOTENCY_KEY: Readonly<Record<OperationId, boolean>> = {\n acceptConsoleInvite: true,\n acceptPlatformAdminInvite: true,\n addChecklistItem: true,\n addItineraryItem: true,\n addPlatformIncidentUpdate: false,\n addTravellerNote: true,\n adjustFloat: true,\n advanceTestTime: true,\n advanceTestTimeConsole: true,\n archiveForm: false,\n assignManager: true,\n assignPickupTraveller: true,\n assignRoomingBed: true,\n assignSeating: true,\n autoAssignRooming: true,\n autoAssignSeating: true,\n boardPickupTraveller: true,\n buildTestFixtures: true,\n buildTestFixturesConsole: true,\n bulkUpsertBookings: true,\n cancelTrip: true,\n changeMyConsolePassword: true,\n changeOwnPlatformPassword: false,\n claimStatusIngest: true,\n cloneForm: true,\n closeForm: false,\n closePickupStop: true,\n confirmFileUpload: true,\n consoleLogin: false,\n consoleLogout: false,\n consoleSwitchPlane: false,\n copyAgencyEntitlement: true,\n correctPickupBoardStatus: false,\n createAgencyConsole: false,\n createApiKey: true,\n createChecklistTemplate: true,\n createCommsProviderCredential: true,\n createCommsProviderCredentialConsole: true,\n createConsoleUser: true,\n createForm: true,\n createFormField: false,\n createFormSection: false,\n createMessageTemplate: true,\n createParty: true,\n createPickupStop: true,\n createPlatformAdmin: false,\n createPlatformIncident: false,\n createPlatformPartner: false,\n createPlatformPartnerConsoleUser: false,\n createRoomingRoom: true,\n createRoomingStayWindow: true,\n createSeatingVehicle: true,\n createSupportGrant: false,\n createTraveller: true,\n createTrekWalkIn: true,\n createVendor: true,\n deleteBooking: true,\n deleteChecklistItem: false,\n deleteChecklistTemplate: false,\n deleteFile: true,\n deleteForm: false,\n deleteFormField: false,\n deleteFormSection: false,\n deleteItineraryItem: false,\n deleteParty: true,\n deletePickupStop: false,\n deletePlatformPartnerPlan: false,\n deleteRoomingRoom: false,\n deleteRoomingStayWindow: false,\n deleteSeatingVehicle: false,\n deleteVendor: true,\n dispatchForm: true,\n editWebhookEndpoint: true,\n eraseTraveller: true,\n exportCloseoutPack: false,\n exportFormResponses: false,\n exportTraveller: false,\n getAgencyAdminMe: false,\n getAgencySettings: false,\n getAgencySettingsSelf: false,\n getAgencyTrip: false,\n getForm: false,\n getFormAggregate: false,\n getFormConsentReceipt: false,\n getFormResponse: false,\n getFormsCompletionMatrix: false,\n getFormsCrossModuleAnswers: false,\n getManagerAgencyProfile: false,\n getManagerInbox: false,\n getNotificationDetail: false,\n getShareManifest: false,\n getShareSnapshot: false,\n getTravellerAgencyProfile: false,\n getTravellerDetail: false,\n getTrip: false,\n getTripManifest: false,\n health: false,\n healthV1: false,\n inspectConsoleInvite: false,\n inspectPlatformAdminInvite: false,\n issueFloat: true,\n linkExpenseReceipt: true,\n linkSeatingManager: true,\n listAgencies: false,\n listAgencyManagers: false,\n listAgencyTrips: false,\n listApiKeys: false,\n listBookings: false,\n listChecklistTemplates: false,\n listChecklistTemplatesAdmin: false,\n listCollections: false,\n listConsoleUsers: false,\n listEligibleCollections: false,\n listEvents: false,\n listExpenses: false,\n listFiles: false,\n listFormBindings: false,\n listForms: false,\n listJourneyTriggers: false,\n listJourneyTriggersConsole: false,\n listManagerExpenses: false,\n listManagerNotifications: false,\n listMessages: false,\n listMessagesConsole: false,\n listMessageTemplates: false,\n listMyConsoleSessions: false,\n listOwnManagerTrips: false,\n listParties: false,\n listPickupStops: false,\n listPlatformAdmins: false,\n listPlatformAudit: false,\n listPlatformIncidents: false,\n listPlatformPartnerApiKeys: false,\n listPlatformPartnerConsoleUsers: false,\n listPlatformPartners: false,\n listPlatformPlanTiers: false,\n listRoomingStayWindows: false,\n listShareTokens: false,\n listSupportIngestLog: false,\n listSupportWebhookDeliveries: false,\n listTravellerFormResponses: false,\n listTrekWalkIns: false,\n listTripFormResponses: false,\n listTripForms: false,\n listTripManagers: false,\n listTripManifest: false,\n listTripVendors: false,\n listWebhookDeliveries: false,\n listWebhookDeliveriesConsole: false,\n listWebhookEndpoints: false,\n lockCloseout: true,\n logExpense: true,\n managerCreateFormResponse: true,\n markNotificationRead: true,\n mintAgencyAdminTokens: false,\n mintManagerTokens: false,\n mintShareToken: true,\n nudgeConsoleInvite: false,\n patchAgencyEntitlement: true,\n patchAgencySettings: false,\n patchAgencySettingsSelf: false,\n patchChecklistItem: false,\n patchChecklistTemplate: false,\n patchConsoleUser: true,\n patchForm: false,\n patchFormField: false,\n patchFormSection: false,\n patchItineraryDay: false,\n patchItineraryItem: false,\n patchJourneyTrigger: true,\n patchJourneyTriggerConsole: true,\n patchMessageTemplate: false,\n patchParty: true,\n patchPickupStop: false,\n patchPlatformAdmin: false,\n patchPlatformPartnerConsoleUser: false,\n patchRoomingRoom: false,\n patchRoomingStayWindow: false,\n patchSeatingVehicle: false,\n patchShareToken: false,\n patchTripManager: false,\n platformHealth: false,\n platformLogin: true,\n platformLogout: false,\n platformMe: false,\n platformRefreshTokens: true,\n platformWebhookHealth: false,\n postponeTrek: true,\n publishChecklistTemplate: false,\n publishForm: false,\n pullChecklistTemplate: true,\n pushBulkTrips: true,\n pushManifest: true,\n pushTripBalances: true,\n putCommsConfig: false,\n putCommsConfigConsole: false,\n putPlatformPartnerPlan: false,\n readAgencyEntitlement: false,\n readAgencyFeedbackSummary: false,\n readApiKey: false,\n readChecklistAggregate: false,\n readChecklistItem: false,\n readCloseout: false,\n readCommsConfig: false,\n readCommsConfigConsole: false,\n readConsoleAudit: false,\n readConsoleCertification: false,\n readConsoleMe: false,\n readConsoleUserInvite: false,\n readEndpointDeliveries: false,\n readEndpointDelivery: false,\n readEntitlementCatalog: false,\n readExpense: false,\n readFile: false,\n readFileUrl: false,\n readFloatLedger: false,\n readFloatSummary: false,\n readIngestLog: false,\n readIngestLogSummary: false,\n readItinerary: false,\n readItineraryChangeLog: false,\n readJourney: false,\n readJourneyCapabilities: false,\n readManagerExpense: false,\n readManagerExpenseLogMeta: false,\n readManagerFileView: false,\n readManagerToday: false,\n readManifestByPickup: false,\n readPlan: false,\n readPlatformPartner: false,\n readRoomingBoard: false,\n readRoomingRoom: false,\n readSeatingBoard: false,\n readShareToken: false,\n readSupportJourneyState: false,\n readSupportWebhookDeliveryDetail: false,\n readTenantDefaultCommsConfig: false,\n readTenantDefaultCommsConfigConsole: false,\n readTestClock: false,\n readTestClockConsole: false,\n readTestFixtures: false,\n readTestFixturesConsole: false,\n readTestQuota: false,\n readTestQuotaConsole: false,\n readTrekBoard: false,\n readTrekWalkInMeta: false,\n readTripFeedbackSummary: false,\n readUsage: false,\n readWebhookDelivery: false,\n readWebhookDeliveryConsole: false,\n readWebhookEndpoint: false,\n readWebhookEventCatalog: false,\n reassignPickupStopTravellers: true,\n rebuildJourney: true,\n recheckConsoleCertification: false,\n reconcileTrekWalkIn: true,\n recordCollection: true,\n redeliverEndpointDelivery: true,\n redeliverWebhookDelivery: true,\n redeliverWebhookDeliveryConsole: true,\n redriveSupportWebhookDelivery: false,\n refreshAgencyAdminTokens: false,\n refreshConsoleSession: false,\n refreshManagerTokens: false,\n regenerateShareToken: true,\n registerWebhookEndpoint: true,\n reissueConsoleUserInvite: true,\n reissuePlatformAdminInvite: false,\n reissuePlatformPartnerConsoleUserInvite: false,\n removeFromManifest: true,\n renamePlatformPartner: false,\n reopenForm: false,\n reopenPickupStop: true,\n reorderForm: false,\n reorderItineraryItem: true,\n reorderPickupStops: true,\n replaceBookingVouchers: false,\n replaySupportWebhookRange: false,\n replayWebhookEndpoint: true,\n replayWebhookEndpointConsole: true,\n requestFileUpload: true,\n resetPlatformPartnerConsoleUser: false,\n resetTestClock: true,\n resetTestClockConsole: true,\n resolvePlatformCredential: false,\n returnFloat: true,\n revealShareToken: false,\n revokeApiKey: true,\n revokeMyConsoleSession: true,\n revokePlatformPartnerApiKey: false,\n revokeShareToken: false,\n rotateApiKey: true,\n rotateWebhookEndpointSecret: true,\n runJourneyStep: true,\n saveCloseoutHandover: true,\n searchTravellerDirectory: false,\n sendCommsTestMessage: true,\n sendCommsTestMessageConsole: true,\n sendMessage: true,\n setPlatformPartnerStatus: false,\n shareListForms: false,\n shareRenderForm: false,\n shareSaveForm: true,\n shareSubmitForm: true,\n submitExpenseClaim: true,\n syncDigest: false,\n syncPullTrip: false,\n syncPush: false,\n syncPushShare: false,\n testCommsProviderCredential: true,\n testCommsProviderCredentialConsole: true,\n testWebhookEndpoint: false,\n testWebhookEndpointApiKey: false,\n toggleChecklistItem: true,\n unarchiveForm: false,\n unassignManager: true,\n unlinkSeatingManager: false,\n unlockCloseout: true,\n upsertAgency: true,\n upsertAgencyAdmin: true,\n upsertManager: true,\n upsertTravellerProfile: true,\n upsertTrip: true,\n upsertVendor: true,\n voidCollection: false,\n voidExpense: false,\n withdrawExpenseClaim: false,\n};\n","/**\n * This file was auto-generated by `scripts/gen-meta.mjs` from\n * `openapi/openapi.json`. Do not make direct changes to the file — re-run\n * `pnpm gen:types` instead.\n *\n * @generated src/generated/error-codes.ts\n */\n\n// `status` is `null` for a code that no operation's `responses` declares in\n// the vendored spec — the code exists in the `ErrorCode` enum and in both\n// `x-kaafil-*` maps, but no current operation returns it. Never backfilled by\n// hand: when an operation starts declaring it, re-running `pnpm gen:types`\n// fills the real status in.\n\nexport const KaafilErrorCode = {\n ActiveRequiresManager: 'ACTIVE_REQUIRES_MANAGER',\n BusinessRuleViolation: 'BUSINESS_RULE_VIOLATION',\n CannotPostpone: 'CANNOT_POSTPONE',\n CapabilityUnavailable: 'CAPABILITY_UNAVAILABLE',\n ConflictVersion: 'CONFLICT_VERSION',\n ConsentRequired: 'CONSENT_REQUIRED',\n FieldNotVisible: 'FIELD_NOT_VISIBLE',\n FileOrphaned: 'FILE_ORPHANED',\n FilePurged: 'FILE_PURGED',\n FormClosed: 'FORM_CLOSED',\n FormDefinitionChanged: 'FORM_DEFINITION_CHANGED',\n FormLockedByResponses: 'FORM_LOCKED_BY_RESPONSES',\n FormNotOpen: 'FORM_NOT_OPEN',\n FormNotPublishable: 'FORM_NOT_PUBLISHABLE',\n FormWindowInvalid: 'FORM_WINDOW_INVALID',\n IdempotencyKeyReused: 'IDEMPOTENCY_KEY_REUSED',\n InternalError: 'INTERNAL_ERROR',\n Locked: 'LOCKED',\n NotATrek: 'NOT_A_TREK',\n NotImplemented: 'NOT_IMPLEMENTED',\n OutOfTripWindow: 'OUT_OF_TRIP_WINDOW',\n PlanFeatureDisabled: 'PLAN_FEATURE_DISABLED',\n RateLimited: 'RATE_LIMITED',\n ReadOnlyRole: 'READ_ONLY_ROLE',\n ResourceNotFound: 'RESOURCE_NOT_FOUND',\n ResponseClosed: 'RESPONSE_CLOSED',\n ResponseLimitReached: 'RESPONSE_LIMIT_REACHED',\n SeatingCapacityOrphan: 'SEATING_CAPACITY_ORPHAN',\n SecretNotReplayable: 'SECRET_NOT_REPLAYABLE',\n ShareTokenExpired: 'SHARE_TOKEN_EXPIRED',\n ShareTokenRevoked: 'SHARE_TOKEN_REVOKED',\n ShareWriteGraceExpired: 'SHARE_WRITE_GRACE_EXPIRED',\n StayWindowHasAssignments: 'STAY_WINDOW_HAS_ASSIGNMENTS',\n StayWindowOverlap: 'STAY_WINDOW_OVERLAP',\n StopHasPending: 'STOP_HAS_PENDING',\n SubjectRequired: 'SUBJECT_REQUIRED',\n SupportGrantRequired: 'SUPPORT_GRANT_REQUIRED',\n SyncTargetRefused: 'SYNC_TARGET_REFUSED',\n TenantScopeMissing: 'TENANT_SCOPE_MISSING',\n TestClockBackwards: 'TEST_CLOCK_BACKWARDS',\n TestClockTooFar: 'TEST_CLOCK_TOO_FAR',\n TestFixtureScenarioUnknown: 'TEST_FIXTURE_SCENARIO_UNKNOWN',\n TestTravellerLimit: 'TEST_TRAVELLER_LIMIT',\n TestTripLimit: 'TEST_TRIP_LIMIT',\n Unauthenticated: 'UNAUTHENTICATED',\n UploadMismatch: 'UPLOAD_MISMATCH',\n ValidationError: 'VALIDATION_ERROR',\n} as const;\nexport type KaafilErrorCode = (typeof KaafilErrorCode)[keyof typeof KaafilErrorCode];\n\nexport const Retryability = {\n No: 'no',\n Yes: 'yes',\n AfterRefresh: 'after-refresh',\n HonourRetryAfter: 'honour-retry-after',\n} as const;\nexport type Retryability = (typeof Retryability)[keyof typeof Retryability];\n\nexport const OutboxClass = {\n Transient: 'TRANSIENT',\n Conflict: 'CONFLICT',\n Fatal: 'FATAL',\n} as const;\nexport type OutboxClass = (typeof OutboxClass)[keyof typeof OutboxClass];\n\nexport interface ErrorCodeTableEntry {\n /** Always present: every code's status comes from the catalog, not from\n * whichever operations happen to declare the code. */\n readonly status: number;\n readonly retryability: Retryability;\n readonly outboxClass: OutboxClass;\n}\n\nexport const ERROR_CODE_TABLE: Readonly<Record<KaafilErrorCode, ErrorCodeTableEntry>> = {\n ACTIVE_REQUIRES_MANAGER: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n BUSINESS_RULE_VIOLATION: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n CANNOT_POSTPONE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n CAPABILITY_UNAVAILABLE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n CONFLICT_VERSION: { status: 409, retryability: 'no', outboxClass: 'CONFLICT' },\n CONSENT_REQUIRED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FIELD_NOT_VISIBLE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FILE_ORPHANED: { status: 409, retryability: 'no', outboxClass: 'FATAL' },\n FILE_PURGED: { status: 410, retryability: 'no', outboxClass: 'FATAL' },\n FORM_CLOSED: { status: 409, retryability: 'no', outboxClass: 'FATAL' },\n FORM_DEFINITION_CHANGED: { status: 409, retryability: 'no', outboxClass: 'FATAL' },\n FORM_LOCKED_BY_RESPONSES: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FORM_NOT_OPEN: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FORM_NOT_PUBLISHABLE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FORM_WINDOW_INVALID: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n IDEMPOTENCY_KEY_REUSED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n INTERNAL_ERROR: { status: 500, retryability: 'yes', outboxClass: 'TRANSIENT' },\n LOCKED: { status: 423, retryability: 'no', outboxClass: 'FATAL' },\n NOT_A_TREK: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n NOT_IMPLEMENTED: { status: 501, retryability: 'no', outboxClass: 'FATAL' },\n OUT_OF_TRIP_WINDOW: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n PLAN_FEATURE_DISABLED: { status: 402, retryability: 'no', outboxClass: 'FATAL' },\n RATE_LIMITED: { status: 429, retryability: 'honour-retry-after', outboxClass: 'TRANSIENT' },\n READ_ONLY_ROLE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n RESOURCE_NOT_FOUND: { status: 404, retryability: 'no', outboxClass: 'FATAL' },\n RESPONSE_CLOSED: { status: 409, retryability: 'no', outboxClass: 'FATAL' },\n RESPONSE_LIMIT_REACHED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n SEATING_CAPACITY_ORPHAN: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n SECRET_NOT_REPLAYABLE: { status: 409, retryability: 'no', outboxClass: 'CONFLICT' },\n SHARE_TOKEN_EXPIRED: { status: 401, retryability: 'no', outboxClass: 'FATAL' },\n SHARE_TOKEN_REVOKED: { status: 401, retryability: 'no', outboxClass: 'FATAL' },\n SHARE_WRITE_GRACE_EXPIRED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n STAY_WINDOW_HAS_ASSIGNMENTS: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n STAY_WINDOW_OVERLAP: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n STOP_HAS_PENDING: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n SUBJECT_REQUIRED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n SUPPORT_GRANT_REQUIRED: { status: 403, retryability: 'no', outboxClass: 'FATAL' },\n SYNC_TARGET_REFUSED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TENANT_SCOPE_MISSING: { status: 500, retryability: 'yes', outboxClass: 'TRANSIENT' },\n TEST_CLOCK_BACKWARDS: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TEST_CLOCK_TOO_FAR: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TEST_FIXTURE_SCENARIO_UNKNOWN: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TEST_TRAVELLER_LIMIT: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TEST_TRIP_LIMIT: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n UNAUTHENTICATED: { status: 401, retryability: 'after-refresh', outboxClass: 'FATAL' },\n UPLOAD_MISMATCH: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n VALIDATION_ERROR: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n};\n","import { ERROR_CODE_TABLE, KaafilErrorCode, Retryability } from '../generated/error-codes';\nimport type { ResponseMeta } from '../types/meta';\n\n// Error semantics cited, never restated: `architecture/08-sdk.md §6`\n// (retries & error handling), `architecture/06-offline-first.md §7` (FATAL /\n// CONFLICT / TRANSIENT classification), `architecture/10-conventions.md §7`\n// (the master error catalog) and `architecture/03-auth-and-tokens.md §2`\n// (manager token rotation / `READ_ONLY_ROLE`).\n\n/**\n * Distinguishes a real API response (has a catalog `.code`) from a\n * transport-level failure (network, timeout, abort — never reached a\n * catalog code because no response envelope was ever parsed). Present on\n * the base class, not just inferable via `instanceof`, so a consumer whose\n * bundler duplicated this package across two copies can still branch —\n * `instanceof` across two module instances of the same package is a real,\n * if rare, hazard.\n */\nexport type KaafilErrorKind = 'api' | 'transport';\n\ninterface KaafilErrorInit {\n readonly code?: KaafilErrorCode;\n readonly status?: number;\n readonly details?: Record<string, unknown>;\n readonly requestId?: string;\n readonly meta?: ResponseMeta;\n readonly cause?: unknown;\n}\n\n/**\n * Base of every error this SDK throws. Carries the fields a consumer needs\n * to branch on (`code`, `kind`) and the fields support needs to trace a\n * request (`status`, `requestId`, `meta`).\n *\n * Subclassing `Error` and relying on `instanceof` later breaks once a build\n * step downlevels the output (the prototype chain gets rebuilt incorrectly\n * by some ES5 target transforms) — every concrete leaf class below restores\n * its own prototype with `Object.setPrototypeOf` after calling `super()`.\n */\nexport abstract class KaafilError extends Error {\n abstract readonly kind: KaafilErrorKind;\n readonly code: KaafilErrorCode | undefined;\n readonly status: number | undefined;\n readonly details: Record<string, unknown> | undefined;\n readonly requestId: string | undefined;\n readonly meta: ResponseMeta | undefined;\n\n protected constructor(message: string, init: KaafilErrorInit = {}) {\n super(message, init.cause !== undefined ? { cause: init.cause } : undefined);\n this.name = 'KaafilError';\n this.code = init.code;\n this.status = init.status;\n this.details = init.details;\n this.requestId = init.requestId;\n this.meta = init.meta;\n }\n}\n\n/**\n * A response the server actually answered, carrying a catalog `.code`. Also\n * the fallback for a catalog code that has no dedicated subclass below —\n * every one of the 24 cross-cutting codes in `ERROR_CODE_TABLE` produces at\n * least a typed `KaafilApiError`, even the ones a consumer rarely needs to\n * branch on by name (`BUSINESS_RULE_VIOLATION`, `TENANT_SCOPE_MISSING`, …).\n *\n * ── WHY 10B's FIVE MODULE-LOCAL CODES DID NOT EARN A DEDICATED SUBCLASS ─────\n *\n * `SEATING_CAPACITY_ORPHAN`, `NOT_A_TREK`, `CANNOT_POSTPONE`,\n * `STAY_WINDOW_OVERLAP` and `STAY_WINDOW_HAS_ASSIGNMENTS` all resolve to a\n * plain `KaafilApiError` through `fromEnvelope`'s `default` branch, same as\n * `BUSINESS_RULE_VIOLATION`. The temptation, having just built the module-\n * local registry that lets a module publish its OWN named code, is to give\n * each one its own class to match — but the twelve codes that DO have a\n * dedicated class below (`ResourceNotFound`, `PlanFeatureDisabled`,\n * `CapabilityUnavailable`, `ReadOnlyRole`, `ValidationError`,\n * `ConflictVersion`, `Locked`, `RateLimited`, `Unauthenticated`,\n * `ShareTokenExpired`, `ShareTokenRevoked`, `NotImplemented`) share a trait\n * none of these five have: each is part of the SDK's OWN cross-module\n * machinery — auth, retry, offline sync, idempotency — reused with an\n * IDENTICAL meaning everywhere it appears, which is exactly why `errors.ts`\n * (a `shared/`-level file) is the right place to name it once. A\n * module-local code is, by the registry's own rule, owned by exactly one\n * module and defined once in that module's FRD; giving it a class in this\n * shared file would start coupling the shared error hierarchy to one\n * module's business specifics — the identical boundary violation\n * `module-error-codes.ts` (engine-side) already refuses for the opposite\n * direction (\"`shared/` may never import a module\").\n *\n * Nor does branching need it: `error.code === KaafilErrorCode.NotATrek` is\n * already fully typed (`KaafilErrorCode` is a real union, not a bare\n * string), so a UI that branches on `NOT_A_TREK` or `SEATING_CAPACITY_ORPHAN`\n * — and the plan for this phase says explicitly that a UI does — gets that\n * from `.code` alone, no `instanceof` required. That is precisely the\n * precedent `STOP_HAS_PENDING` and `OUT_OF_TRIP_WINDOW` already set: both are\n * equally single-meaning, equally UI-branchable codes from earlier phases,\n * and neither got a class either. Multiplying subclasses per code the moment\n * a caller might name-check one would eventually turn this file into a\n * mirror of the whole catalog — which is the same \"just add a 25th entry\"\n * instinct the module-local registry was built specifically to avoid on the\n * engine side (see `module-error-codes.ts`'s header). `SEATING_CAPACITY_ORPHAN`\n * carries an orphaned count and labels in `details` — read those\n * defensively off `.details`, the same as `KaafilValidationError.fields`\n * would if this file ever decides the getter is worth adding; it does not\n * change which class the error is.\n *\n * This is not a permanent ruling. If a module-local code later needs a typed\n * getter over `details` the way `KaafilVersionConflictError.currentVersion`\n * does, that is the trigger to add ONE dedicated class for THAT code — not a\n * reason to add all five at once pre-emptively.\n */\nexport class KaafilApiError extends KaafilError {\n override readonly kind = 'api' as const;\n override readonly code: KaafilErrorCode;\n\n constructor(code: KaafilErrorCode, message: string, init: Omit<KaafilErrorInit, 'code'> = {}) {\n super(message, { ...init, code });\n this.name = 'KaafilApiError';\n this.code = code;\n Object.setPrototypeOf(this, KaafilApiError.prototype);\n }\n}\n\ntype ApiErrorInit = Omit<KaafilErrorInit, 'code'>;\n\n/**\n * `404 RESOURCE_NOT_FOUND` — the **only** not-found class this SDK has, on\n * purpose. Tenant isolation and genuine absence answer the identical `404`\n * by design: a distinguishing code would itself be an existence leak (a\n * cross-tenant probe could tell \"wrong tenant\" apart from \"never existed\").\n * Do not add a second not-found class — the ambiguity is the contract, not\n * a gap in it (`10-conventions.md §7`, `06-offline-first.md §7`).\n */\nexport class KaafilNotFoundError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ResourceNotFound'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ResourceNotFound, message, init);\n this.name = 'KaafilNotFoundError';\n this.code = KaafilErrorCode.ResourceNotFound;\n Object.setPrototypeOf(this, KaafilNotFoundError.prototype);\n }\n}\n\n/**\n * Every `details.reason` a `402 PLAN_FEATURE_DISABLED` refusal can carry —\n * mirrors the engine's `PlanRefusalReason`\n * (`shared/errors/error-factory.ts`). Not generated from the vendored spec:\n * `ErrorEnvelope.error.details` is `{ additionalProperties: {} }` there —\n * deliberately untyped, because `details`' shape varies by code — so this\n * one field, on this one code, is hand-declared rather than produced by\n * `gen-meta.mjs`. Different people act on the four values: the CRM flips\n * its own switch (`agencyFlag`), Kaafil sells an upgrade (`partnerTier`),\n * nobody does anything until the billing period rolls (`tripQuota`), or\n * someone frees storage or upgrades — a storage cap never resets\n * (`storageQuota`) — a bare `402` cannot tell a caller which.\n */\nexport type PlanRefusalReason = 'agencyFlag' | 'partnerTier' | 'tripQuota' | 'storageQuota';\n\nconst PLAN_REFUSAL_REASONS: ReadonlySet<string> = new Set<PlanRefusalReason>([\n 'agencyFlag',\n 'partnerTier',\n 'tripQuota',\n 'storageQuota',\n]);\n\n/**\n * `402 PLAN_FEATURE_DISABLED` — an entitlement gap. Never retried.\n *\n * `details`' shape is per-`reason`, and the one field worth calling out is\n * `storageQuota`'s `includedBytes`: it is `number | null`, not a number.\n * `null` is what the TEST plane sends — a sandbox has no soft, billable rung\n * to overshoot, only the hard cap (`hardCapBytes`) — so a UI must not render\n * a `null` `includedBytes` as `0`, and must not compute \"bytes remaining\"\n * from it without a null check. On LIVE it is the plan's included figure,\n * and usage above it but under `hardCapBytes` is billed as overage rather\n * than refused. See `../resources/test.ts`'s `quota()` for the sandbox side\n * of the same cap.\n */\nexport class KaafilEntitlementError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['PlanFeatureDisabled'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.PlanFeatureDisabled, message, init);\n this.name = 'KaafilEntitlementError';\n this.code = KaafilErrorCode.PlanFeatureDisabled;\n Object.setPrototypeOf(this, KaafilEntitlementError.prototype);\n }\n\n /**\n * `details.reason` — which person (or which wait) fixes this. Read\n * defensively, like `.fields`/`.currentVersion` below: `details` is\n * untyped at the transport boundary, so a value this SDK does not\n * recognise (an engine that ships a fifth reason before this SDK knows\n * about it) surfaces as `undefined` rather than a wrong branch. The guard\n * reads the same set the type is declared from, so adding a reason is one\n * edit, not two that can drift — `storageQuota` shipped on the engine\n * before this guard knew it, and every storage refusal read as `undefined`.\n */\n get reason(): PlanRefusalReason | undefined {\n const value = this.details?.reason;\n return typeof value === 'string' && PLAN_REFUSAL_REASONS.has(value)\n ? (value as PlanRefusalReason)\n : undefined;\n }\n\n /**\n * `details.requiredTier` — the cheapest tier that would lift this refusal,\n * carried on `partnerTier` and `tripQuota`; `null` on `agencyFlag` (no tier\n * would help — the agency never asked) and absent on `storageQuota`.\n */\n get requiredTier(): string | null | undefined {\n const value = this.details?.requiredTier;\n return value === null || typeof value === 'string' ? value : undefined;\n }\n}\n\n/**\n * `422 CAPABILITY_UNAVAILABLE` — a dark capability (ingested data absent or\n * mode-inapplicable for the trip). Shares HTTP status 422 with several other\n * codes; `.code` is the discriminant, never the status.\n */\nexport class KaafilCapabilityUnavailableError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['CapabilityUnavailable'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.CapabilityUnavailable, message, init);\n this.name = 'KaafilCapabilityUnavailableError';\n this.code = KaafilErrorCode.CapabilityUnavailable;\n Object.setPrototypeOf(this, KaafilCapabilityUnavailableError.prototype);\n }\n}\n\n/**\n * `422 READ_ONLY_ROLE` — a `COORDINATOR` manager token attempted a write on\n * a `PERSONALIZED` trip; the role reads everything and writes nothing, with\n * no exception (`03-auth-and-tokens.md §2`). Also shares status 422.\n */\nexport class KaafilReadOnlyRoleError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ReadOnlyRole'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ReadOnlyRole, message, init);\n this.name = 'KaafilReadOnlyRoleError';\n this.code = KaafilErrorCode.ReadOnlyRole;\n Object.setPrototypeOf(this, KaafilReadOnlyRoleError.prototype);\n }\n}\n\n/**\n * `422 VALIDATION_ERROR` — body/params failed schema validation. `.fields`\n * reads `details.fields` defensively, since `details` is untyped at the\n * transport boundary.\n */\nexport class KaafilValidationError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ValidationError'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ValidationError, message, init);\n this.name = 'KaafilValidationError';\n this.code = KaafilErrorCode.ValidationError;\n Object.setPrototypeOf(this, KaafilValidationError.prototype);\n }\n\n get fields(): Record<string, unknown> | undefined {\n const value = this.details?.fields;\n return typeof value === 'object' && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n }\n}\n\n/**\n * `409 CONFLICT_VERSION` — `If-Match`/`expectedVersion` went stale.\n * `.currentVersion` reads `details.currentVersion` (`06-offline-first.md\n * §6`); the SDK's sync engine re-pulls and reconciles rather than\n * blind-retrying.\n */\nexport class KaafilVersionConflictError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ConflictVersion'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ConflictVersion, message, init);\n this.name = 'KaafilVersionConflictError';\n this.code = KaafilErrorCode.ConflictVersion;\n Object.setPrototypeOf(this, KaafilVersionConflictError.prototype);\n }\n\n get currentVersion(): number | undefined {\n const value = this.details?.currentVersion;\n return typeof value === 'number' ? value : undefined;\n }\n}\n\n/**\n * `423 LOCKED` — a write raced past trip close-out. Terminal: park the op,\n * never retry (`08-sdk.md §6`, `06-offline-first.md §7`).\n */\nexport class KaafilLockedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['Locked'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.Locked, message, init);\n this.name = 'KaafilLockedError';\n this.code = KaafilErrorCode.Locked;\n Object.setPrototypeOf(this, KaafilLockedError.prototype);\n }\n}\n\n/**\n * `429 RATE_LIMITED`. `.retryAfterSeconds` is a transport fact (the\n * `Retry-After` header), not part of the error envelope schema — the\n * factory that builds this error is responsible for supplying it from the\n * response headers.\n */\nexport class KaafilRateLimitedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['RateLimited'];\n readonly retryAfterSeconds: number | undefined;\n\n constructor(message: string, init: ApiErrorInit & { readonly retryAfterSeconds?: number } = {}) {\n const { retryAfterSeconds, ...rest } = init;\n super(KaafilErrorCode.RateLimited, message, rest);\n this.name = 'KaafilRateLimitedError';\n this.code = KaafilErrorCode.RateLimited;\n this.retryAfterSeconds = retryAfterSeconds;\n Object.setPrototypeOf(this, KaafilRateLimitedError.prototype);\n }\n}\n\n/**\n * `401 UNAUTHENTICATED` — missing/expired credential. The SDK attempts\n * exactly one token refresh before surfacing this (`03-auth-and-tokens.md\n * §2`); by the time a consumer sees it, that attempt already failed.\n */\nexport class KaafilUnauthenticatedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['Unauthenticated'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.Unauthenticated, message, init);\n this.name = 'KaafilUnauthenticatedError';\n this.code = KaafilErrorCode.Unauthenticated;\n Object.setPrototypeOf(this, KaafilUnauthenticatedError.prototype);\n }\n}\n\n/**\n * `401 SHARE_TOKEN_EXPIRED` — terminal, unlike `UNAUTHENTICATED`: there is\n * no refresh to attempt for a share token. Purges the cached snapshot\n * (`06-offline-first.md §8`).\n */\nexport class KaafilShareTokenExpiredError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ShareTokenExpired'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ShareTokenExpired, message, init);\n this.name = 'KaafilShareTokenExpiredError';\n this.code = KaafilErrorCode.ShareTokenExpired;\n Object.setPrototypeOf(this, KaafilShareTokenExpiredError.prototype);\n }\n}\n\n/** `401 SHARE_TOKEN_REVOKED` — terminal, same purge behaviour as expiry. */\nexport class KaafilShareTokenRevokedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ShareTokenRevoked'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ShareTokenRevoked, message, init);\n this.name = 'KaafilShareTokenRevokedError';\n this.code = KaafilErrorCode.ShareTokenRevoked;\n Object.setPrototypeOf(this, KaafilShareTokenRevokedError.prototype);\n }\n}\n\n/**\n * `501 NOT_IMPLEMENTED` — a reserved surface: the route is real and\n * validates its body, but the behaviour behind it lands in a later phase.\n * Deliberately distinct from `404` (`10-conventions.md §7`).\n */\nexport class KaafilNotImplementedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['NotImplemented'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.NotImplemented, message, init);\n this.name = 'KaafilNotImplementedError';\n this.code = KaafilErrorCode.NotImplemented;\n Object.setPrototypeOf(this, KaafilNotImplementedError.prototype);\n }\n}\n\n/**\n * A failure that never produced a server response to parse — timeout,\n * abort, DNS/connection failure. These have no catalog `.code`: inventing\n * one would claim a server actually answered when it did not.\n */\nexport abstract class KaafilTransportError extends KaafilError {\n override readonly kind = 'transport' as const;\n override readonly code: undefined;\n\n protected constructor(message: string, init: Omit<KaafilErrorInit, 'code'> = {}) {\n super(message, init);\n this.code = undefined;\n }\n}\n\ntype TransportErrorInit = Omit<KaafilErrorInit, 'code'>;\n\n/** The request exceeded the SDK's own timeout budget. Retryable (transient). */\nexport class KaafilTimeoutError extends KaafilTransportError {\n constructor(message = 'Request timed out', init: TransportErrorInit = {}) {\n super(message, init);\n this.name = 'KaafilTimeoutError';\n Object.setPrototypeOf(this, KaafilTimeoutError.prototype);\n }\n}\n\n/**\n * The caller's own `AbortController` fired. Deliberately not retryable —\n * unlike a timeout, this is the caller cancelling, not a transient failure.\n */\nexport class KaafilAbortError extends KaafilTransportError {\n constructor(message = 'Request aborted', init: TransportErrorInit = {}) {\n super(message, init);\n this.name = 'KaafilAbortError';\n Object.setPrototypeOf(this, KaafilAbortError.prototype);\n }\n}\n\n/** `fetch` itself rejected — offline, DNS failure, connection reset. Retryable. */\nexport class KaafilNetworkError extends KaafilTransportError {\n constructor(message = 'Network request failed', init: TransportErrorInit = {}) {\n super(message, init);\n this.name = 'KaafilNetworkError';\n Object.setPrototypeOf(this, KaafilNetworkError.prototype);\n }\n}\n\n/**\n * The caller built an impossible request — a missing path parameter, say.\n *\n * A programmer error, not a transport one, and the distinction is not cosmetic:\n * before this class existed, a missing path parameter escaped as a bare `Error`\n * from inside a send attempt, got wrapped as a `KaafilNetworkError`, and was\n * therefore **retried across the whole ladder** while reporting \"Unexpected\n * transport failure\". A typo in an argument name spent minutes backing off and\n * then blamed the network. It is `NEVER` retryable, because trying the same\n * malformed request again cannot make it well-formed.\n *\n * It extends `KaafilTransportError` only to inherit the \"no server response, so\n * no catalog code\" shape. `isRetryable` special-cases it — see there.\n */\nexport class KaafilInvalidRequestError extends KaafilTransportError {\n constructor(message: string, init: TransportErrorInit = {}) {\n super(message, init);\n this.name = 'KaafilInvalidRequestError';\n Object.setPrototypeOf(this, KaafilInvalidRequestError.prototype);\n }\n}\n\n/**\n * Structural guard, not `instanceof`-only: a consumer whose bundler ended up\n * with two copies of this package (a real, if rare, hazard) still gets a\n * correct answer, because it falls back to checking the shape every\n * `KaafilError` instance carries.\n */\nexport function isKaafilError(error: unknown): error is KaafilError {\n if (error instanceof KaafilError) {\n return true;\n }\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n const candidate = error as { kind?: unknown; message?: unknown };\n return (\n (candidate.kind === 'api' || candidate.kind === 'transport') &&\n typeof candidate.message === 'string'\n );\n}\n\nconst RETRYABLE_CODES: ReadonlySet<KaafilErrorCode> = new Set(\n (Object.keys(ERROR_CODE_TABLE) as KaafilErrorCode[]).filter(\n (code) => ERROR_CODE_TABLE[code].retryability !== Retryability.No,\n ),\n);\n\n/**\n * Whether the retry ladder (`08-sdk.md §6`) should ever re-attempt this\n * failure. Driven entirely by the generated `ERROR_CODE_TABLE` — retryability\n * is an allowlist there, and this function is the one place that allowlist\n * gets read, so a code the table marks non-retryable can never sneak back in\n * via a hand-written switch here.\n *\n * Transport failures are retryable except a caller-initiated abort, which is\n * not a transient condition to retry through.\n */\nexport function isRetryable(error: unknown): boolean {\n if (!isKaafilError(error)) {\n return false;\n }\n if (error.kind === 'transport') {\n // Two transport failures are NOT transient and must not be retried: an abort\n // the caller asked for, and a request the caller built wrongly. Retrying a\n // malformed request cannot make it well-formed, and doing so once cost a\n // full backoff ladder while reporting a network fault.\n return !(error instanceof KaafilAbortError) && !(error instanceof KaafilInvalidRequestError);\n }\n return error.code !== undefined && RETRYABLE_CODES.has(error.code);\n}\n\ninterface ParsedErrorEnvelope {\n readonly code: KaafilErrorCode;\n readonly message: string;\n readonly details: Record<string, unknown> | undefined;\n}\n\nconst KAAFIL_ERROR_CODE_VALUES: ReadonlySet<string> = new Set(Object.values(KaafilErrorCode));\n\nfunction isKaafilErrorCode(value: string): value is KaafilErrorCode {\n return KAAFIL_ERROR_CODE_VALUES.has(value);\n}\n\n/**\n * Parses `{ error: { code, message, details? } }` defensively — an\n * intermediary (gateway, proxy) can return anything as a body, so every\n * field is checked before use rather than cast. Returns `undefined` for\n * anything that isn't a recognizable error envelope, which `fromEnvelope`\n * treats as a transport failure rather than guessing a catalog code.\n */\nfunction parseErrorEnvelope(body: unknown): ParsedErrorEnvelope | undefined {\n if (typeof body !== 'object' || body === null) {\n return undefined;\n }\n const errorField = (body as Record<string, unknown>).error;\n if (typeof errorField !== 'object' || errorField === null) {\n return undefined;\n }\n const errorRecord = errorField as Record<string, unknown>;\n const code = errorRecord.code;\n const message = errorRecord.message;\n if (typeof code !== 'string' || !isKaafilErrorCode(code) || typeof message !== 'string') {\n return undefined;\n }\n const details = errorRecord.details;\n return {\n code,\n message,\n details:\n typeof details === 'object' && details !== null\n ? (details as Record<string, unknown>)\n : undefined,\n };\n}\n\nexport interface FromEnvelopeInit {\n readonly status: number;\n readonly requestId?: string;\n readonly meta?: ResponseMeta;\n readonly retryAfterSeconds?: number;\n readonly cause?: unknown;\n}\n\nfunction buildApiErrorInit(\n init: FromEnvelopeInit,\n details: Record<string, unknown> | undefined,\n): ApiErrorInit {\n return {\n status: init.status,\n ...(details !== undefined ? { details } : {}),\n ...(init.requestId !== undefined ? { requestId: init.requestId } : {}),\n ...(init.meta !== undefined ? { meta: init.meta } : {}),\n ...(init.cause !== undefined ? { cause: init.cause } : {}),\n };\n}\n\n/**\n * Turns a parsed HTTP body plus the transport-level facts about the\n * response into the right `KaafilError` subclass. Guards its own parse: a\n * gateway `502` with an HTML or empty body has no `{ error: { code, ... } }`\n * shape to read, so this returns a `KaafilNetworkError` for it rather than\n * throwing a `TypeError` from inside error handling or inventing a fake\n * catalog code for a response the engine never actually sent.\n */\nexport function fromEnvelope(body: unknown, init: FromEnvelopeInit): KaafilError {\n const parsed = parseErrorEnvelope(body);\n if (parsed === undefined) {\n return new KaafilNetworkError(\n `Received an unrecognizable error body for HTTP ${init.status}`,\n buildApiErrorInit(init, undefined),\n );\n }\n\n const commonInit = buildApiErrorInit(init, parsed.details);\n\n switch (parsed.code) {\n case KaafilErrorCode.ResourceNotFound:\n return new KaafilNotFoundError(parsed.message, commonInit);\n case KaafilErrorCode.PlanFeatureDisabled:\n return new KaafilEntitlementError(parsed.message, commonInit);\n case KaafilErrorCode.CapabilityUnavailable:\n return new KaafilCapabilityUnavailableError(parsed.message, commonInit);\n case KaafilErrorCode.ReadOnlyRole:\n return new KaafilReadOnlyRoleError(parsed.message, commonInit);\n case KaafilErrorCode.ValidationError:\n return new KaafilValidationError(parsed.message, commonInit);\n case KaafilErrorCode.ConflictVersion:\n return new KaafilVersionConflictError(parsed.message, commonInit);\n case KaafilErrorCode.Locked:\n return new KaafilLockedError(parsed.message, commonInit);\n case KaafilErrorCode.RateLimited:\n return new KaafilRateLimitedError(parsed.message, {\n ...commonInit,\n ...(init.retryAfterSeconds !== undefined\n ? { retryAfterSeconds: init.retryAfterSeconds }\n : {}),\n });\n case KaafilErrorCode.Unauthenticated:\n return new KaafilUnauthenticatedError(parsed.message, commonInit);\n case KaafilErrorCode.ShareTokenExpired:\n return new KaafilShareTokenExpiredError(parsed.message, commonInit);\n case KaafilErrorCode.ShareTokenRevoked:\n return new KaafilShareTokenRevokedError(parsed.message, commonInit);\n case KaafilErrorCode.NotImplemented:\n return new KaafilNotImplementedError(parsed.message, commonInit);\n default:\n return new KaafilApiError(parsed.code, parsed.message, commonInit);\n }\n}\n","/**\n * Credential resolution for `kaafil-js`: the discriminated credential\n * model, scheme selection against an operation's accepted schemes, and the\n * single-flight manager-session refresh. See\n * `architecture/03-auth-and-tokens.md §2` and `architecture/08-sdk.md §6`.\n */\n\nimport type { components } from '../generated/schema';\nimport {\n type OperationId,\n SECURITY_SCHEME_CARRIERS,\n SecuritySchemeId,\n} from '../generated/security';\n// A value import, and safe in the browser bundle: `../http/errors.ts` reaches\n// only the generated code table and type-only `types/meta`, never a credential\n// path, and every class in it is already re-exported from the browser entry.\nimport { KaafilInvalidRequestError } from '../http/errors';\n\n/**\n * A credential value the host may supply as a literal or as a resolver\n * invoked at header-assembly time, on every request — never captured once\n * and reused, which is how a stale credential gets sent.\n */\nexport type Resolvable<T> = T | (() => T | Promise<T>);\n\nasync function resolveValue<T>(value: Resolvable<T>): Promise<T> {\n return typeof value === 'function' ? await (value as () => T | Promise<T>)() : value;\n}\n\n/**\n * The credential kind is declared by the caller, never derived from which\n * field happens to be populated.\n *\n * `agencyAdmin` is named after the engine's own JWT `kind` claim\n * (`kaafil-engine`'s `CLAIM_DISCRIMINATED_AUTH_KINDS`), the same way `apiKey`\n * and `shareToken` are named after what identifies the credential rather\n * than the flow that produced it — unlike `managerSession`, which predates\n * this convention. It rotates exactly like `managerSession` does (see\n * `RotatingSessionCredentialConfig` below): a bearer access/refresh pair\n * minted by `mintAgencyAdminTokens` and rotated forward by\n * `refreshAgencyAdminTokens`.\n */\nexport const CredentialKind = {\n AgencyAdmin: 'agencyAdmin',\n ApiKey: 'apiKey',\n ManagerSession: 'managerSession',\n ShareToken: 'shareToken',\n} as const;\nexport type CredentialKind = (typeof CredentialKind)[keyof typeof CredentialKind];\n\nexport interface ApiKeyCredentialConfig {\n readonly kind: typeof CredentialKind.ApiKey;\n readonly apiKey: Resolvable<string>;\n}\n\nexport interface ShareTokenCredentialConfig {\n readonly kind: typeof CredentialKind.ShareToken;\n readonly token: Resolvable<string>;\n}\n\n/** `refreshManagerTokens`'s success shape, straight out of the generated\n * schema — never hand-typed, so a spec change surfaces here as a type error\n * rather than a silently-stale hand-written interface. */\ntype ManagerSessionResponseShape = components['schemas']['ManagerSessionResponse'];\n\n/** `refreshAgencyAdminTokens`'s success shape, straight out of the generated\n * schema, for the same reason as `ManagerSessionResponseShape` above. */\ntype AgencyAdminSessionResponseShape = components['schemas']['AgencyAdminSessionResponse'];\n\n/**\n * The result of a manager-session refresh exchange. Only this shape may\n * ever rotate the manager-session credential — never a value sniffed out of\n * an unrelated response body.\n */\nexport type ManagerRefreshResult = Pick<\n ManagerSessionResponseShape,\n 'accessToken' | 'refreshToken' | 'expiresAt'\n>;\n\n/**\n * The result of an agency-admin session refresh exchange — the\n * agency-admin analogue of `ManagerRefreshResult` above, derived\n * independently from its own generated response shape rather than reused\n * from the manager one, so the two are only ever accidentally identical,\n * never structurally coupled: a future spec revision that adds a field to\n * one and not the other surfaces here as a type error, not a silent share.\n */\nexport type AgencyAdminRefreshResult = Pick<\n AgencyAdminSessionResponseShape,\n 'accessToken' | 'refreshToken' | 'expiresAt'\n>;\n\n/**\n * The shape both rotating credentials' refresh results happen to share —\n * `ManagerRefreshResult` and `AgencyAdminRefreshResult` are each already\n * structurally assignable to this, so the single-flight machinery below can\n * be written once, generically, against this shape instead of against\n * either concrete one.\n */\nexport interface RotatingRefreshResult {\n readonly accessToken: string;\n readonly refreshToken: string;\n readonly expiresAt: string;\n}\n\n/**\n * The one HTTP call a rotating-session resolver is allowed to make. Typed as\n * this single narrow function — not the whole `KaafilHttpClient` — so\n * whatever this resolver is given cannot be used to make any other request.\n * Shared by both rotating kinds (`managerSession`, `agencyAdmin`): the two\n * differ only in which endpoint the exchange hits, not in this shape.\n *\n * `credentials.ts` cannot import `./http/client.ts` to build this itself:\n * that module already imports `CredentialKind`/`CredentialResolver` from\n * here to drive its own 401-triggered refresh, and the reverse import would\n * make a cycle. So the concrete implementation is built in `http/client.ts`\n * (which already knows how to talk to the engine and parse its envelope) and\n * handed down through `CredentialResolver`'s constructor by whichever entry\n * point (`../client-entry.ts`) opens the session — the top of the graph is\n * where both sides are already in scope.\n */\nexport type RotatingSessionExchange = (\n accessToken: string,\n refreshToken: string,\n) => Promise<RotatingRefreshResult>;\n\n/** @deprecated Kept as an alias of {@link RotatingSessionExchange} for\n * existing call sites that name it for the manager kind specifically —\n * both rotating kinds now share the one type. */\nexport type ManagerSessionExchange = RotatingSessionExchange;\n\n/**\n * Access-token skew window: refresh pre-emptively once fewer than this many\n * milliseconds remain, instead of waiting to learn from a `401` what the\n * mint response already told us. Shared by both rotating kinds — a manager\n * or agency-admin access token each live 15 minutes\n * (`architecture/03-auth-and-tokens.md §2`); 30s is generous next to typical\n * request latency (so a request built just inside the window still lands\n * before the server's own clock expires it) and small next to the 900s\n * lifetime (so it only ever preempts the closing seconds, never meaningfully\n * shortening the token's usable life).\n */\nconst ROTATING_ACCESS_TOKEN_REFRESH_SKEW_MS = 30_000;\n\n/**\n * The shape shared by both rotating credential kinds — everything about a\n * `managerSession`/`agencyAdmin` config except the discriminant `kind`\n * itself. `ManagerSessionCredentialConfig` and `AgencyAdminCredentialConfig`\n * below are each this shape plus their own literal `kind`, so the\n * single-flight refresh machinery can take either without a second copy of\n * itself per kind.\n */\ninterface RotatingSessionCredentialConfig<\n TKind extends CredentialKind,\n TResult extends RotatingRefreshResult,\n> {\n readonly kind: TKind;\n readonly accessToken: Resolvable<string>;\n readonly refreshToken: Resolvable<string>;\n /**\n * The access token's absolute expiry (the mint/refresh response's\n * `expiresAt`), if the host has it. Enables the pre-emptive refresh above\n * — without it the resolver only learns a token is dead from a `401`.\n */\n readonly expiresAt?: Resolvable<string>;\n /**\n * Overrides the default exchange (a direct call to this kind's own\n * refresh endpoint, authorised by the session's own access token —\n * `architecture/03-auth-and-tokens.md §2`) with an integrator-supplied\n * one, for a host that wants the rotation to pass through its own backend\n * instead. Most hosts never set this: the default path handles the\n * exchange without it. Called at most once per pre-emptive-or-401\n * trigger, and single-flighted across concurrent callers by\n * `CredentialResolver.refreshRotatingSession` — the refresh token\n * rotates, and presenting a rotated one twice revokes the whole family\n * (same section).\n */\n readonly refresh?: (refreshToken: string) => Promise<TResult>;\n /**\n * Fires once per successful rotation so a host can persist the new\n * refresh token. Never fires on a failed refresh. This SDK has no\n * persistence in this version, so surviving a reload is the one other\n * thing it cannot do for the consumer — this callback is that hand-off.\n */\n readonly onRefresh?: (result: TResult) => void | Promise<void>;\n}\n\nexport interface ManagerSessionCredentialConfig\n extends RotatingSessionCredentialConfig<\n typeof CredentialKind.ManagerSession,\n ManagerRefreshResult\n > {}\n\nexport interface AgencyAdminCredentialConfig\n extends RotatingSessionCredentialConfig<\n typeof CredentialKind.AgencyAdmin,\n AgencyAdminRefreshResult\n > {}\n\nexport type CredentialConfig =\n | AgencyAdminCredentialConfig\n | ApiKeyCredentialConfig\n | ManagerSessionCredentialConfig\n | ShareTokenCredentialConfig;\n\n/** Either rotating kind's config — the shape `CredentialResolver`'s\n * single-flight machinery actually operates on, once the discriminant has\n * narrowed `CredentialConfig` down to one of these two. */\ntype AnyRotatingCredentialConfig = AgencyAdminCredentialConfig | ManagerSessionCredentialConfig;\n\n/**\n * `true` for the two credential kinds that rotate (`managerSession`,\n * `agencyAdmin`) — the ones `refreshRotatingSession` and the pre-emptive\n * skew check apply to. `apiKey`/`shareToken` never rotate: an API key is\n * revoked out of band and a share token simply expires, so neither has a\n * refresh endpoint to call.\n */\nexport function isRotatingCredentialKind(\n kind: CredentialKind,\n): kind is typeof CredentialKind.AgencyAdmin | typeof CredentialKind.ManagerSession {\n return kind === CredentialKind.AgencyAdmin || kind === CredentialKind.ManagerSession;\n}\n\n/** Same test as `isRotatingCredentialKind`, narrowing the whole config\n * rather than just its `kind` — what `refreshRotatingSession` needs to hand\n * a properly-typed config down to `performRotatingRefresh`. */\nfunction isRotatingConfig(config: CredentialConfig): config is AnyRotatingCredentialConfig {\n return isRotatingCredentialKind(config.kind);\n}\n\n/**\n * Exactly one accepted scheme per credential kind. No kind maps to\n * `consoleAuth` — the SDK does not serve the console, and its cookie is\n * never a client-wide default (see `headersForCarrier`'s `cookie` branch).\n */\nconst CREDENTIAL_KIND_SCHEME: Readonly<Record<CredentialKind, SecuritySchemeId>> = {\n agencyAdmin: SecuritySchemeId.AgencyAdminAuth,\n apiKey: SecuritySchemeId.ApiKeyAuth,\n managerSession: SecuritySchemeId.ManagerAuth,\n shareToken: SecuritySchemeId.ShareAuth,\n};\n\nexport interface ResolvedCredentialHeaders {\n /** `null` for a public operation (no accepted schemes) — no header is due. */\n readonly schemeId: SecuritySchemeId | null;\n readonly headers: Readonly<Record<string, string>>;\n}\n\n/**\n * Thrown before any HTTP round trip when the configured credential cannot\n * satisfy any scheme an operation accepts. Never let a missing credential\n * surface as a `404`, which on this API means tenant isolation or genuine\n * absence (`architecture/10-conventions.md §7`).\n *\n * Extends `KaafilInvalidRequestError` — it is not merely an `Error` — because\n * `execute()` normalises any throw outside the `KaafilError` hierarchy into a\n * retryable `KaafilNetworkError`. As a bare `Error` this class never escaped:\n * a consumer following the documented `catch (e) { e instanceof\n * UnsatisfiableSchemeError }` pattern got `false`, saw \"Unexpected transport\n * failure\" for a call that made no request at all, and `isRetryable` said\n * `true` — so a retry queue burned the whole backoff ladder on a condition\n * that is permanent by construction. Choosing this parent rather than\n * `KaafilTransportError` directly is what keeps it non-retryable: `isRetryable`\n * already excludes `KaafilInvalidRequestError`, so there is no second\n * special case to keep in step with this one. The classification is right\n * on the merits too — the wrong credential for an operation is a request the\n * caller built wrongly, and re-sending it cannot make it satisfiable.\n */\nexport class UnsatisfiableSchemeError extends KaafilInvalidRequestError {\n readonly operationId: OperationId;\n readonly acceptedSchemes: readonly SecuritySchemeId[];\n readonly credentialKind: CredentialKind;\n\n constructor(\n operationId: OperationId,\n acceptedSchemes: readonly SecuritySchemeId[],\n credentialKind: CredentialKind,\n ) {\n const schemeList =\n acceptedSchemes.length > 0 ? acceptedSchemes.join(', ') : '(no scheme declared)';\n super(\n `\"${operationId}\" accepts [${schemeList}], but the configured \"${credentialKind}\" ` +\n 'credential cannot satisfy any of them.',\n );\n this.name = 'UnsatisfiableSchemeError';\n // Same reason every class in `../http/errors.ts` does this: an ES5 target\n // loses the prototype chain through `super()`, and without it `instanceof`\n // fails for the one class whose whole purpose is to be caught by name.\n Object.setPrototypeOf(this, UnsatisfiableSchemeError.prototype);\n this.operationId = operationId;\n this.acceptedSchemes = acceptedSchemes;\n this.credentialKind = credentialKind;\n }\n}\n\nfunction headersForCarrier(\n schemeId: SecuritySchemeId,\n value: string,\n): Readonly<Record<string, string>> {\n const carrier = SECURITY_SCHEME_CARRIERS[schemeId];\n switch (carrier.kind) {\n case 'header':\n return { [carrier.headerName]: value };\n case 'bearer':\n return { Authorization: `Bearer ${value}` };\n case 'cookie':\n // No entry in `CREDENTIAL_KIND_SCHEME` maps to a cookie-borne scheme —\n // the SDK does not serve the console, so this branch is unreachable\n // through `CredentialResolver`. Kept explicit (never a bare `false`)\n // so an SDK-side scheme added later without a credential kind fails\n // loudly instead of silently attaching a cookie.\n throw new Error(`Scheme \"${schemeId}\" is cookie-borne and has no SDK-side credential kind.`);\n }\n}\n\ninterface RotatingSessionState {\n current: { accessToken: string; refreshToken: string; expiresAt: string | undefined } | null;\n refreshPromise: Promise<RotatingRefreshResult> | null;\n}\n\n/**\n * Every piece of this resolver's per-session state, in one object, so\n * `reset()` is a single assignment that cannot forget a field. Only a\n * rotating kind (`managerSession`, `agencyAdmin`) has anything to hold —\n * `apiKey`/`shareToken` values are read fresh from their resolver on every\n * call and never cached here. One `rotating` slot, not one per kind: a\n * config is exactly one kind, so it never needs both at once.\n */\ninterface CredentialResolverState {\n rotating: RotatingSessionState | null;\n}\n\nfunction createInitialState(config: CredentialConfig): CredentialResolverState {\n return {\n rotating: isRotatingCredentialKind(config.kind)\n ? { current: null, refreshPromise: null }\n : null,\n };\n}\n\n/**\n * `true` once fewer than `ROTATING_ACCESS_TOKEN_REFRESH_SKEW_MS` remain\n * before `expiresAt`, or once it has already passed. `undefined` (no\n * `expiresAt` known yet) is never treated as expiring — the resolver simply\n * has nothing to preempt with and falls back to learning from a `401`.\n */\nfunction isExpiringSoon(expiresAt: string | undefined, nowMs: number): boolean {\n if (expiresAt === undefined) {\n return false;\n }\n const expiryMs = Date.parse(expiresAt);\n if (Number.isNaN(expiryMs)) {\n return false;\n }\n return expiryMs - nowMs <= ROTATING_ACCESS_TOKEN_REFRESH_SKEW_MS;\n}\n\n/**\n * Resolves headers for one immutable, declared credential. Constructed once\n * per client with no credential baked into the transport; every header is\n * assembled from the current credential value at call time.\n */\nexport class CredentialResolver {\n private readonly config: CredentialConfig;\n private state: CredentialResolverState;\n /**\n * The default exchange for a rotating (`managerSession`/`agencyAdmin`)\n * credential — `undefined` for the two non-rotating kinds, and for a\n * rotating config that always uses its own `refresh` override instead.\n * See `RotatingSessionExchange`'s doc comment for why this arrives as a\n * constructor argument rather than an import.\n */\n private readonly rotatingSessionExchange: RotatingSessionExchange | undefined;\n\n constructor(config: CredentialConfig, rotatingSessionExchange?: RotatingSessionExchange) {\n this.config = config;\n this.state = createInitialState(config);\n this.rotatingSessionExchange = rotatingSessionExchange;\n }\n\n get kind(): CredentialKind {\n return this.config.kind;\n }\n\n /**\n * Picks the first scheme in `acceptedSchemes` (spec declaration order)\n * the configured credential can satisfy and returns its headers. Throws\n * `UnsatisfiableSchemeError` — never makes the doomed round trip — if\n * none match. An empty `acceptedSchemes` (a public operation) needs no\n * credential and returns no headers.\n */\n async resolveHeaders(\n operationId: OperationId,\n acceptedSchemes: readonly SecuritySchemeId[],\n ): Promise<ResolvedCredentialHeaders> {\n if (acceptedSchemes.length === 0) {\n return { schemeId: null, headers: {} };\n }\n\n const config = this.config;\n const mySchemeId = CREDENTIAL_KIND_SCHEME[config.kind];\n if (!acceptedSchemes.includes(mySchemeId)) {\n throw new UnsatisfiableSchemeError(operationId, acceptedSchemes, config.kind);\n }\n\n const value = await this.currentValue(config);\n return { schemeId: mySchemeId, headers: headersForCarrier(mySchemeId, value) };\n }\n\n private async currentValue(config: CredentialConfig): Promise<string> {\n switch (config.kind) {\n case CredentialKind.ApiKey:\n return resolveValue(config.apiKey);\n case CredentialKind.ShareToken:\n return resolveValue(config.token);\n case CredentialKind.ManagerSession:\n case CredentialKind.AgencyAdmin:\n return this.currentRotatingAccessToken(config);\n }\n }\n\n private async currentRotatingAccessToken(config: AnyRotatingCredentialConfig): Promise<string> {\n const state = this.rotatingSessionState();\n if (!state.current) {\n const [accessToken, refreshToken, expiresAt] = await Promise.all([\n resolveValue(config.accessToken),\n resolveValue(config.refreshToken),\n config.expiresAt !== undefined\n ? resolveValue(config.expiresAt)\n : Promise.resolve(undefined),\n ]);\n state.current = { accessToken, refreshToken, expiresAt };\n }\n\n // Pre-emptive refresh: act on what the mint response already told us\n // instead of spending a round trip to relearn it via a `401`. Routed\n // through the same single-flight path as the reactive 401-triggered\n // refresh in `http/client.ts` — two refresh paths would defeat the\n // single-flight guarantee the rotating refresh token depends on.\n if (isExpiringSoon(state.current.expiresAt, Date.now())) {\n const result = await this.refreshRotatingSession();\n return result.accessToken;\n }\n return state.current.accessToken;\n }\n\n /**\n * Single-flight refresh: concurrent triggers (N simultaneous `401`s, or a\n * pre-emptive check racing a `401`) share one in-flight promise, so the\n * rotating refresh token is presented exactly once. The promise is\n * cleared on both success and failure — a rejected refresh never stays\n * sticky, and the next trigger always starts a fresh exchange\n * (`architecture/03-auth-and-tokens.md §2`). Callers make one attempt per\n * request and surface the failure; this method does not loop. Shared by\n * both rotating kinds — see the module header's argument for why this is\n * one implementation, not one per kind.\n */\n async refreshRotatingSession(): Promise<RotatingRefreshResult> {\n const config = this.config;\n if (!isRotatingConfig(config)) {\n throw new Error(\n 'refreshRotatingSession() is only valid for a rotating (\"managerSession\" or ' +\n '\"agencyAdmin\") credential.',\n );\n }\n\n const state = this.rotatingSessionState();\n if (state.refreshPromise) {\n return state.refreshPromise;\n }\n\n const promise = this.performRotatingRefresh(config, state);\n state.refreshPromise = promise;\n try {\n return await promise;\n } finally {\n state.refreshPromise = null;\n }\n }\n\n private async performRotatingRefresh(\n config: AnyRotatingCredentialConfig,\n state: RotatingSessionState,\n ): Promise<RotatingRefreshResult> {\n const refreshToken = state.current?.refreshToken ?? (await resolveValue(config.refreshToken));\n const result =\n config.refresh !== undefined\n ? await config.refresh(refreshToken)\n : await this.defaultRotatingRefresh(config, state, refreshToken);\n state.current = {\n accessToken: result.accessToken,\n refreshToken: result.refreshToken,\n expiresAt: result.expiresAt,\n };\n await config.onRefresh?.(result);\n return result;\n }\n\n private async defaultRotatingRefresh(\n config: AnyRotatingCredentialConfig,\n state: RotatingSessionState,\n refreshToken: string,\n ): Promise<RotatingRefreshResult> {\n if (this.rotatingSessionExchange === undefined) {\n throw new Error(\n 'invariant: a rotating credential without a \"refresh\" override needs the exchange ' +\n 'function the entry point constructs it with — see \"./client-entry.ts\".',\n );\n }\n // The bearer's job here is to identify WHICH session is being rotated,\n // not to be current — the engine accepts it even once expired, bounded\n // by the refresh token's own lifetime (`03-auth-and-tokens.md §2`). So\n // the possibly-stale `state.current.accessToken` is exactly what this\n // call is supposed to send, not a reason to resolve a fresh one first.\n const accessToken = state.current?.accessToken ?? (await resolveValue(config.accessToken));\n return this.rotatingSessionExchange(accessToken, refreshToken);\n }\n\n private rotatingSessionState(): RotatingSessionState {\n const state = this.state.rotating;\n if (!state) {\n throw new Error('invariant: rotating-session state missing for a rotating credential.');\n }\n return state;\n }\n\n /**\n * Resets every piece of per-session state in one assignment — teardown\n * that cannot forget a field because the state is rebuilt from scratch,\n * not cleared field by field.\n */\n reset(): void {\n this.state = createInitialState(this.config);\n }\n}\n","/**\n * Construction-time configuration for `kaafil-js`: environment → base URL\n * mapping, and every check that can be made before the first request goes\n * out. `architecture/08-sdk.md §2` (\"Environments are selected at init and\n * pinned to the key prefix\"), `architecture/03-auth-and-tokens.md §1`.\n *\n * A mistake this module can catch at construction is caught here, with a\n * message naming the offending field — never turned into a confusing HTTP\n * failure three requests later.\n */\n\nimport type { Resolvable } from './auth/credentials';\n\nexport const Environment = {\n Live: 'live',\n Test: 'test',\n} as const;\nexport type Environment = (typeof Environment)[keyof typeof Environment];\n\n/**\n * Default base URL per environment. There is exactly one real engine host,\n * `https://engine.kaafil.in` — `live` and `test` are Tenants reached through\n * that same host and distinguished by which credential resolves, never by a\n * different domain (`environments.mdx §\"LIVE and TEST are Tenants\"`). Both\n * entries below point at it on purpose, not by coincidence: an integrator\n * never needs to pass `baseUrl` for a real deployment, and should not be\n * told to. `baseUrl` remains available on `KaafilOptions` purely for\n * self-hosted/local-engine development against a non-production host.\n */\nconst ENVIRONMENT_BASE_URLS: Readonly<Record<Environment, string>> = {\n live: 'https://engine.kaafil.in',\n test: 'https://engine.kaafil.in',\n};\n\n/**\n * `kf_live_…` / `kf_test_…` — verified against the engine's own key\n * material generator (`kaafil-engine/src/shared/auth/constants.ts`:\n * `API_KEY_PREFIX_LIVE = 'kf_live_'`, `API_KEY_PREFIX_TEST = 'kf_test_'`),\n * never trusted from the spec's prose alone.\n */\nconst API_KEY_ENVIRONMENT_PREFIX: Readonly<Record<Environment, string>> = {\n live: 'kf_live_',\n test: 'kf_test_',\n};\n\n/** Every construction-time configuration mistake this module can catch,\n * in one class, so a consumer can `instanceof`-branch on \"my init call was\n * wrong\" without also catching a runtime/HTTP failure. */\nexport class KaafilConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'KaafilConfigError';\n }\n}\n\n/**\n * An API key whose prefix doesn't match the `environment` it was configured\n * against. Thrown at construction for a literal key, or the first time a\n * resolver-supplied key actually resolves (see `guardApiKeyEnvironment`) —\n * either way, before the doomed request that a live key against a test\n * tenant (or vice versa) would otherwise produce.\n */\nexport class ApiKeyEnvironmentMismatchError extends KaafilConfigError {\n readonly environment: Environment;\n readonly keyPrefix: string;\n\n constructor(environment: Environment, apiKey: string) {\n const keyPrefix = apiKey.includes('_') ? `${apiKey.split('_').slice(0, 2).join('_')}_` : apiKey;\n super(\n `environment: \"${environment}\" expects an API key prefixed ` +\n `\"${API_KEY_ENVIRONMENT_PREFIX[environment]}\", but the configured key is prefixed ` +\n `\"${keyPrefix}\".`,\n );\n this.name = 'ApiKeyEnvironmentMismatchError';\n this.environment = environment;\n this.keyPrefix = keyPrefix;\n }\n}\n\n/** Renders an offending config value for a message: a string quoted as the\n * caller typed it, anything else (including `undefined`) as itself. */\nfunction describeConfigValue(value: unknown): string {\n return typeof value === 'string' ? `\"${value}\"` : String(value);\n}\n\n/**\n * `environment` is required and has exactly two values. Checked before any\n * per-environment table is indexed with it, because an absent or misspelled\n * `environment` otherwise reaches `assertApiKeyMatchesEnvironment`, where\n * the expected-prefix lookup misses and the resulting\n * `ApiKeyEnvironmentMismatchError` tells the caller their key should have\n * been prefixed `\"undefined\"` — blaming `apiKey` for a mistake that is in\n * `environment`.\n */\nexport function assertValidEnvironment(environment: Environment): void {\n if (environment !== Environment.Live && environment !== Environment.Test) {\n throw new KaafilConfigError(\n `\"environment\" is required and must be \"${Environment.Live}\" or \"${Environment.Test}\"; ` +\n `received ${describeConfigValue(environment)}.`,\n );\n }\n}\n\nfunction isValidAbsoluteUrl(value: string): boolean {\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\n/**\n * `environment` selects a default; an explicit `baseUrl` overrides it\n * outright (self-hosted / proxied / sandbox deployment) — the two are never\n * merged or partially applied. Construction-time and immutable: there is no\n * setter, callers re-construct a client to point elsewhere.\n *\n * `environment` is validated here rather than in each constructor because\n * this is the one call every client entry point makes before anything else\n * reads `environment` — including the `baseUrl`-override path, where the\n * value is otherwise never looked at and would go on to mis-shape the API\n * key guard and the sandbox-only `test` resource.\n */\nexport function resolveBaseUrl(environment: Environment, baseUrl?: string): string {\n assertValidEnvironment(environment);\n if (baseUrl === undefined) {\n return ENVIRONMENT_BASE_URLS[environment];\n }\n if (!isValidAbsoluteUrl(baseUrl)) {\n throw new KaafilConfigError(\n `\"baseUrl\" must be an absolute http(s) URL; received \"${baseUrl}\".`,\n );\n }\n return baseUrl;\n}\n\n/** Throws `KaafilConfigError` naming the field if `timeoutMs` is present and\n * not a positive, finite number. `undefined` is valid — the transport\n * applies its own default (`http/client.ts`'s `DEFAULT_TIMEOUT_MS`). */\nexport function assertValidTimeout(timeoutMs: number | undefined): void {\n if (timeoutMs === undefined) {\n return;\n }\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new KaafilConfigError(`\"timeoutMs\" must be a positive number; received ${timeoutMs}.`);\n }\n}\n\n/** Throws `KaafilConfigError` naming the field if `maxAttempts` is present\n * and not a positive integer. `undefined` is valid — the retry ladder\n * applies its own default (`http/retry.ts`). */\nexport function assertValidMaxAttempts(maxAttempts: number | undefined): void {\n if (maxAttempts === undefined) {\n return;\n }\n if (!Number.isInteger(maxAttempts) || maxAttempts <= 0) {\n throw new KaafilConfigError(\n `\"maxAttempts\" must be a positive integer; received ${maxAttempts}.`,\n );\n }\n}\n\n/**\n * Checks one API key's prefix against `environment`, throwing\n * `ApiKeyEnvironmentMismatchError` naming both sides on a mismatch, and\n * `KaafilConfigError` if the key doesn't even look like a Kaafil key (wrong\n * shape is a construction mistake in its own right, not just a wrong\n * environment).\n */\nexport function assertApiKeyMatchesEnvironment(apiKey: string, environment: Environment): void {\n const expectedPrefix = API_KEY_ENVIRONMENT_PREFIX[environment];\n const isKnownPrefix =\n apiKey.startsWith(API_KEY_ENVIRONMENT_PREFIX.live) ||\n apiKey.startsWith(API_KEY_ENVIRONMENT_PREFIX.test);\n if (!isKnownPrefix) {\n throw new KaafilConfigError(\n `\"apiKey\" does not look like a Kaafil API key (expected a \"${API_KEY_ENVIRONMENT_PREFIX.live}\" ` +\n `or \"${API_KEY_ENVIRONMENT_PREFIX.test}\" prefix).`,\n );\n }\n if (!apiKey.startsWith(expectedPrefix)) {\n throw new ApiKeyEnvironmentMismatchError(environment, apiKey);\n }\n}\n\n/**\n * Guards an `apiKey` against `environment`, honestly, for both shapes\n * `Resolvable<string>` allows:\n *\n * - A literal key is known now, so it is checked now — the whole point of\n * catching a construction mistake at construction.\n * - A resolver's value is not known until it first resolves (that's what\n * \"resolver\" means), so it genuinely cannot be checked any earlier than\n * that. This wraps the resolver so the check runs against every resolved\n * value, starting with the first — cheap (a string-prefix comparison) and\n * correct even though `CredentialResolver` never caches a resolver's\n * value: a resolver's whole contract is that its answer may legitimately\n * change between calls (`credentials.ts`'s `Resolvable<T>`), so a\n * check-once-then-trust would miss a later swap to a key from the wrong\n * environment.\n *\n * Returns a `Resolvable<string>` suitable to hand straight to an\n * `ApiKeyCredentialConfig`.\n */\nexport function guardApiKeyEnvironment(\n apiKey: Resolvable<string>,\n environment: Environment,\n): Resolvable<string> {\n if (typeof apiKey !== 'function') {\n assertApiKeyMatchesEnvironment(apiKey, environment);\n return apiKey;\n }\n const resolver = apiKey as () => string | Promise<string>;\n return async () => {\n const value = await resolver();\n assertApiKeyMatchesEnvironment(value, environment);\n return value;\n };\n}\n","/**\n * The retry ladder and retry policy — architecture/08-sdk.md §6.\n *\n * Retryability is an allowlist: a failure is only retried when the\n * generated `ERROR_CODE_TABLE` (`src/generated/error-codes.ts`) marks its\n * code retryable, or when there is no code at all because the request never\n * got an HTTP response (a genuine transport failure). A denylist would\n * default to retrying anything not explicitly excluded — including outcomes\n * that can never succeed — and hoard requests forever with no way out.\n */\n\nimport { ERROR_CODE_TABLE, type KaafilErrorCode, Retryability } from '../generated/error-codes';\n\n/** `1s → 5s → 15s → 1m → 5m → 15m → 1h`, then hold at the last rung. */\nexport const RETRY_LADDER_MS = [1_000, 5_000, 15_000, 60_000, 300_000, 900_000, 3_600_000] as const;\n\n/**\n * A per-request cap, never a client-global one: this counter is a local\n * variable inside a single `executeWithRetry()` call and starts fresh for\n * every request. A client-global counter would let one unlucky endpoint\n * poison retries for every other call sharing it. The default covers the\n * full ladder (six escalating rungs) plus roughly a day of holding at the\n * last rung; pass `maxAttempts` to change it per call.\n */\nexport const DEFAULT_MAX_ATTEMPTS = 24;\n\nexport interface RetryClassificationInput {\n /** `null` means no HTTP response reached the client at all. */\n readonly status: number | null;\n readonly code?: KaafilErrorCode;\n}\n\n/**\n * Whether a failure is eligible for the backoff ladder at all. This is the\n * allowlist: retryable only if the generated table says so for a\n * recognized `code`, or if there was no response to key a code off of.\n */\nexport function isRetryableFailure(input: RetryClassificationInput): boolean {\n if (input.status === null) {\n return true;\n }\n\n const entry = input.code !== undefined ? ERROR_CODE_TABLE[input.code] : undefined;\n if (entry !== undefined) {\n return (\n entry.retryability === Retryability.Yes ||\n entry.retryability === Retryability.HonourRetryAfter\n );\n }\n\n // No recognized code: allow only the same statuses the table's retryable\n // entries all share — 5xx and 429. `after-refresh` (401) is deliberately\n // excluded here: it is one refresh-then-replay attempt owned by the\n // credential layer (03-auth-and-tokens.md §2), not a ladder retry.\n return input.status === 429 || (input.status >= 500 && input.status <= 599);\n}\n\nexport interface DelayOptions {\n /** Present only for a 429 that carried `Retry-After`. Integer seconds,\n * exposed cross-origin and readable in a browser; never below 1. */\n readonly retryAfterSeconds?: number;\n readonly random?: () => number;\n}\n\n/**\n * Pure backoff computation — exported standalone so the ladder is\n * inspectable without actually waiting. `attempt` is 1 for the first retry\n * (the call that failed once already), 2 for the second, and so on; values\n * beyond the ladder's length clamp to its last rung (\"then hold\").\n *\n * Uses equal jitter (half the rung is guaranteed, half is random) rather\n * than full jitter, so the wait still holds near the top of the ladder\n * instead of collapsing back toward zero on every attempt.\n */\nexport function computeRetryDelayMs(attempt: number, options: DelayOptions = {}): number {\n if (options.retryAfterSeconds !== undefined) {\n return Math.max(1, Math.floor(options.retryAfterSeconds)) * 1000;\n }\n\n const index = Math.min(Math.max(attempt - 1, 0), RETRY_LADDER_MS.length - 1);\n const base = RETRY_LADDER_MS[index];\n if (base === undefined) {\n throw new Error('unreachable: index is clamped to RETRY_LADDER_MS bounds');\n }\n const random = options.random ?? Math.random;\n const half = base / 2;\n return Math.floor(half + random() * half);\n}\n\n/**\n * Sleeps for `ms`, but rejects with the signal's abort reason immediately\n * if `signal` fires while waiting — a caller who aborts must not be held\n * through a 15-minute backoff just because the timer was already running.\n */\nexport function delayWithAbort(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted === true) {\n return Promise.reject(signal.reason);\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport interface RetryFailure {\n readonly status: number | null;\n readonly code?: KaafilErrorCode;\n readonly retryAfterSeconds?: number;\n}\n\nexport type AttemptOutcome<T> =\n | { readonly ok: true; readonly value: T }\n | ({ readonly ok: false } & RetryFailure);\n\nexport class RetryExhaustedError extends Error {\n readonly failure: RetryFailure;\n readonly attempts: number;\n\n constructor(failure: RetryFailure, attempts: number) {\n super(`retry exhausted after ${attempts} attempt(s), last status ${String(failure.status)}`);\n this.name = 'RetryExhaustedError';\n this.failure = failure;\n this.attempts = attempts;\n }\n}\n\nexport interface RetryOptions {\n readonly maxAttempts?: number;\n readonly signal?: AbortSignal;\n readonly random?: () => number;\n /**\n * The stable idempotency key for this logical operation, if the\n * underlying request carries a body (`architecture/08-sdk.md §5`). The\n * caller mints it once and must pass the *same* value on every attempt —\n * this module never mints or rotates one itself, it only reads whether\n * one was supplied.\n */\n readonly idempotencyKey?: string;\n /**\n * True when the underlying request carries a body that isn't safely\n * replayable on its own (a write). Leave false/omitted for GET/HEAD-style\n * calls with no body, which are always safe to retry. A body-bearing\n * request with no `idempotencyKey` is treated as unsafe to replay and is\n * attempted once, never retried, regardless of `maxAttempts`.\n */\n readonly hasBody?: boolean;\n}\n\n/**\n * Runs `attempt` against the retry ladder, honouring `Retry-After` on 429s,\n * an `AbortSignal` while sleeping, and a per-request attempt cap. Resolves\n * with the first successful value, or throws `RetryExhaustedError` once the\n * failure is non-retryable or the cap is reached.\n */\nexport async function executeWithRetry<T>(\n attempt: (attemptNumber: number) => Promise<AttemptOutcome<T>>,\n options: RetryOptions = {},\n): Promise<T> {\n const unsafeToReplay = options.hasBody === true && options.idempotencyKey === undefined;\n const maxAttempts = unsafeToReplay ? 1 : (options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);\n const random = options.random ?? Math.random;\n\n for (let attemptNumber = 1; attemptNumber <= maxAttempts; attemptNumber += 1) {\n if (options.signal?.aborted === true) {\n throw options.signal.reason;\n }\n\n const outcome = await attempt(attemptNumber);\n if (outcome.ok) {\n return outcome.value;\n }\n\n const retryable = isRetryableFailure(outcome);\n if (!retryable || attemptNumber === maxAttempts) {\n throw new RetryExhaustedError(outcome, attemptNumber);\n }\n\n const delayMs = computeRetryDelayMs(attemptNumber, {\n ...(outcome.retryAfterSeconds !== undefined\n ? { retryAfterSeconds: outcome.retryAfterSeconds }\n : {}),\n random,\n });\n await delayWithAbort(delayMs, options.signal);\n }\n\n // Unreachable: maxAttempts is always >= 1, so the loop above always\n // returns or throws before falling out the bottom.\n throw new Error('unreachable: executeWithRetry loop exited without returning or throwing');\n}\n","/**\n * The single HTTP choke point for `kaafil-js` — every request, from every\n * module method on either entry point, passes through `execute()`.\n * `architecture/08-sdk.md §5, §6`, `architecture/06-offline-first.md §7`,\n * `architecture/03-auth-and-tokens.md §2`.\n *\n * `execute()` is the one exported entry point: it takes a fully-described\n * `RequestDescriptor` and returns a typed `KaafilResponse<T>`. The actual\n * network call lives in the separately named `sendOnce()`, which knows\n * nothing about retries, refresh, or ladders — that split is deliberate.\n * A later offline-outbox phase decorates this exact seam (queue a write\n * durably, then call through) by wrapping `execute()` or splicing into the\n * `attempt` closure that calls `sendOnce()`; neither this file's public\n * shape nor `sendOnce()`'s signature needs to change for that phase to land.\n */\n\nimport {\n type CredentialResolver,\n isRotatingCredentialKind,\n type RotatingRefreshResult,\n type RotatingSessionExchange,\n} from '../auth/credentials';\nimport { KaafilErrorCode } from '../generated/error-codes';\nimport type { components } from '../generated/schema';\nimport {\n OPERATION_ACCEPTS_IDEMPOTENCY_KEY,\n OPERATION_SECURITY,\n type OperationId,\n} from '../generated/security';\nimport type {\n BinaryResponseMeta,\n KaafilBinaryResponse,\n KaafilResponse,\n ResponseMeta,\n} from '../types/meta';\nimport {\n fromEnvelope,\n isKaafilError,\n isRetryable,\n KaafilAbortError,\n type KaafilError,\n KaafilInvalidRequestError,\n KaafilNetworkError,\n KaafilRateLimitedError,\n KaafilTimeoutError,\n} from './errors';\nimport { type AttemptOutcome, executeWithRetry, RetryExhaustedError } from './retry';\n\ntype EnvelopeMetaShape = components['schemas']['EnvelopeMeta'];\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';\n\n/**\n * The SDK's own request shape — deliberately not `extends RequestInit`.\n * Inheriting the transport's option bag would make swapping `fetch` for a\n * different transport a breaking change to this type, and would let an\n * unrecognized caller-supplied key ride straight through to `fetch`.\n */\nexport interface RequestDescriptor {\n readonly method: HttpMethod;\n readonly operationId: OperationId;\n /** e.g. `/v1/trips/{tripId}` — every `{name}` is replaced from `pathParams`. */\n readonly path: string;\n readonly pathParams?: Readonly<Record<string, string | number>>;\n /** A value of `undefined` is omitted — it never becomes the string `\"undefined\"`. */\n readonly query?: Readonly<Record<string, string | number | boolean | undefined>>;\n readonly body?: unknown;\n /** Extra headers a specific method needs (`If-Match` on a versioned write,\n * `08-sdk.md §5`) — merged in last, after the credential and idempotency\n * headers this module owns. */\n readonly headers?: Readonly<Record<string, string>>;\n /**\n * A caller-supplied idempotency key, for resuming a logical operation\n * across a process restart. Omitted lets this module mint one — either\n * way, the same value rides every retry attempt for this call, which is\n * the entire point of the header.\n */\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n /**\n * The `Accept` header for this one request. Defaults to\n * `application/json`, which is what every enveloped operation wants and\n * what this field existed to leave alone. Set by `executeBinary()`'s\n * callers for the handful of operations the engine answers with bytes —\n * see that method on {@link KaafilHttpClient}.\n */\n readonly accept?: string;\n}\n\nexport interface KaafilClientConfig {\n /** Fixed at construction — no runtime `setBaseUrl` (module header). */\n readonly baseUrl: string;\n readonly credentials: CredentialResolver;\n /** Per-attempt network timeout. Default 30s. */\n readonly timeoutMs?: number;\n /** Per-call attempt cap passed through to the retry ladder. */\n readonly maxAttempts?: number;\n /** Sent as `User-Agent` where the platform permits setting one. */\n readonly userAgent?: string;\n readonly random?: () => number;\n}\n\nexport interface KaafilHttpClient {\n execute<T>(request: RequestDescriptor): Promise<KaafilResponse<T>>;\n /**\n * For the operations whose SUCCESS body is bytes, not a\n * `{ ok, data, meta }` envelope. Same credential resolution, same\n * idempotency handling, same retry-and-refresh ladder as `execute()` —\n * the only difference is how a `2xx` body is read.\n *\n * This exists because `execute()` structurally cannot serve these: it\n * calls `response.text()` and then requires `isSuccessEnvelope`, so a PDF\n * arrives as a `KaafilNetworkError('Received an unrecognizable success\n * body')` — a transport-shaped error for a response that was completely\n * fine. Only the SUCCESS path differs: the engine's error middleware\n * still emits a JSON `ErrorEnvelope` on every non-2xx, so failures come\n * back through the identical `fromEnvelope` mapping and the identical\n * typed error classes.\n *\n * Returns a {@link KaafilBinaryResponse} wrapper rather than the\n * `KaafilResponse<T>` intersection, because there is no envelope to take\n * a `meta` from — see that type's own doc for what is and is not known\n * about an envelope-less response.\n */\n executeBinary(request: RequestDescriptor): Promise<KaafilBinaryResponse>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\ninterface ClientContext {\n readonly baseUrl: string;\n readonly credentials: CredentialResolver;\n readonly timeoutMs: number;\n readonly maxAttempts: number | undefined;\n readonly userAgent: string | undefined;\n readonly random: (() => number) | undefined;\n}\n\n/** Public constructor. Everything below `execute()` is this module's private machinery. */\nexport function createHttpClient(config: KaafilClientConfig): KaafilHttpClient {\n const ctx: ClientContext = {\n baseUrl: config.baseUrl,\n credentials: config.credentials,\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxAttempts: config.maxAttempts,\n userAgent: config.userAgent,\n random: config.random,\n };\n return {\n execute: <T>(request: RequestDescriptor) => execute<T>(ctx, request),\n executeBinary: (request: RequestDescriptor) => executeBinary(ctx, request),\n };\n}\n\n// --- URL composition --------------------------------------------------\n\nfunction renderPath(\n template: string,\n params: Readonly<Record<string, string | number>> | undefined,\n): string {\n return template.replace(/\\{([^}]+)\\}/g, (_match, name: string) => {\n const raw = params?.[name];\n if (raw === undefined) {\n // Typed, and deliberately not a bare `Error`: an untyped throw from here\n // was wrapped as a retryable `KaafilNetworkError` and spent the whole\n // backoff ladder before reporting \"Unexpected transport failure\" for what\n // is a mistake in the call itself.\n throw new KaafilInvalidRequestError(\n `Missing path parameter \"${name}\" for \"${template}\". Pass it in the call's options.`,\n );\n }\n return encodeURIComponent(String(raw));\n });\n}\n\nfunction buildUrl(\n baseUrl: string,\n renderedPath: string,\n query: Readonly<Record<string, string | number | boolean | undefined>> | undefined,\n): URL {\n const normalizedBase = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;\n const relativePath = renderedPath.startsWith('/') ? renderedPath.slice(1) : renderedPath;\n const url = new URL(relativePath, normalizedBase);\n if (query !== undefined) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) {\n continue;\n }\n url.searchParams.set(key, String(value));\n }\n }\n return url;\n}\n\n// --- Abort + timeout combination ---------------------------------------\n\n/** Identity sentinel, never surfaced — only used to tell \"our own timeout\n * fired\" apart from \"the caller's signal fired\" once `combined.signal` aborts. */\nconst TIMEOUT_REASON = Symbol('kaafil-timeout');\n\ninterface CombinedSignal {\n readonly signal: AbortSignal;\n readonly isTimeout: () => boolean;\n readonly cleanup: () => void;\n}\n\n/**\n * Combines the caller's `AbortSignal` with this module's own timeout so\n * whichever fires first wins, without ever mutating or replacing the\n * caller's signal — a single client-wide \"next request\" abort slot binds to\n * whichever request happens to run next, which is the footgun this avoids.\n */\nfunction combineSignals(callerSignal: AbortSignal | undefined, timeoutMs: number): CombinedSignal {\n const controller = new AbortController();\n const cleanupFns: Array<() => void> = [];\n\n if (callerSignal !== undefined) {\n if (callerSignal.aborted) {\n controller.abort(callerSignal.reason);\n } else {\n const onAbort = (): void => controller.abort(callerSignal.reason);\n callerSignal.addEventListener('abort', onAbort, { once: true });\n cleanupFns.push(() => callerSignal.removeEventListener('abort', onAbort));\n }\n }\n\n const timer = setTimeout(() => controller.abort(TIMEOUT_REASON), timeoutMs);\n cleanupFns.push(() => clearTimeout(timer));\n\n return {\n signal: controller.signal,\n isTimeout: () => controller.signal.reason === TIMEOUT_REASON,\n cleanup: () => {\n for (const fn of cleanupFns) {\n fn();\n }\n },\n };\n}\n\n// --- Header assembly -----------------------------------------------------\n\nasync function buildHeaders(\n ctx: ClientContext,\n request: RequestDescriptor,\n idempotencyKey: string | undefined,\n hasBody: boolean,\n): Promise<Headers> {\n const acceptedSchemes = OPERATION_SECURITY[request.operationId];\n const credential = await ctx.credentials.resolveHeaders(request.operationId, acceptedSchemes);\n\n const headers = new Headers();\n headers.set('Accept', request.accept ?? 'application/json');\n if (hasBody) {\n headers.set('Content-Type', 'application/json');\n }\n for (const [key, value] of Object.entries(credential.headers)) {\n headers.set(key, value);\n }\n if (idempotencyKey !== undefined) {\n headers.set('Idempotency-Key', idempotencyKey);\n }\n if (ctx.userAgent !== undefined) {\n try {\n headers.set('User-Agent', ctx.userAgent);\n } catch {\n // Some fetch implementations (browsers) forbid setting `User-Agent` on\n // outgoing requests. A build stamp is a nice-to-have for support, never\n // load-bearing for the request itself — fail silently.\n }\n }\n if (request.headers !== undefined) {\n for (const [key, value] of Object.entries(request.headers)) {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\n// --- Response parsing ------------------------------------------------\n\nfunction tryParseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isSuccessEnvelope(\n body: unknown,\n): body is { ok: true; data: unknown; meta: EnvelopeMetaShape; facets?: unknown } {\n if (typeof body !== 'object' || body === null) {\n return false;\n }\n const record = body as Record<string, unknown>;\n if (record.ok !== true) {\n return false;\n }\n if (typeof record.data !== 'object' || record.data === null) {\n return false;\n }\n const meta = record.meta;\n if (typeof meta !== 'object' || meta === null) {\n return false;\n }\n return typeof (meta as Record<string, unknown>).serverTime === 'string';\n}\n\nfunction buildResponseMeta(\n status: number,\n requestId: string | undefined,\n meta: EnvelopeMetaShape,\n): ResponseMeta {\n return {\n status,\n serverTime: meta.serverTime,\n requestId,\n page: meta.page,\n };\n}\n\nfunction parseRetryAfterSeconds(headerValue: string | null): number | undefined {\n if (headerValue === null) {\n return undefined;\n }\n const seconds = Number(headerValue);\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;\n}\n\n/**\n * Attaches `meta` to a successful payload. `data` is `object`-typed by\n * `isSuccessEnvelope`'s guard, but that includes arrays — several operations\n * in this API return `data: T[]` directly (`listTripVendors`,\n * `listWebhookDeliveries`, …), and spreading an array with `{ ...data }`\n * copies its indices into a plain `{0: ..., 1: ...}` object, silently\n * discarding `Array.isArray`/`.length`/`.map` for every caller. `Object.assign`\n * mutates and returns the freshly-parsed body in place instead, which\n * preserves array-ness when `data` is an array and behaves identically to\n * the previous spread when it's a plain object.\n */\n/**\n * Attach the envelope's out-of-band values onto the payload.\n *\n * `facets` rides along the same way `meta` does, and ONLY when the envelope\n * actually carried one — which is every response's behaviour today except the\n * two operations whose engine-side schema declares it (`listAgencyTrips`,\n * `listWebhookDeliveries*`). Without this the key was read off the wire and\n * then thrown away here, so an aggregate the engine computed over the whole\n * filtered set could never reach a caller: exactly the \"extra key disappears\n * without anyone deciding that\" hazard the engine's own response wrapper\n * documents on its `KNOWN_PAGINATED_EXTRA_KEYS` allowlist, one layer further\n * out.\n *\n * The intersection is collision-safe for the same reason `meta`'s is\n * (`types/meta.ts`'s own note): `facets` appears only on envelope-shaped\n * schemas in the catalog, never as a property of a payload DTO — and a\n * paginated payload is an array, which owns no such key.\n */\nfunction attachMeta<T>(data: unknown, meta: ResponseMeta, facets: unknown): KaafilResponse<T> {\n // ── `data` CAN BE ABSENT, AND `Object.assign` THROWS ON IT ────────────────\n //\n // A `204 No Content` has no envelope and so no `data`. `Object.assign(\n // undefined, …)` raises a TypeError, and because a TypeError is not a\n // `KaafilError` the layer above classified it as a TRANSPORT failure and\n // RETRIED — so a delete that had already succeeded ran a second time against\n // a row that no longer existed, and the caller was handed the retry's `404`\n // for an operation that worked. The bytes really were gone; the answer was\n // simply the wrong request's.\n //\n // `null` gets the same treatment for the same reason: it is equally\n // impossible to hang a property off, and an enveloped `data: null` is a\n // shape the server is free to send.\n const base = data === undefined || data === null ? {} : (data as object);\n const withMeta = Object.assign(base, { meta });\n return (\n facets === undefined ? withMeta : Object.assign(withMeta, { facets })\n ) as KaafilResponse<T>;\n}\n\n// --- Cross-origin diagnostic (browser only) -------------------------------\n\n/**\n * Heuristic-only classification of a rejected `fetch` as a likely in-browser\n * CORS block, never a determination. From inside the page, `fetch` rejecting\n * with no status is indistinguishable between \"the network is down\" and \"the\n * browser withheld a cross-origin response because the API has not\n * allowlisted this page's origin\" — the browser hides the real reason either\n * way, so this can only name the more likely cause, not confirm it. A\n * genuine network outage produces the exact same rejection.\n *\n * Returns `undefined` outside a browser: `globalThis.location` does not\n * exist in Node, there is no same-origin policy to violate there, and this\n * must neither fire nor throw for a server-side caller.\n */\nfunction describeCrossOriginSuspect(url: URL): string | undefined {\n const loc = (globalThis as { location?: unknown }).location;\n if (typeof loc !== 'object' || loc === null) {\n return undefined;\n }\n const origin = (loc as { origin?: unknown }).origin;\n if (typeof origin !== 'string' || origin === url.origin) {\n return undefined;\n }\n return (\n `Request failed while calling a different origin (${url.origin}) than the page's own origin ` +\n `(${origin}). The most likely cause is that the API has not allowlisted this origin for CORS — ` +\n 'but the browser withholds the actual reason from JavaScript when it blocks a cross-origin ' +\n 'response, so the SDK cannot confirm this; a genuine network outage produces the same ' +\n \"rejection. If this is unexpected, the fix is server-side: add this origin to the API's CORS \" +\n 'allowlist.'\n );\n}\n\n// --- The one place a request is actually sent -----------------------------\n\n/**\n * Reads a non-2xx response and throws the right typed `KaafilError`. Shared\n * verbatim by both success readers below, and that sharing is the load-bearing\n * part: an operation whose SUCCESS body is bytes still fails through the\n * engine's ordinary JSON `ErrorEnvelope`, so its `404`/`422`/`423`/`429` must\n * land in exactly the same typed classes as every other operation's. Never\n * returns.\n */\nasync function throwFromErrorResponse(\n response: Response,\n status: number,\n requestId: string | undefined,\n): Promise<never> {\n // Guarded end to end: an empty body, or a non-JSON body from an\n // intermediary (a `502` with an HTML page), must never throw out of\n // `response.text()`/`JSON.parse` — `fromEnvelope` turns an unrecognizable\n // body into a coherent typed error on its own.\n const text = await response.text();\n const body = text.length > 0 ? tryParseJson(text) : undefined;\n const retryAfterSeconds = parseRetryAfterSeconds(response.headers.get('retry-after'));\n throw fromEnvelope(body, {\n status,\n ...(requestId !== undefined ? { requestId } : {}),\n ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),\n });\n}\n\n/**\n * Sends exactly one HTTP attempt and hands the 2xx `Response` to\n * `readSuccess`, or throws the right typed `KaafilError`. Knows nothing\n * about retries, ladders, or refresh — `execute()`/`executeBinary()` own all\n * of that and call this once per attempt.\n *\n * Generic over how a success body is READ, and over nothing else: the URL,\n * the credential, the idempotency header, the abort/timeout combination and\n * the whole error path are identical whether the answer is an envelope or a\n * PDF, and duplicating them for the binary case is how the two drift.\n */\nasync function sendOnceWith<R>(\n ctx: ClientContext,\n request: RequestDescriptor,\n idempotencyKey: string | undefined,\n readSuccess: (response: Response, status: number, requestId: string | undefined) => Promise<R>,\n): Promise<R> {\n const hasBody = request.body !== undefined;\n const renderedPath = renderPath(request.path, request.pathParams);\n const url = buildUrl(ctx.baseUrl, renderedPath, request.query);\n const headers = await buildHeaders(ctx, request, idempotencyKey, hasBody);\n const combined = combineSignals(request.signal, ctx.timeoutMs);\n\n try {\n const response = await fetch(url, {\n method: request.method,\n headers,\n signal: combined.signal,\n ...(hasBody ? { body: JSON.stringify(request.body) } : {}),\n });\n\n const requestId = response.headers.get('x-request-id') ?? undefined;\n const status = response.status;\n\n if (response.ok) {\n return await readSuccess(response, status, requestId);\n }\n return await throwFromErrorResponse(response, status, requestId);\n } catch (error) {\n // Errors thrown above are already the right typed `KaafilError` —\n // propagate them untouched. Anything else reaching here is a genuine\n // transport failure: `fetch()` rejecting, or `response.text()`\n // rejecting mid-stream (network drop, our own timeout, or the caller's\n // abort — `combined` tells these two apart).\n if (isKaafilError(error)) {\n throw error;\n }\n if (combined.signal.aborted) {\n if (combined.isTimeout()) {\n throw new KaafilTimeoutError('Request timed out', { cause: error });\n }\n throw new KaafilAbortError('Request aborted', { cause: error });\n }\n throw new KaafilNetworkError(describeCrossOriginSuspect(url) ?? 'Request failed', {\n cause: error,\n });\n } finally {\n combined.cleanup();\n }\n}\n\n/** The enveloped success reader — every operation but the byte-bodied few. */\nfunction sendOnce<T>(\n ctx: ClientContext,\n request: RequestDescriptor,\n idempotencyKey: string | undefined,\n): Promise<{ readonly data: T; readonly meta: ResponseMeta; readonly facets: unknown }> {\n return sendOnceWith(ctx, request, idempotencyKey, async (response, status, requestId) => {\n const text = await response.text();\n const body = text.length > 0 ? tryParseJson(text) : undefined;\n\n // ── A 2xx WITH NO BODY IS A SUCCESS, NOT AN UNRECOGNIZABLE ONE ──────────\n //\n // Every DELETE in this API answers `204 No Content`, and HTTP forbids a\n // body on a 204 — so there is no envelope to find and demanding one turned\n // every successful delete into a thrown `KaafilNetworkError` carrying\n // `status: 204`. `vendors.remove()` and `files.remove()` were both\n // unusable because of it.\n //\n // `serverTime` is the one field a caller loses here, and it cannot be\n // recovered: it lives in the envelope the response does not have. Rather\n // than invent one from the device clock — the exact thing this SDK refuses\n // to do everywhere else — `meta.serverTime` carries the `Date` header when\n // the server sent one, and is absent otherwise.\n if (body === undefined && status >= 200 && status < 300) {\n const serverDate = response.headers.get('date');\n return {\n data: undefined as T,\n meta: {\n status,\n requestId,\n ...(serverDate === null ? {} : { serverTime: new Date(serverDate).toISOString() }),\n } as ResponseMeta,\n facets: undefined,\n };\n }\n\n if (!isSuccessEnvelope(body)) {\n throw new KaafilNetworkError(`Received an unrecognizable success body for HTTP ${status}`, {\n status,\n ...(requestId !== undefined ? { requestId } : {}),\n });\n }\n return {\n data: body.data as T,\n meta: buildResponseMeta(status, requestId, body.meta),\n facets: body.facets,\n };\n });\n}\n\n/**\n * The byte success reader. Asserts NOTHING about the payload beyond \"it\n * arrived\": no magic-number check, no `Content-Type` allowlist. A caller\n * that cares which format it got reads `meta.contentType`, which is the\n * server's own header verbatim — this SDK does not re-decide what a\n * successfully-served body is.\n *\n * `arrayBuffer()` rather than `blob()`: `Blob` is not a Node global before\n * 18 and is awkward to get bytes out of anywhere, while `ArrayBuffer` →\n * `Uint8Array` is one allocation-free wrap in every runtime.\n */\nfunction sendOnceBinary(\n ctx: ClientContext,\n request: RequestDescriptor,\n idempotencyKey: string | undefined,\n): Promise<KaafilBinaryResponse> {\n return sendOnceWith(ctx, request, idempotencyKey, async (response, status, requestId) => {\n const buffer = await response.arrayBuffer();\n const meta: BinaryResponseMeta = {\n status,\n requestId,\n contentType: response.headers.get('content-type') ?? undefined,\n };\n return { bytes: new Uint8Array(buffer), meta };\n });\n}\n\n// --- The rotating-session exchanges, standing alone from `execute()` -------\n\nconst MANAGER_TOKENS_REFRESH_PATH = '/api/v1/auth/manager-tokens/refresh';\nconst AGENCY_ADMIN_TOKENS_REFRESH_PATH = '/api/v1/auth/agency-admin-tokens/refresh';\n\n/**\n * Builds the `RotatingSessionExchange` a rotating (`managerSession`/\n * `agencyAdmin`) credential is constructed with by default\n * (`../client-entry.ts`). Deliberately its own tiny `fetch` call rather than\n * a call through `execute()`: `execute()` resolves its request's credential\n * through the very `CredentialResolver` this function is handed into, so\n * routing the refresh itself through `execute()` would recurse back into the\n * resolver mid-refresh; and `execute()`'s retry ladder is built to retry a\n * request, not to retry a single-use rotation that revokes its whole family\n * on a second presentation (`../auth/credentials.ts`'s\n * `RotatingSessionExchange` doc comment, `architecture/03-auth-and-tokens.md\n * §2`). One attempt, no ladder, no credential resolution — just the one POST\n * the session's own access token authorises.\n *\n * Shared by both `createManagerSessionRefreshExchange` and\n * `createAgencyAdminSessionRefreshExchange` below — the two differ only in\n * which endpoint they hit, and hand-rolling the fetch/parse/error-mapping\n * dance a second time for the second kind would be exactly the kind of copy\n * this lane's brief calls out for the engine's own rotation extraction.\n */\nfunction createRotatingSessionRefreshExchange(\n baseUrl: string,\n refreshPath: string,\n networkErrorMessage: string,\n): RotatingSessionExchange {\n return async (accessToken, refreshToken) => {\n const url = buildUrl(baseUrl, refreshPath, undefined);\n const headers = new Headers({\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n });\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify({ refreshToken }),\n });\n } catch (error) {\n throw new KaafilNetworkError(networkErrorMessage, { cause: error });\n }\n\n const requestId = response.headers.get('x-request-id') ?? undefined;\n const status = response.status;\n const text = await response.text();\n const body = text.length > 0 ? tryParseJson(text) : undefined;\n\n if (!response.ok) {\n throw fromEnvelope(body, {\n status,\n ...(requestId !== undefined ? { requestId } : {}),\n });\n }\n if (!isSuccessEnvelope(body)) {\n throw new KaafilNetworkError(`Received an unrecognizable success body for HTTP ${status}`, {\n status,\n ...(requestId !== undefined ? { requestId } : {}),\n });\n }\n return body.data as RotatingRefreshResult;\n };\n}\n\nexport function createManagerSessionRefreshExchange(baseUrl: string): RotatingSessionExchange {\n return createRotatingSessionRefreshExchange(\n baseUrl,\n MANAGER_TOKENS_REFRESH_PATH,\n 'Manager-session refresh request failed',\n );\n}\n\nexport function createAgencyAdminSessionRefreshExchange(baseUrl: string): RotatingSessionExchange {\n return createRotatingSessionRefreshExchange(\n baseUrl,\n AGENCY_ADMIN_TOKENS_REFRESH_PATH,\n 'Agency-admin session refresh request failed',\n );\n}\n\n// --- Retry + refresh orchestration --------------------------------------\n\nfunction toKaafilError(error: unknown): KaafilError {\n if (isKaafilError(error)) {\n return error;\n }\n return new KaafilNetworkError('Unexpected transport failure', { cause: error });\n}\n\nfunction toFailureOutcome<T>(error: KaafilError): AttemptOutcome<T> {\n return {\n ok: false,\n status: error.status ?? null,\n ...(error.code !== undefined ? { code: error.code } : {}),\n ...(error instanceof KaafilRateLimitedError && error.retryAfterSeconds !== undefined\n ? { retryAfterSeconds: error.retryAfterSeconds }\n : {}),\n };\n}\n\n/**\n * Runs one logical call end to end: mints (or reuses) the idempotency key,\n * drives the retry ladder (`retry.ts`) whose allowlist is itself built from\n * the same `ERROR_CODE_TABLE` that `classify.ts` classifies transient /\n * conflict / fatal from (`06-offline-first.md §7`) — so a code the table\n * marks non-retryable never gets a second ladder attempt here, and grants\n * `401 UNAUTHENTICATED` exactly one refresh-then-replay outside the ladder\n * (`03-auth-and-tokens.md §2`; `after-refresh` is deliberately excluded from\n * the ladder's own allowlist in `retry.ts`, precisely so it can't also be\n * retried there).\n */\nasync function runWithLadder<R>(\n ctx: ClientContext,\n request: RequestDescriptor,\n send: (idempotencyKey: string | undefined) => Promise<R>,\n): Promise<R> {\n const idempotencyKey = OPERATION_ACCEPTS_IDEMPOTENCY_KEY[request.operationId]\n ? (request.idempotencyKey ?? globalThis.crypto.randomUUID())\n : undefined;\n\n let lastError: KaafilError | undefined;\n let refreshAttempted = false;\n\n const sendAndClassify = async (): Promise<AttemptOutcome<R>> => {\n try {\n return { ok: true, value: await send(idempotencyKey) };\n } catch (error) {\n const typed = toKaafilError(error);\n lastError = typed;\n // A malformed request never enters the ladder. `isRetryableFailure`\n // (`./retry.ts`) classifies from a bare `{ status, code }`, and a\n // usage error carries NEITHER — no response reached the client, so\n // `status` is `null`, which that function reads as \"transport blip,\n // retry\". It cannot tell a dropped connection apart from a request\n // that was rejected before it was ever built.\n //\n // This mattered concretely, and the scale of it is the point.\n // `UnsatisfiableSchemeError` — thrown by `CredentialResolver` inside\n // `buildHeaders`, i.e. before `fetch` is reached at all — is the\n // answer for every operation the open credential's scheme cannot\n // satisfy (`closeout.unlock` and `expenses.claims.ingest` from a\n // manager session; `journey.rebuild`/`journey.runStep` likewise, which\n // is how long this has been true). Classified as a null-status failure\n // it entered the full default ladder: `DEFAULT_MAX_ATTEMPTS` is 24 and\n // `RETRY_LADDER_MS` holds at its 3,600,000 ms top rung, so the 23 waits\n // sum to 62,481,000 ms before jitter — between roughly 8.7 and 17.4\n // hours of a pending promise, with ZERO requests sent, for a mistake\n // the SDK had already diagnosed completely on the first microtask.\n // Observed directly: a probe left running past 25 minutes had not yet\n // surfaced it. The eventual error was the right one; nobody is awake\n // to read it.\n //\n // `isRetryable` (`./errors.ts`) already encodes exactly this rule for\n // consumers, and its own comment names this failure — the ladder was\n // simply never consulting it. Deferring to it here rather than\n // re-testing `instanceof KaafilInvalidRequestError` keeps one\n // definition of \"retryable\", so a future change to that predicate\n // cannot leave the transport disagreeing with the package's exported\n // answer. `KaafilAbortError` comes along for the ride, correctly: the\n // caller asked to stop.\n if (typed.kind === 'transport' && !isRetryable(typed)) {\n throw typed;\n }\n return toFailureOutcome(typed);\n }\n };\n\n const attempt = async (_attemptNumber: number): Promise<AttemptOutcome<R>> => {\n const outcome = await sendAndClassify();\n if (outcome.ok) {\n return outcome;\n }\n\n const canRefresh =\n !refreshAttempted &&\n outcome.code === KaafilErrorCode.Unauthenticated &&\n isRotatingCredentialKind(ctx.credentials.kind);\n if (!canRefresh) {\n return outcome;\n }\n\n refreshAttempted = true;\n try {\n await ctx.credentials.refreshRotatingSession();\n } catch {\n // The refresh itself failed — surface the original 401, not a\n // refresh-plumbing error the consumer never asked about.\n return outcome;\n }\n return sendAndClassify();\n };\n\n // Rendered once here, BEFORE the retry loop, purely so a malformed request\n // fails on the caller's first await instead of inside an attempt. `sendOnce`\n // renders it again per attempt — the function is pure and cheap, and having\n // the validation live at the boundary is worth the duplicate call: a usage\n // error that escapes from inside `attempt` is one classification mistake away\n // from being retried.\n renderPath(request.path, request.pathParams);\n\n try {\n return await executeWithRetry(attempt, {\n ...(ctx.maxAttempts !== undefined ? { maxAttempts: ctx.maxAttempts } : {}),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n ...(ctx.random !== undefined ? { random: ctx.random } : {}),\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n hasBody: request.body !== undefined,\n });\n } catch (error) {\n if (error instanceof RetryExhaustedError) {\n // Never replace a typed failure with a generic \"retry exhausted\"\n // message — that is precisely how a tenant-isolation 404 becomes an\n // untyped string. Throw the last real `KaafilError` we saw instead.\n throw lastError ?? error;\n }\n if (request.signal?.aborted === true) {\n throw new KaafilAbortError('Request aborted', { cause: lastError ?? error });\n }\n throw error;\n }\n}\n\n/** The enveloped call — what every resource method but `closeout.exportPdf`\n * goes through. */\nfunction execute<T>(ctx: ClientContext, request: RequestDescriptor): Promise<KaafilResponse<T>> {\n return runWithLadder(ctx, request, async (idempotencyKey) => {\n const { data, meta, facets } = await sendOnce<T>(ctx, request, idempotencyKey);\n return attachMeta<T>(data, meta, facets);\n });\n}\n\n/** The byte-bodied call. Same ladder, same refresh grant, same typed errors\n * — see `KaafilHttpClient.executeBinary`'s doc for why it cannot go through\n * `execute()` above. */\nfunction executeBinary(\n ctx: ClientContext,\n request: RequestDescriptor,\n): Promise<KaafilBinaryResponse> {\n return runWithLadder(ctx, request, (idempotencyKey) =>\n sendOnceBinary(ctx, request, idempotencyKey),\n );\n}\n","/**\n * Mints a fresh idempotency key. Not credential-specific and not tied to\n * either entry point — both `Kaafil` (`../client.ts`) and `KaafilClient`\n * (`../client-entry.ts`) expose this as a static `newIdempotencyKey()`, and\n * this is the one place the actual minting happens so the two never drift.\n *\n * Every mutating call already mints and reuses a key automatically\n * (`http/client.ts`'s `execute()` — `globalThis.crypto.randomUUID()` when the\n * caller didn't supply one). Calling this directly is the rare case: pinning\n * a key ahead of time so a caller can replay the exact same logical\n * operation — with the exact same key — across a process restart, which\n * `execute()` has no way to do on the caller's behalf since it has no\n * visibility into the caller's own retry-across-restart bookkeeping.\n */\nexport function newIdempotencyKey(): string {\n return globalThis.crypto.randomUUID();\n}\n","/**\n * Coercion for the caller-supplied date-time fields scattered across the\n * ingest surface (`trips.upsert`, `trips.travellers.*`, `trips.managers.*`,\n * `trips.balance.push`, `trips.bulk.push`, `shareTokens.create`). Every one\n * of those fields is, in the generated schema, a bare `string` that the API\n * requires to be a full ISO-8601 datetime WITH an offset — a caller who\n * hand-builds that string is the single most common way to fail this API's\n * validation, and JavaScript already has a `Date` for exactly this job.\n *\n * This module is the one seam every such field routes through. It is not\n * wired into the generated schema types (those stay a faithful mirror of\n * the OpenAPI spec) — it is wired into the hand-written `*Options` types in\n * `resources/trips.ts` and `resources/share-tokens.ts`, which widen the\n * relevant fields from `string` to `DateTimeInput` and normalize back down\n * to the schema's `string` shape before the body reaches `client.execute`.\n */\n\nimport { KaafilInvalidRequestError } from './http/errors';\n\n/**\n * What a caller may hand a date-time field on the ingest surface.\n *\n * - `Date` is the point of this whole module: build it however you like,\n * the SDK converts it correctly.\n * - `number` is epoch milliseconds — `Date.now()` and friends, without\n * forcing a caller to wrap it in `new Date(...)` first.\n * - `string` is the escape hatch for a caller who already has a correctly\n * formatted ISO datetime (e.g. echoed back from another system) and does\n * not want it touched — see `normalizeDateTimeInput` for why a full\n * datetime string passes through byte-for-byte instead of round-tripping\n * through `Date`.\n */\nexport type DateTimeInput = Date | number | string;\n\n// A full ISO-8601 datetime with an explicit offset — `Z` or `±HH:MM`.\n// Anchored both ends: a substring match here would let e.g. free text that\n// merely *contains* a valid datetime slip through as \"already valid\".\nconst FULL_DATETIME_WITH_OFFSET =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/;\n\n// `YYYY-MM-DD` — the specific, seductive wrong answer this module refuses\n// to guess its way out of. See the throw site below for why.\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nfunction invalidRequest(fieldPath: string, message: string): KaafilInvalidRequestError {\n return new KaafilInvalidRequestError(`${fieldPath}: ${message}`);\n}\n\n/**\n * Normalizes one caller-supplied date-time field to the ISO string the API\n * expects. `fieldPath` is a dotted/indexed path (e.g.\n * `\"trips[2].travellers[0].sourceUpdatedAt\"`) so a thrown error names\n * exactly which field, in which nested row, is wrong — a caller pushing a\n * bulk batch of 50 trips should not have to bisect the payload by hand.\n *\n * A `string` that is already a full ISO datetime with an offset is\n * returned UNCHANGED, not round-tripped through `new Date(...).toISOString()`.\n * `toISOString()` always normalizes to `Z`, so round-tripping would silently\n * rewrite a caller's explicit `+05:30` to `Z` — same instant, different text\n * — and change what gets echoed back to them on every read. An existing\n * caller who already builds this string correctly must see it pass through\n * byte-for-byte; this function only ever *adds* a coercion path, never\n * alters the one that already worked.\n *\n * A `string` that is date-only (`YYYY-MM-DD`) is REFUSED, not coerced to\n * midnight UTC. That coercion looks helpful and is a correctness trap: a\n * trip starting \"20 August\" in `Asia/Kolkata` does not begin at `00:00Z`,\n * and picking UTC on the caller's behalf would silently invent a timezone\n * they never chose, shifting a real trip's start by hours. Guessing wrong\n * here is worse than refusing — so this throws a `KaafilInvalidRequestError`\n * (a caller-built-it-wrong error, never retried, per `http/errors.ts`)\n * naming the field and showing the fix, and the caller finds out locally\n * and instantly instead of after a round trip to a remote `422`.\n */\nexport function normalizeDateTimeInput(value: DateTimeInput, fieldPath: string): string {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw invalidRequest(fieldPath, 'received an invalid Date (getTime() is NaN).');\n }\n return value.toISOString();\n }\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw invalidRequest(\n fieldPath,\n `received a non-finite number (${String(value)}); expected epoch milliseconds.`,\n );\n }\n return new Date(value).toISOString();\n }\n\n if (FULL_DATETIME_WITH_OFFSET.test(value)) {\n return value;\n }\n\n if (DATE_ONLY.test(value)) {\n throw invalidRequest(\n fieldPath,\n `received a date-only string (\"${value}\"). This API requires a full ISO-8601 ` +\n 'datetime WITH an offset, and the SDK will not guess which timezone you meant ' +\n '(midnight UTC is rarely midnight where the trip actually starts). Pass a ' +\n '`Date` instead — e.g. `new Date(\"2026-08-20T09:00:00+05:30\")` — or add an ' +\n 'explicit offset yourself, e.g. \"2026-08-20T00:00:00+05:30\".',\n );\n }\n\n throw invalidRequest(\n fieldPath,\n `received \"${value}\", which is not a full ISO-8601 datetime with an offset. Pass a ` +\n '`Date`, an epoch-milliseconds number, or a string like \"2026-08-20T09:00:00+05:30\".',\n );\n}\n\n/**\n * Same contract as `normalizeDateTimeInput`, for a field that is optional on\n * the wire (`expiresAt?:` on `MintShareTokenRequest`, say). `undefined` in\n * means `undefined` out — the caller omitted it, so there is nothing to\n * normalize and nothing to throw about.\n */\nexport function normalizeOptionalDateTimeInput(\n value: DateTimeInput | undefined,\n fieldPath: string,\n): string | undefined {\n return value === undefined ? undefined : normalizeDateTimeInput(value, fieldPath);\n}\n\n/**\n * Same contract again, for a NULLABLE field (`startTime`/`endTime` on an\n * itinerary item, where `null` clears a time that was set).\n *\n * `null` passes through as `null`; it is never coerced to a timestamp and\n * never folded into `undefined`. On these fields the two mean opposite\n * things — `undefined` is \"leave whatever is there alone\", `null` is \"clear\n * it\" — and collapsing them would turn an attempt to clear a start time into\n * a silent no-op.\n *\n * `undefined` is deliberately NOT in this signature, unlike\n * `normalizeOptionalDateTimeInput`'s. Every field that reaches this function\n * is optional on the wire too, and `exactOptionalPropertyTypes` means an\n * omitted field must be omitted from the object literal rather than set to\n * `undefined` — so the call site already has to branch on `undefined` to build\n * its conditional spread. Accepting it here as well would let a `undefined`\n * return leak into a field typed `string | null`.\n */\nexport function normalizeNullableDateTimeInput(\n value: DateTimeInput | null,\n fieldPath: string,\n): string | null {\n return value === null ? null : normalizeDateTimeInput(value, fieldPath);\n}\n","/**\n * Cursor pagination for `kaafil-js`. Six list operations are\n * cursor-paginated (`cursor` + `limit` query params, `meta.page.hasNext` in\n * the envelope) — the SDK holds the cursor so a consumer never sees one\n * (`architecture/08-sdk.md §5`: \"pagination cursors are exposed on the\n * result\"; the cursor itself is documented OPAQUE per-operation in\n * `openapi/openapi.json`, e.g. `listApiKeys`, `listWebhookEndpoints`,\n * `listWebhookDeliveries`).\n *\n * `hasNext` is read from `meta.page.hasNext` and never inferred from \"the\n * page came back empty\" or \"fewer than `limit` rows came back\" — the server\n * already answers this question, and guessing it from row counts is exactly\n * how a reference SDK's list object gets it wrong at a page boundary that\n * lands on a multiple of `limit`.\n */\n\nimport type { PagedResponseMeta } from '../types/meta';\n\n/** One fetched page: its rows plus the envelope metadata that came with them. */\nexport interface PaginatorPage<T> {\n readonly items: readonly T[];\n readonly meta: PagedResponseMeta;\n}\n\n/**\n * Fetches one page for a given cursor/limit/filters triple. A resource\n * module supplies this as a thin closure over `KaafilHttpClient.execute` —\n * this module knows nothing about HTTP, operation ids, or query-param names,\n * only that a page has `items` and cursor-pagination `meta`.\n */\nexport type FetchPage<T, F> = (request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: F;\n}) => Promise<PaginatorPage<T>>;\n\n/**\n * Thrown by `next()` instead of ever resolving to `[]` for a state that\n * isn't \"the server returned zero rows this page\". A reference SDK resolves\n * an empty array on a re-entrant call, on exhaustion, AND on a genuinely\n * empty page — collapsing three different states into one indistinguishable\n * answer, so a double-fire on a UI mount looks exactly like \"no more data\".\n * These two named subclasses exist so a caller can `instanceof`-branch and\n * tell them apart; a real empty page still just resolves normally with\n * `items: []` and whatever `hasNext` the server said.\n */\nexport abstract class KaafilPaginationError extends Error {\n protected constructor(message: string) {\n super(message);\n this.name = 'KaafilPaginationError';\n }\n}\n\n/** `next()` was called again before the in-flight call for this paginator settled. */\nexport class KaafilPaginationInFlightError extends KaafilPaginationError {\n constructor() {\n super('next() was called while a previous call on this paginator was still in flight.');\n this.name = 'KaafilPaginationInFlightError';\n Object.setPrototypeOf(this, KaafilPaginationInFlightError.prototype);\n }\n}\n\n/** `next()` was called after `hasNext` had already gone `false`. */\nexport class KaafilPaginationExhaustedError extends KaafilPaginationError {\n constructor() {\n super('next() was called after this paginator was already exhausted (hasNext is false).');\n this.name = 'KaafilPaginationExhaustedError';\n Object.setPrototypeOf(this, KaafilPaginationExhaustedError.prototype);\n }\n}\n\n/**\n * The HTTP statuses this module treats as terminal: the server has answered\n * definitively that this call can never succeed by paging further (a plan\n * gate, a validation failure, tenant-scoped absence). On one of these, the\n * paginator sets `hasNext` to `false` and files the typed error in\n * `lastError` rather than throwing it out of `next()` or the async\n * iterator — a caller iterating a list is not the place to force a `try`\n * around a condition that means \"there is nothing more to show,\" and the\n * error is still there in `lastError` for anyone who wants to inspect why.\n * Any other failure (a 5xx, a timeout that survived the transport's own\n * retry ladder) is NOT terminal here: it is re-thrown, because the paginator\n * cannot tell whether paging further would still work.\n */\nconst TERMINAL_STATUSES: ReadonlySet<number> = new Set([402, 404, 422]);\n\nfunction isTerminalStatus(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'status' in error &&\n typeof (error as { status: unknown }).status === 'number' &&\n TERMINAL_STATUSES.has((error as { status: number }).status)\n );\n}\n\n/**\n * A `list()` call builds one of these and returns it SYNCHRONOUSLY, before\n * any request goes out: it is not a promise, and `await list()` is a no-op\n * that hands back this same object with `items: []`. The first page arrives\n * only from `await paginator.next()` or from iterating the paginator — an\n * untouched paginator reading as an empty tenant is the shape of that\n * mistake, and `meta === undefined` distinguishes \"not fetched yet\" from a\n * genuinely empty first page.\n */\nexport interface KaafilPaginator<T, F> {\n /** Every row fetched so far, across every page pulled on the current\n * filters — `[]` until `next()` (or iteration) has actually run. */\n readonly items: readonly T[];\n /** From the last page's `meta.page.hasNext` — `true` until a first fetch has run. */\n readonly hasNext: boolean;\n readonly isLoading: boolean;\n /** The typed error from the last failed fetch, if any. Cleared by `setFilters`. */\n readonly lastError: unknown;\n /** The last page's full envelope `meta`, or `undefined` before a first fetch. */\n readonly meta: PagedResponseMeta | undefined;\n /**\n * Fetches the next page and returns just that page's rows (also appended\n * to `items`). Throws `KaafilPaginationInFlightError` on a re-entrant\n * call and `KaafilPaginationExhaustedError` once `hasNext` is `false` —\n * neither case reaches the network.\n */\n next(): Promise<readonly T[]>;\n /**\n * Replaces the filters, resets the cursor to the start, clears\n * `items`/`lastError`, and sets `hasNext` back to `true`. A\n * stale-cursor-with-new-filters state is unrepresentable: there is no way\n * to change `filters` without also discarding whatever cursor was in\n * flight for the old ones.\n */\n setFilters(filters: F): void;\n /**\n * Drives `next()` until the server says `hasNext: false`, yielding one row\n * at a time so a Node backend can `for await (const row of paginator)` and\n * never think about paging. A terminal error ends the iteration quietly\n * (see `TERMINAL_STATUSES`); anything else propagates out of the loop.\n */\n [Symbol.asyncIterator](): AsyncIterator<T>;\n}\n\ninterface PaginatorState<T, F> {\n cursor: string | undefined;\n hasNext: boolean;\n isLoading: boolean;\n lastError: unknown;\n meta: PagedResponseMeta | undefined;\n items: T[];\n filters: F;\n}\n\nfunction createInitialState<T, F>(filters: F): PaginatorState<T, F> {\n return {\n cursor: undefined,\n hasNext: true,\n isLoading: false,\n lastError: undefined,\n meta: undefined,\n items: [],\n filters,\n };\n}\n\nexport interface CreatePaginatorConfig<T, F> {\n readonly fetchPage: FetchPage<T, F>;\n readonly filters: F;\n /** Page size sent as the `limit` query param. Omitted lets the server default apply. */\n readonly limit?: number;\n}\n\n/**\n * Builds a `KaafilPaginator`. A resource module's `list()` method calls this\n * once per invocation and hands back the result directly — the paginator\n * owns every subsequent page fetch.\n */\nexport function createPaginator<T, F>(config: CreatePaginatorConfig<T, F>): KaafilPaginator<T, F> {\n const { fetchPage, limit } = config;\n const state = createInitialState<T, F>(config.filters);\n\n async function next(): Promise<readonly T[]> {\n if (state.isLoading) {\n throw new KaafilPaginationInFlightError();\n }\n if (!state.hasNext) {\n throw new KaafilPaginationExhaustedError();\n }\n\n state.isLoading = true;\n try {\n const page = await fetchPage({ cursor: state.cursor, limit, filters: state.filters });\n state.items.push(...page.items);\n state.cursor = page.meta.page.cursor ?? undefined;\n state.hasNext = page.meta.page.hasNext;\n state.meta = page.meta;\n state.lastError = undefined;\n return page.items;\n } catch (error) {\n state.lastError = error;\n if (isTerminalStatus(error)) {\n state.hasNext = false;\n return [];\n }\n throw error;\n } finally {\n state.isLoading = false;\n }\n }\n\n function setFilters(filters: F): void {\n const fresh = createInitialState<T, F>(filters);\n state.cursor = fresh.cursor;\n state.hasNext = fresh.hasNext;\n state.isLoading = fresh.isLoading;\n state.lastError = fresh.lastError;\n state.meta = fresh.meta;\n state.items.length = 0;\n state.filters = filters;\n }\n\n async function* iterate(): AsyncGenerator<T> {\n while (state.hasNext) {\n const page = await next();\n for (const item of page) {\n yield item;\n }\n }\n }\n\n return {\n get items() {\n return state.items;\n },\n get hasNext() {\n return state.hasNext;\n },\n get isLoading() {\n return state.isLoading;\n },\n get lastError() {\n return state.lastError;\n },\n get meta() {\n return state.meta;\n },\n next,\n setFilters,\n [Symbol.asyncIterator]: iterate,\n };\n}\n","/**\n * Helpers shared by more than one resource file. Not a resource itself, and\n * not the barrel that assembles resources into a client — that belongs to\n * the next lane. Kept here once instead of duplicated in `webhooks.ts` and\n * `events.ts`, the two groups in this lane whose list operation is\n * cursor-paginated (`architecture/08-sdk.md §5`, `../pagination/paginator.ts`).\n */\n\nimport type { PaginatorPage } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\n\n/**\n * Narrows a response's `meta` from `ResponseMeta` (where `.page` is optional\n * because most operations aren't paginated) to `PagedResponseMeta` (where\n * it's guaranteed). Every cursor-paginated operation's envelope always\n * carries `meta.page` — this only guards the boundary between \"the generated\n * type says optional\" and \"this specific endpoint always sends it,\" so a\n * response that somehow arrived without one fails loudly here rather than\n * quietly widening to a paginator that can never learn `hasNext`.\n */\nexport function narrowPaged<T>(response: KaafilResponse<T>): KaafilPagedResponse<T> {\n if (response.meta.page === undefined) {\n throw new Error('invariant: a cursor-paginated response arrived without meta.page.');\n }\n return response as KaafilPagedResponse<T>;\n}\n\n/**\n * Adapts one already-fetched list response into the shape\n * `createPaginator`'s `fetchPage` closures return. The response value\n * itself, once narrowed, already satisfies `readonly T[]` (the transport\n * attaches `meta` onto the array in place, `../http/client.ts`'s\n * `attachMeta`), so `items` and the array are the same object.\n */\nexport function toPaginatorPage<T>(response: KaafilResponse<readonly T[]>): PaginatorPage<T> {\n const paged = narrowPaged(response);\n return { items: paged, meta: paged.meta };\n}\n","/**\n * `agencies` — the agency record itself, plus the agency-wide manager\n * directory. `architecture/08-sdk.md §4`.\n *\n * `upsert` (`upsertAgency`, `PUT /api/v1/agencies/{ref}`) is `apiKeyAuth`-only\n * in the spec (`../generated/security.ts`'s `OPERATION_SECURITY`) — the same\n * ingest credential `POST /api/v1/trips` and every other `trip-ingest` write\n * use. LWW, first-ingest-creates: `sourceUpdatedAt` is REQUIRED, with no\n * \"defaults to now\", for the same staleness-detection reason as every other\n * last-write-wins field in this SDK (see `trips.ts`'s `UpsertTripOptions`) —\n * a push whose stamp is not newer than the stored one comes back `200` with\n * `verdict: ignored_stale`, never a `409`.\n *\n * `managers.list` (`listAgencyManagers`, `GET /api/v1/agencies/{ref}/managers`)\n * accepts `apiKeyAuth`, `managerAuth`, OR `agencyAdminAuth` in the spec — the\n * same multi-scheme shape `./vendors.ts`'s `listTripVendors` has — so,\n * following that file's precedent, this resource (`upsert` included) is\n * exposed unchanged from both `../client.ts` and `../client-entry.ts`; a\n * manager- or agency-admin-opened `KaafilClient` calling `upsert` simply fails\n * at the point of use with `UnsatisfiableSchemeError`, the same way a\n * `shareToken`-opened client calling `vendors`/`journey` already does.\n * `settings.get`/`settings.patch` (below) are agency-scoped and, on\n * `../client-entry.ts`, agencyRef-BOUND — see that file's \"agencyRef-bound\n * option types\" section, the same treatment `managers.list`/`.listPage` get\n * there.\n *\n * `managers.list` is cursor-paginated (`cursor`/`limit` query params), with an\n * optional free-text `q` filter and an optional `forTripRef` that additionally\n * computes each returned manager's availability against that trip's own dates\n * (`../generated/schema.d.ts`'s `ManagerListRowResponse.availability`).\n * Modeled as a `KaafilPaginator`, the same as `./travellers.ts`'s\n * `listForAgency` — unlike that one, though, every filter here (including `q`)\n * is optional, so `filters` may be an empty object. `managers.listPage` is the\n * manual single-page escape hatch, same convention.\n *\n * ── `settings` — THE SIBLING ROUTE, NEVER A WIDENED AUTH ARRAY (GAP-002) ────\n *\n * `settings.get`/`settings.patch` wrap `GET`/`PATCH\n * /api/v1/agencies/{ref}/settings/self` (`getAgencySettingsSelf`/\n * `patchAgencySettingsSelf`) — a SEPARATE route from the console's own\n * `GET`/`PATCH /api/v1/agencies/{ref}/settings` (`getAgencySettings`/\n * `patchAgencySettings`, `consoleAuth`-only, not exposed by this package; see\n * `./checklists.ts`'s header for the same console-exclusion reasoning). The\n * engine deliberately ships two routes rather than one route with a widened\n * `security` array: `../shared/http/route-pipeline.ts`'s `pipeline()` throws\n * at import time if `'consoleAuth'` ever appears in a multi-scheme set,\n * because a cookie is ambient and a multi-kind set could silently prefer a\n * console session from another browser tab. `settings.get` accepts\n * `apiKeyAuth` OR `agencyAdminAuth`; `settings.patch` is `agencyAdminAuth`-\n * only — an API key pushes trip/booking data, never this agency's own\n * operational knobs. Both share the exact same request/response body shape\n * as the console pair (`PatchAgencySettingsRequest`/\n * `PatchAgencySettingsSelfRequest` are structurally identical in the\n * vendored spec), so nothing here is a lesser version of the console form.\n * `settings.patch` requires `If-Match`, the same optimistic-concurrency\n * contract as every other version-guarded write in this SDK.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type {\n KaafilFacetedPagedResponse,\n KaafilPagedResponse,\n KaafilResponse,\n} from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype UpsertAgencyRequest = components['schemas']['UpsertAgencyRequest'];\ntype AgencyUpsertResponse = components['schemas']['AgencyUpsertResponse'];\ntype ManagerListRowResponse = components['schemas']['ManagerListRowResponse'];\nexport type ManagerAgencyProfileResponse = components['schemas']['ManagerAgencyProfileResponse'];\ntype AgencySettingsResponse = components['schemas']['AgencySettingsResponse'];\ntype TripDirectoryRowResponse = components['schemas']['TripDirectoryRowResponse'];\ntype TripManifestRowResponse = components['schemas']['TripManifestRowResponse'];\ntype PatchAgencySettingsSelfRequest = components['schemas']['PatchAgencySettingsSelfRequest'];\n\nexport interface UpsertAgencyOptions extends Omit<UpsertAgencyRequest, 'sourceUpdatedAt'> {\n readonly agencyRef: string;\n /** The CRM's own record-updated timestamp — required, no \"defaults to\n * now\". See this file's header for why. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- agencies.managers ---------------------------------------------------\n\ntype ListAgencyManagersQuery = NonNullable<operations['listAgencyManagers']['parameters']['query']>;\n/** The filterable half of `listAgencyManagers`'s query params —\n * `cursor`/`limit` are the paginator's job. Unlike\n * `./travellers.ts`'s `TravellerDirectoryFilters`, both `q` and `forTripRef`\n * here are optional, so an empty object is a valid `filters`. */\nexport type AgencyManagerFilters = Omit<ListAgencyManagersQuery, 'cursor' | 'limit'>;\n\nasync function fetchAgencyManagersPage(\n client: KaafilHttpClient,\n agencyRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: AgencyManagerFilters;\n },\n) {\n const response = await client.execute<readonly ManagerListRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListAgencyManagers,\n path: '/api/v1/agencies/{ref}/managers',\n pathParams: { ref: agencyRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListAgencyManagersOptions {\n readonly agencyRef: string;\n readonly filters?: AgencyManagerFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListAgencyManagersPageOptions extends AgencyManagerFilters {\n readonly agencyRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface GetAgencyManagerProfileOptions {\n readonly agencyRef: string;\n readonly managerRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencyManagersResource {\n /** `GET /api/v1/agencies/{ref}/managers` as a `KaafilPaginator` — the\n * agency's whole manager directory, `q`-filterable, and, with\n * `forTripRef`, availability-annotated against that trip's dates. */\n list(\n options: ListAgencyManagersOptions,\n ): KaafilPaginator<ManagerListRowResponse, AgencyManagerFilters>;\n /** The manual single-page escape hatch for `list`. */\n listPage(\n options: ListAgencyManagersPageOptions,\n ): Promise<KaafilPagedResponse<readonly ManagerListRowResponse[]>>;\n /** `GET /api/v1/agencies/{ref}/managers/{managerRef}` — one manager's own\n * agency-wide profile: identity plus every trip they've been on. The\n * traveller-profile sibling (`./travellers.ts`'s `getAgencyProfile`,\n * GAP-016) — same `apiKeyAuth`/`agencyAdminAuth`-only posture, never\n * `managerAuth`, for the identical reason. */\n get(\n options: GetAgencyManagerProfileOptions,\n ): Promise<KaafilResponse<ManagerAgencyProfileResponse>>;\n}\n\n// --- agencies.trips -------------------------------------------------------\n\ntype ListAgencyTripsQuery = NonNullable<operations['listAgencyTrips']['parameters']['query']>;\n/** The filterable half of `listAgencyTrips`'s query params — `cursor`/`limit`\n * are the paginator's job. Every member is optional, so `{}` is valid. */\nexport type AgencyTripFilters = Omit<ListAgencyTripsQuery, 'cursor' | 'limit'>;\n\n/**\n * Per-bucket trip counts over the WHOLE agency, not the current page.\n *\n * Hand-written rather than taken from `components['schemas']` on purpose:\n * the engine's OpenAPI generator can only describe\n * `SuccessEnvelope & { data: X }`, so it has no way to declare the `facets`\n * sibling the response wrapper actually sends, and the shape therefore never\n * reaches the generated catalog. The source of truth is\n * `kaafil-engine/src/modules/trip-directory/trip-directory.dto.ts`'s\n * `tripSegmentCountsResponseSchema` — keep the two in step by hand.\n *\n * The five non-`all` buckets partition every live trip, so they sum to\n * `all`. There is no `draft` bucket: `TripStatus` has no draft member.\n */\nexport interface AgencyTripSegmentCounts {\n readonly all: number;\n /** In progress, or confirmed and inside its own date window. */\n readonly active: number;\n /** Confirmed and starting later. */\n readonly upcoming: number;\n /** Completed, or confirmed and already ended. */\n readonly past: number;\n readonly postponed: number;\n readonly cancelled: number;\n}\n\n/** What `listAgencyTrips` carries in the envelope's `facets` key. */\nexport interface AgencyTripFacets {\n readonly segments: AgencyTripSegmentCounts;\n}\n\nasync function fetchAgencyTripsPage(\n client: KaafilHttpClient,\n agencyRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: AgencyTripFilters;\n },\n) {\n const response = await client.execute<readonly TripDirectoryRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListAgencyTrips,\n path: '/api/v1/agencies/{ref}/trips',\n pathParams: { ref: agencyRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListAgencyTripsOptions {\n readonly agencyRef: string;\n readonly filters?: AgencyTripFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListAgencyTripsPageOptions extends AgencyTripFilters {\n readonly agencyRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface GetAgencyTripOptions {\n readonly agencyRef: string;\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencyTripsResource {\n /**\n * `GET /api/v1/agencies/{ref}/trips` as a `KaafilPaginator` — the agency's\n * whole trip list, filterable by `q`/`eventType`/`status`/`segment` and\n * orderable by `sort`.\n *\n * THE ONLY trip-collection read reachable by an agency admin. `managerMe.\n * listTrips` is a manager's own assignments and `managerAuth`-only; the\n * `trips` resource itself (`upsert`/`get`/`cancel`) is `apiKeyAuth`-only\n * ingest. Prefer `listPage` when you need the segment counts — a paginator\n * surfaces pages, not the envelope's `facets`.\n */\n list(\n options: ListAgencyTripsOptions,\n ): KaafilPaginator<TripDirectoryRowResponse, AgencyTripFilters>;\n /**\n * The manual single-page escape hatch for `list`, and the only way to read\n * `facets.segments` — the per-bucket counts a filter-chip row needs, which\n * are computed over the whole agency rather than the page.\n */\n listPage(\n options: ListAgencyTripsPageOptions,\n ): Promise<KaafilFacetedPagedResponse<readonly TripDirectoryRowResponse[], AgencyTripFacets>>;\n /**\n * `GET /api/v1/agencies/{ref}/trips/{tripRef}` — one trip's own console\n * read: identity, live manifest size, the FULL manager roster and a money\n * rollup.\n *\n * Distinct from `trips.get`, which is `apiKeyAuth`-only and returns the\n * ingest ECHO. `managers.get`'s (GAP-016) exact sibling, scoped to `Trip`,\n * with the same `apiKeyAuth`/`agencyAdminAuth`-only posture and never\n * `managerAuth`.\n */\n get(options: GetAgencyTripOptions): Promise<KaafilResponse<TripDirectoryRowResponse>>;\n /** That trip's manifest, for the office — see `TripManifestResource`. */\n readonly manifest: TripManifestResource;\n}\n\n// --- agencies.trips.manifest ----------------------------------------------\n\ntype ListTripManifestQuery = NonNullable<operations['listTripManifest']['parameters']['query']>;\n/** The filterable half of `listTripManifest`'s query params. Every member is\n * optional, so `{}` is valid. */\nexport type TripManifestFilters = Omit<ListTripManifestQuery, 'cursor' | 'limit'>;\n\n/**\n * Whole-set aggregates over the manifest, in the envelope's `facets` key.\n *\n * Hand-written for the same reason `AgencyTripFacets` is — the engine's\n * generator can only describe `SuccessEnvelope & { data: X }` and so cannot\n * declare the `facets` sibling the response wrapper actually sends. Kept in\n * step with `trip-directory.dto.ts#tripManifestFacetsResponseSchema` by hand.\n *\n * These describe the CURRENT FILTERED SET, unlike `AgencyTripFacets.segments`\n * which spans the whole agency: a head-count above a filtered table has to\n * describe that table.\n */\nexport interface TripManifestFacets {\n /** Rows matching the current filters, across every page. */\n readonly total: number;\n /** Head-count by booking status. Every member present, zeros included. */\n readonly byBookingStatus: {\n readonly CONFIRMED: number;\n readonly TENTATIVE: number;\n readonly CANCELLED: number;\n };\n readonly medicalCount: number;\n readonly dueCount: number;\n /**\n * Histogram over the raw, lower-cased `dietary` string — an OPEN key set,\n * because that column is free text rather than an enum. Travellers with no\n * value group under `unspecified` rather than being dropped, so these\n * always sum to `total`.\n */\n readonly dietCounts: Readonly<Record<string, number>>;\n}\n\nasync function fetchTripManifestPage(\n client: KaafilHttpClient,\n agencyRef: string,\n tripRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: TripManifestFilters;\n },\n) {\n const response = await client.execute<readonly TripManifestRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTripManifest,\n path: '/api/v1/agencies/{ref}/trips/{tripRef}/manifest',\n pathParams: { ref: agencyRef, tripRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListTripManifestOptions {\n readonly agencyRef: string;\n readonly tripRef: string;\n readonly filters?: TripManifestFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListTripManifestPageOptions extends TripManifestFilters {\n readonly agencyRef: string;\n readonly tripRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripManifestResource {\n /**\n * `GET /api/v1/agencies/{ref}/trips/{tripRef}/manifest` as a\n * `KaafilPaginator` — the office-side manifest read.\n *\n * DISTINCT FROM `travellers.listForTrip`, which is the same trip's manifest\n * for the FIELD app: that one takes no query parameters and returns the full\n * roster in one array, which is what a manager's device wants. This one is\n * filterable and paginated, and its row additionally carries `gender`,\n * `medicalFlag`, `dateOfBirth` and the traveller's `party` denormalised.\n * Neither replaces the other.\n *\n * Prefer `listPage` when you need `facets` — a paginator surfaces pages, not\n * the envelope's extras.\n */\n list(\n options: ListTripManifestOptions,\n ): KaafilPaginator<TripManifestRowResponse, TripManifestFilters>;\n /**\n * The manual single-page escape hatch for `list`, and the only way to read\n * `facets` — the head-count, booking-status split, medical count, due count\n * and diet histogram, computed over the whole FILTERED set rather than the\n * page.\n */\n listPage(\n options: ListTripManifestPageOptions,\n ): Promise<KaafilFacetedPagedResponse<readonly TripManifestRowResponse[], TripManifestFacets>>;\n}\n\n// --- agencies.settings ----------------------------------------------------\n\nexport interface ReadAgencySettingsOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchAgencySettingsOptions extends PatchAgencySettingsSelfRequest {\n readonly agencyRef: string;\n /**\n * Required, not optional — same `If-Match` contract as every other\n * version-guarded write in this SDK. Pass the `version` from a prior\n * `settings.get()`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencySettingsResource {\n /** `GET /api/v1/agencies/{ref}/settings/self` — the sibling of the\n * console's own `GET .../settings`. See this file's header, \"the sibling\n * route\" section. */\n get(options: ReadAgencySettingsOptions): Promise<KaafilResponse<AgencySettingsResponse>>;\n /** `PATCH /api/v1/agencies/{ref}/settings/self` — `agencyAdminAuth`-only.\n * See this file's header, \"the sibling route\" section. */\n patch(options: PatchAgencySettingsOptions): Promise<KaafilResponse<AgencySettingsResponse>>;\n}\n\nexport interface AgenciesResource {\n /** `PUT /api/v1/agencies/{ref}` — first sighting of `{ref}` creates the\n * agency (`created: true`); every later call re-syncs `name`/\n * `sourceUpdatedAt` on the existing row (`created: false`). */\n upsert(options: UpsertAgencyOptions): Promise<KaafilResponse<AgencyUpsertResponse>>;\n readonly managers: AgencyManagersResource;\n /** The agency's trip list and per-trip console read — the only\n * trip-collection surface an agency admin can reach. */\n readonly trips: AgencyTripsResource;\n /** The agency's own operational settings document — see this file's\n * header, \"the sibling route\" section. */\n readonly settings: AgencySettingsResource;\n}\n\nexport function createAgenciesResource(client: KaafilHttpClient): AgenciesResource {\n return {\n async upsert(options) {\n const { agencyRef, idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n const body: UpsertAgencyRequest = {\n ...rest,\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n };\n return client.execute<AgencyUpsertResponse>({\n method: 'PUT',\n operationId: OperationId.UpsertAgency,\n path: '/api/v1/agencies/{ref}',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n managers: {\n list(options) {\n const { agencyRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchAgencyManagersPage(client, agencyRef, request),\n filters: filters ?? {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { agencyRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly ManagerListRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListAgencyManagers,\n path: '/api/v1/agencies/{ref}/managers',\n pathParams: { ref: agencyRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n async get(options) {\n const { agencyRef, managerRef, signal } = options;\n return client.execute<ManagerAgencyProfileResponse>({\n method: 'GET',\n operationId: OperationId.GetManagerAgencyProfile,\n path: '/api/v1/agencies/{ref}/managers/{managerRef}',\n pathParams: { ref: agencyRef, managerRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n trips: {\n list(options) {\n const { agencyRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchAgencyTripsPage(client, agencyRef, request),\n filters: filters ?? {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { agencyRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly TripDirectoryRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListAgencyTrips,\n path: '/api/v1/agencies/{ref}/trips',\n pathParams: { ref: agencyRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response) as KaafilFacetedPagedResponse<\n readonly TripDirectoryRowResponse[],\n AgencyTripFacets\n >;\n },\n async get(options) {\n const { agencyRef, tripRef, signal } = options;\n return client.execute<TripDirectoryRowResponse>({\n method: 'GET',\n operationId: OperationId.GetAgencyTrip,\n path: '/api/v1/agencies/{ref}/trips/{tripRef}',\n pathParams: { ref: agencyRef, tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n manifest: {\n list(options) {\n const { agencyRef, tripRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchTripManifestPage(client, agencyRef, tripRef, request),\n filters: filters ?? {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { agencyRef, tripRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly TripManifestRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTripManifest,\n path: '/api/v1/agencies/{ref}/trips/{tripRef}/manifest',\n pathParams: { ref: agencyRef, tripRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response) as KaafilFacetedPagedResponse<\n readonly TripManifestRowResponse[],\n TripManifestFacets\n >;\n },\n },\n },\n\n settings: {\n async get(options) {\n const { agencyRef, signal } = options;\n return client.execute<AgencySettingsResponse>({\n method: 'GET',\n operationId: OperationId.GetAgencySettingsSelf,\n path: '/api/v1/agencies/{ref}/settings/self',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { agencyRef, version, signal, ...body } = options;\n return client.execute<AgencySettingsResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchAgencySettingsSelf,\n path: '/api/v1/agencies/{ref}/settings/self',\n pathParams: { ref: agencyRef },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `agencyAdmins` — the agency admin roster (dual-mode identity). One\n * operation, `upsertAgencyAdmin` (`POST /api/v1/agency-admins`),\n * `apiKeyAuth`-only in the spec (`../generated/security.ts`'s\n * `OPERATION_SECURITY`) — the same ingest credential `PUT\n * /api/v1/agencies/{ref}` and every other `trip-ingest` write use.\n * LWW: `sourceUpdatedAt` is REQUIRED, with no \"defaults to now\", for the\n * same staleness-detection reason as every other last-write-wins field in\n * this SDK (see `agencies.ts`'s `UpsertAgencyOptions`) — a push whose\n * stamp is not newer than the stored one comes back `200` with\n * `verdict: ignored_stale`, never a `409`.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype UpsertAgencyAdminRequest = components['schemas']['UpsertAgencyAdminRequest'];\ntype AgencyAdminResponse = components['schemas']['AgencyAdminResponse'];\n\nexport interface UpsertAgencyAdminOptions\n extends Omit<UpsertAgencyAdminRequest, 'sourceUpdatedAt'> {\n /** The CRM's own record-updated timestamp — required, no \"defaults to\n * now\". See this file's header for why. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencyAdminsResource {\n /** `POST /api/v1/agency-admins` — dual-mode identity: first sighting of\n * `externalAgencyAdminId` (or an omitted one) mints a new admin\n * (`created: true`); a later call re-syncs the existing row\n * (`created: false`). */\n upsert(options: UpsertAgencyAdminOptions): Promise<KaafilResponse<AgencyAdminResponse>>;\n}\n\nexport function createAgencyAdminsResource(client: KaafilHttpClient): AgencyAdminsResource {\n return {\n async upsert(options) {\n const { idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n const body: UpsertAgencyAdminRequest = {\n ...rest,\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n };\n return client.execute<AgencyAdminResponse>({\n method: 'POST',\n operationId: OperationId.UpsertAgencyAdmin,\n path: '/api/v1/agency-admins',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `auth` — minting a manager session or an agency-admin session.\n * `architecture/08-sdk.md §3.2, §4`.\n *\n * Rotation is deliberately absent as a public method for either kind:\n * `../auth/credentials.ts` calls each kind's own refresh endpoint itself,\n * pre-emptively and reactively, as part of resolving every request's\n * credential — a consumer never calls it directly (this wave's governing\n * principle: the SDK does the refresh, the consumer only ever hands the SDK\n * the tokens it was given).\n *\n * `08-sdk.md §4`'s table also lists a `revoke` method for this group. No such\n * operation exists anywhere in the vendored spec: the `Auth` tag in\n * `openapi/openapi.json` names exactly four operations —\n * `mintManagerTokens`, `refreshManagerTokens`, `mintAgencyAdminTokens`,\n * `refreshAgencyAdminTokens` (verified via `jq '.paths[][] | select(.tags ==\n * [\"Auth\"]) | .operationId'`) — and the two `refresh*` ones are the\n * resolver's job, not a public method here. Per this lane's brief — \"if this\n * list and the spec disagree, the spec wins, and you say so\" — no `revoke`\n * method ships. Flagged here rather than silently dropped.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype MintManagerTokenRequest = components['schemas']['MintManagerTokensRequest'];\ntype ManagerSessionResponse = components['schemas']['ManagerSessionResponse'];\ntype MintAgencyAdminTokenRequest = components['schemas']['MintAgencyAdminTokensRequest'];\ntype AgencyAdminSessionResponse = components['schemas']['AgencyAdminSessionResponse'];\n\nexport interface MintManagerTokenOptions extends MintManagerTokenRequest {\n readonly signal?: AbortSignal;\n}\n\nexport interface MintAgencyAdminTokenOptions extends MintAgencyAdminTokenRequest {\n readonly signal?: AbortSignal;\n}\n\nexport interface AuthResource {\n /**\n * `POST /api/v1/auth/manager-tokens` — opens a manager session. Server-side\n * only (API key; `mintManagerTokens` accepts only `apiKeyAuth`). The\n * returned `refreshToken` is shown exactly once, here and at every\n * subsequent rotation — hand `accessToken`, `refreshToken`, and\n * `expiresAt` straight to a `managerSession`-credentialed client\n * (`../auth/credentials.ts`'s `ManagerSessionCredentialConfig`, or the\n * browser entry's `session.open(...)`).\n *\n * Not idempotent — no `idempotencyKey` field on this options type — by the\n * operation's own design (`refreshManagerTokens`'s response carries a\n * plaintext refresh token; replaying it from an idempotency cache would\n * mean persisting that secret, which the hash-only refresh-token storage\n * rule forbids). A caller that loses this response to a network error\n * simply mints again.\n */\n mintManagerToken(\n options: MintManagerTokenOptions,\n ): Promise<KaafilResponse<ManagerSessionResponse>>;\n /**\n * `POST /api/v1/auth/agency-admin-tokens` — opens an agency-admin session,\n * the agency-admin analogue of `mintManagerToken` above. Server-side only\n * (API key; `mintAgencyAdminTokens` accepts only `apiKeyAuth`) — hand the\n * response's `accessToken`, `refreshToken`, and `expiresAt` straight to an\n * `agencyAdmin`-credentialed client (`../auth/credentials.ts`'s\n * `AgencyAdminCredentialConfig`, or the browser entry's `admin.open(...)`).\n *\n * Not idempotent, for the same reason as `mintManagerToken`: the response\n * carries a plaintext refresh token, and the hash-only refresh-token\n * storage rule forbids persisting one in an idempotency cache to replay.\n */\n mintAgencyAdminToken(\n options: MintAgencyAdminTokenOptions,\n ): Promise<KaafilResponse<AgencyAdminSessionResponse>>;\n}\n\nexport function createAuthResource(client: KaafilHttpClient): AuthResource {\n return {\n async mintManagerToken(options) {\n const { signal, ...body } = options;\n return client.execute<ManagerSessionResponse>({\n method: 'POST',\n operationId: OperationId.MintManagerTokens,\n path: '/api/v1/auth/manager-tokens',\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async mintAgencyAdminToken(options) {\n const { signal, ...body } = options;\n return client.execute<AgencyAdminSessionResponse>({\n method: 'POST',\n operationId: OperationId.MintAgencyAdminTokens,\n path: '/api/v1/auth/agency-admin-tokens',\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `bookings` — a trip's third-party reservations (accommodation, transport,\n * activity), pushed by the CRM and read back by a manager. `architecture/08-\n * sdk.md §4`. `bulkUpsert`/`delete` are `apiKeyAuth`-only (CRM-backend\n * ingest, the same reason `trips.ts`'s whole module is). Two operations are\n * wider, and this header used to claim otherwise:\n *\n * `list` `apiKeyAuth` | `managerAuth` | `agencyAdminAuth`\n * `vouchers.replace` `apiKeyAuth` | `agencyAdminAuth`\n *\n * The ground team still only READS what the CRM pushed. The desk reads too,\n * and may point a booking at a voucher file — the one write it has here —\n * because a CRM that never pushed the voucher otherwise left the desk\n * holding a document with no way to attach it. Creating, editing or removing\n * a booking remains the CRM's alone.\n *\n * `vouchers.replace` is a FULL-ARRAY REPLACE (R6), which matters more now\n * that a browser can call it: send the complete set every time, including\n * keys already attached. A client that sends only its new key DETACHES every\n * voucher the CRM had attached.\n *\n * ── `bulkUpsert`'S ITEM SHAPE IS HAND-TYPED, NOT GENERATED ──────────────────\n *\n * `BulkUpsertBookingsRequest` is declared in the vendored spec as a bare\n * `{ propertyNames: string; additionalProperties: {} }[]` — an opaque array\n * of untyped objects, unlike `trips.ts`'s `PushBulkTripsRequest` (a real,\n * fully-typed item schema this SDK indexes off of with\n * `components['schemas']['PushBulkTripsRequest'][number]`). There is no\n * generated item type to index off here, so `BulkUpsertBookingItem` below is\n * hand-typed from `BookingResponse` instead (every field the engine echoes\n * back, minus the four it derives itself: `id`, `version`, `createdAt`,\n * `updatedAt`). If the engine ever tightens `BulkUpsertBookingsRequest` to a\n * real item schema, this hand-typed shape should be re-verified against it\n * rather than assumed still correct.\n *\n * `kind` is typed off `BookingResponse['kind']` for the same reason —\n * `ACCOMMODATION|TRANSPORT|ACTIVITY` never appears in ANY request-body\n * schema this spec declares (the bulk item is opaque, so `scripts/gen-\n * meta.mjs`'s request-enum walk never reaches it), so there is no\n * `../generated/enums.ts` runtime constant for it the way `FormFieldKind`\n * or `MessageChannel` get one; a caller compares against the literal\n * strings, or against `BookingResponse.kind` read back from `list()`.\n *\n * `externalBookingId` + `sourceUpdatedAt` is the same last-write-wins pair\n * `trips.ts`'s bulk push uses — `sourceUpdatedAt` is required, with no\n * \"defaults to now\", for the identical reason: defaulting it would make\n * every write look like the newest one and defeat out-of-order staleness\n * detection. Per-item `verdict` on the response\n * (`applied`/`ignored_stale`/`rejected`) reports which of the three\n * happened; `errorCode`/`message` are populated only for `rejected`.\n *\n * `list`'s rows may be a live booking OR the tombstone shape (`_tombstone:\n * true`) for one deleted since `?since=` — the same delta shape\n * `itinerary`/`pickups`/`checklists` already use.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype BookingResponse = components['schemas']['BookingResponse'];\ntype BulkUpsertResponse = components['schemas']['BulkUpsertResponse'];\ntype ListBookingsResponse = components['schemas']['ListBookingsResponse'];\ntype BookingDeleteResponse = components['schemas']['BookingDeleteResponse'];\ntype ReplaceBookingVouchersRequest = components['schemas']['ReplaceBookingVouchersRequest'];\n\n/** `BookingResponse.kind` — see this file's header for why this is a type\n * alias off the response, not a `../generated/enums.ts` runtime constant. */\nexport type BookingKind = BookingResponse['kind'];\n\n/** One row of `list`'s response: a live booking, or the tombstone for one\n * deleted since the cursor. See this file's header. */\nexport type BookingListRow = ListBookingsResponse[number];\n\ntype ListBookingsQuery = NonNullable<operations['listBookings']['parameters']['query']>;\n/** The filterable half of `list`'s query params — `since` is the delta\n * cursor and is passed as its own option, never bundled in here. */\nexport type BookingFilters = Omit<ListBookingsQuery, 'since'>;\n\n// --- bookings.bulkUpsert ---------------------------------------------------\n\n/**\n * One item of `bulkUpsert`'s array body. Hand-typed off `BookingResponse` —\n * see this file's header for why there is no generated request-item type to\n * extend instead.\n */\nexport interface BulkUpsertBookingItem {\n readonly externalBookingId: string;\n readonly kind: BookingKind;\n readonly title: string;\n readonly confirmationRef?: string | null;\n readonly startAt: DateTimeInput;\n readonly endAt?: DateTimeInput | null;\n readonly providerName?: string | null;\n readonly providerPhone?: string | null;\n readonly locationText?: string | null;\n readonly details?: Readonly<Record<string, unknown>> | null;\n readonly voucherFileKeys?: readonly string[];\n /** The CRM's own record-updated timestamp — required, no \"defaults to\n * now\". See this file's header for why. */\n readonly sourceUpdatedAt: DateTimeInput;\n}\n\nexport interface BulkUpsertBookingsOptions {\n readonly tripRef: string;\n readonly items: readonly BulkUpsertBookingItem[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- bookings.list ----------------------------------------------------------\n\nexport interface ListBookingsOptions extends BookingFilters {\n readonly tripRef: string;\n /** The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit for the full live set. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand, same as every other\n * delta read in this SDK. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- bookings.delete / bookings.vouchers -----------------------------------\n\nexport interface DeleteBookingOptions {\n readonly tripRef: string;\n readonly bookingRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReplaceBookingVouchersOptions extends ReplaceBookingVouchersRequest {\n readonly tripRef: string;\n readonly bookingRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface BookingVouchersResource {\n /** `PATCH /api/v1/trips/{ref}/bookings/{bookingRef}/vouchers` — replaces\n * the FULL `voucherFileKeys` list; there is no add/remove-one call. Each\n * key must resolve to a `ready` file (`files.*`) with `purpose:\n * 'booking_voucher'` — an unconfirmed or wrong-purpose key is\n * `422 VALIDATION_ERROR`. */\n replace(options: ReplaceBookingVouchersOptions): Promise<KaafilResponse<BookingResponse>>;\n}\n\n// --- bookings ----------------------------------------------------------------\n\nexport interface BookingsResource {\n /**\n * `POST /api/v1/trips/{ref}/bookings` — up to 2000 items per call. See\n * this file's header for the item shape, the last-write-wins pair, and\n * the per-item `verdict`. A partial failure never fails the whole call —\n * inspect `items[].verdict`/`errorCode` on the response, never a thrown\n * error, to find a `rejected` row.\n */\n bulkUpsert(options: BulkUpsertBookingsOptions): Promise<KaafilResponse<BulkUpsertResponse>>;\n /** `GET /api/v1/trips/{ref}/bookings` — optionally filtered by `kind`. See\n * this file's header for the delta-cursor semantics and the tombstone row\n * shape. */\n list(options: ListBookingsOptions): Promise<KaafilResponse<ListBookingsResponse>>;\n /** `DELETE /api/v1/trips/{ref}/bookings/{bookingRef}` — `bookingRef` is a\n * dual-mode ref (Kaafil id or the CRM's `externalBookingId`), same as\n * every other `ref` in this SDK. */\n delete(options: DeleteBookingOptions): Promise<KaafilResponse<BookingDeleteResponse>>;\n readonly vouchers: BookingVouchersResource;\n}\n\nexport function createBookingsResource(client: KaafilHttpClient): BookingsResource {\n return {\n async bulkUpsert(options) {\n const { tripRef, items, idempotencyKey, signal } = options;\n const body = items.map((item, index) => {\n const { startAt, endAt, sourceUpdatedAt, ...rest } = item;\n return {\n ...rest,\n startAt: normalizeDateTimeInput(startAt, `items[${index}].startAt`),\n ...(endAt !== undefined\n ? {\n endAt:\n endAt === null ? null : normalizeDateTimeInput(endAt, `items[${index}].endAt`),\n }\n : {}),\n sourceUpdatedAt: normalizeDateTimeInput(\n sourceUpdatedAt,\n `items[${index}].sourceUpdatedAt`,\n ),\n };\n });\n return client.execute<BulkUpsertResponse>({\n method: 'POST',\n operationId: OperationId.BulkUpsertBookings,\n path: '/api/v1/trips/{ref}/bookings',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { tripRef, since, signal, ...filters } = options;\n return client.execute<ListBookingsResponse>({\n method: 'GET',\n operationId: OperationId.ListBookings,\n path: '/api/v1/trips/{ref}/bookings',\n pathParams: { ref: tripRef },\n query: { ...filters, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async delete(options) {\n const { tripRef, bookingRef, idempotencyKey, signal } = options;\n return client.execute<BookingDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteBooking,\n path: '/api/v1/trips/{ref}/bookings/{bookingRef}',\n pathParams: { ref: tripRef, bookingRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n vouchers: {\n async replace(options) {\n const { tripRef, bookingRef, signal, ...body } = options;\n return client.execute<BookingResponse>({\n method: 'PATCH',\n operationId: OperationId.ReplaceBookingVouchers,\n path: '/api/v1/trips/{ref}/bookings/{bookingRef}/vouchers',\n pathParams: { ref: tripRef, bookingRef },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `checklists` — sections, items, toggle, and the agency's reusable template\n * library. `architecture/08-sdk.md §4`. `checklists` FRD §3, RULES R1–R14,\n * `D-029` (pull-template copy semantics), `modules/checklists/checklists\n * .routes.ts`'s own header (the source of every auth/lock line below).\n *\n * `read` and `templates.list` accept a manager session OR an API key; every\n * WRITE (`items.add/patch/remove/toggle`, `templates.pull`) is\n * `managerAuth`-only — admin template CONFIG (`POST/PATCH` against the\n * library itself) does not exist yet (`checklists.routes.ts`'s \"ADMIN\n * TEMPLATE CONFIG IS DEFERRED\" note), so there is no write here an API key\n * could ever reach even in principle. Every write also declares\n * `closeoutLock: 'ref'` engine-side — a write racing trip close-out answers\n * `423 LOCKED` (`KaafilLockedError`), terminal, never retried.\n *\n * ── FOUR QUIRKS A CONSUMER WILL OTHERWISE GET WRONG ─────────────────────────\n *\n * 1. **`toggle`'s concurrency guard is on the item's STATUS, not its\n * `version`.** Every OTHER version-guarded write in this API takes an\n * `If-Match`/`version` and answers `409 CONFLICT_VERSION` with\n * `details.currentVersion` on staleness. `toggle` takes `expectedStatus`\n * in the BODY instead, and a stale value still answers\n * `409 CONFLICT_VERSION` — same code, `KaafilVersionConflictError` still\n * catches it — but the payload carries `details.currentStatus`, never\n * `details.currentVersion`. Reading `.currentVersion` off the caught\n * error here is silently `undefined`; read `error.details?.currentStatus`\n * (typed `ChecklistItemStatus`) instead. This file does not add a second\n * getter to `KaafilVersionConflictError` for it — `../http/errors.ts`'s\n * own header states the bar for a code-specific getter, and one class per\n * code that merely carries an unusual `details` shape is exactly what\n * that bar exists to avoid.\n * 2. **A `COMPLETE` item cannot be deleted.** `items.remove` on a `COMPLETE`\n * item answers `422 BUSINESS_RULE_VIOLATION` with\n * `details.rule: 'item_complete_delete_blocked'` — un-toggle it first.\n * Not a module-local code: the FRD only describes the refusal, never\n * names it as an identity a client branches on, so it never got minted\n * one (`checklists.constants.ts`'s own line on the point).\n * 3. **`templates.pull` COPIES (`D-029`).** Both `append` and `replace`\n * write TRIP-OWNED rows; neither creates a live link. A template edited\n * AFTER a pull never reaches the trip's copy, and an edit to the trip's\n * copy never reaches the template. `sourceSectionId` on the pulled\n * section is the only trace of where it came from, stamped once, on\n * first pull only — a second pull of the same template onto a section\n * that already exists never rewrites it.\n * 4. **Editing an item's `phase` RE-DERIVES its `gate`, unless `gate` is\n * sent in the SAME request.** `phase` is a hint only — `ChecklistItem`\n * has no `phase` column (phase is the SECTION's) — so `items.patch` never\n * echoes it back on the response, and an explicit `gate` in the same call\n * always wins over the fixed phase→gate map.\n * 5. **A `DRAFT` agency template (GAP-004) is invisible to\n * `templates.list`/`templates.pull`.** `ChecklistTemplateSectionResponse\n * .status ∈ DRAFT|PUBLISHED`; a new `agencyTemplates.create` starts\n * `DRAFT` and stays that way until `agencyTemplates.publish` flips it.\n * Only `agencyTemplates.list` (the authoring library) shows both; the\n * trip-facing `templates.list`/`templates.pull` see `PUBLISHED` only.\n *\n * Beyond those four: the aggregate's `sections[]` is always the FULL live\n * set (a trip's sections are a handful); `items[]` is the ONLY delta axis —\n * `?since=` narrows it, with a deletion arriving as the same tombstone shape\n * `itinerary`/`pickups` already use. `progress` and `hasOpenMandatoryByPhase`\n * are always computed over the full live set, independent of `?since=`. The\n * four reserved sections (`medical`/`documents`/`logistics`/`handover`) are\n * seeded at TRIP-INGEST, inside the upsert transaction — never by this\n * read — so a fresh trip's `read()` already carries them on its very first\n * call; there is no seed-on-read call to make or race against.\n *\n * ── THE SIX `console`-PLANE READS ARE NOT IN THIS PACKAGE ───────────────────\n *\n * `GET /api/v1/console/trips/{ref}/checklist` (`readConsoleChecklist`) and\n * its five siblings (`listConsoleTrips`, `…/itinerary`, `…/rooming`,\n * `…/seating`, `…/pickups`) exist in the vendored spec and are excluded from\n * this SDK on purpose — the same decision `../auth/credentials.ts` and\n * `webhooks.ts` already state for `consoleAuth` generally. They authenticate\n * with a console session cookie (`consoleAuth`), which is the partner\n * console's OWN administrative UI's credential, never something a CRM\n * integrating this package holds — a partner API key satisfies none of\n * `readConsoleChecklist`'s `security` alternatives (there is only one:\n * `consoleAuth`), so a method wrapping it would be uncallable by every\n * consumer of this package. `scripts/gen-meta.mjs`'s\n * `nonIntegrationRequestSchemaNames` already enforces the analogous exclusion\n * for request-body enums reachable only from a console/platform path; this\n * resource file is the read-side statement of the identical decision. If a\n * console read ever gains a second, API-key-satisfiable security\n * alternative, that is a spec change this SDK would need to notice and\n * decide about again — not something to pre-empt here.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype ChecklistAggregateResponse = components['schemas']['ChecklistAggregateResponse'];\ntype ChecklistItemResponse = components['schemas']['ChecklistItemResponse'];\ntype DeleteItemResponse = components['schemas']['DeleteItemResponse'];\ntype ToggleResponse = components['schemas']['ToggleResponse'];\ntype TemplatesListResponse = components['schemas']['TemplatesListResponse'];\ntype AddChecklistItemRequest = components['schemas']['AddChecklistItemRequest'];\ntype PatchChecklistItemRequest = components['schemas']['PatchChecklistItemRequest'];\ntype ToggleChecklistItemRequest = components['schemas']['ToggleChecklistItemRequest'];\ntype PullChecklistTemplateRequest = components['schemas']['PullChecklistTemplateRequest'];\ntype ChecklistTemplateAdminListResponse =\n components['schemas']['ChecklistTemplateAdminListResponse'];\ntype ChecklistTemplateSectionResponse = components['schemas']['ChecklistTemplateSectionResponse'];\ntype DeleteChecklistTemplateResponse = components['schemas']['DeleteChecklistTemplateResponse'];\ntype CreateChecklistTemplateRequest = components['schemas']['CreateChecklistTemplateRequest'];\ntype PatchChecklistTemplateRequest = components['schemas']['PatchChecklistTemplateRequest'];\n\n/**\n * One row of `read`'s `items[]`: a live item, or the tombstone for one\n * deleted since the cursor. Aliased off the response type, never restated —\n * `itinerary.ts#ItineraryItemDeltaRow`'s own reasoning applies verbatim.\n */\nexport type ChecklistItemDeltaRow = ChecklistAggregateResponse['items'][number];\n\n// --- checklists.read ---------------------------------------------------------\n\nexport interface ReadChecklistOptions {\n readonly tripRef: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit for the full aggregate — `sections[]` and the two\n * progress figures are always full regardless; only `items[]` narrows.\n * Prefer `createDeltaCursor` (`../delta/cursor.ts`) over passing this by\n * hand, same as every other delta read in this SDK.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- checklists.items ---------------------------------------------------------\n\nexport interface AddChecklistItemOptions extends AddChecklistItemRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchChecklistItemOptions extends PatchChecklistItemRequest {\n readonly tripRef: string;\n readonly itemId: string;\n /**\n * Required, not optional — `itinerary.ts#PatchItineraryItemOptions\n * .version`'s own argument for why a missing `If-Match` and a stale one\n * answering the identical `409 CONFLICT_VERSION` means this SDK should\n * make forgetting it impossible rather than merely discouraged. Pass the\n * `version` from the item as last read; the SDK builds the `If-Match`\n * header itself. NOT the same guard as `toggle`'s `expectedStatus` — see\n * this file's header, quirk 1.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface GetChecklistItemOptions {\n readonly tripRef: string;\n readonly itemId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteChecklistItemOptions {\n readonly tripRef: string;\n readonly itemId: string;\n /** See `PatchChecklistItemOptions.version` — same contract. Refused with\n * `422 BUSINESS_RULE_VIOLATION` while the item is `COMPLETE` — this file's\n * header, quirk 2. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ToggleChecklistItemOptions extends ToggleChecklistItemRequest {\n readonly tripRef: string;\n readonly itemId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ChecklistItemsResource {\n /**\n * `GET …/checklist/items/{itemId}` — one item's current state, without\n * pulling the whole trip aggregate. Same read auth as `read()` above\n * (a manager session or an API key), not the write triple the other four\n * methods on this resource use.\n */\n get(options: GetChecklistItemOptions): Promise<KaafilResponse<ChecklistItemResponse>>;\n /**\n * `POST …/checklist/items` — auto-creates the section when `sectionKey`\n * is new FOR THIS TRIP (taking `sectionTitle`/`audience` as the new\n * section's display; both are ignored on an already-existing section). An\n * omitted `key` is slugged from `title` and de-duplicated within the\n * section; an explicit colliding `key` is `422 VALIDATION_ERROR`, never a\n * silent rename. `gate` is derived from the section's `phase` — the\n * create body carries no `gate` of its own.\n */\n add(options: AddChecklistItemOptions): Promise<KaafilResponse<ChecklistItemResponse>>;\n /** See this file's header, quirk 4 — a `phase` sent here without an\n * explicit `gate` re-derives the item's `gate`. */\n patch(options: PatchChecklistItemOptions): Promise<KaafilResponse<ChecklistItemResponse>>;\n /** See this file's header, quirk 2. */\n remove(options: DeleteChecklistItemOptions): Promise<KaafilResponse<DeleteItemResponse>>;\n /**\n * `POST …/checklist/items/{itemId}/toggle` — flips OPEN↔COMPLETE. See\n * this file's header, quirk 1, before catching `KaafilVersionConflictError`\n * off this call. Returns the updated item PLUS its section's and the\n * trip's own progress, so a caller patches its local state without a\n * refetch. `checklist.item_completed` fires on every `OPEN → COMPLETE`\n * transition; `checklist.completed` fires additionally when it was the\n * LAST mandatory item trip-wide. `COMPLETE → OPEN` emits nothing.\n */\n toggle(options: ToggleChecklistItemOptions): Promise<KaafilResponse<ToggleResponse>>;\n}\n\n// --- checklists.templates ------------------------------------------------------\n\nexport interface ListChecklistTemplatesOptions {\n readonly tripRef: string;\n /** Default `\"en\"`, with `\"en\"` fallback on no exact match. */\n readonly locale?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PullChecklistTemplateOptions extends PullChecklistTemplateRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ChecklistTemplatesResource {\n /** `GET …/checklist/templates` — the agency's library (`tripId` is\n * `null`), resolved to `?locale=`. `lastUsedAt` is `null` until this\n * template is pulled onto some trip, or the pull marker has expired. */\n list(options: ListChecklistTemplatesOptions): Promise<KaafilResponse<TemplatesListResponse>>;\n /** See this file's header, quirk 3 — COPY semantics, never a live link.\n * Returns the FULL new aggregate (cold, no `?since=`) for atomic\n * replacement. */\n pull(options: PullChecklistTemplateOptions): Promise<KaafilResponse<ChecklistAggregateResponse>>;\n}\n\n// --- checklists.agencyTemplates -------------------------------------------------\n//\n// The AGENCY-level template library itself (`GET/POST/PATCH/DELETE\n// /api/v1/agencies/{ref}/checklist-templates[/{id}[/publish]]`) — distinct\n// from `templates` above, which is trip-scoped (`.../trips/{ref}/checklist\n// /templates`) and read/pull only. `list`/`create`/`patch`/`remove`/`publish`\n// here ALL accept the same pair, an API key OR an agency-admin session,\n// never `managerAuth` — the \"ADMIN TEMPLATE CONFIG IS DEFERRED\" note this\n// file's header cites for `templates` was about the TRIP-scoped surface\n// only; the agency-scoped CRUD below is a separate, already-shipped route\n// group. `publish` (GAP-004) is the DRAFT→PUBLISHED transition — see\n// `AgencyChecklistTemplatesResource.publish`'s own doc comment.\n\nexport interface ListAgencyChecklistTemplatesOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CreateAgencyChecklistTemplateOptions extends CreateChecklistTemplateRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchAgencyChecklistTemplateOptions extends PatchChecklistTemplateRequest {\n readonly agencyRef: string;\n readonly templateId: string;\n /**\n * Required, not optional — same `If-Match` contract as\n * `PatchChecklistItemOptions.version`. Pass the `version` from the\n * template as last read; the SDK builds the `If-Match` header itself.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteAgencyChecklistTemplateOptions {\n readonly agencyRef: string;\n readonly templateId: string;\n /** See `PatchAgencyChecklistTemplateOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface PublishAgencyChecklistTemplateOptions {\n readonly agencyRef: string;\n readonly templateId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencyChecklistTemplatesResource {\n /** `GET /api/v1/agencies/{ref}/checklist-templates` — the agency's full\n * template library, across every locale. */\n list(\n options: ListAgencyChecklistTemplatesOptions,\n ): Promise<KaafilResponse<ChecklistTemplateAdminListResponse>>;\n /** `POST /api/v1/agencies/{ref}/checklist-templates`. */\n create(\n options: CreateAgencyChecklistTemplateOptions,\n ): Promise<KaafilResponse<ChecklistTemplateSectionResponse>>;\n /** `PATCH /api/v1/agencies/{ref}/checklist-templates/{id}` — `items`, when\n * sent, is the FULL replacement list, not a delta. */\n patch(\n options: PatchAgencyChecklistTemplateOptions,\n ): Promise<KaafilResponse<ChecklistTemplateSectionResponse>>;\n /** `DELETE /api/v1/agencies/{ref}/checklist-templates/{id}`. */\n remove(\n options: DeleteAgencyChecklistTemplateOptions,\n ): Promise<KaafilResponse<DeleteChecklistTemplateResponse>>;\n /**\n * `POST /api/v1/agencies/{ref}/checklist-templates/{id}/publish` (GAP-004)\n * — moves a template `DRAFT` → `PUBLISHED`. Bodiless, no `If-Match`. A\n * `DRAFT` template is excluded from `templates.pull` and from the\n * manager-facing `templates.list`; only `PUBLISHED` is visible on either.\n * `create` above has no `status` field on its request — every new template\n * starts `DRAFT`, and this is the only way to flip it.\n */\n publish(\n options: PublishAgencyChecklistTemplateOptions,\n ): Promise<KaafilResponse<ChecklistTemplateSectionResponse>>;\n}\n\n// --- checklists ----------------------------------------------------------------\n\nexport interface ChecklistsResource {\n /** `GET …/trips/{ref}/checklist` — the full aggregate: sections, items,\n * both progress figures, and the agency's available templates. A PURE\n * READ — it never seeds; the four reserved sections are already present\n * by trip-ingest time (this file's header). */\n read(options: ReadChecklistOptions): Promise<KaafilResponse<ChecklistAggregateResponse>>;\n readonly items: ChecklistItemsResource;\n readonly templates: ChecklistTemplatesResource;\n /** The agency-level template library — see this file's `checklists\n * .agencyTemplates` section header for how it differs from `templates`. */\n readonly agencyTemplates: AgencyChecklistTemplatesResource;\n}\n\nexport function createChecklistsResource(client: KaafilHttpClient): ChecklistsResource {\n return {\n async read(options) {\n const { tripRef, since, signal } = options;\n return client.execute<ChecklistAggregateResponse>({\n method: 'GET',\n operationId: OperationId.ReadChecklistAggregate,\n path: '/api/v1/trips/{ref}/checklist',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n items: {\n async get(options) {\n const { tripRef, itemId, signal } = options;\n return client.execute<ChecklistItemResponse>({\n method: 'GET',\n operationId: OperationId.ReadChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async add(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<ChecklistItemResponse>({\n method: 'POST',\n operationId: OperationId.AddChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, itemId, version, signal, ...body } = options;\n return client.execute<ChecklistItemResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, itemId, version, signal } = options;\n return client.execute<DeleteItemResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async toggle(options) {\n const { tripRef, itemId, idempotencyKey, signal, ...body } = options;\n return client.execute<ToggleResponse>({\n method: 'POST',\n operationId: OperationId.ToggleChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items/{itemId}/toggle',\n pathParams: { ref: tripRef, itemId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n templates: {\n async list(options) {\n const { tripRef, locale, signal } = options;\n return client.execute<TemplatesListResponse>({\n method: 'GET',\n operationId: OperationId.ListChecklistTemplates,\n path: '/api/v1/trips/{ref}/checklist/templates',\n pathParams: { ref: tripRef },\n query: { locale },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async pull(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<ChecklistAggregateResponse>({\n method: 'POST',\n operationId: OperationId.PullChecklistTemplate,\n path: '/api/v1/trips/{ref}/checklist/pull-template',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n agencyTemplates: {\n async list(options) {\n const { agencyRef, signal } = options;\n return client.execute<ChecklistTemplateAdminListResponse>({\n method: 'GET',\n operationId: OperationId.ListChecklistTemplatesAdmin,\n path: '/api/v1/agencies/{ref}/checklist-templates',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<ChecklistTemplateSectionResponse>({\n method: 'POST',\n operationId: OperationId.CreateChecklistTemplate,\n path: '/api/v1/agencies/{ref}/checklist-templates',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { agencyRef, templateId, version, signal, ...body } = options;\n return client.execute<ChecklistTemplateSectionResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchChecklistTemplate,\n path: '/api/v1/agencies/{ref}/checklist-templates/{id}',\n pathParams: { ref: agencyRef, id: templateId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { agencyRef, templateId, version, signal } = options;\n return client.execute<DeleteChecklistTemplateResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteChecklistTemplate,\n path: '/api/v1/agencies/{ref}/checklist-templates/{id}',\n pathParams: { ref: agencyRef, id: templateId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async publish(options) {\n const { agencyRef, templateId, signal } = options;\n return client.execute<ChecklistTemplateSectionResponse>({\n method: 'POST',\n operationId: OperationId.PublishChecklistTemplate,\n path: '/api/v1/agencies/{ref}/checklist-templates/{id}/publish',\n pathParams: { ref: agencyRef, id: templateId },\n body: {},\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `closeout` — the closing day: what is still open, the handover note, the\n * lock that freezes the trip, the admin-only reopen, and the printed pack.\n * Five operations over `/api/v1/trips/{ref}/closeout*`.\n *\n * ── `get()`'s `?since=` IS NOT A DELTA CURSOR ───────────────────────────────\n *\n * It looks like every other `?since=` in this SDK and it is not one. The\n * aggregate is fully DERIVED — `blockers[]` is recomputed from ten modules on\n * every read and stored nowhere, so there is no `updatedAt` to window and no\n * tombstone to emit. The body is therefore ALWAYS whole and always\n * authoritative, cursor or no cursor. `?since=` narrows nothing; it answers\n * exactly one extra question, in exactly one extra field: did the STORED\n * record — the handover note, the lock, the reopen — move since that instant?\n * (`recordChangedSince`, `null` when no cursor was sent.)\n *\n * Two consequences, both easy to get wrong:\n *\n * 1. Do NOT feed this through `createDeltaCursor` (`../delta/cursor.ts`).\n * That helper merges narrowed rows into a local set and applies\n * tombstones; here it would be merging a full body into itself every\n * pull. Pass `since` by hand — a previous response's `meta.serverTime`,\n * the same value every other cursor in this SDK uses — or omit it.\n * 2. `recordChangedSince: false` does NOT mean \"nothing changed\". A balance\n * ingested a second ago moves `blockers[]` and `canLock` without touching\n * the stored row at all. It is a narrow claim about one record, and a\n * client that reads it as \"safe to skip the re-render\" will leave a lock\n * button greyed out after it has gone live.\n *\n * ── THE TWO VERSION GUARDS ARE BODY FIELDS, NOT `If-Match` ─────────────────\n *\n * Unlike `checklists.items.patch` / `expenses.void` / `collections.void`,\n * which carry their optimistic-concurrency guard in an `If-Match` header,\n * `saveHandover` and `lock` take `expectedVersion` as a REQUEST BODY field —\n * that is how the spec declares them (`SaveCloseoutHandoverRequest`,\n * `LockCloseoutRequest`), so this file passes it through as body and builds\n * no header. Read it from `handover.version` on a prior `get()`. A stale one\n * is answered `409 CONFLICT_VERSION` (`KaafilVersionConflictError`); rebase\n * against the current record and retry.\n *\n * It is REQUIRED on `saveHandover` (the spec marks it so: two managers\n * writing a closing narrative from two devices is the case it exists for) and\n * OPTIONAL on `lock` (`LockCloseoutRequest` does not require it — a lock\n * re-derives `canLock` inside the request anyway, so a stale `true` from a\n * `get()` can never win; `expectedVersion` there guards the record, not the\n * decision).\n *\n * ── `unlock` IS `apiKeyAuth`-ONLY, AND THAT IS THE POINT ───────────────────\n *\n * `OPERATION_SECURITY.unlockCloseout` is `['apiKeyAuth']` — the only one of\n * these five a manager session cannot satisfy. Reopening a locked trip is a\n * back-office act, not an on-ground one. This resource still exposes it\n * uniformly rather than branching per credential kind: a manager-session\n * client calling `unlock()` gets `UnsatisfiableSchemeError` from\n * `CredentialResolver` BEFORE any request is sent, which is a better answer\n * than a `401` from the engine and is exactly how `journey.rebuild`/\n * `journey.runStep` already behave on the browser entry.\n *\n * ── `exportPdf` RETURNS BYTES, NOT AN ENVELOPE ─────────────────────────────\n *\n * The engine sets `Content-Type: application/pdf` and sends the buffer\n * directly, so `responseWrapperMiddleware` never wraps it — there is no\n * `{ ok, data, meta }` around a closeout pack. The vendored spec describes\n * the `200` as `application/json` holding a `CloseoutPackBinaryResponse`,\n * which the generator renders as a bare `string`; that is the spec being\n * imprecise about a binary route, not the wire being JSON, and this method\n * follows the WIRE. It is the one method in this package that goes through\n * `KaafilHttpClient.executeBinary` (added for it) and the one that returns a\n * `KaafilBinaryResponse` — `{ bytes, meta }`, with `meta` carrying only\n * `status`/`requestId`/`contentType`, because an envelope-less response has\n * no `serverTime` and no `page` to report. Do not pass `meta` from here as a\n * `?since=` cursor anywhere; there is nothing in it to pass.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilBinaryResponse, KaafilResponse } from '../types/meta';\n\ntype CloseoutAggregateResponse = components['schemas']['CloseoutAggregateResponse'];\ntype SaveCloseoutHandoverRequest = components['schemas']['SaveCloseoutHandoverRequest'];\ntype LockCloseoutRequest = components['schemas']['LockCloseoutRequest'];\ntype UnlockCloseoutRequest = components['schemas']['UnlockCloseoutRequest'];\ntype ExportCloseoutPackRequest = components['schemas']['ExportCloseoutPackRequest'];\n\n/** One row of `blockers[]` — what is still open, and which screen clears it.\n * Aliased off the response type, never restated, so a spec change to the\n * closed eleven-key inventory reaches call sites as a type error rather than\n * silently widening. */\nexport type CloseoutBlocker = CloseoutAggregateResponse['blockers'][number];\n\n// --- closeout.get ----------------------------------------------------------\n\nexport interface ReadCloseoutOptions {\n readonly tripRef: string;\n /**\n * A previous response's own `meta.serverTime`, and nothing else. NOT a\n * delta cursor — see this file's header for what it does and does not\n * narrow. Omit it and `recordChangedSince` comes back `null`.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- closeout.saveHandover / .lock / .unlock -------------------------------\n\nexport interface SaveCloseoutHandoverOptions extends SaveCloseoutHandoverRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface LockCloseoutOptions extends LockCloseoutRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UnlockCloseoutOptions extends UnlockCloseoutRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- closeout.exportPdf ----------------------------------------------------\n\nexport interface ExportCloseoutPackOptions extends ExportCloseoutPackRequest {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- closeout --------------------------------------------------------------\n\nexport interface CloseoutResource {\n /** `GET /api/v1/trips/{ref}/closeout` — the whole closing-day picture:\n * the derived `stage`, `canLock` with its human `lockDisabledReason`, every\n * open `blockers[]` row hard-first, the handover note with the `version` the\n * two writes below need, and the financial summary. Always complete; see\n * this file's header for what `since` adds. */\n get(options: ReadCloseoutOptions): Promise<KaafilResponse<CloseoutAggregateResponse>>;\n /** `POST …/closeout/handover` — writes (or, with `handoverNote: null`,\n * clears) the closing narrative. `expectedVersion` is required; a stale one\n * answers `409 CONFLICT_VERSION`. Refused `423 LOCKED` once the trip is\n * locked. Returns the full re-derived aggregate. */\n saveHandover(\n options: SaveCloseoutHandoverOptions,\n ): Promise<KaafilResponse<CloseoutAggregateResponse>>;\n /** `POST …/closeout/lock` — freezes the trip. `canLock` is re-computed\n * inside this request, so a stale `true` from an earlier `get()` never wins:\n * an open hard blocker answers `422 BUSINESS_RULE_VIOLATION` however\n * confident the last read was. Returns the full re-derived aggregate. */\n lock(options: LockCloseoutOptions): Promise<KaafilResponse<CloseoutAggregateResponse>>;\n /** `POST …/closeout/unlock` — reopens a locked trip, with a `reason` that is\n * kept on the record and carried on the `closeout.reopened` event.\n * `apiKeyAuth`-ONLY: from a manager session this throws\n * `UnsatisfiableSchemeError` locally, before any request. See this file's\n * header. */\n unlock(options: UnlockCloseoutOptions): Promise<KaafilResponse<CloseoutAggregateResponse>>;\n /** `POST …/closeout/export-pdf` — the printed pack. Returns BYTES, not an\n * envelope: `{ bytes: Uint8Array, meta: { status, requestId, contentType } }`.\n * `sections` chooses which chapters print, in the array's own order (omit for\n * the agency default, which is all of them); `redactPii` reduces traveller\n * names to initials for a copy that leaves the agency. See this file's\n * header for why this one method is shaped differently from every other. */\n exportPdf(options: ExportCloseoutPackOptions): Promise<KaafilBinaryResponse>;\n}\n\nexport function createCloseoutResource(client: KaafilHttpClient): CloseoutResource {\n return {\n async get(options) {\n const { tripRef, since, signal } = options;\n return client.execute<CloseoutAggregateResponse>({\n method: 'GET',\n operationId: OperationId.ReadCloseout,\n path: '/api/v1/trips/{ref}/closeout',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async saveHandover(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<CloseoutAggregateResponse>({\n method: 'POST',\n operationId: OperationId.SaveCloseoutHandover,\n path: '/api/v1/trips/{ref}/closeout/handover',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async lock(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<CloseoutAggregateResponse>({\n method: 'POST',\n operationId: OperationId.LockCloseout,\n path: '/api/v1/trips/{ref}/closeout/lock',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async unlock(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<CloseoutAggregateResponse>({\n method: 'POST',\n operationId: OperationId.UnlockCloseout,\n path: '/api/v1/trips/{ref}/closeout/unlock',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async exportPdf(options) {\n const { tripRef, signal, ...body } = options;\n return client.executeBinary({\n method: 'POST',\n operationId: OperationId.ExportCloseoutPack,\n path: '/api/v1/trips/{ref}/closeout/export-pdf',\n pathParams: { ref: tripRef },\n body,\n // The one place a non-JSON `Accept` is sent. `exportCloseoutPack`\n // declares no `Idempotency-Key` parameter\n // (`OPERATION_ACCEPTS_IDEMPOTENCY_KEY.exportCloseoutPack` is `false`),\n // and rightly — printing the same pack twice creates nothing — so no\n // key is offered here and the transport mints none.\n accept: 'application/pdf',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `collections` — customer payments recorded against a traveller's balance,\n * who still owes, and the void correction. `architecture/08-sdk.md §4`.\n *\n * `list`/`eligible` accept a manager session OR an API key; `record`/`void`\n * are `managerAuth`-only — collecting cash and correcting a mistake both\n * happen on the ground.\n *\n * `mode ∈ CollectionMode` (`CASH|UPI|CARD|BANK`) is a CUSTOMER payment\n * mode, disjoint from `expenses`' agency-spend `paymentMode` — the two\n * enums never overlap and are never interchangeable even where a value\n * name might coincide.\n *\n * ── THE OVERPAY GUARD IS A HARD REFUSAL ──────────────────────────────────\n *\n * `record()`'s `amountMinor` must not exceed the traveller's DERIVED\n * `outstandingMinor` (computed live from the ingested `Balance`, never\n * stored) — a caller cannot record more than what is actually owed.\n * Exceeding it answers `422 BUSINESS_RULE_VIOLATION` with\n * `details.remainingMinor`, the room actually left. `eligible()` is the\n * companion read — which travellers it returns depends on its `status`\n * option, below; a traveller Kaafil cannot say anything about (no `Balance`\n * row at all) is absent regardless, though still recordable through\n * `record()` as an advance.\n *\n * `void()` is a correction, never an edit or a hard delete — there is no\n * edit-after-record. `If-Match: <version>` is required; a missing or stale\n * one answers `409 CONFLICT_VERSION` with `details.currentVersion`, never\n * silently overwriting a version the caller has not seen.\n *\n * `eligible()`'s `status` option (default `'due'`, matching the engine's own\n * default so an existing caller's response never changes underneath it):\n * `'due'` is travellers who still owe (`outstandingMinor > 0`, the original\n * behaviour); `'settled'` is travellers who are fully paid up\n * (`outstandingMinor === 0`); `'all'` is both together. A traveller Kaafil\n * cannot say anything about — no `Balance` row yet, or a credit balance — is\n * absent under every status, not folded into `'settled'`.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype CollectionResponse = components['schemas']['CollectionResponse'];\ntype CollectionDeltaResponse = components['schemas']['CollectionDeltaResponse'];\ntype EligibleRowResponse = components['schemas']['EligibleRowResponse'];\ntype RecordCollectionRequest = components['schemas']['RecordCollectionRequest'];\ntype VoidCollectionRequest = components['schemas']['VoidCollectionRequest'];\n\n/**\n * One row of `list`'s result: a live collection with its derived\n * `outstandingMinor`, or the tombstone for one deleted since the cursor.\n * Aliased off the response type rather than restated — see\n * `../delta/cursor.ts`'s `isTombstone`.\n */\nexport type CollectionDeltaRow = CollectionDeltaResponse;\n\n// --- date-time widening --------------------------------------------------\n//\n// `collectedAt` is `string` (`Format: date-time`) in the generated schema,\n// because the schema is a faithful mirror of the spec and the wire format\n// really is a string. `RecordCollectionOptions` widens exactly that field\n// to `DateTimeInput` (see `../datetime`) by indexing off the generated type\n// and overriding — never restating a request body by hand. The factory\n// normalizes back down to `string` before the body reaches the wire.\n\n// --- collections.list / collections.eligible -----------------------------\n\nexport interface ListCollectionsOptions {\n readonly tripRef: string;\n /** Narrows to one traveller. Omitted lists every traveller's rows. */\n readonly travellerId?: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit it for the full list. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the window is\n * INCLUSIVE and overlapped by five seconds, so a pull is at-least-once\n * and re-delivers rows a caller already holds; that module owns the\n * bookkeeping this endpoint's overlap assumes.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\ntype ListEligibleQuery = NonNullable<operations['listEligibleCollections']['parameters']['query']>;\n\n/** `'due' | 'settled' | 'all'` — the engine's own `?status=` enum on this route. */\nexport type EligibleCollectionsStatus = NonNullable<ListEligibleQuery['status']>;\n\nexport interface ListEligibleCollectionsOptions {\n readonly tripRef: string;\n /** Defaults to `'due'` — the endpoint's original, unwidened response. */\n readonly status?: EligibleCollectionsStatus;\n readonly signal?: AbortSignal;\n}\n\n// --- collections.record ---------------------------------------------------\n\nexport interface RecordCollectionOptions extends Omit<RecordCollectionRequest, 'collectedAt'> {\n readonly tripRef: string;\n readonly collectedAt?: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- collections.void ------------------------------------------------------\n\nexport interface VoidCollectionOptions extends VoidCollectionRequest {\n readonly tripRef: string;\n readonly collectionId: string;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both\n * answer `409 CONFLICT_VERSION` — identically confusing either way — so\n * this method makes forgetting it impossible instead of merely\n * discouraged. Pass the `version` from a collection just read via\n * `list()` or the row `record()` returned. The SDK builds the `If-Match`\n * header itself; never set it in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\n// --- collections -----------------------------------------------------------\n\nexport interface CollectionsResource {\n /** `GET /api/v1/trips/{ref}/collections` — recorded collections, each row's\n * `outstandingMinor` derived live on this read. See this file's header for\n * the delta-cursor semantics. */\n list(options: ListCollectionsOptions): Promise<KaafilResponse<readonly CollectionDeltaRow[]>>;\n /** `GET /api/v1/trips/{ref}/collections/eligible` — travellers filtered by\n * `status` (default `'due'`: `outstandingMinor > 0`, \"who has a balance to\n * chase\", not \"who may be collected from\"; `'settled'`: `outstandingMinor\n * === 0`; `'all'`: both). See this file's header for the full contract. */\n eligible(\n options: ListEligibleCollectionsOptions,\n ): Promise<KaafilResponse<readonly EligibleRowResponse[]>>;\n /** `POST /api/v1/trips/{ref}/collections` — records a customer payment.\n * See this file's header for the overpay guard. */\n record(options: RecordCollectionOptions): Promise<KaafilResponse<CollectionResponse>>;\n /** `DELETE /api/v1/trips/{ref}/collections/{id}/void` — a correction, not\n * an edit or a hard delete. `DELETE`, not the FRD table's nominal `POST`:\n * a real `If-Match` guard is unsatisfiable on a `POST` under this\n * engine's OpenAPI generator, and a version-guarded soft void is the\n * shape the generator already blesses `DELETE` for — same path, same\n * body, same response either way. */\n void(options: VoidCollectionOptions): Promise<KaafilResponse<CollectionResponse>>;\n}\n\nexport function createCollectionsResource(client: KaafilHttpClient): CollectionsResource {\n return {\n async list(options) {\n const { tripRef, travellerId, since, signal } = options;\n return client.execute<readonly CollectionDeltaRow[]>({\n method: 'GET',\n operationId: OperationId.ListCollections,\n path: '/api/v1/trips/{ref}/collections',\n pathParams: { ref: tripRef },\n query: { travellerId, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async eligible(options) {\n const { tripRef, status, signal } = options;\n return client.execute<readonly EligibleRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListEligibleCollections,\n path: '/api/v1/trips/{ref}/collections/eligible',\n pathParams: { ref: tripRef },\n query: { status },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async record(options) {\n const { tripRef, idempotencyKey, signal, collectedAt, ...rest } = options;\n const body: RecordCollectionRequest = {\n ...rest,\n ...(collectedAt !== undefined\n ? { collectedAt: normalizeDateTimeInput(collectedAt, 'collectedAt') }\n : {}),\n };\n return client.execute<CollectionResponse>({\n method: 'POST',\n operationId: OperationId.RecordCollection,\n path: '/api/v1/trips/{ref}/collections',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async void(options) {\n const { tripRef, collectionId, version, signal, ...body } = options;\n return client.execute<CollectionResponse>({\n method: 'DELETE',\n operationId: OperationId.VoidCollection,\n path: '/api/v1/trips/{ref}/collections/{id}/void',\n pathParams: { ref: tripRef, id: collectionId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `comms` — an agency's messaging config, its outbound message log, its\n * reusable template library, its BYO provider credentials, and its\n * tenant-level config default and test-send routes. `architecture/08-sdk.md\n * §4`. Every operation here is `apiKeyAuth`-only in the spec — this is a\n * CRM/agency-admin-console configuration surface, never something a manager\n * or a share-token holder reaches.\n *\n * ── `KAAFIL_SEND` vs `CRM_SEND` ───────────────────────────────────────────\n *\n * `config.read()`/`config.put()`'s `mode` (`CommsMode`) decides who actually\n * dispatches a message once `send()` (or an internal trigger elsewhere in\n * the API) requests one: `KAAFIL_SEND` has the engine deliver it through its\n * own provider, `CRM_SEND` has the engine log the request\n * (`MessageLogListResponse`/`SendMessageResponse`) WITHOUT delivering it —\n * the CRM's own systems own delivery, and this API is a record of intent,\n * not a guarantee of a provider call. `channels.*.enabled` and\n * `fallbackOrder` (`MessageChannel[]`) only matter under `KAAFIL_SEND`;\n * `quietHours` (`null` = no quiet window) suppresses a send until the\n * window ends, producing `status: 'DEFERRED_QUIET'` rather than dropping it.\n *\n * ── `send()`'S BODY CARRIES ITS OWN SCOPE, UNLIKE EVERY OTHER MODULE ─────\n *\n * Every other resource in this SDK takes its agency/trip ref as a named\n * field on the options object, resolved into the PATH\n * (`/api/v1/trips/{ref}/...`). `send()` is the one exception: the route is\n * the ref-less `POST /api/v1/messages/send`, and `agencyRef` (required) plus\n * `tripRef` (optional, for a trip-scoped template) travel in the BODY\n * instead — the spec's own shape, not a stylistic choice this file made.\n * `clientToken` is required and is this route's OWN idempotency guard,\n * DISTINCT from the `Idempotency-Key` header every mutating call in this\n * SDK already gets automatically (`08-sdk.md §5`) — both are sent, and both\n * must be supplied or minted for a retried `send()` to dedupe correctly.\n *\n * ── `templates.patch` LIVES AT A DIFFERENT PATH THAN `templates.list` ────\n *\n * `templates.create`/`templates.list` are `/api/v1/agencies/{ref}/templates`\n * (agency-scoped, matching every other agency-scoped list in this SDK);\n * `templates.patch` is the ref-less `PATCH /api/v1/templates/{id}` — the\n * template's own id already disambiguates it without an agency ref in the\n * path, the same way `forms.ts`'s `formId`-keyed routes need no agency ref\n * once a caller already holds the id. `patch` requires `If-Match` (`version`\n * on this options object), the same optimistic-concurrency contract as\n * every other versioned write in this SDK.\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\nimport { narrowPaged } from './internal';\n\ntype CommsConfigResponse = components['schemas']['CommsConfigResponse'];\ntype PutCommsConfigRequest = components['schemas']['PutCommsConfigRequest'];\ntype MessageLogListResponse = components['schemas']['MessageLogListResponse'];\ntype MessageLogRow = MessageLogListResponse['items'][number];\ntype SendMessageRequest = components['schemas']['SendMessageRequest'];\ntype SendMessageResponse = components['schemas']['SendMessageResponse'];\ntype MessageTemplateResponse = components['schemas']['MessageTemplateResponse'];\ntype MessageTemplateListResponse = components['schemas']['MessageTemplateListResponse'];\ntype CreateMessageTemplateRequest = components['schemas']['CreateMessageTemplateRequest'];\ntype PatchMessageTemplateRequest = components['schemas']['PatchMessageTemplateRequest'];\ntype CreateCommsProviderCredentialRequest =\n components['schemas']['CreateCommsProviderCredentialRequest'];\ntype CreateProviderCredentialResponse = components['schemas']['CreateProviderCredentialResponse'];\ntype TestCommsProviderCredentialRequest =\n components['schemas']['TestCommsProviderCredentialRequest'];\ntype TestProviderCredentialResponse = components['schemas']['TestProviderCredentialResponse'];\ntype SendCommsTestMessageRequest = components['schemas']['SendCommsTestMessageRequest'];\ntype TestMessageResponse = components['schemas']['TestMessageResponse'];\n\n// --- comms.config ------------------------------------------------------------\n\nexport interface ReadCommsConfigOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PutCommsConfigOptions extends PutCommsConfigRequest {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadDefaultCommsConfigOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface CommsConfigResource {\n /** `GET /api/v1/agencies/{ref}/comms-config`. */\n read(options: ReadCommsConfigOptions): Promise<KaafilResponse<CommsConfigResponse>>;\n /** `PUT /api/v1/agencies/{ref}/comms-config` — replaces the FULL config;\n * there is no PATCH for this resource. See this file's header for what\n * `mode` decides. */\n put(options: PutCommsConfigOptions): Promise<KaafilResponse<CommsConfigResponse>>;\n /** `GET /api/v1/comms/config/default` — the tenant-level comms-config\n * default, unresolved against any agency. Ref-less, unlike `read`/`put`. */\n readDefault(\n options?: ReadDefaultCommsConfigOptions,\n ): Promise<KaafilResponse<CommsConfigResponse>>;\n}\n\n// --- comms.messages ------------------------------------------------------------\n\ntype ListMessagesQuery = NonNullable<operations['listMessages']['parameters']['query']>;\n/** The filterable half of `messages.list`'s query params — `cursor` and\n * `limit` are the paginator's job, never the caller's to hold. */\nexport type MessageFilters = Omit<ListMessagesQuery, 'cursor' | 'limit'>;\n\n/**\n * `MessageLogListResponse` is `{ items, meta: { page } }` — an OBJECT, not a\n * bare array like every other cursor-paginated list in this SDK\n * (`events.ts`, `webhooks.ts`). This is also the one response DTO in the\n * whole vendored spec that declares its OWN `meta` property, alongside\n * `SuccessEnvelope`/`ErrorEnvelope` — `../types/meta.ts`'s header states\n * that invariant as verified by a `jq` query over `components.schemas`; this\n * schema now breaks it. Today the two `meta.page` shapes (this schema's own,\n * and the transport's `CursorPageMeta`) happen to be structurally identical,\n * so `http/client.ts`'s `attachMeta` — which does `Object.assign(data, {\n * meta })`, REPLACING whatever `meta` the wire payload already carried —\n * still leaves `response.meta.page` holding a valid cursor. But that is a\n * coincidence of today's two shapes matching, not a contract either schema\n * promises going forward; if the engine ever changes what\n * `MessageLogListResponse.meta` carries without changing the envelope's own\n * `EnvelopeMeta.page` to match, `attachMeta` silently drops the payload's\n * own value and this fetch keeps working only because the REPLACEMENT\n * value happens to still be usable. Flagged here rather than assumed away.\n */\nasync function fetchMessagesPage(\n client: KaafilHttpClient,\n request: {\n readonly agencyRef: string;\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: MessageFilters;\n },\n) {\n const response = await client.execute<MessageLogListResponse>({\n method: 'GET',\n operationId: OperationId.ListMessages,\n path: '/api/v1/agencies/{ref}/messages',\n pathParams: { ref: request.agencyRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n const paged = narrowPaged(response);\n return { items: paged.items, meta: paged.meta };\n}\n\nexport interface ListMessagesOptions {\n readonly agencyRef: string;\n readonly filters?: MessageFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListMessagesPageOptions extends MessageFilters {\n readonly agencyRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface SendMessageOptions extends SendMessageRequest {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface MessagesResource {\n /** `GET /api/v1/agencies/{ref}/messages` as a `KaafilPaginator` — the SDK\n * holds the cursor; the consumer never sees or stores one. See this\n * file's `fetchMessagesPage` for a caveat on this endpoint's response\n * shape. */\n list(options: ListMessagesOptions): KaafilPaginator<MessageLogRow, MessageFilters>;\n /** The manual single-page escape hatch — fetches exactly one page and\n * returns it directly, for a caller who wants to drive paging itself. */\n listPage(\n options: ListMessagesPageOptions,\n ): Promise<KaafilPagedResponse<readonly MessageLogRow[]>>;\n /** `POST /api/v1/messages/send` — one-off send outside any module's own\n * trigger. See this file's header for why `agencyRef`/`tripRef` travel in\n * the body, and for `clientToken` vs. the automatic `Idempotency-Key`. */\n send(options: SendMessageOptions): Promise<KaafilResponse<SendMessageResponse>>;\n}\n\n// --- comms.templates -----------------------------------------------------------\n\nexport interface ListMessageTemplatesOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CreateMessageTemplateOptions extends CreateMessageTemplateRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchMessageTemplateOptions extends PatchMessageTemplateRequest {\n readonly templateId: string;\n /** Required — see `checklists.ts#PatchChecklistItemOptions.version`'s own\n * argument for why this SDK never leaves `If-Match` optional on a\n * versioned write. Pass the `version` from the template as last read. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface MessageTemplatesResource {\n /** `GET /api/v1/agencies/{ref}/templates`. */\n list(options: ListMessageTemplatesOptions): Promise<KaafilResponse<MessageTemplateListResponse>>;\n /** `POST /api/v1/agencies/{ref}/templates`. */\n create(options: CreateMessageTemplateOptions): Promise<KaafilResponse<MessageTemplateResponse>>;\n /** `PATCH /api/v1/templates/{id}` — see this file's header for why this\n * one route carries no agency ref in its path. */\n patch(options: PatchMessageTemplateOptions): Promise<KaafilResponse<MessageTemplateResponse>>;\n}\n\n// --- comms.providers -------------------------------------------------------------\n\nexport interface CreateCommsProviderCredentialOptions extends CreateCommsProviderCredentialRequest {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TestCommsProviderCredentialOptions extends TestCommsProviderCredentialRequest {\n readonly providerId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CommsProvidersResource {\n /** `POST /api/v1/comms/providers` — seals a BYO email-provider API key and\n * mints a `providerRefId`. */\n create(\n options: CreateCommsProviderCredentialOptions,\n ): Promise<KaafilResponse<CreateProviderCredentialResponse>>;\n /** `POST /api/v1/comms/providers/{id}/test` — sends a real test email\n * through a saved provider credential. */\n test(\n options: TestCommsProviderCredentialOptions,\n ): Promise<KaafilResponse<TestProviderCredentialResponse>>;\n}\n\n// --- comms.sendTestMessage -------------------------------------------------------\n\nexport interface SendCommsTestMessageOptions extends SendCommsTestMessageRequest {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- comms ---------------------------------------------------------------------\n\nexport interface CommsResource {\n readonly config: CommsConfigResource;\n readonly messages: MessagesResource;\n readonly templates: MessageTemplatesResource;\n readonly providers: CommsProvidersResource;\n /** `POST /api/v1/comms/test-message` — the header action (\"Test message\n * queued to your own sender\"). */\n sendTestMessage(\n options: SendCommsTestMessageOptions,\n ): Promise<KaafilResponse<TestMessageResponse>>;\n}\n\nexport function createCommsResource(client: KaafilHttpClient): CommsResource {\n return {\n config: {\n async read(options) {\n const { agencyRef, signal } = options;\n return client.execute<CommsConfigResponse>({\n method: 'GET',\n operationId: OperationId.ReadCommsConfig,\n path: '/api/v1/agencies/{ref}/comms-config',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async put(options) {\n const { agencyRef, signal, ...body } = options;\n return client.execute<CommsConfigResponse>({\n method: 'PUT',\n operationId: OperationId.PutCommsConfig,\n path: '/api/v1/agencies/{ref}/comms-config',\n pathParams: { ref: agencyRef },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async readDefault(options) {\n const { signal } = options ?? {};\n return client.execute<CommsConfigResponse>({\n method: 'GET',\n operationId: OperationId.ReadTenantDefaultCommsConfig,\n path: '/api/v1/comms/config/default',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n messages: {\n list(options) {\n const { agencyRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchMessagesPage(client, { ...request, agencyRef }),\n filters: filters ?? {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { agencyRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<MessageLogListResponse>({\n method: 'GET',\n operationId: OperationId.ListMessages,\n path: '/api/v1/agencies/{ref}/messages',\n pathParams: { ref: agencyRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n const paged = narrowPaged(response);\n return Object.assign(paged.items, { meta: paged.meta }) as KaafilPagedResponse<\n readonly MessageLogRow[]\n >;\n },\n async send(options) {\n const { idempotencyKey, signal, ...body } = options;\n return client.execute<SendMessageResponse>({\n method: 'POST',\n operationId: OperationId.SendMessage,\n path: '/api/v1/messages/send',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n templates: {\n async list(options) {\n const { agencyRef, signal } = options;\n return client.execute<MessageTemplateListResponse>({\n method: 'GET',\n operationId: OperationId.ListMessageTemplates,\n path: '/api/v1/agencies/{ref}/templates',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<MessageTemplateResponse>({\n method: 'POST',\n operationId: OperationId.CreateMessageTemplate,\n path: '/api/v1/agencies/{ref}/templates',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { templateId, version, signal, ...body } = options;\n return client.execute<MessageTemplateResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchMessageTemplate,\n path: '/api/v1/templates/{id}',\n pathParams: { id: templateId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n providers: {\n async create(options) {\n const { idempotencyKey, signal, ...body } = options;\n return client.execute<CreateProviderCredentialResponse>({\n method: 'POST',\n operationId: OperationId.CreateCommsProviderCredential,\n path: '/api/v1/comms/providers',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async test(options) {\n const { providerId, idempotencyKey, signal, ...body } = options;\n return client.execute<TestProviderCredentialResponse>({\n method: 'POST',\n operationId: OperationId.TestCommsProviderCredential,\n path: '/api/v1/comms/providers/{id}/test',\n pathParams: { id: providerId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n async sendTestMessage(options) {\n const { idempotencyKey, signal, ...body } = options;\n return client.execute<TestMessageResponse>({\n method: 'POST',\n operationId: OperationId.SendCommsTestMessage,\n path: '/api/v1/comms/test-message',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `events` — the event feed. `architecture/08-sdk.md §4`: \"the delta feed for\n * missed-webhook recovery.\" `listEvents` is `apiKeyAuth`-only and\n * cursor-paginated (`cursor`+`limit` query params, `meta.page.hasNext`);\n * `list()` returns a `KaafilPaginator` and `listPage()` is the manual\n * single-page escape hatch (`../pagination/paginator.ts`).\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse } from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype EventEnvelopeResponse = components['schemas']['EventEnvelopeResponse'];\n\ntype ListEventsQuery = NonNullable<operations['listEvents']['parameters']['query']>;\n/** The filterable half of `listEvents`'s query params — `cursor` and\n * `limit` are the paginator's job, never the caller's to hold. */\nexport type EventFilters = Omit<ListEventsQuery, 'cursor' | 'limit'>;\n\nasync function fetchEventsPage(\n client: KaafilHttpClient,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: EventFilters;\n },\n) {\n const response = await client.execute<readonly EventEnvelopeResponse[]>({\n method: 'GET',\n operationId: OperationId.ListEvents,\n path: '/api/v1/events',\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListEventsOptions {\n readonly filters?: EventFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListEventsPageOptions extends EventFilters {\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface EventsResource {\n /** `GET /api/v1/events` as a `KaafilPaginator` — the SDK holds the cursor;\n * the consumer never sees or stores one. */\n list(options?: ListEventsOptions): KaafilPaginator<EventEnvelopeResponse, EventFilters>;\n /** The manual single-page escape hatch: fetches exactly one page and\n * returns it directly, for a caller who wants to drive paging itself\n * rather than use the paginator `list()` returns. */\n listPage(\n options?: ListEventsPageOptions,\n ): Promise<KaafilPagedResponse<readonly EventEnvelopeResponse[]>>;\n}\n\nexport function createEventsResource(client: KaafilHttpClient): EventsResource {\n return {\n list(options = {}) {\n return createPaginator({\n fetchPage: (request) => fetchEventsPage(client, request),\n filters: options.filters ?? {},\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n });\n },\n async listPage(options = {}) {\n const { cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly EventEnvelopeResponse[]>({\n method: 'GET',\n operationId: OperationId.ListEvents,\n path: '/api/v1/events',\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n };\n}\n","/**\n * `expenses` — on-trip agency spend, its receipt lane, and the claim\n * lifecycle for a manager's own `PERSONAL` spend. `architecture/08-\n * sdk.md §4`.\n *\n * `list`/`read` accept a manager session OR an API key, never an agency\n * admin. `log`, `linkReceipt` and `void` additionally accept an agency-admin\n * session (three alternatives: `managerAuth`, `apiKeyAuth`,\n * `agencyAdminAuth`) — an agency back-office can log/annotate/void a trip's\n * spend without a manager on the ground. `claims.submit`/`claims.withdraw`\n * accept `managerAuth` OR `apiKeyAuth`, never `agencyAdminAuth` — a claim is\n * the manager's own reimbursement request, not something an agency admin\n * files on their behalf. `claims.ingest` is the one method on this resource\n * an API key alone may call — see its own doc below. Checked against\n * `../generated/security.ts`'s `OPERATION_SECURITY`, the source of truth.\n *\n * `paymentMode ∈ ExpensePaymentMode` (`FLOAT_CASH|PERSONAL|OTHER`) is\n * IMMUTABLE after `log()` and never accepted on any later call — an agency\n * spend mode, disjoint from `collections`' customer payment `mode`.\n * `category ∈ ExpenseCategory`.\n *\n * ── FLOAT_CASH AUTO-COUPLES TO THE FLOAT LEDGER ──────────────────────────\n *\n * `log()` with `paymentMode: 'FLOAT_CASH'` creates, in ONE transaction, the\n * expense, a paired `FloatMovement.EXPENSE(OUT)`, and sets the expense's\n * `floatMovementId` — the negative-float guard (`float.ts`'s header)\n * applies unconditionally, so an expense that would overdraw the manager's\n * float is refused rather than logged. `PERSONAL`/`OTHER` touch no float\n * at all. `log({ submitClaim: true, ... })` (PERSONAL only) files the\n * claim in the SAME transaction — equivalent to a `log()` immediately\n * followed by `claims.submit()`, but atomic.\n *\n * ── THE CLAIM STATE MACHINE, AND WHO MAY MOVE IT ─────────────────────────\n *\n * `ExpenseResponse.claimStatus` is a five-member vocabulary —\n * `SUBMITTED|WITHDRAWN|APPROVED|PAID|REJECTED` — split down the middle by\n * WHO can set each value. `claims.submit()`/`claims.withdraw()` are the\n * only two a Kaafil caller ever drives, and neither takes a `status` field\n * at all: submitting always produces `SUBMITTED`, withdrawing always\n * produces `WITHDRAWN`, so there is no enum a manager writes here.\n * `APPROVED|PAID|REJECTED` arrive ONLY through `claims.ingest()` — the\n * CRM's own decision, mirrored, never decided by Kaafil. That three-member\n * subset is `ClaimStatusIngest` (`../generated/enums.ts`), deliberately not\n * named `ClaimStatus` — see `scripts/gen-meta.mjs`'s `REQUEST_ENUM_NAMES`\n * comment on that entry for why a bare domain name here would be the same\n * trap as `ItineraryItemStatusUpdate`'s.\n *\n * `claims.submit()` only succeeds on a row the caller themselves logged —\n * a different manager's row answers `404 RESOURCE_NOT_FOUND`, never `403`\n * — with `paymentMode: 'PERSONAL'` and `claimStatus` currently `null` or\n * `WITHDRAWN`. `claims.withdraw()` requires `If-Match` and only succeeds\n * while `claimStatus = SUBMITTED` AND no CRM decision has landed yet — a\n * decision arriving mid-flight wins the race cleanly, the withdraw loses.\n * `claims.ingest()` accepts ONLY the three CRM-only values; `SUBMITTED` or\n * `WITHDRAWN` on this route is `422 VALIDATION_ERROR` — the ingest route is\n * one-directional by contract, not just by convention.\n *\n * `void()` reverses the paired float movement (if any) and cascades an\n * open claim; `linkReceipt()` back-fills `receiptFileKey` for a client that\n * logged an expense offline before an upload could confirm — it takes an\n * `Idempotency-Key`, never an `If-Match`: it addresses no client-held\n * version, only a key the log call could not carry offline. Both refuse on\n * an already-voided row or one the CRM has already decided.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype ExpenseResponse = components['schemas']['ExpenseResponse'];\ntype ExpenseListResponse = components['schemas']['ExpenseListResponse'];\ntype ClaimStatusIngestResponse = components['schemas']['ClaimStatusIngestResponse'];\ntype LogExpenseRequest = components['schemas']['LogExpenseRequest'];\ntype LinkExpenseReceiptRequest = components['schemas']['LinkExpenseReceiptRequest'];\ntype VoidExpenseRequest = components['schemas']['VoidExpenseRequest'];\ntype ClaimStatusIngestRequest = components['schemas']['ClaimStatusIngestRequest'];\n\ntype ListExpensesQuery = NonNullable<operations['listExpenses']['parameters']['query']>;\n/** The filterable half of `list`'s query params — `since` is the delta\n * cursor and is passed as its own option, never bundled in here. */\nexport type ExpenseFilters = Omit<ListExpensesQuery, 'since'>;\n\n// --- date-time widening --------------------------------------------------\n//\n// `spentAt` (`LogExpenseRequest`) and `decisionAt` (`ClaimStatusIngestRequest`)\n// are `string` (`Format: date-time`) in the generated schema, because the\n// schema is a faithful mirror of the spec and the wire format really is a\n// string. The `*Options` types below widen exactly those fields to\n// `DateTimeInput` (see `../datetime`) by indexing off the generated type and\n// overriding — never restating a request body by hand. The factory\n// normalizes back down to `string` before the body reaches the wire.\n\n// --- expenses.list / expenses.read ----------------------------------------\n\nexport interface ListExpensesOptions extends ExpenseFilters {\n readonly tripRef: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit it for the full list. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the window is\n * INCLUSIVE and overlapped by five seconds, so a pull is at-least-once.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadExpenseOptions {\n readonly tripRef: string;\n readonly expenseId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- expenses.log ----------------------------------------------------------\n\nexport interface LogExpenseOptions extends Omit<LogExpenseRequest, 'spentAt'> {\n readonly tripRef: string;\n readonly spentAt?: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- expenses.linkReceipt / expenses.void ---------------------------------\n\nexport interface LinkExpenseReceiptOptions extends LinkExpenseReceiptRequest {\n readonly tripRef: string;\n readonly expenseId: string;\n /** Required — this route addresses no client-held version; see this\n * file's header for why `If-Match` never applies here. */\n readonly idempotencyKey: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface VoidExpenseOptions extends VoidExpenseRequest {\n readonly tripRef: string;\n readonly expenseId: string;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both\n * answer `409 CONFLICT_VERSION` — identically confusing either way — so\n * this method makes forgetting it impossible instead of merely\n * discouraged. Pass the `version` from an expense just read via `list()`\n * or `read()`. The SDK builds the `If-Match` header itself; never set it\n * in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\n// --- expenses.claims -------------------------------------------------------\n\nexport interface SubmitExpenseClaimOptions {\n readonly tripRef: string;\n readonly expenseId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface WithdrawExpenseClaimOptions {\n readonly tripRef: string;\n readonly expenseId: string;\n /** Required — see `VoidExpenseOptions.version` above for why this SDK\n * never makes `If-Match` optional on a versioned write. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface IngestClaimStatusOptions extends Omit<ClaimStatusIngestRequest, 'decisionAt'> {\n readonly tripRef: string;\n readonly expenseId: string;\n readonly decisionAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ExpenseClaimsResource {\n /** `POST /api/v1/trips/{ref}/expenses/{id}/claim` — files a claim on the\n * caller's own `PERSONAL` expense. No body: submitting always produces\n * `SUBMITTED`, never a status the caller names. */\n submit(options: SubmitExpenseClaimOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `DELETE /api/v1/trips/{ref}/expenses/{id}/claim/withdraw` — only while\n * still `SUBMITTED` with no CRM decision landed. `DELETE`, not the FRD\n * table's nominal `POST` — the same forced deviation `expenses.void()`\n * and `collections.void()` make, for the identical `If-Match`-on-`POST`\n * reason; nothing else about the contract changes. */\n withdraw(options: WithdrawExpenseClaimOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `POST /api/v1/trips/{ref}/expenses/{id}/claim-status` — partner API\n * key ONLY; a manager bearer answers `401 UNAUTHENTICATED`, never `403`.\n * The CRM's own decision, mirrored — Kaafil never approves, rejects or\n * pays. `status` accepts only `ClaimStatusIngest`'s three values;\n * `SUBMITTED`/`WITHDRAWN` here is `422 VALIDATION_ERROR`. The response's\n * `verdict` (`applied`/`ignored_stale`) tells the CRM whether this\n * decision actually landed or arrived after a newer one already had. */\n ingest(options: IngestClaimStatusOptions): Promise<KaafilResponse<ClaimStatusIngestResponse>>;\n}\n\n// --- expenses ----------------------------------------------------------------\n\nexport interface ExpensesResource {\n /** `GET /api/v1/trips/{ref}/expenses` — a trip's expenses, with category\n * totals and a spend summary over the filtered set (live rows only). See\n * this file's header for the delta-cursor semantics. */\n list(options: ListExpensesOptions): Promise<KaafilResponse<ExpenseListResponse>>;\n /** `GET /api/v1/trips/{ref}/expenses/{id}` — one expense, including its\n * claim view. `id` is a plain Kaafil id, never dual-resolved. */\n read(options: ReadExpenseOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `POST /api/v1/trips/{ref}/expenses` — logs an on-trip spend. See this\n * file's header for `FLOAT_CASH` auto-coupling and `submitClaim`. */\n log(options: LogExpenseOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `PATCH /api/v1/trips/{ref}/expenses/{id}/receipt` — back-fills\n * `receiptFileKey` against a confirmed (`ready`) upload from `files.*`. */\n linkReceipt(options: LinkExpenseReceiptOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `DELETE /api/v1/trips/{ref}/expenses/{id}/void` — reverses the paired\n * float movement and cascades an open claim. See this file's header for\n * the `DELETE`-not-`POST` note. */\n void(options: VoidExpenseOptions): Promise<KaafilResponse<ExpenseResponse>>;\n readonly claims: ExpenseClaimsResource;\n}\n\nexport function createExpensesResource(client: KaafilHttpClient): ExpensesResource {\n return {\n async list(options) {\n const { tripRef, since, signal, ...filters } = options;\n return client.execute<ExpenseListResponse>({\n method: 'GET',\n operationId: OperationId.ListExpenses,\n path: '/api/v1/trips/{ref}/expenses',\n pathParams: { ref: tripRef },\n query: { ...filters, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async read(options) {\n const { tripRef, expenseId, signal } = options;\n return client.execute<ExpenseResponse>({\n method: 'GET',\n operationId: OperationId.ReadExpense,\n path: '/api/v1/trips/{ref}/expenses/{id}',\n pathParams: { ref: tripRef, id: expenseId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async log(options) {\n const { tripRef, idempotencyKey, signal, spentAt, ...rest } = options;\n const body: LogExpenseRequest = {\n ...rest,\n ...(spentAt !== undefined ? { spentAt: normalizeDateTimeInput(spentAt, 'spentAt') } : {}),\n };\n return client.execute<ExpenseResponse>({\n method: 'POST',\n operationId: OperationId.LogExpense,\n path: '/api/v1/trips/{ref}/expenses',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async linkReceipt(options) {\n const { tripRef, expenseId, idempotencyKey, signal, ...body } = options;\n return client.execute<ExpenseResponse>({\n method: 'PATCH',\n operationId: OperationId.LinkExpenseReceipt,\n path: '/api/v1/trips/{ref}/expenses/{id}/receipt',\n pathParams: { ref: tripRef, id: expenseId },\n body,\n idempotencyKey,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async void(options) {\n const { tripRef, expenseId, version, signal, ...body } = options;\n return client.execute<ExpenseResponse>({\n method: 'DELETE',\n operationId: OperationId.VoidExpense,\n path: '/api/v1/trips/{ref}/expenses/{id}/void',\n pathParams: { ref: tripRef, id: expenseId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n claims: {\n async submit(options) {\n const { tripRef, expenseId, idempotencyKey, signal } = options;\n return client.execute<ExpenseResponse>({\n method: 'POST',\n operationId: OperationId.SubmitExpenseClaim,\n path: '/api/v1/trips/{ref}/expenses/{id}/claim',\n pathParams: { ref: tripRef, id: expenseId },\n body: {},\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async withdraw(options) {\n const { tripRef, expenseId, version, signal } = options;\n return client.execute<ExpenseResponse>({\n method: 'DELETE',\n operationId: OperationId.WithdrawExpenseClaim,\n path: '/api/v1/trips/{ref}/expenses/{id}/claim/withdraw',\n pathParams: { ref: tripRef, id: expenseId },\n body: {},\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async ingest(options) {\n const { tripRef, expenseId, idempotencyKey, signal, decisionAt, ...rest } = options;\n const body: ClaimStatusIngestRequest = {\n ...rest,\n decisionAt: normalizeDateTimeInput(decisionAt, 'decisionAt'),\n };\n return client.execute<ClaimStatusIngestResponse>({\n method: 'POST',\n operationId: OperationId.ClaimStatusIngest,\n path: '/api/v1/trips/{ref}/expenses/{id}/claim-status',\n pathParams: { ref: tripRef, id: expenseId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `feedbackNps` — two read-only rollups over `forms` responses to whichever\n * form an agency has designated its feedback/NPS survey: one across an\n * agency's forms catalog, one scoped to a single trip.\n * `architecture/08-sdk.md §4`. Both accept an API key; `trip` additionally\n * accepts a manager session or an agency-admin session, `agency` an\n * agency-admin session — never a manager alone (an agency-wide rollup is\n * not a single trip's manager's business).\n *\n * This resource is READ-ONLY by design: there is no \"designate this form as\n * the feedback survey\" write anywhere in the vendored spec. That\n * designation is `forms.create`/`forms.patch`'s `templateKey`/`programKey`\n * (`forms.ts`) — `feedbackNps` only reads the rollup the engine computes\n * over whichever form already carries that designation; it mints nothing\n * of its own.\n *\n * ── BOTH RESPONSE SCHEMAS NEST A SECOND `data` INSIDE THE ENVELOPE'S OWN\n * `data` ──────────────────────────────────────────────────────────────────\n *\n * Every other `SuccessEnvelope`-wrapped response in this SDK has the\n * envelope's `data` land directly on the resource shape (`trip.data` reads\n * as \"the trip\", not \"the trip's own `.data` field\"). Both\n * `AgencyFeedbackSummaryResponse` and `TripFeedbackSummaryResponse` are\n * exceptions: EACH schema itself declares a `data` property one level in,\n * so the value this SDK hands back is `{ data: { definitions: [...] } }`\n * (agency) or `{ data: { configured: false, reason } | { configured: true,\n * ... } }` (trip) — a caller reads `response.data.definitions` /\n * `response.data.configured`, not `response.definitions` /\n * `response.configured`. This SDK does not unwrap the extra layer or\n * rename it — the generated schema is a faithful mirror of the spec, same\n * as everywhere else in this package — but it is worth stating plainly\n * once, here, rather than leaving a caller to discover the double nesting\n * by trial and error.\n *\n * `trip.read()`'s result is a discriminated union on `data.configured`:\n * `false` carries only `reason` (no form has ever been designated, or the\n * designated form was archived); `true` carries the window, the funnel\n * counts (`dispatched`/`started`/`submitted`), `completionRate` (`null`\n * until at least one dispatch), the same `nps` shape `agency.read()`'s\n * `definitions[]` rows carry, and `reopenClosesAt`. Narrow on\n * `data.configured` before reading any of the `true`-only fields —\n * TypeScript enforces this at the call site.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype AgencyFeedbackSummaryResponse = components['schemas']['AgencyFeedbackSummaryResponse'];\ntype TripFeedbackSummaryResponse = components['schemas']['TripFeedbackSummaryResponse'];\n\n// --- feedbackNps.agency ------------------------------------------------------\n\nexport interface ReadAgencyFeedbackSummaryOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- feedbackNps.trip ---------------------------------------------------------\n\nexport interface ReadTripFeedbackSummaryOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- feedbackNps ---------------------------------------------------------------\n\nexport interface FeedbackNpsResource {\n /** `GET /api/v1/agencies/{ref}/feedback/summary` — one row per designated\n * feedback form across the agency's whole forms catalog. See this file's\n * header for the double `data.data`-shaped nesting. */\n agency(\n options: ReadAgencyFeedbackSummaryOptions,\n ): Promise<KaafilResponse<AgencyFeedbackSummaryResponse>>;\n /** `GET /api/v1/trips/{ref}/feedback/summary` — one trip's rollup, or\n * `{ configured: false, reason }` if no feedback form is designated for\n * it. See this file's header for the discriminated union and the double\n * `data.data`-shaped nesting. */\n trip(\n options: ReadTripFeedbackSummaryOptions,\n ): Promise<KaafilResponse<TripFeedbackSummaryResponse>>;\n}\n\nexport function createFeedbackNpsResource(client: KaafilHttpClient): FeedbackNpsResource {\n return {\n async agency(options) {\n const { agencyRef, signal } = options;\n return client.execute<AgencyFeedbackSummaryResponse>({\n method: 'GET',\n operationId: OperationId.ReadAgencyFeedbackSummary,\n path: '/api/v1/agencies/{ref}/feedback/summary',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async trip(options) {\n const { tripRef, signal } = options;\n return client.execute<TripFeedbackSummaryResponse>({\n method: 'GET',\n operationId: OperationId.ReadTripFeedbackSummary,\n path: '/api/v1/trips/{ref}/feedback/summary',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `files` — the blob lane: request a presigned upload slot, confirm it,\n * read metadata, and mint a short-lived signed GET. `architecture/08-\n * sdk.md §4`. All four operations — `request`/`confirm`/`meta`/`url` —\n * accept the SAME three alternatives: a manager session, an agency-admin\n * session, OR an API key (`managerAuth`, `agencyAdminAuth`, `apiKeyAuth`;\n * never an AND). Checked against `../generated/security.ts`'s\n * `OPERATION_SECURITY`, the source of truth. An agency admin confirming a\n * `PENDING` upload attributes the confirmation to itself, not to whichever\n * manager (if any) requested the slot — see the actor-attribution fields on\n * the eight models and `ItineraryChangeLog` for the general shape of that\n * distinction; `FileResponse` itself still carries none (`uploadedByManagerId`\n * only, `null` for a non-manager caller).\n *\n * `purpose` is further gated per credential kind server-side, and the three\n * kinds no longer collapse into two:\n *\n * apiKey `booking_voucher` | `trip_document`\n * manager `expense_receipt` | `form_attachment`\n * agencyAdmin ALL FOUR\n *\n * This paragraph used to say a manager and an agency admin shared one set and\n * that `booking_voucher` was \"apiKey-only regardless of session kind\" — both\n * halves are now false. The desk may file a voucher the CRM never pushed, and\n * `trip_document` (new) is the desk's own purpose for the trip's paperwork.\n * A purpose outside the caller's set answers **404, with no capability hint**,\n * not a 422 — so a refused request looks like a missing trip, which is\n * deliberate and worth knowing when debugging one.\n *\n * `trip_document` carries two fields no other purpose accepts, and supplying\n * either elsewhere is a `422`, never a silent drop:\n *\n * `title` REQUIRED — nothing else names this file. The other three\n * are named by the expense, form field or booking they hang\n * off; a trip document hangs off nothing.\n * `travellerRef` optional — omit it and the document belongs to the whole\n * trip and reaches every share link on it; name a traveller\n * and it reaches only a share token whose SUBJECT is that\n * traveller. It also decides retention: scoped →\n * `TRAVELLER_PII` (24-month ceiling), unscoped →\n * `OPERATIONAL` (no clock).\n *\n * That gate is enforced by the engine, not this SDK.\n *\n * ── THE FOUR-STATUS LIFECYCLE ────────────────────────────────────────────\n *\n * `FileResponse.status` is `pending → ready → orphaned`/`purged`. Bytes\n * never pass through this SDK or the Kaafil API at all: `request()` hands\n * back a presigned `PUT` URL (`CreateFileResponse.uploadUrl`) that the\n * caller's own HTTP stack uses to write directly to object storage, with\n * NO Kaafil auth header — the signed URL itself is the authorization. This\n * package does not perform that `PUT`; it only mints the URL and later\n * confirms what landed.\n *\n * `confirm()` verifies the object actually arrived — existence, the\n * declared `sizeBytes`, and the leading bytes against `contentType`'s file\n * signature — because the presigned `PUT` pins `sizeBytes` into its\n * signature but NOT `contentType`, so a caller-declared type is otherwise\n * unverified. A mismatch answers `422 UPLOAD_MISMATCH` and the file stays\n * `pending`; re-`PUT` and re-confirm until the presigned URL's window\n * lapses. On success `retentionClass` is stamped SERVER-SIDE (never\n * client-declared) and the file flips to `ready`. It is a function of\n * `purpose` for two of the four; the other two SPLIT — `form_attachment` on\n * the answering field's kind (`SIGNATURE` → `CONSENT_EVIDENCE`, else\n * `TRAVELLER_PII`) and `trip_document` on whether it names a traveller.\n *\n * `url()` mints a fresh 5-minute signed GET on every call — never stored,\n * never reused — and only for a `ready` file. A `purged` file answers\n * `410 FILE_PURGED`: the metadata row survives forever, the bytes do not.\n * `meta()` itself never 404s for a purged file — it is the one read that\n * still answers `200` whatever `status` says, which is how a caller tells\n * \"gone\" (`410` from `url()`) apart from \"never existed\" (`404` from\n * `meta()`) without a second not-found class.\n *\n * `purpose ∈ FilePurpose` gates what `contentType ∈ FileContentType` may\n * accompany it server-side; both are `../generated/enums.ts` constants\n * that come from the same vendored spec.\n *\n * `list()` and `managerView()` are two additive reads alongside the original\n * four, both `managerAuth`/`apiKeyAuth`/`agencyAdminAuth` like every other\n * read here. `list()` is the one method on this resource that needs no\n * `fileId` at all — it is how a caller with no id yet discovers what exists\n * for a trip. `managerView()` composes `meta()` + `url()` server-side into\n * one manager-doc-viewer-shaped response; it never refuses on a non-`ready`\n * file the way `url()` does — `url`/`urlExpiresAt` simply come back `null`.\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype CreateFileResponse = components['schemas']['CreateFileResponse'];\ntype FileResponse = components['schemas']['FileResponse'];\ntype FileUrlResponse = components['schemas']['FileUrlResponse'];\ntype FileListResponse = components['schemas']['FileListResponse'];\ntype ManagerFileViewResponse = components['schemas']['ManagerFileViewResponse'];\ntype RequestFileUploadRequest = components['schemas']['RequestFileUploadRequest'];\n\ntype ListFilesQuery = NonNullable<operations['listFiles']['parameters']['query']>;\n\n// --- files.request -----------------------------------------------------\n\nexport interface RequestFileUploadOptions extends RequestFileUploadRequest {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- files.meta / files.confirm / files.url -----------------------------\n\nexport interface ReadFileOptions {\n readonly fileId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ConfirmFileUploadOptions {\n readonly fileId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFileUrlOptions {\n readonly fileId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- files.list ------------------------------------------------------------\n\nexport interface ListFilesOptions extends ListFilesQuery {\n readonly signal?: AbortSignal;\n}\n\n// --- files.managerView -----------------------------------------------------\n\nexport interface DeleteFileOptions {\n readonly fileId: string;\n /**\n * The `version` from the file as last read. Required, not optional: a\n * missing `If-Match` and a stale one both answer `409 CONFLICT_VERSION`,\n * identically confusing either way, so this makes forgetting it impossible\n * rather than merely discouraged. The SDK builds the header itself.\n */\n readonly version: number;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadManagerFileViewOptions {\n readonly fileId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- files ---------------------------------------------------------------\n\nexport interface FilesResource {\n /** `POST /api/v1/files` — mints a `pending` metadata row plus a presigned\n * `PUT`, 15-minute window, `contentType`/`sizeBytes` pinned as request\n * conditions. This method never uploads bytes itself — see this file's\n * header. */\n request(options: RequestFileUploadOptions): Promise<KaafilResponse<CreateFileResponse>>;\n /** `GET /api/v1/files/{id}` — the metadata skeleton, `200` for every\n * status including `purged`. Never carries `storageKey`, `tripRef` or\n * `agencyId`; `retentionClass` is `null` until the file is `ready`. */\n meta(options: ReadFileOptions): Promise<KaafilResponse<FileResponse>>;\n /** `POST /api/v1/files/{id}/confirm` — verifies the uploaded object and\n * flips `pending` → `ready`. See this file's header for the mismatch and\n * retention-stamping behaviour. */\n confirm(options: ConfirmFileUploadOptions): Promise<KaafilResponse<FileResponse>>;\n /** `GET /api/v1/files/{id}/url` — a fresh 5-minute signed GET for a\n * `ready` file. `410 FILE_PURGED` once the bytes are gone. */\n url(options: ReadFileUrlOptions): Promise<KaafilResponse<FileUrlResponse>>;\n /** `GET /api/v1/files?tripRef=` — every file for a trip, newest first,\n * optionally narrowed by `purpose`/`status`. The one method on this\n * resource that needs no `fileId` — see this file's header. */\n list(options: ListFilesOptions): Promise<KaafilResponse<FileListResponse>>;\n /** `GET /api/v1/files/{id}/manager-view` — `meta()` + `url()` composed\n * into one manager-doc-viewer-shaped response. See this file's header for\n * why it never refuses on a non-`ready` file the way `url()` does. */\n managerView(\n options: ReadManagerFileViewOptions,\n ): Promise<KaafilResponse<ManagerFileViewResponse>>;\n /**\n * `DELETE /api/v1/files/{id}` — withdraw a `trip_document` and DELETE THE\n * STORED OBJECT. The one call on this resource that destroys bytes.\n *\n * `trip_document` ONLY. The other three purposes are evidence owned by a\n * parent record that decides its own life — a receipt by its expense, an\n * attachment by its form field, a voucher by its booking (use\n * `bookings.vouchers.replace`) — so calling this on one is `422\n * BUSINESS_RULE_VIOLATION`, `details.rule:\n * \"file.deleteRestrictedToTripDocument\"`. A `retentionClass` of `financial`\n * or `consent_evidence` is refused the same way with\n * `\"file.deleteBlockedByRetention\"`: those carry an obligation to KEEP.\n *\n * Afterwards the id is GONE — `meta()` answers `404`, not the `200`\n * skeleton a retention-purged file still returns. So unlike a purge, a\n * withdrawn document cannot be told apart from one that never existed. That\n * is deliberate; a caller who needs a record of the withdrawal keeps it on\n * their own side before calling.\n *\n * Safe to repeat: a retry after a partial failure finishes the job rather\n * than erroring.\n */\n remove(options: DeleteFileOptions): Promise<KaafilResponse<false>>;\n}\n\nexport function createFilesResource(client: KaafilHttpClient): FilesResource {\n return {\n async request(options) {\n const { idempotencyKey, signal, ...body } = options;\n return client.execute<CreateFileResponse>({\n method: 'POST',\n operationId: OperationId.RequestFileUpload,\n path: '/api/v1/files',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async meta(options) {\n const { fileId, signal } = options;\n return client.execute<FileResponse>({\n method: 'GET',\n operationId: OperationId.ReadFile,\n path: '/api/v1/files/{id}',\n pathParams: { id: fileId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async confirm(options) {\n const { fileId, idempotencyKey, signal } = options;\n return client.execute<FileResponse>({\n method: 'POST',\n operationId: OperationId.ConfirmFileUpload,\n path: '/api/v1/files/{id}/confirm',\n pathParams: { id: fileId },\n body: {},\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async url(options) {\n const { fileId, signal } = options;\n return client.execute<FileUrlResponse>({\n method: 'GET',\n operationId: OperationId.ReadFileUrl,\n path: '/api/v1/files/{id}/url',\n pathParams: { id: fileId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { signal, ...query } = options;\n return client.execute<FileListResponse>({\n method: 'GET',\n operationId: OperationId.ListFiles,\n path: '/api/v1/files',\n query,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { fileId, version, idempotencyKey, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteFile,\n path: '/api/v1/files/{id}',\n pathParams: { id: fileId },\n headers: { 'If-Match': String(version) },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async managerView(options) {\n const { fileId, signal } = options;\n return client.execute<ManagerFileViewResponse>({\n method: 'GET',\n operationId: OperationId.ReadManagerFileView,\n path: '/api/v1/files/{id}/manager-view',\n pathParams: { id: fileId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `float` — cash advanced to a manager, its ledger, and the derived\n * per-manager balance. `architecture/08-sdk.md §4`.\n *\n * ALL FIVE methods accept a manager session, an API key, OR an agency-admin\n * session. `return` included: this file previously described it as\n * `managerAuth`-only, \"an admin is view-only on that row\", and that was\n * wrong — `float.routes.ts` declares\n * `auth: ['manager', 'apiKey', 'agencyAdmin']` on it and its own route\n * description says so outright: \"A manager session, an API key, or an\n * agency admin session may call this (full parity with `issue`/`adjust` —\n * owner decision)\". An office reconciling a returned cash box is exactly\n * the case that parity exists for.\n *\n * Every movement is one of four `type`s (`ISSUE|RETURN|ADJUSTMENT|EXPENSE`)\n * with a `direction ∈ FloatDirection` (`IN|OUT`) — `EXPENSE` movements are\n * created by `expenses.log` when `paymentMode: 'FLOAT_CASH'`, never by a\n * method on this resource directly.\n *\n * ── THE NEGATIVE-FLOAT GUARD ─────────────────────────────────────────────\n *\n * Every `OUT` movement — `return()` and `adjust()` with `direction: 'OUT'`\n * — is guarded: `amountMinor` must not exceed the manager's current\n * derived `balanceMinor`, checked and enforced under an advisory lock so\n * two concurrent `OUT`s can never both pass the same stale read. A refusal\n * is `422 BUSINESS_RULE_VIOLATION` with `details.currentBalanceMinor` — the\n * figure the guard actually compared against. `issue()` (`direction: 'IN'`,\n * always additive) and `adjust()` with `direction: 'IN'` are never guarded.\n *\n * `adjust()`'s `note` is REQUIRED (the audit trail of every manual\n * correction) — unlike `issue()`/`return()`, where it is optional.\n * `issue()` never accepts a `currency` field: every write takes the trip's\n * own currency, never a caller-named one.\n *\n * ── DERIVED, NOT DELTA-MERGEABLE (readSummary) vs A PLAIN DELTA (readLedger) ──\n *\n * `readSummary()`'s rows are entirely derived (`issuedMinor`,\n * `returnedMinor`, `spentMinor`, `adjustmentsMinor`, `balanceMinor`) —\n * nothing here is stored. `since` narrows WHICH managers are returned (only\n * those with a movement at or after the cursor) but every returned row\n * still carries its FULL current balance, never a partial delta — a\n * derived scalar cannot be delta-merged the way a versioned list row can.\n * `mergeDeltaRows`/`isTombstone` (`../delta/cursor.ts`) do not apply here:\n * there is no tombstone case and no per-row `version` to compare.\n *\n * `readLedger()`'s `since`, by contrast, IS a plain delta over a genuine\n * append-only list: it narrows the returned MOVEMENT rows to those at or\n * after the cursor. Each surviving row's `runningBalanceMinor` is still its\n * correct absolute balance — the server computes the running sum over the\n * manager's full history before the cursor narrows what ships, so a client\n * resuming from a cursor never sees a balance re-based to zero.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype FloatSummaryResponse = components['schemas']['FloatSummaryResponse'];\ntype FloatLedgerResponse = components['schemas']['FloatLedgerResponse'];\ntype AdjustFloatResponse = components['schemas']['AdjustFloatResponse'];\ntype IssueFloatResponse = components['schemas']['IssueFloatResponse'];\ntype ReturnFloatResponse = components['schemas']['ReturnFloatResponse'];\ntype AdjustFloatRequest = components['schemas']['AdjustFloatRequest'];\ntype IssueFloatRequest = components['schemas']['IssueFloatRequest'];\ntype ReturnFloatRequest = components['schemas']['ReturnFloatRequest'];\n\n// --- float.readSummary / float.readLedger --------------------------------\n\nexport interface ReadFloatSummaryOptions {\n readonly tripRef: string;\n /** Narrows which managers are returned to those with a movement at or\n * after this cursor. See this file's header — the rows themselves are\n * never partial, so this is not a `../delta/cursor.ts` cursor. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFloatLedgerOptions {\n readonly tripRef: string;\n readonly managerId: string;\n /** Narrows the returned movement rows to those at or after this cursor —\n * a plain delta pull, unlike `ReadFloatSummaryOptions.since`. See this\n * file's header. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- float.issue / float.return / float.adjust ---------------------------\n\nexport interface IssueFloatOptions extends IssueFloatRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReturnFloatOptions extends ReturnFloatRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AdjustFloatOptions extends AdjustFloatRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- float -----------------------------------------------------------------\n\nexport interface FloatResource {\n /** `GET /api/v1/trips/{ref}/float` — one row per manager who has ever had\n * a movement on this trip, entirely derived. See this file's header. */\n readSummary(options: ReadFloatSummaryOptions): Promise<KaafilResponse<FloatSummaryResponse>>;\n /** `GET /api/v1/trips/{ref}/float/{managerId}/ledger` — one manager's\n * movement history, ordered `(createdAt asc, id asc)`, each row carrying\n * `runningBalanceMinor`. `404` if `managerId` does not name a manager\n * currently assigned to this trip. `since` narrows the rows returned to\n * those at or after the cursor — see this file's header. */\n readLedger(options: ReadFloatLedgerOptions): Promise<KaafilResponse<FloatLedgerResponse>>;\n /** `POST /api/v1/trips/{ref}/float/issue` — `type=ISSUE`, `direction=IN`,\n * never negative-float guarded. An admin or the manager themselves may\n * call this; both paths produce the identical row. */\n issue(options: IssueFloatOptions): Promise<KaafilResponse<IssueFloatResponse>>;\n /** `POST /api/v1/trips/{ref}/float/return` — `type=RETURN`,\n * `direction=OUT`, negative-float guarded. A manager, an API key or an\n * agency admin may call it — full parity with `issue`/`adjust`, see this\n * file's header. */\n return(options: ReturnFloatOptions): Promise<KaafilResponse<ReturnFloatResponse>>;\n /** `POST /api/v1/trips/{ref}/float/adjust` — `type=ADJUSTMENT`, direction\n * named by the caller; `note` is required. `direction: 'OUT'` is\n * negative-float guarded identically to `return()`; `direction: 'IN'`\n * never is. */\n adjust(options: AdjustFloatOptions): Promise<KaafilResponse<AdjustFloatResponse>>;\n}\n\nexport function createFloatResource(client: KaafilHttpClient): FloatResource {\n return {\n async readSummary(options) {\n const { tripRef, since, signal } = options;\n return client.execute<FloatSummaryResponse>({\n method: 'GET',\n operationId: OperationId.ReadFloatSummary,\n path: '/api/v1/trips/{ref}/float',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async readLedger(options) {\n const { tripRef, managerId, since, signal } = options;\n return client.execute<FloatLedgerResponse>({\n method: 'GET',\n operationId: OperationId.ReadFloatLedger,\n path: '/api/v1/trips/{ref}/float/{managerId}/ledger',\n pathParams: { ref: tripRef, managerId },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async issue(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<IssueFloatResponse>({\n method: 'POST',\n operationId: OperationId.IssueFloat,\n path: '/api/v1/trips/{ref}/float/issue',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async return(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<ReturnFloatResponse>({\n method: 'POST',\n operationId: OperationId.ReturnFloat,\n path: '/api/v1/trips/{ref}/float/return',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async adjust(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<AdjustFloatResponse>({\n method: 'POST',\n operationId: OperationId.AdjustFloat,\n path: '/api/v1/trips/{ref}/float/adjust',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `forms` — the agency's form-authoring surface (definitions, sections,\n * fields, publish lifecycle, response export) plus the trip-scoped read/\n * write surface a manager uses on the ground. `architecture/08-sdk.md §4`.\n *\n * Every authoring write (`create`/`patch`/`delete`/`archive`/`unarchive`/\n * `publish`/`close`/`reopen`/`clone`/`reorder`, and every `sections.*`/\n * `fields.*` write) accepts an API key OR an agency-admin session — never a\n * manager alone; a manager reads a form's definition (`get`) but never\n * authors one. The trip-scoped surface (`trip.*`) now accepts ALL THREE —\n * `list`/`answers`/`completion`/`dispatch`/`responses.list`/\n * `responses.get`/`export`/`consentReceipt` were a manager session or an\n * API key until this pass, which left an agency admin able to CREATE a\n * response on a traveller's behalf (`responses.create` always took the\n * triple) and unable to read the trip's responses to know one was\n * missing. The engine closed that asymmetry; these methods are now\n * reachable from a desk console. `bindings.list` accepts\n * all three (API key, agency-admin, manager) — it is a read-only catalog of\n * what a field MAY bind to, useful to every caller building a form UI.\n *\n * ── VERSIONED WRITES: `If-Match` EVERYWHERE, `data: false` ON DELETE ─────\n *\n * Every PATCH/DELETE below (the form itself, a section, a field) is a\n * versioned write and takes a required `version` — this SDK builds the\n * `If-Match` header itself, the same contract as every other versioned\n * write in this package (`checklists.ts#PatchChecklistItemOptions.version`'s\n * own argument for why it is never optional). `delete`/`sections.delete`/\n * `fields.delete`/`reorder` all answer their success body as a literal\n * `data: false` — not a deleted-row echo the way `checklists.items.remove`\n * or `bookings.delete` return one — so this file types those four returns\n * as `KaafilResponse<false>` rather than inventing a response shape the\n * spec does not declare.\n *\n * ── `getFormConsentReceipt` LIVES OUTSIDE `{formId}` ──────────────────────\n *\n * Every other response-scoped read/write nests under `/forms/{formId}/...`.\n * `responses.consentReceipt` is the one exception —\n * `GET /api/v1/forms/responses/{responseId}/consent-receipt` — because a\n * response's `id` alone already disambiguates it; the spec's own path\n * shape, not a stylistic choice made here.\n *\n * ── TWO BYTE-BODIED READS ─────────────────────────────────────────────────\n *\n * `responses.export` and `responses.consentReceipt` answer RAW BYTES, not a\n * `{ ok, data, meta }` envelope: the engine sets `text/csv; charset=utf-8`\n * or `application/pdf` and writes the file straight onto the response\n * (`forms.controller.ts#exportResponses`/`#consentReceipt`). They therefore\n * go through `client.executeBinary` and return `KaafilBinaryResponse` —\n * `{ bytes, meta }` — exactly like `closeout.exportPdf`.\n *\n * The generated schema types both payloads as `FormsBinaryResponse`, a bare\n * `string`. That is the SPEC being lossy about a binary body, not a promise\n * of a JSON string, and honouring it literally through `client.execute` made\n * every SUCCESSFUL call throw `KaafilNetworkError('Received an\n * unrecognizable success body')`: the enveloped reader calls `text()` and\n * then demands an envelope the engine never sends. The generated alias is\n * deliberately unused here rather than re-exported as a lie.\n *\n * `Accept` follows the request — `text/csv` when `format === 'csv'`,\n * `application/pdf` otherwise — and `meta.contentType` carries the server's\n * own header verbatim, which is where a caller reads what it actually got.\n *\n * `aggregate` answers `AggregateResponse` — an open `Record<string,\n * unknown>`, the field-key keyed rollup `getFormAggregate`'s own `fieldKey`\n * query param narrows.\n *\n * ── `trip.answers` AND `trip.completion` ARE OPEN-SHAPED TOO ─────────────\n *\n * `CrossModuleAnswersResponse` is a `Record<string, { travellerId, value\n * }[]>` keyed by whatever binding key `?keys=` asked for — there is no\n * closed set of keys this SDK could name in advance (`bindings.list` is the\n * read of what keys exist, but the two are not cross-checked here).\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilBinaryResponse, KaafilResponse } from '../types/meta';\n\ntype FormDetailResponse = components['schemas']['FormDetailResponse'];\ntype FormDefinitionResponse = components['schemas']['FormDefinitionResponse'];\ntype FormListResponse = components['schemas']['FormListResponse'];\ntype FormSectionResponse = components['schemas']['FormSectionResponse'];\ntype FormFieldResponse = components['schemas']['FormFieldResponse'];\ntype ResponseDetailResponse = components['schemas']['ResponseDetailResponse'];\ntype ResponsesListResponse = components['schemas']['ResponsesListResponse'];\ntype TripFormsListResponse = components['schemas']['TripFormsListResponse'];\ntype CrossModuleAnswersResponse = components['schemas']['CrossModuleAnswersResponse'];\ntype CompletionMatrixResponse = components['schemas']['CompletionMatrixResponse'];\ntype DispatchResultResponse = components['schemas']['DispatchResultResponse'];\ntype BindingsListResponse = components['schemas']['BindingsListResponse'];\ntype AggregateResponse = components['schemas']['AggregateResponse'];\n\ntype CreateFormRequest = components['schemas']['CreateFormRequest'];\ntype PatchFormRequest = components['schemas']['PatchFormRequest'];\ntype CloneFormRequest = components['schemas']['CloneFormRequest'];\ntype ReorderFormRequest = components['schemas']['ReorderFormRequest'];\ntype CreateFormSectionRequest = components['schemas']['CreateFormSectionRequest'];\ntype PatchFormSectionRequest = components['schemas']['PatchFormSectionRequest'];\ntype CreateFormFieldRequest = components['schemas']['CreateFormFieldRequest'];\ntype PatchFormFieldRequest = components['schemas']['PatchFormFieldRequest'];\ntype ExportFormResponsesRequest = components['schemas']['ExportFormResponsesRequest'];\ntype DispatchFormRequest = components['schemas']['DispatchFormRequest'];\ntype ManagerCreateFormResponseRequest = components['schemas']['ManagerCreateFormResponseRequest'];\ntype FormResponseResponse = components['schemas']['FormResponseResponse'];\n\n// --- forms.{create,list,get,patch,delete} -----------------------------------\n\nexport interface CreateFormOptions extends CreateFormRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ListFormsOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchFormOptions extends PatchFormRequest {\n readonly formId: string;\n /** See this file's header — required, builds `If-Match` itself. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteFormOptions {\n readonly formId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\n// --- forms.{archive,unarchive,publish,close,reopen,clone,reorder} ----------\n\nexport interface ArchiveFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UnarchiveFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PublishFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CloseFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReopenFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CloneFormOptions extends CloneFormRequest {\n readonly formId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReorderFormOptions extends ReorderFormRequest {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- forms.sections / forms.fields ------------------------------------------\n\nexport interface CreateFormSectionOptions extends CreateFormSectionRequest {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchFormSectionOptions extends PatchFormSectionRequest {\n readonly formId: string;\n readonly sectionId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteFormSectionOptions {\n readonly formId: string;\n readonly sectionId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface FormSectionsResource {\n /** `POST /api/v1/forms/{formId}/sections`. */\n create(options: CreateFormSectionOptions): Promise<KaafilResponse<FormSectionResponse>>;\n /** `PATCH /api/v1/forms/{formId}/sections/{sectionId}`. */\n patch(options: PatchFormSectionOptions): Promise<KaafilResponse<FormSectionResponse>>;\n /** `DELETE /api/v1/forms/{formId}/sections/{sectionId}` — cascades its\n * fields. See this file's header for the `data: false` response shape. */\n delete(options: DeleteFormSectionOptions): Promise<KaafilResponse<false>>;\n}\n\nexport interface CreateFormFieldOptions extends CreateFormFieldRequest {\n readonly formId: string;\n readonly sectionId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchFormFieldOptions extends PatchFormFieldRequest {\n readonly formId: string;\n readonly fieldId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteFormFieldOptions {\n readonly formId: string;\n readonly fieldId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface FormFieldsResource {\n /** `POST /api/v1/forms/{formId}/sections/{sectionId}/fields`. */\n create(options: CreateFormFieldOptions): Promise<KaafilResponse<FormFieldResponse>>;\n /** `PATCH /api/v1/forms/{formId}/fields/{fieldId}`. */\n patch(options: PatchFormFieldOptions): Promise<KaafilResponse<FormFieldResponse>>;\n /** `DELETE /api/v1/forms/{formId}/fields/{fieldId}`. See this file's\n * header for the `data: false` response shape. */\n delete(options: DeleteFormFieldOptions): Promise<KaafilResponse<false>>;\n}\n\n// --- forms.aggregate ---------------------------------------------------------\n\ntype GetFormAggregateQuery = NonNullable<operations['getFormAggregate']['parameters']['query']>;\n\nexport interface ReadFormAggregateOptions extends GetFormAggregateQuery {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- forms.responses -----------------------------------------------------------\n\nexport interface ReadFormResponseOptions {\n readonly formId: string;\n readonly responseId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ExportFormResponsesOptions extends ExportFormResponsesRequest {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFormConsentReceiptOptions {\n readonly responseId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface FormResponsesResource {\n /** `GET /api/v1/forms/{formId}/responses/{responseId}` — the full answer\n * set, plus staleness flags against the CURRENT form version\n * (`formVersionNow`/`definitionChangedSince`/`staleAnswers`). */\n get(options: ReadFormResponseOptions): Promise<KaafilResponse<ResponseDetailResponse>>;\n /** `POST /api/v1/forms/{formId}/responses/export` — the CSV or PDF file\n * itself, as bytes. See this file's header for why this is a\n * `KaafilBinaryResponse` and not an envelope. */\n export(options: ExportFormResponsesOptions): Promise<KaafilBinaryResponse>;\n /** `GET /api/v1/forms/responses/{responseId}/consent-receipt` — the receipt\n * PDF as bytes. See this file's header for why this one route carries no\n * `formId` in its path, and why it answers bytes. */\n consentReceipt(options: ReadFormConsentReceiptOptions): Promise<KaafilBinaryResponse>;\n}\n\n// --- forms.bindings ------------------------------------------------------------\n\nexport interface ListFormBindingsOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface FormBindingsResource {\n /** `GET /api/v1/forms/bindings` — the closed catalog of profile/CRM keys\n * a field's `binding` may target, with `optionSet` for the ones that\n * resolve to a fixed choice list. */\n list(options?: ListFormBindingsOptions): Promise<KaafilResponse<BindingsListResponse>>;\n}\n\n// --- forms.trip ------------------------------------------------------------------\n\nexport interface ListTripFormsOptions {\n readonly tripRef: string;\n readonly phase?: components['schemas']['FormDetailResponse']['phase'];\n /** The delta cursor: a previous response's own `meta.serverTime`. Omit\n * for the full live set. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFormsCrossModuleAnswersOptions {\n readonly tripRef: string;\n /** Comma-separated binding keys (`bindings.list()`'s own `key` column) to\n * resolve — the wire shape is one query string, not an array; this SDK\n * does not join one for you, since the spec itself types `keys` as a\n * single string. */\n readonly keys: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFormsCompletionMatrixOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface DispatchFormOptions extends DispatchFormRequest {\n readonly tripRef: string;\n readonly formId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ManagerCreateFormResponseOptions extends ManagerCreateFormResponseRequest {\n readonly tripRef: string;\n readonly formId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\ntype ListTripFormResponsesQuery = NonNullable<\n operations['listTripFormResponses']['parameters']['query']\n>;\n\nexport interface ListTripFormResponsesOptions extends Omit<ListTripFormResponsesQuery, 'since'> {\n readonly tripRef: string;\n readonly formId: string;\n /** The delta cursor: a previous response's own `meta.serverTime`. Omit\n * for the full live set. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripFormResponsesResource {\n /** `POST /api/v1/trips/{ref}/forms/{formId}/responses` — on-behalf\n * capture. Accepts a manager session, an API key OR an agency-admin\n * session; this comment claimed `managerAuth`-only and was wrong even\n * before the trip-scoped reads were widened — the route has carried the\n * triple all along, which is exactly why the read gap beside it was\n * worth closing.\n * `startNew` forces a fresh response even under `responsePolicy:\n * 'SINGLE'`, where the form would otherwise resume the traveller's one\n * open response. */\n create(options: ManagerCreateFormResponseOptions): Promise<KaafilResponse<FormResponseResponse>>;\n /** `GET /api/v1/trips/{ref}/forms/{formId}/responses`. */\n list(options: ListTripFormResponsesOptions): Promise<KaafilResponse<ResponsesListResponse>>;\n}\n\nexport interface ListTravellerFormResponsesOptions {\n readonly tripRef: string;\n /** A `tripTravellerId` or the traveller's own `travellerId` — the engine\n * resolves either the same way `responses.create`'s `travellerRef` does. */\n readonly travellerRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripTravellerResponsesResource {\n /** `GET /api/v1/trips/{ref}/travellers/{travellerRef}/forms/responses` —\n * one traveller's `FormResponse` rows across every form on the trip, the\n * cross-form read `TripFormResponsesResource.list` cannot give you since\n * that one is scoped to a single `formId`. */\n list(options: ListTravellerFormResponsesOptions): Promise<KaafilResponse<ResponsesListResponse>>;\n}\n\nexport interface FormsTripResource {\n /** `GET /api/v1/trips/{ref}/forms` — this trip's applicable forms, each\n * with its resolved open/close `window` and `dispatched`/`submitted`\n * counts. */\n list(options: ListTripFormsOptions): Promise<KaafilResponse<TripFormsListResponse>>;\n /** `GET /api/v1/trips/{ref}/forms/answers` — see this file's header for\n * the open, `?keys=`-shaped response. */\n answers(\n options: ReadFormsCrossModuleAnswersOptions,\n ): Promise<KaafilResponse<CrossModuleAnswersResponse>>;\n /** `GET /api/v1/trips/{ref}/forms/completion` — per-form dispatched/\n * submitted/total counts across the trip's whole forms set. */\n completion(\n options: ReadFormsCompletionMatrixOptions,\n ): Promise<KaafilResponse<CompletionMatrixResponse>>;\n /** `POST /api/v1/trips/{ref}/forms/{formId}/dispatch` — an explicit send\n * outside the form's own `dispatchMode: 'JOURNEY'` trigger; `reason`\n * defaults to `'manual'`. */\n dispatch(options: DispatchFormOptions): Promise<KaafilResponse<DispatchResultResponse>>;\n readonly responses: TripFormResponsesResource;\n readonly travellerResponses: TripTravellerResponsesResource;\n}\n\n// --- forms -------------------------------------------------------------------\n\nexport interface FormsResource {\n /** `POST /api/v1/agencies/{ref}/forms` — authors a new definition\n * (`DRAFT`). */\n create(options: CreateFormOptions): Promise<KaafilResponse<FormDetailResponse>>;\n /** `GET /api/v1/agencies/{ref}/forms` — the agency's whole catalog. */\n list(options: ListFormsOptions): Promise<KaafilResponse<FormListResponse>>;\n /** `GET /api/v1/forms/{formId}` — definition detail: sections + fields +\n * resolved options. */\n get(options: ReadFormOptions): Promise<KaafilResponse<FormDetailResponse>>;\n /** `PATCH /api/v1/forms/{formId}`. See this file's header for the\n * required `version`. */\n patch(options: PatchFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `DELETE /api/v1/forms/{formId}`. See this file's header for the\n * required `version` and the `data: false` response shape. */\n delete(options: DeleteFormOptions): Promise<KaafilResponse<false>>;\n /** `POST /api/v1/forms/{formId}/archive`. */\n archive(options: ArchiveFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/unarchive`. */\n unarchive(options: UnarchiveFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/publish` — `DRAFT` → `ACTIVE`. */\n publish(options: PublishFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/close`. */\n close(options: CloseFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/reopen` — only within `reopenDays` of\n * closing. */\n reopen(options: ReopenFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/clone` — a new `DRAFT` copy under `key`. */\n clone(options: CloneFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/reorder` — sets every section's and\n * field's `sortOrder` in one call. See this file's header for the\n * `data: false` response shape. */\n reorder(options: ReorderFormOptions): Promise<KaafilResponse<false>>;\n readonly sections: FormSectionsResource;\n readonly fields: FormFieldsResource;\n /** `GET /api/v1/forms/{formId}/aggregate` — see this file's header for\n * the open `AggregateResponse` payload. */\n aggregate(options: ReadFormAggregateOptions): Promise<KaafilResponse<AggregateResponse>>;\n readonly responses: FormResponsesResource;\n readonly bindings: FormBindingsResource;\n readonly trip: FormsTripResource;\n}\n\nexport function createFormsResource(client: KaafilHttpClient): FormsResource {\n return {\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<FormDetailResponse>({\n method: 'POST',\n operationId: OperationId.CreateForm,\n path: '/api/v1/agencies/{ref}/forms',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { agencyRef, signal } = options;\n return client.execute<FormListResponse>({\n method: 'GET',\n operationId: OperationId.ListForms,\n path: '/api/v1/agencies/{ref}/forms',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async get(options) {\n const { formId, signal } = options;\n return client.execute<FormDetailResponse>({\n method: 'GET',\n operationId: OperationId.GetForm,\n path: '/api/v1/forms/{formId}',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { formId, version, signal, ...body } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchForm,\n path: '/api/v1/forms/{formId}',\n pathParams: { formId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async delete(options) {\n const { formId, version, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteForm,\n path: '/api/v1/forms/{formId}',\n pathParams: { formId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async archive(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.ArchiveForm,\n path: '/api/v1/forms/{formId}/archive',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async unarchive(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.UnarchiveForm,\n path: '/api/v1/forms/{formId}/unarchive',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async publish(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.PublishForm,\n path: '/api/v1/forms/{formId}/publish',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async close(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.CloseForm,\n path: '/api/v1/forms/{formId}/close',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reopen(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.ReopenForm,\n path: '/api/v1/forms/{formId}/reopen',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async clone(options) {\n const { formId, idempotencyKey, signal, ...body } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.CloneForm,\n path: '/api/v1/forms/{formId}/clone',\n pathParams: { formId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reorder(options) {\n const { formId, signal, ...body } = options;\n return client.execute<false>({\n method: 'POST',\n operationId: OperationId.ReorderForm,\n path: '/api/v1/forms/{formId}/reorder',\n pathParams: { formId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n sections: {\n async create(options) {\n const { formId, signal, ...body } = options;\n return client.execute<FormSectionResponse>({\n method: 'POST',\n operationId: OperationId.CreateFormSection,\n path: '/api/v1/forms/{formId}/sections',\n pathParams: { formId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { formId, sectionId, version, signal, ...body } = options;\n return client.execute<FormSectionResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchFormSection,\n path: '/api/v1/forms/{formId}/sections/{sectionId}',\n pathParams: { formId, sectionId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async delete(options) {\n const { formId, sectionId, version, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteFormSection,\n path: '/api/v1/forms/{formId}/sections/{sectionId}',\n pathParams: { formId, sectionId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n fields: {\n async create(options) {\n const { formId, sectionId, signal, ...body } = options;\n return client.execute<FormFieldResponse>({\n method: 'POST',\n operationId: OperationId.CreateFormField,\n path: '/api/v1/forms/{formId}/sections/{sectionId}/fields',\n pathParams: { formId, sectionId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { formId, fieldId, version, signal, ...body } = options;\n return client.execute<FormFieldResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchFormField,\n path: '/api/v1/forms/{formId}/fields/{fieldId}',\n pathParams: { formId, fieldId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async delete(options) {\n const { formId, fieldId, version, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteFormField,\n path: '/api/v1/forms/{formId}/fields/{fieldId}',\n pathParams: { formId, fieldId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n async aggregate(options) {\n const { formId, signal, ...query } = options;\n return client.execute<AggregateResponse>({\n method: 'GET',\n operationId: OperationId.GetFormAggregate,\n path: '/api/v1/forms/{formId}/aggregate',\n pathParams: { formId },\n query,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n responses: {\n async get(options) {\n const { formId, responseId, signal } = options;\n return client.execute<ResponseDetailResponse>({\n method: 'GET',\n operationId: OperationId.GetFormResponse,\n path: '/api/v1/forms/{formId}/responses/{responseId}',\n pathParams: { formId, responseId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async export(options) {\n const { formId, signal, ...body } = options;\n return client.executeBinary({\n method: 'POST',\n operationId: OperationId.ExportFormResponses,\n path: '/api/v1/forms/{formId}/responses/export',\n pathParams: { formId },\n body,\n // Follows the requested format rather than being hardcoded: the\n // engine branches on `body.format` and sets the matching\n // `Content-Type` (`forms.controller.ts#exportResponses`).\n accept: body.format === 'csv' ? 'text/csv' : 'application/pdf',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async consentReceipt(options) {\n const { responseId, signal } = options;\n return client.executeBinary({\n method: 'GET',\n operationId: OperationId.GetFormConsentReceipt,\n path: '/api/v1/forms/responses/{responseId}/consent-receipt',\n pathParams: { responseId },\n accept: 'application/pdf',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n bindings: {\n async list(options = {}) {\n const { signal } = options;\n return client.execute<BindingsListResponse>({\n method: 'GET',\n operationId: OperationId.ListFormBindings,\n path: '/api/v1/forms/bindings',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n trip: {\n async list(options) {\n const { tripRef, phase, since, signal } = options;\n return client.execute<TripFormsListResponse>({\n method: 'GET',\n operationId: OperationId.ListTripForms,\n path: '/api/v1/trips/{ref}/forms',\n pathParams: { ref: tripRef },\n query: { phase, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async answers(options) {\n const { tripRef, keys, signal } = options;\n return client.execute<CrossModuleAnswersResponse>({\n method: 'GET',\n operationId: OperationId.GetFormsCrossModuleAnswers,\n path: '/api/v1/trips/{ref}/forms/answers',\n pathParams: { ref: tripRef },\n query: { keys },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async completion(options) {\n const { tripRef, signal } = options;\n return client.execute<CompletionMatrixResponse>({\n method: 'GET',\n operationId: OperationId.GetFormsCompletionMatrix,\n path: '/api/v1/trips/{ref}/forms/completion',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async dispatch(options) {\n const { tripRef, formId, idempotencyKey, signal, ...body } = options;\n return client.execute<DispatchResultResponse>({\n method: 'POST',\n operationId: OperationId.DispatchForm,\n path: '/api/v1/trips/{ref}/forms/{formId}/dispatch',\n pathParams: { ref: tripRef, formId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n responses: {\n async create(options) {\n const { tripRef, formId, idempotencyKey, signal, ...body } = options;\n return client.execute<FormResponseResponse>({\n method: 'POST',\n operationId: OperationId.ManagerCreateFormResponse,\n path: '/api/v1/trips/{ref}/forms/{formId}/responses',\n pathParams: { ref: tripRef, formId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { tripRef, formId, since, signal, ...filters } = options;\n return client.execute<ResponsesListResponse>({\n method: 'GET',\n operationId: OperationId.ListTripFormResponses,\n path: '/api/v1/trips/{ref}/forms/{formId}/responses',\n pathParams: { ref: tripRef, formId },\n query: { ...filters, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n travellerResponses: {\n async list(options) {\n const { tripRef, travellerRef, signal } = options;\n return client.execute<ResponsesListResponse>({\n method: 'GET',\n operationId: OperationId.ListTravellerFormResponses,\n path: '/api/v1/trips/{ref}/travellers/{travellerRef}/forms/responses',\n pathParams: { ref: tripRef, travellerRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n },\n };\n}\n","/**\n * `itinerary` — the day cards and their ordered items, plus the change log.\n * `architecture/08-sdk.md §4`.\n *\n * EVERY operation here — both reads AND all five writes — accepts an API key,\n * a manager session OR an agency-admin session, never an AND; the consumer\n * never chooses which, `../auth/credentials.ts`'s `CredentialResolver` picks\n * whichever scheme the configured credential satisfies.\n *\n * This block previously said \"Every WRITE here is `managerAuth`-only: the\n * itinerary is edited on the ground, and an API-key write answers `401`.\" That\n * is no longer true and is corrected rather than softened, because it is the\n * sentence a reader would act on. `itinerary.routes.ts` now declares\n * `auth: ['manager', 'apiKey', 'agencyAdmin']` on all five writes — the same\n * triple the reads already carried — and `../generated/security.ts` agrees\n * (`addItineraryItem`, `patchItineraryItem`, `deleteItineraryItem`,\n * `reorderItineraryItem` and `patchItineraryDay` each list all three schemes).\n * The engine's own router header carries the argument: the agency knob FRD §9\n * describes (`itinerary.adminEditing`) has no flag-catalog key to live in, so\n * the widening landed ahead of a gate that has nothing to switch off. A\n * COORDINATOR-role manager still reads 200 and is refused every write with\n * `422 READ_ONLY_ROLE`, which is a role check on the SESSION, not a scheme.\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so `items.patch` (a trip ref AND an item id) and\n * `days.patch` (a trip ref AND a day index) can't be called with their\n * arguments swapped.\n *\n * `read` is one operation with three modes, because OpenAPI keys an operation\n * by (path, method) and all three are `GET /trips/{ref}/itinerary`: the full\n * aggregate, `?dayIndex=` for one day, and `?since=` for a delta. The two\n * compose. For the delta mode, drive `since` through\n * `../delta/cursor.ts`'s `createDeltaCursor` rather than by hand — that file's\n * header is the argument for why any other cursor loses rows.\n */\n\nimport {\n type DateTimeInput,\n normalizeDateTimeInput,\n normalizeNullableDateTimeInput,\n} from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype ItineraryReadResponse = components['schemas']['ItineraryReadResponse'];\ntype ItineraryDayResponse = components['schemas']['ItineraryDayResponse'];\ntype ItineraryItemResponse = components['schemas']['ItineraryItemResponse'];\ntype ItineraryItemTombstoneResponse = components['schemas']['ItineraryItemTombstoneResponse'];\ntype ItineraryReorderResponse = components['schemas']['ItineraryReorderResponse'];\ntype ItineraryChangeLogEntryResponse = components['schemas']['ItineraryChangeLogEntryResponse'];\ntype AddItineraryItemRequest = components['schemas']['AddItineraryItemRequest'];\ntype PatchItineraryItemRequest = components['schemas']['PatchItineraryItemRequest'];\ntype ReorderItineraryItemRequest = components['schemas']['ReorderItineraryItemRequest'];\ntype PatchItineraryDayRequest = components['schemas']['PatchItineraryDayRequest'];\n\n/**\n * One row of `read`'s `items[]`: a live item, or the tombstone for one deleted\n * since the cursor. Aliased off the response type rather than restated, so the\n * union stays whatever the contract says it is.\n *\n * Named and exported because a consumer writing a render function over\n * `items` has to name its parameter, and the union is the whole point — see\n * `../delta/cursor.ts`'s `isTombstone`.\n */\nexport type ItineraryItemDeltaRow = ItineraryReadResponse['items'][number];\n\n// --- date-time widening --------------------------------------------------\n//\n// `isoDate`, `startTime` and `endTime` are `string` (`Format: date-time`) in\n// the generated schema, because the schema is a faithful mirror of the spec\n// and the wire format really is a string. The `*Options` types below widen\n// exactly those fields to `DateTimeInput` (see `../datetime`) by indexing off\n// the generated type and overriding — never restating a request body by hand —\n// so a spec change to any other field flows through untouched. The factory\n// normalizes back down to `string` before the body reaches the wire.\n//\n// `startTime`/`endTime` widen to `DateTimeInput | null`, not just\n// `DateTimeInput`: `null` is how a manager CLEARS a time that was set, and it\n// is distinct from omitting the field. `../datetime.ts`'s\n// `normalizeNullableDateTimeInput` carries that argument.\n\n// --- itinerary.read ----------------------------------------------------------\n\nexport interface ReadItineraryOptions {\n readonly tripRef: string;\n /** Narrows the same shape to one day. 0-based, as `days[].dayIndex` reports it. */\n readonly dayIndex?: number;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and nothing\n * else. Omit it for the full aggregate. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the boundary is the one\n * thing that silently loses rows, and that module owns it.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- itinerary.items ----------------------------------------------------------\n\nexport interface AddItineraryItemOptions\n extends Omit<AddItineraryItemRequest, 'isoDate' | 'startTime' | 'endTime'> {\n readonly tripRef: string;\n /**\n * Which day the item belongs to, as a date. The engine resolves it to a day\n * index in the TRIP's timezone and find-or-creates the day — a client never\n * computes a day index itself, and must not, because the answer depends on a\n * timezone the client may not be in.\n */\n readonly isoDate: DateTimeInput;\n readonly startTime?: DateTimeInput | null;\n readonly endTime?: DateTimeInput | null;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchItineraryItemOptions\n extends Omit<PatchItineraryItemRequest, 'startTime' | 'endTime'> {\n readonly tripRef: string;\n readonly itemId: string;\n readonly startTime?: DateTimeInput | null;\n readonly endTime?: DateTimeInput | null;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this method\n * makes forgetting it impossible instead of merely discouraged. Pass the\n * `version` from the item as last read. The SDK builds the `If-Match` header\n * itself; never set it in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteItineraryItemOptions {\n readonly tripRef: string;\n readonly itemId: string;\n /** See `PatchItineraryItemOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReorderItineraryItemOptions extends ReorderItineraryItemRequest {\n readonly tripRef: string;\n readonly itemId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ItineraryItemsResource {\n /**\n * `POST …/itinerary/items` — APPENDS at the tail of its day.\n *\n * This is the one write in the ingest path that is not an upsert, and the\n * asymmetry is worth stating because everything around it is. `trips.upsert`,\n * `travellers.pushManifest` and `managers.upsert` are all safe to replay —\n * push the same payload twice and the second is answered `ignored_stale`.\n * Call this twice with the same title and you get TWO items on that day.\n *\n * ── WHY A RETRY DOES NOT SAVE YOU ──────────────────────────────────────────\n *\n * `Idempotency-Key` protects the TRANSPORT: the SDK mints one per call\n * (`../http/client.ts`'s `execute()`), so a socket that dies after the server\n * committed cannot create the item twice on the automatic retry.\n *\n * It does NOT protect an APPLICATION retry. Re-running your seeding script,\n * or catching an error and calling `add` again, is a NEW call with a NEW\n * generated key, and the server appends again. The auto-minting is what makes\n * this easy to miss — the safety is real and it is guarding a different thing.\n *\n * ── WHAT TO DO INSTEAD ─────────────────────────────────────────────────────\n *\n * Either pass your own stable `idempotencyKey` derived from the content\n * (`newIdempotencyKey()` in `../idempotency.ts` explains the shape), or read\n * the day first with `itinerary.read()` and skip titles already on it. A\n * seeding script that runs more than once wants the second.\n */\n add(options: AddItineraryItemOptions): Promise<KaafilResponse<ItineraryItemResponse>>;\n patch(options: PatchItineraryItemOptions): Promise<KaafilResponse<ItineraryItemResponse>>;\n /**\n * Soft-deletes the item. Answers the TOMBSTONE — the same `_tombstone`\n * marker a later `?since=` pull would carry for it — rather than an empty\n * body, so the caller that issued the delete applies the identical drop to\n * its local store as one that learned about it from a delta.\n */\n remove(\n options: DeleteItineraryItemOptions,\n ): Promise<KaafilResponse<ItineraryItemTombstoneResponse>>;\n /**\n * Moves the item to `index` within its own day; the index is clamped\n * server-side, and the whole day is re-stamped densely so two devices\n * replaying the same reorder land on identical `sortOrder` values.\n *\n * No `version` and no `If-Match`, deliberately: a reorder is last-write-wins\n * by design, and a conflict is resolved by re-reading the day (the response\n * already carries the day's full item list, in its new order).\n */\n reorder(options: ReorderItineraryItemOptions): Promise<KaafilResponse<ItineraryReorderResponse>>;\n}\n\n// --- itinerary.days -----------------------------------------------------------\n\nexport interface PatchItineraryDayOptions extends PatchItineraryDayRequest {\n readonly tripRef: string;\n /** 0-based, as `days[].dayIndex` reports it — the day's position, not its id. */\n readonly dayIndex: number;\n /** See `PatchItineraryItemOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ItineraryDaysResource {\n /** `PATCH …/itinerary/days/{dayIndex}` — the card title and the summary line. */\n patch(options: PatchItineraryDayOptions): Promise<KaafilResponse<ItineraryDayResponse>>;\n}\n\n// --- itinerary.changeLog ------------------------------------------------------\n\nexport interface ListItineraryChangeLogOptions {\n readonly tripRef: string;\n /** See `ReadItineraryOptions.since`. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ItineraryChangeLogResource {\n /** `GET …/itinerary/change-log` — the most recent entries, newest first.\n * Not cursor-paginated (no `cursor`/`limit` query params in the spec).\n * `performedByKind ∈ MANAGER|AGENCY_ADMIN|API_KEY|SYSTEM` and\n * `performedById` (nullable for `SYSTEM`) name WHO made each change — the\n * same actor-attribution pair now normalized onto this and eight other\n * response models, replacing the old free-form `actorType`/`actorId`\n * shape. */\n list(\n options: ListItineraryChangeLogOptions,\n ): Promise<KaafilResponse<readonly ItineraryChangeLogEntryResponse[]>>;\n}\n\n// --- itinerary ----------------------------------------------------------------\n\nexport interface ItineraryResource {\n read(options: ReadItineraryOptions): Promise<KaafilResponse<ItineraryReadResponse>>;\n readonly items: ItineraryItemsResource;\n readonly days: ItineraryDaysResource;\n readonly changeLog: ItineraryChangeLogResource;\n}\n\nexport function createItineraryResource(client: KaafilHttpClient): ItineraryResource {\n return {\n async read(options) {\n const { tripRef, dayIndex, since, signal } = options;\n return client.execute<ItineraryReadResponse>({\n method: 'GET',\n operationId: OperationId.ReadItinerary,\n path: '/api/v1/trips/{ref}/itinerary',\n pathParams: { ref: tripRef },\n query: { dayIndex, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n items: {\n async add(options) {\n const { tripRef, idempotencyKey, signal, isoDate, startTime, endTime, ...rest } = options;\n const body: AddItineraryItemRequest = {\n ...rest,\n isoDate: normalizeDateTimeInput(isoDate, 'isoDate'),\n ...(startTime !== undefined\n ? { startTime: normalizeNullableDateTimeInput(startTime, 'startTime') }\n : {}),\n ...(endTime !== undefined\n ? { endTime: normalizeNullableDateTimeInput(endTime, 'endTime') }\n : {}),\n };\n return client.execute<ItineraryItemResponse>({\n method: 'POST',\n operationId: OperationId.AddItineraryItem,\n path: '/api/v1/trips/{ref}/itinerary/items',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, itemId, version, signal, startTime, endTime, ...rest } = options;\n const body: PatchItineraryItemRequest = {\n ...rest,\n ...(startTime !== undefined\n ? { startTime: normalizeNullableDateTimeInput(startTime, 'startTime') }\n : {}),\n ...(endTime !== undefined\n ? { endTime: normalizeNullableDateTimeInput(endTime, 'endTime') }\n : {}),\n };\n return client.execute<ItineraryItemResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchItineraryItem,\n path: '/api/v1/trips/{ref}/itinerary/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, itemId, version, signal } = options;\n return client.execute<ItineraryItemTombstoneResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteItineraryItem,\n path: '/api/v1/trips/{ref}/itinerary/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reorder(options) {\n const { tripRef, itemId, idempotencyKey, signal, ...body } = options;\n return client.execute<ItineraryReorderResponse>({\n method: 'POST',\n operationId: OperationId.ReorderItineraryItem,\n path: '/api/v1/trips/{ref}/itinerary/items/{itemId}/reorder',\n pathParams: { ref: tripRef, itemId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n days: {\n async patch(options) {\n const { tripRef, dayIndex, version, signal, ...body } = options;\n return client.execute<ItineraryDayResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchItineraryDay,\n path: '/api/v1/trips/{ref}/itinerary/days/{dayIndex}',\n pathParams: { ref: tripRef, dayIndex },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n changeLog: {\n async list(options) {\n const { tripRef, since, signal } = options;\n return client.execute<readonly ItineraryChangeLogEntryResponse[]>({\n method: 'GET',\n operationId: OperationId.ReadItineraryChangeLog,\n path: '/api/v1/trips/{ref}/itinerary/change-log',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `journey` — get, capabilities, rebuild, runStep, and the agency-level\n * triggers (list, patch). `architecture/08-sdk.md §4`, amended `C-028`.\n *\n * `get`/`capabilities` accept an API key, a manager session, OR an\n * agency-admin session (`readJourney`/`readJourneyCapabilities` declare\n * `security: [{apiKeyAuth}, {managerAuth}, {agencyAdminAuth}]` — three\n * alternatives, `D-067`/`D-070`) — the consumer never chooses which;\n * `../auth/credentials.ts`'s `CredentialResolver` already picks whichever\n * scheme the configured credential satisfies. `triggers.list`/`triggers.patch`\n * accept the same set minus the API key\n * (`listJourneyTriggers`/`patchJourneyTrigger` declare `apiKeyAuth` OR\n * `agencyAdminAuth`).\n *\n * The trip-scoped methods (`get`, `capabilities`, `rebuild`, `runStep`) and\n * the agency-scoped ones (`triggers.list`, `triggers.patch`) use different\n * `{ref}` path parameters in the spec — a trip ref for the former, an agency\n * ref for the latter. Named `tripRef` / `agencyRef` respectively so the two\n * can never be confused for one another at a call site.\n *\n * `capabilities({ live: true })` (GAP-003) asks for a synchronous recompute\n * against live trip/entitlement state instead of the last persisted build —\n * never persisted itself. This is a query-param addition to\n * `readJourneyCapabilities`, not a new operation, so it carries the exact\n * same three-scheme accept list as a plain `capabilities()` call.\n * `rebuild` (`rebuildJourney`) was deliberately NOT widened to take `live` —\n * it stays `apiKeyAuth`-only, a full async rebuild, and remains a distinct\n * operation from this synchronous read.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { KaafilAbortError, KaafilNotFoundError, KaafilTimeoutError } from '../http/errors';\nimport { delayWithAbort } from '../http/retry';\nimport type { KaafilResponse } from '../types/meta';\n\ntype JourneyReadResponse = components['schemas']['JourneyReadResponse'];\ntype JourneyCapabilitiesResponse = components['schemas']['JourneyCapabilitiesResponse'];\ntype JourneyRebuildResponse = components['schemas']['JourneyRebuildResponse'];\ntype JourneyStepRunResponse = components['schemas']['JourneyStepRunResponse'];\ntype JourneyTriggerResponse = components['schemas']['JourneyTriggerResponse'];\ntype PatchJourneyTriggerRequest = components['schemas']['PatchJourneyTriggerRequest'];\n\n// --- journey.{get,capabilities,rebuild,runStep} -----------------------------\n\nexport interface ReadJourneyOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadJourneyCapabilitiesOptions {\n readonly tripRef: string;\n /**\n * `true` for a synchronous recompute against LIVE trip/entitlement state,\n * never persisted — GAP-003. Omit (or `false`) for the last persisted\n * build, the unchanged default. The spec declares `live` as the literal\n * string `\"true\"` (`operations['readJourneyCapabilities']['parameters']\n * ['query']`), never a JSON boolean — this method takes a real `boolean`\n * and does the `'true'` string conversion itself so a caller never has to\n * know that.\n */\n readonly live?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface RebuildJourneyOptions {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface RunJourneyStepOptions {\n readonly tripRef: string;\n readonly stepId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- journey.waitUntilReady ---------------------------------------------------\n\n/**\n * There is no ready endpoint — a journey build is enqueued by\n * `trips.upsert` plus a manager assignment, consumed asynchronously by a\n * background worker, and `journey.get` answers `404 RESOURCE_NOT_FOUND`\n * until it lands (`architecture/06-offline-first.md`). Every consumer was\n * hand-writing this same poll loop; this method owns it instead so a\n * caller cannot get it wrong by forgetting a deadline or by treating the\n * interim `404` as fatal.\n */\nexport interface WaitUntilJourneyReadyOptions {\n readonly tripRef: string;\n /** Total budget before giving up. Default ~60s — comfortably above a\n * healthy worker's build time, short enough not to hang a caller forever\n * behind a dead one. */\n readonly timeoutMs?: number;\n /** Delay between polls once a `404` says \"not yet\". Default ~1s. */\n readonly pollIntervalMs?: number;\n readonly signal?: AbortSignal;\n}\n\nconst DEFAULT_WAIT_UNTIL_READY_TIMEOUT_MS = 60_000;\nconst DEFAULT_WAIT_UNTIL_READY_POLL_INTERVAL_MS = 1_000;\n\n// --- journey.triggers ---------------------------------------------------------\n\nexport interface ListJourneyTriggersOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchJourneyTriggerOptions extends PatchJourneyTriggerRequest {\n readonly agencyRef: string;\n readonly key: string;\n /**\n * Disambiguates which row to patch when `key` exists under more than one\n * trip mode (`@@unique([agencyId, tripMode, key])` on the engine's own\n * `JourneyTrigger` — the seeded set does this for\n * `form.post-trip-feedback`). Omit when `key` is unique for this agency;\n * the engine falls back to a deterministic GROUP-first resolution in that\n * case, but a caller that already knows which `tripMode` row it read via\n * `triggers.list()` should always pass it back here rather than rely on\n * that fallback.\n */\n readonly tripMode?: 'GROUP' | 'PERSONALIZED';\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this\n * method makes forgetting it impossible instead of merely discouraged.\n * Pass the `version` from a trigger just read via `triggers.list()`. The\n * SDK builds the `If-Match` header itself; never set it in `headers`.\n */\n readonly version: number;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface JourneyTriggersResource {\n /** `GET /api/v1/agencies/{ref}/journey-triggers` — not cursor-paginated\n * (no `cursor`/`limit` query params in the spec); returns the full list. */\n list(\n options: ListJourneyTriggersOptions,\n ): Promise<KaafilResponse<readonly JourneyTriggerResponse[]>>;\n /** `PATCH /api/v1/agencies/{ref}/journey-triggers/{key}`. */\n patch(options: PatchJourneyTriggerOptions): Promise<KaafilResponse<JourneyTriggerResponse>>;\n}\n\n// --- journey -------------------------------------------------------------------\n\nexport interface JourneyResource {\n get(options: ReadJourneyOptions): Promise<KaafilResponse<JourneyReadResponse>>;\n capabilities(\n options: ReadJourneyCapabilitiesOptions,\n ): Promise<KaafilResponse<readonly JourneyCapabilitiesResponse[]>>;\n rebuild(options: RebuildJourneyOptions): Promise<KaafilResponse<JourneyRebuildResponse>>;\n runStep(options: RunJourneyStepOptions): Promise<KaafilResponse<JourneyStepRunResponse>>;\n /**\n * Polls `get` until the journey lands, resolving with the exact same\n * value `get` would — a drop-in replacement for \"get, but wait for it\".\n * A `404` is treated as \"not ready yet\"; every other typed error (a\n * `402`, `422`, `401`, …) propagates immediately, since retrying those\n * only burns the deadline on an outcome that will never change.\n */\n waitUntilReady(\n options: WaitUntilJourneyReadyOptions,\n ): Promise<KaafilResponse<JourneyReadResponse>>;\n readonly triggers: JourneyTriggersResource;\n}\n\nexport function createJourneyResource(client: KaafilHttpClient): JourneyResource {\n const resource: JourneyResource = {\n async get(options) {\n const { tripRef, signal } = options;\n return client.execute<JourneyReadResponse>({\n method: 'GET',\n operationId: OperationId.ReadJourney,\n path: '/api/v1/trips/{ref}/journey',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async capabilities(options) {\n const { tripRef, live, signal } = options;\n return client.execute<readonly JourneyCapabilitiesResponse[]>({\n method: 'GET',\n operationId: OperationId.ReadJourneyCapabilities,\n path: '/api/v1/trips/{ref}/journey/capabilities',\n pathParams: { ref: tripRef },\n ...(live === true ? { query: { live: 'true' as const } } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async rebuild(options) {\n const { tripRef, idempotencyKey, signal } = options;\n return client.execute<JourneyRebuildResponse>({\n method: 'POST',\n operationId: OperationId.RebuildJourney,\n path: '/api/v1/trips/{ref}/journey/rebuild',\n pathParams: { ref: tripRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async runStep(options) {\n const { tripRef, stepId, idempotencyKey, signal } = options;\n return client.execute<JourneyStepRunResponse>({\n method: 'POST',\n operationId: OperationId.RunJourneyStep,\n path: '/api/v1/trips/{ref}/journey/steps/{stepId}/run',\n pathParams: { ref: tripRef, stepId },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n async waitUntilReady(options) {\n const {\n tripRef,\n timeoutMs = DEFAULT_WAIT_UNTIL_READY_TIMEOUT_MS,\n pollIntervalMs = DEFAULT_WAIT_UNTIL_READY_POLL_INTERVAL_MS,\n signal,\n } = options;\n const deadlineAt = Date.now() + timeoutMs;\n\n for (;;) {\n try {\n return await resource.get({ tripRef, ...(signal !== undefined ? { signal } : {}) });\n } catch (error) {\n // Everything except \"not ready yet\" is terminal: a 402, 422 or\n // 401 will never become ready, so propagate it immediately\n // rather than spending the caller's deadline retrying it.\n if (!(error instanceof KaafilNotFoundError)) {\n throw error;\n }\n\n const remainingMs = deadlineAt - Date.now();\n if (remainingMs <= 0) {\n throw new KaafilTimeoutError(\n `journey.waitUntilReady timed out after ${String(timeoutMs)}ms waiting for trip ` +\n `\"${tripRef}\" to become ready. The most likely cause is that the background worker ` +\n 'that consumes the build queue is not running against this engine.',\n { cause: error },\n );\n }\n\n try {\n await delayWithAbort(Math.min(pollIntervalMs, remainingMs), signal);\n } catch (sleepError) {\n // `delayWithAbort` only ever rejects because `signal` fired —\n // normalize to the same `KaafilAbortError` a `get()` abort\n // would have thrown, so a caller branching on error type sees\n // one shape regardless of which tick the abort landed on.\n throw new KaafilAbortError('Request aborted', { cause: sleepError });\n }\n }\n }\n },\n\n triggers: {\n async list(options) {\n const { agencyRef, signal } = options;\n return client.execute<readonly JourneyTriggerResponse[]>({\n method: 'GET',\n operationId: OperationId.ListJourneyTriggers,\n path: '/api/v1/agencies/{ref}/journey-triggers',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { agencyRef, key, tripMode, version, idempotencyKey, signal, ...body } = options;\n return client.execute<JourneyTriggerResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchJourneyTrigger,\n path: '/api/v1/agencies/{ref}/journey-triggers/{key}',\n pathParams: { ref: agencyRef, key },\n ...(tripMode !== undefined ? { query: { tripMode } } : {}),\n body,\n headers: { 'If-Match': String(version) },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n\n return resource;\n}\n","/**\n * `managerToday` — `GET /trips/{ref}/manager/today`, the phase-and-day-aware\n * aggregate a manager operating a trip in the field needs, so they do not\n * have to call `itinerary`, `pickups`, `rooming`, `checklists` and `seating`\n * separately and merge them on the phone. `architecture/08-sdk.md §4`.\n *\n * One read, `readManagerToday` — declares the same three-alternative auth set\n * `itinerary.read` does (an API key, a manager session OR an agency-admin\n * session), because it is itself a read composing five other already-gated\n * reads, never a write.\n *\n * `data.kind` discriminates the response: `'idle'` (the trip is not\n * `ON_TRIP` right now — nothing before departure or after close to report),\n * `'trip'`, or `'trek'` (`'trek'` carries every field `'trip'` does, plus its\n * own `trekPhase`). Narrow on `kind` before reading any of the\n * `trip`/`trek`-only fields — the response type already forces this.\n *\n * `itinerary`/`checklist`/`pickups`/`rooming`/`transport` are each\n * independently `null` when that domain's OWN capability is dark for the\n * agency, never a thrown error for the whole read — branch on `null`, not on\n * a catch.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\nexport type ManagerTodayResponse = components['schemas']['ManagerTodayResponse'];\n\n/** The `kind: 'idle'` reading, narrowed off the union. */\nexport type ManagerTodayIdle = Extract<ManagerTodayResponse, { kind: 'idle' }>;\n/** The `kind: 'trip'` reading, narrowed off the union. */\nexport type ManagerTodayTrip = Extract<ManagerTodayResponse, { kind: 'trip' }>;\n/** The `kind: 'trek'` reading, narrowed off the union — `ManagerTodayTrip`'s fields plus `trekPhase`. */\nexport type ManagerTodayTrek = Extract<ManagerTodayResponse, { kind: 'trek' }>;\n\nexport interface ReadManagerTodayOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ManagerTodayResource {\n read(options: ReadManagerTodayOptions): Promise<KaafilResponse<ManagerTodayResponse>>;\n}\n\nexport function createManagerTodayResource(client: KaafilHttpClient): ManagerTodayResource {\n return {\n async read(options) {\n const { tripRef, signal } = options;\n return client.execute<ManagerTodayResponse>({\n method: 'GET',\n operationId: OperationId.ReadManagerToday,\n path: '/api/v1/trips/{ref}/manager/today',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `pickups` — the stop list, reorder, manifest-by-pickup, assign/board and\n * the close/reopen policy. `architecture/08-sdk.md §4`.\n *\n * `list` and `manifestByPickup` accept a manager session, an agency-admin\n * session OR an API key (three alternatives, never an AND) — same for the\n * authoring writes `create`/`patch`/`remove`/`reorder`/`assign`/\n * `correctBoardStatus` (stop-list management an agency admin or a CRM can do\n * off the ground). Only the three ON-GROUND actions — `board`, `close`,\n * `reopen` — are `managerAuth`-only, the same split `seating`, `rooming` and\n * `itinerary` have and for the same reason: boarding a traveller or\n * closing/reopening a stop is a call made standing at the stop, not from an\n * office. Checked against `../generated/security.ts`'s `OPERATION_SECURITY`,\n * the source of truth.\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so `assign` (a trip ref AND a stop id) can't be called\n * with its arguments swapped.\n *\n * ── ONE `close` METHOD, TWO POLICIES, ONE CODE ──────────────────────────────\n *\n * `close()` is a single operation whichever `Trip.eventType` the trip carries\n * — never two endpoints and never two codes. On a `TRIP`, every `PENDING`\n * traveller must appear in `resolutions[]` with a terminal status, and\n * `confirm` is ignored; on a `TREK`, `resolutions[]` is optional and a short\n * close (`boardedCount < expectedCount`) needs `confirm: true` PLUS\n * `confirmedHeadCount`. Both branches answer the SAME `422 STOP_HAS_PENDING`\n * when they refuse — a TREK short-close refusal additionally carries\n * `details.requiresConfirm: true`, which is what tells a caller to show the\n * confirm sheet rather than the per-traveller resolver, and NOT a second\n * code. `details` is untyped at the transport boundary (the envelope\n * schema's own `additionalProperties: {}`), so read it defensively:\n * `error.details?.requiresConfirm === true`.\n *\n * `confirmedHeadCount` disagreeing with the actual count is FLAGGED\n * (`CloseResponse.headCountMismatch`), never blocking — \"a manager on a\n * trailhead can't wait forever.\"\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype PickupStopResponse = components['schemas']['PickupStopResponse'];\ntype PickupStopDeltaResponse = components['schemas']['PickupStopDeltaResponse'];\ntype PickupStopDeleteResponse = components['schemas']['PickupStopDeleteResponse'];\ntype ManifestByPickupResponse = components['schemas']['ManifestByPickupResponse'];\ntype AssignResponse = components['schemas']['AssignResponse'];\ntype ReassignResponse = components['schemas']['ReassignResponse'];\ntype ReassignPickupStopTravellersRequest =\n components['schemas']['ReassignPickupStopTravellersRequest'];\ntype BoardResponse = components['schemas']['BoardResponse'];\ntype CorrectPickupBoardStatusRequest = components['schemas']['CorrectPickupBoardStatusRequest'];\ntype CloseResponse = components['schemas']['CloseResponse'];\ntype ReopenResponse = components['schemas']['ReopenResponse'];\ntype CreatePickupStopRequest = components['schemas']['CreatePickupStopRequest'];\ntype PatchPickupStopRequest = components['schemas']['PatchPickupStopRequest'];\ntype ReorderPickupStopsRequest = components['schemas']['ReorderPickupStopsRequest'];\ntype AssignPickupTravellerRequest = components['schemas']['AssignPickupTravellerRequest'];\ntype BoardPickupTravellerRequest = components['schemas']['BoardPickupTravellerRequest'];\ntype ClosePickupStopRequest = components['schemas']['ClosePickupStopRequest'];\n\n/**\n * One row of `list`'s result: a live stop, or the tombstone for one deleted\n * since the cursor. Aliased off the response type rather than restated, so\n * the union stays whatever the contract says it is. See `../delta/cursor.ts`'s\n * `isTombstone`.\n */\nexport type PickupStopDeltaRow = PickupStopDeltaResponse;\n\n// --- date-time widening --------------------------------------------------\n//\n// `scheduledTime` is `string` (`Format: date-time`) in the generated schema,\n// because the schema is a faithful mirror of the spec and the wire format\n// really is a string. The `*Options` types below widen exactly that field to\n// `DateTimeInput` (see `../datetime`) by indexing off the generated type and\n// overriding — never restating a request body by hand. The factory\n// normalizes back down to `string` before the body reaches the wire.\n\n// --- pickups.list / pickups.manifestByPickup ---------------------------------\n\nexport interface ListPickupStopsOptions {\n readonly tripRef: string;\n /** Narrows to one stop kind. Omitted lists both `PICKUP` and `DROP`. */\n readonly kind?: components['schemas']['PickupStopResponse']['kind'];\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit it for the full list. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the boundary is the\n * one thing that silently loses rows, and that module owns it.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadManifestByPickupOptions {\n readonly tripRef: string;\n /** See `ListPickupStopsOptions.kind`. */\n readonly kind?: components['schemas']['PickupStopResponse']['kind'];\n readonly signal?: AbortSignal;\n}\n\n// --- pickups CRUD --------------------------------------------------------\n\nexport interface CreatePickupStopOptions extends Omit<CreatePickupStopRequest, 'scheduledTime'> {\n readonly tripRef: string;\n readonly scheduledTime: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchPickupStopOptions extends Omit<PatchPickupStopRequest, 'scheduledTime'> {\n readonly tripRef: string;\n readonly pointId: string;\n readonly scheduledTime?: DateTimeInput;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this\n * method makes forgetting it impossible instead of merely discouraged.\n * Pass the `version` from the stop as last read. The SDK builds the\n * `If-Match` header itself; never set it in `headers`.\n *\n * Changing `kind` while the stop holds assignments is refused with\n * `422 BUSINESS_RULE_VIOLATION` and `details.assignedCount` — reassign or\n * clear the stop first.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeletePickupStopOptions {\n readonly tripRef: string;\n readonly pointId: string;\n /** See `PatchPickupStopOptions.version` — same contract. */\n readonly version: number;\n /** Releases every assignment on this stop back to unassigned before\n * deleting it. Without it, a stop with assignments is refused. */\n readonly force?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReorderPickupStopsOptions extends ReorderPickupStopsRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- pickups.assign / pickups.board -------------------------------------------\n\nexport interface AssignPickupTravellerOptions extends AssignPickupTravellerRequest {\n readonly tripRef: string;\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReassignPickupStopTravellersOptions extends ReassignPickupStopTravellersRequest {\n readonly tripRef: string;\n /** The stop to move every live, not-yet-boarded traveller OFF of. */\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface BoardPickupTravellerOptions extends BoardPickupTravellerRequest {\n readonly tripRef: string;\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CorrectPickupBoardStatusOptions extends CorrectPickupBoardStatusRequest {\n readonly tripRef: string;\n readonly pointId: string;\n readonly travellerId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- pickups.close / pickups.reopen -------------------------------------------\n\nexport interface ClosePickupStopOptions extends ClosePickupStopRequest {\n readonly tripRef: string;\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReopenPickupStopOptions {\n readonly tripRef: string;\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- pickups -------------------------------------------------------------\n\nexport interface PickupsResource {\n /** `GET /api/v1/trips/{ref}/pickups`. With `?since=` the rows are\n * `PickupStopDeltaResponse` — a union with the tombstone, so the drop case\n * cannot be forgotten. Without one, no tombstone can appear. */\n list(options: ListPickupStopsOptions): Promise<KaafilResponse<readonly PickupStopDeltaRow[]>>;\n create(options: CreatePickupStopOptions): Promise<KaafilResponse<PickupStopResponse>>;\n patch(options: PatchPickupStopOptions): Promise<KaafilResponse<PickupStopResponse>>;\n remove(options: DeletePickupStopOptions): Promise<KaafilResponse<PickupStopDeleteResponse>>;\n reorder(\n options: ReorderPickupStopsOptions,\n ): Promise<KaafilResponse<readonly PickupStopResponse[]>>;\n /**\n * `POST …/pickups/{pointId}/assign` — puts one traveller on one stop. If\n * they were already on a different stop of the SAME `kind`, the move is one\n * atomic delete+create (R1: at most one `PICKUP` and one `DROP` per\n * traveller, enforced by a composite unique, not merely a service-layer\n * promise), and the response's `previousPickupPointId` names where they\n * moved from.\n */\n assign(options: AssignPickupTravellerOptions): Promise<KaafilResponse<AssignResponse>>;\n /**\n * `POST …/pickups/{pointId}/reassign` — the bulk, stop-level sibling of\n * `assign()`: moves every live, not-yet-boarded traveller off `pointId`\n * onto `toPickupPointId` in one call (FRD §8's \"delete a stop with\n * travellers on it\" flow — reassign the survivors first, then `remove()`\n * the now-empty stop). `toPickupPointId` must be a different, live stop of\n * the SAME `kind` — else `422 BUSINESS_RULE_VIOLATION`. A traveller already\n * `BOARDED` at the source stop is left there, not moved; the response's\n * `skippedBoardedCount` says how many, `movedCount` everyone else. Both\n * affected stops come back whole, same \"rebase without a follow-up read\"\n * convention as `assign()`.\n */\n reassign(options: ReassignPickupStopTravellersOptions): Promise<KaafilResponse<ReassignResponse>>;\n board(options: BoardPickupTravellerOptions): Promise<KaafilResponse<BoardResponse>>;\n /**\n * `PATCH …/pickups/{pointId}/board/{travellerId}` — amends or reverses a\n * board/no-show observation `board()` already recorded; it can never\n * ORIGINATE one. A still-`PENDING` row is refused with\n * `422 pickups.correctionRequiresObservation`. Accepts a manager session,\n * an agency-admin session, OR an API key — unlike `board()`, which is\n * `managerAuth`-only. Not `Idempotency-Key`- or `If-Match`-guarded: same\n * unversioned `setBoardStatus` write `board()` makes, and re-sending the\n * same corrected status is naturally idempotent.\n */\n correctBoardStatus(\n options: CorrectPickupBoardStatusOptions,\n ): Promise<KaafilResponse<BoardResponse>>;\n /** See this file's header for the close policy: one method, two branches\n * on `Trip.eventType`, one code (`STOP_HAS_PENDING`) either way. */\n close(options: ClosePickupStopOptions): Promise<KaafilResponse<CloseResponse>>;\n /** Flips `CLOSED → OPEN` and clears `closedAt`/`closedByManagerId` — there\n * is no `REOPENED` state. The next `close()` on this stop emits a fresh\n * CORRECTIVE `pickup.stop_closed` event, `reopened: true`. */\n reopen(options: ReopenPickupStopOptions): Promise<KaafilResponse<ReopenResponse>>;\n /** `GET …/manifest-by-pickup` — the roster grouped by stop, for a printed\n * or on-screen boarding sheet. Renders the same glyph/tone canon as\n * `rooming`'s and `seating`'s occupants — no second derivation. */\n manifestByPickup(\n options: ReadManifestByPickupOptions,\n ): Promise<KaafilResponse<ManifestByPickupResponse>>;\n}\n\nexport function createPickupsResource(client: KaafilHttpClient): PickupsResource {\n return {\n async list(options) {\n const { tripRef, kind, since, signal } = options;\n return client.execute<readonly PickupStopDeltaRow[]>({\n method: 'GET',\n operationId: OperationId.ListPickupStops,\n path: '/api/v1/trips/{ref}/pickups',\n pathParams: { ref: tripRef },\n query: { kind, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { tripRef, idempotencyKey, signal, scheduledTime, ...rest } = options;\n const body: CreatePickupStopRequest = {\n ...rest,\n scheduledTime: normalizeDateTimeInput(scheduledTime, 'scheduledTime'),\n };\n return client.execute<PickupStopResponse>({\n method: 'POST',\n operationId: OperationId.CreatePickupStop,\n path: '/api/v1/trips/{ref}/pickups',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, pointId, version, signal, scheduledTime, ...rest } = options;\n const body: PatchPickupStopRequest = {\n ...rest,\n ...(scheduledTime !== undefined\n ? { scheduledTime: normalizeDateTimeInput(scheduledTime, 'scheduledTime') }\n : {}),\n };\n return client.execute<PickupStopResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchPickupStop,\n path: '/api/v1/trips/{ref}/pickups/{pointId}',\n pathParams: { ref: tripRef, pointId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, pointId, version, force, signal } = options;\n return client.execute<PickupStopDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeletePickupStop,\n path: '/api/v1/trips/{ref}/pickups/{pointId}',\n pathParams: { ref: tripRef, pointId },\n query: { force },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reorder(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<readonly PickupStopResponse[]>({\n method: 'POST',\n operationId: OperationId.ReorderPickupStops,\n path: '/api/v1/trips/{ref}/pickups/reorder',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async assign(options) {\n const { tripRef, pointId, idempotencyKey, signal, ...body } = options;\n return client.execute<AssignResponse>({\n method: 'POST',\n operationId: OperationId.AssignPickupTraveller,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/assign',\n pathParams: { ref: tripRef, pointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reassign(options) {\n const { tripRef, pointId, idempotencyKey, signal, ...body } = options;\n return client.execute<ReassignResponse>({\n method: 'POST',\n operationId: OperationId.ReassignPickupStopTravellers,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/reassign',\n pathParams: { ref: tripRef, pointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async board(options) {\n const { tripRef, pointId, idempotencyKey, signal, ...body } = options;\n return client.execute<BoardResponse>({\n method: 'POST',\n operationId: OperationId.BoardPickupTraveller,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/board',\n pathParams: { ref: tripRef, pointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async correctBoardStatus(options) {\n const { tripRef, pointId, travellerId, signal, ...body } = options;\n return client.execute<BoardResponse>({\n method: 'PATCH',\n operationId: OperationId.CorrectPickupBoardStatus,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/board/{travellerId}',\n pathParams: { ref: tripRef, pointId, travellerId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async close(options) {\n const { tripRef, pointId, idempotencyKey, signal, ...body } = options;\n return client.execute<CloseResponse>({\n method: 'POST',\n operationId: OperationId.ClosePickupStop,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/close',\n pathParams: { ref: tripRef, pointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reopen(options) {\n const { tripRef, pointId, idempotencyKey, signal } = options;\n return client.execute<ReopenResponse>({\n method: 'POST',\n operationId: OperationId.ReopenPickupStop,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/reopen',\n pathParams: { ref: tripRef, pointId },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async manifestByPickup(options) {\n const { tripRef, kind, signal } = options;\n return client.execute<ManifestByPickupResponse>({\n method: 'GET',\n operationId: OperationId.ReadManifestByPickup,\n path: '/api/v1/trips/{ref}/manifest-by-pickup',\n pathParams: { ref: tripRef },\n query: { kind },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `rooming` — the board, stay windows, rooms, manual bed assignment and\n * auto-assign. `architecture/08-sdk.md §4`.\n *\n * `board.read` and `stayWindows.list` accept a manager session, an\n * agency-admin session OR an API key (three alternatives, never an AND); every\n * WRITE is `managerAuth`-only, the same split `itinerary` has and for the same\n * reason — rooming is decided on the ground.\n *\n * Rooming is a gated capability (`GROUP` trips only, behind the `rooming` plan\n * flag), so its refusals are ordinary typed errors a caller should expect:\n * `402` for a flag that is off, `422 CAPABILITY_UNAVAILABLE` on a\n * `PERSONALIZED` trip, `422 READ_ONLY_ROLE` for a COORDINATOR. See\n * `../http/errors.ts`.\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so `rooms.patch` (a trip ref AND a room id) and\n * `stayWindows.patch` (a trip ref AND a window id) can't be called with their\n * arguments swapped. The two child ids are named `roomId` and `windowId` after\n * the thing they identify, never both `id`.\n *\n * `HEURISTIC_SEVERITY` and the glyph/tone vocabulary a client needs to RENDER\n * this module's output are not here — they are not on the wire. See\n * `../rooming/vocabulary.ts`.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype RoomingBoardResponse = components['schemas']['RoomingBoardResponse'];\ntype RoomingStayWindowResponse = components['schemas']['RoomingStayWindowResponse'];\ntype RoomingStayWindowDeltaResponse = components['schemas']['RoomingStayWindowDeltaResponse'];\ntype RoomingRoomResponse = components['schemas']['RoomingRoomResponse'];\ntype RoomingDeleteResponse = components['schemas']['RoomingDeleteResponse'];\ntype RoomingAssignResponse = components['schemas']['RoomingAssignResponse'];\ntype RoomingAutoAssignResponse = components['schemas']['RoomingAutoAssignResponse'];\ntype CreateRoomingStayWindowRequest = components['schemas']['CreateRoomingStayWindowRequest'];\ntype PatchRoomingStayWindowRequest = components['schemas']['PatchRoomingStayWindowRequest'];\ntype CreateRoomingRoomRequest = components['schemas']['CreateRoomingRoomRequest'];\ntype PatchRoomingRoomRequest = components['schemas']['PatchRoomingRoomRequest'];\ntype AssignRoomingBedRequest = components['schemas']['AssignRoomingBedRequest'];\ntype AutoAssignRoomingRequest = components['schemas']['AutoAssignRoomingRequest'];\n\n/**\n * One row of the board's `rooms[]`: a live room, or the tombstone for one\n * deleted since the cursor. Aliased off the response type, never restated.\n */\nexport type RoomingRoomDeltaRow = RoomingBoardResponse['rooms'][number];\n\n/** One traveller's chip, wherever it appears — in a bed, or in `unassigned[]`. */\nexport type RoomingOccupant = RoomingBoardResponse['unassigned'][number];\n\n/**\n * `autoAssign`'s rules block, named so a caller can build one and hold it in a\n * variable. Indexed off the request type, so the three knobs stay whatever the\n * contract says they are.\n */\nexport type RoomingAutoAssignRules = NonNullable<AutoAssignRoomingRequest['rules']>;\n\n// --- date-time widening --------------------------------------------------\n//\n// A stay window's `startDate`/`endDate` are `string` (`Format: date-time`) in\n// the generated schema — a faithful mirror of the spec, where the wire format\n// really is a string. The `*Options` types below widen exactly those two\n// fields to `DateTimeInput` (see `../datetime`) by indexing off the generated\n// type and overriding — never restating a request body by hand. The factory\n// normalizes back down to `string` before the body reaches the wire.\n//\n// Nothing else on this surface takes a date: rooms, beds and assignments are\n// all identified by id and label.\n\n// --- rooming.board -------------------------------------------------------------\n\nexport interface ReadRoomingBoardOptions {\n readonly tripRef: string;\n /** Narrows the board to one stay window. Omitted reads every window. */\n readonly stayWindowId?: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and nothing\n * else. Omit it for the full board. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the boundary is the one\n * thing that silently loses rows, and that module owns it.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- rooming.stayWindows -------------------------------------------------------\n\nexport interface ListRoomingStayWindowsOptions {\n readonly tripRef: string;\n /** See `ReadRoomingBoardOptions.since`. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CreateRoomingStayWindowOptions\n extends Omit<CreateRoomingStayWindowRequest, 'startDate' | 'endDate'> {\n readonly tripRef: string;\n readonly startDate: DateTimeInput;\n /**\n * Half-open with `startDate`: a checkout date equal to the next window's\n * check-in is legal, because multi-hotel trips are contiguous by nature.\n * Overlap beyond that is refused with `422 BUSINESS_RULE_VIOLATION` and\n * `details.rule === 'stay_window_overlap'`.\n */\n readonly endDate: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchRoomingStayWindowOptions\n extends Omit<PatchRoomingStayWindowRequest, 'startDate' | 'endDate'> {\n readonly tripRef: string;\n readonly windowId: string;\n readonly startDate?: DateTimeInput;\n readonly endDate?: DateTimeInput;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this method\n * makes forgetting it impossible instead of merely discouraged. Pass the\n * `version` from the window as last read. The SDK builds the `If-Match`\n * header itself; never set it in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteRoomingStayWindowOptions {\n readonly tripRef: string;\n readonly windowId: string;\n /** See `PatchRoomingStayWindowOptions.version` — same contract. */\n readonly version: number;\n /**\n * Deleting a window that still has rooms with occupants is REFUSED\n * (`422 BUSINESS_RULE_VIOLATION`, `details.rule ===\n * 'stay_window_has_assignments'`) unless this is `true`, which also releases\n * the beds. A query param and never a body, because a DELETE body is not\n * reliably carried; an explicit opt-in and never the default, because the\n * refusal is the whole safety property — a manager who did not mean to empty\n * a hotel gets told, not obeyed.\n */\n readonly force?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface RoomingStayWindowsResource {\n /**\n * `GET …/rooming/stay-windows`. With `?since=` the rows are\n * `RoomingStayWindowDeltaResponse` — a union with the tombstone, so the drop\n * case cannot be forgotten (`../delta/cursor.ts`'s `isTombstone`). Without\n * one, no tombstone can appear: a cold read has nothing to drop.\n */\n list(\n options: ListRoomingStayWindowsOptions,\n ): Promise<KaafilResponse<readonly RoomingStayWindowDeltaResponse[]>>;\n create(\n options: CreateRoomingStayWindowOptions,\n ): Promise<KaafilResponse<RoomingStayWindowResponse>>;\n patch(options: PatchRoomingStayWindowOptions): Promise<KaafilResponse<RoomingStayWindowResponse>>;\n remove(options: DeleteRoomingStayWindowOptions): Promise<KaafilResponse<RoomingDeleteResponse>>;\n}\n\n// --- rooming.rooms -------------------------------------------------------------\n\nexport interface CreateRoomingRoomOptions extends CreateRoomingRoomRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchRoomingRoomOptions extends PatchRoomingRoomRequest {\n readonly tripRef: string;\n readonly roomId: string;\n /** See `PatchRoomingStayWindowOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteRoomingRoomOptions {\n readonly tripRef: string;\n readonly roomId: string;\n /** See `PatchRoomingStayWindowOptions.version` — same contract. */\n readonly version: number;\n /** See `DeleteRoomingStayWindowOptions.force` — same contract, one room's worth. */\n readonly force?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadRoomingRoomOptions {\n readonly tripRef: string;\n readonly roomId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface RoomingRoomsResource {\n /**\n * `GET …/rooming/rooms/{roomId}` — one room, whole: its synthesised beds,\n * their occupants and its notes. The same shape every write on this\n * resource already returns, narrowed to one room, for a room-detail screen\n * that does not need the whole board.\n */\n get(options: ReadRoomingRoomOptions): Promise<KaafilResponse<RoomingRoomResponse>>;\n create(options: CreateRoomingRoomOptions): Promise<KaafilResponse<RoomingRoomResponse>>;\n /**\n * Beds are synthesised from `capacity` (`A`..`H`, truncated), never stored,\n * so `beds[]` on the response is derived — dropping `capacity` below the\n * room's current occupancy is refused with `422 BUSINESS_RULE_VIOLATION` and\n * `details.rule === 'room_capacity_below_occupancy'` rather than silently\n * evicting whoever was in the last bed.\n */\n patch(options: PatchRoomingRoomOptions): Promise<KaafilResponse<RoomingRoomResponse>>;\n remove(options: DeleteRoomingRoomOptions): Promise<KaafilResponse<RoomingDeleteResponse>>;\n}\n\n// --- rooming.assign / rooming.autoAssign ---------------------------------------\n\nexport interface AssignRoomingBedOptions extends AssignRoomingBedRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AutoAssignRoomingOptions extends AutoAssignRoomingRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- rooming -------------------------------------------------------------------\n\nexport interface RoomingResource {\n /** `GET /api/v1/trips/{ref}/rooming` — windows, rooms with their beds, the\n * unassigned roster, and the summary counters. */\n read(options: ReadRoomingBoardOptions): Promise<KaafilResponse<RoomingBoardResponse>>;\n /**\n * `POST …/rooming/assign` — puts one traveller in one bed. `bedLabel: null`\n * un-assigns them. If the target bed is taken the occupant is displaced, and\n * the response names them in `displacedTravellerId` rather than leaving the\n * caller to diff two boards to notice a second person moved.\n */\n assign(options: AssignRoomingBedOptions): Promise<KaafilResponse<RoomingAssignResponse>>;\n /**\n * `POST …/rooming/auto-assign`. `dryRun: true` returns the plan without\n * writing it; `dryRun: false` returns the plan it actually applied. The two\n * are the SAME computation — the solver is pure and the only difference is\n * whether the result is also written — so a preview and its apply agree by\n * construction, and a client that stored the preview can diff it against the\n * applied plan to see whether the rooms moved underneath it.\n *\n * Every rule reports an outcome in `perRule`, including rules that had\n * nothing to do; a relaxation is never silent. How loudly to render each one\n * is `HEURISTIC_SEVERITY` in `../rooming/vocabulary.ts`. A traveller who got\n * no bed is in `unassigned[]` WITH a reason — absence from `plan` alone is\n * ambiguous, because a manually-pinned traveller is also absent and is fine.\n */\n autoAssign(options: AutoAssignRoomingOptions): Promise<KaafilResponse<RoomingAutoAssignResponse>>;\n readonly stayWindows: RoomingStayWindowsResource;\n readonly rooms: RoomingRoomsResource;\n}\n\nexport function createRoomingResource(client: KaafilHttpClient): RoomingResource {\n return {\n async read(options) {\n const { tripRef, stayWindowId, since, signal } = options;\n return client.execute<RoomingBoardResponse>({\n method: 'GET',\n operationId: OperationId.ReadRoomingBoard,\n path: '/api/v1/trips/{ref}/rooming',\n pathParams: { ref: tripRef },\n query: { stayWindowId, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async assign(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<RoomingAssignResponse>({\n method: 'POST',\n operationId: OperationId.AssignRoomingBed,\n path: '/api/v1/trips/{ref}/rooming/assign',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async autoAssign(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<RoomingAutoAssignResponse>({\n method: 'POST',\n operationId: OperationId.AutoAssignRooming,\n path: '/api/v1/trips/{ref}/rooming/auto-assign',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n stayWindows: {\n async list(options) {\n const { tripRef, since, signal } = options;\n return client.execute<readonly RoomingStayWindowDeltaResponse[]>({\n method: 'GET',\n operationId: OperationId.ListRoomingStayWindows,\n path: '/api/v1/trips/{ref}/rooming/stay-windows',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { tripRef, idempotencyKey, signal, startDate, endDate, ...rest } = options;\n const body: CreateRoomingStayWindowRequest = {\n ...rest,\n startDate: normalizeDateTimeInput(startDate, 'startDate'),\n endDate: normalizeDateTimeInput(endDate, 'endDate'),\n };\n return client.execute<RoomingStayWindowResponse>({\n method: 'POST',\n operationId: OperationId.CreateRoomingStayWindow,\n path: '/api/v1/trips/{ref}/rooming/stay-windows',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, windowId, version, signal, startDate, endDate, ...rest } = options;\n const body: PatchRoomingStayWindowRequest = {\n ...rest,\n ...(startDate !== undefined\n ? { startDate: normalizeDateTimeInput(startDate, 'startDate') }\n : {}),\n ...(endDate !== undefined ? { endDate: normalizeDateTimeInput(endDate, 'endDate') } : {}),\n };\n return client.execute<RoomingStayWindowResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchRoomingStayWindow,\n path: '/api/v1/trips/{ref}/rooming/stay-windows/{windowId}',\n pathParams: { ref: tripRef, windowId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, windowId, version, force, signal } = options;\n return client.execute<RoomingDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteRoomingStayWindow,\n path: '/api/v1/trips/{ref}/rooming/stay-windows/{windowId}',\n pathParams: { ref: tripRef, windowId },\n query: { force },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n rooms: {\n async get(options) {\n const { tripRef, roomId, signal } = options;\n return client.execute<RoomingRoomResponse>({\n method: 'GET',\n operationId: OperationId.ReadRoomingRoom,\n path: '/api/v1/trips/{ref}/rooming/rooms/{roomId}',\n pathParams: { ref: tripRef, roomId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<RoomingRoomResponse>({\n method: 'POST',\n operationId: OperationId.CreateRoomingRoom,\n path: '/api/v1/trips/{ref}/rooming/rooms',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, roomId, version, signal, ...body } = options;\n return client.execute<RoomingRoomResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchRoomingRoom,\n path: '/api/v1/trips/{ref}/rooming/rooms/{roomId}',\n pathParams: { ref: tripRef, roomId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, roomId, version, force, signal } = options;\n return client.execute<RoomingDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteRoomingRoom,\n path: '/api/v1/trips/{ref}/rooming/rooms/{roomId}',\n pathParams: { ref: tripRef, roomId },\n query: { force },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `seating` — the transport board, vehicles, manual seat assignment,\n * auto-assign and the vehicle-manager link. `architecture/08-sdk.md §4`.\n *\n * `read` accepts a manager session, an agency-admin session OR an API key\n * (three alternatives, never an AND); every WRITE is `managerAuth`-only, the\n * same split `rooming` and `itinerary` have and for the same reason — seating\n * is decided on the ground.\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so `vehicles.patch` (a trip ref AND a vehicle id) can't\n * be called with its arguments swapped.\n *\n * `deriveOccupantMark` and `synthesiseBedLabels` — the glyph/tone and\n * bed-label logic a client needs to RENDER this module's output — are not\n * here; they are rooming's, imported by the engine's seating module rather\n * than re-derived (`architecture` 10B notes), and are not on the wire either.\n * A client renders an occupant's `glyph`/`tone` fields straight off the\n * response, the same as `rooming`'s occupants.\n *\n * ── THE TYPE↔LAYOUT RULE, AND WHY `seatLabel` CANNOT BE STATICALLY TIED TO IT ──\n *\n * A vehicle's `layout` is non-null only for `type ∈ {FLIGHT, TRAIN}`\n * (`Vehicle_layout_requires_seatable_type`, enforced server-side by a CHECK).\n * `layout: null` means the vehicle carries no seat map at all — most road\n * vehicles, because \"the label grid was a fiction the manager maintained and\n * the driver ignored\" — and on such a vehicle every assignment's `seatLabel`\n * is `null`, enforced on write. The converse is deliberately NOT an invariant:\n * a seat-mapped vehicle may still hold `seatLabel: null` rows (a group\n * confirmed on a flight before the airline issues seat numbers), so `layout`\n * being non-null does not mean `seatLabel` is required either.\n *\n * `assign()` below is intentionally NOT generic over \"which vehicle\", so\n * `AssignSeatingOptions.seatLabel` cannot be narrowed to \"required when this\n * vehicle has a layout, forbidden when it doesn't\" at the type level: the\n * call site names a `vehicleId`, not the vehicle object it was read from, and\n * whether that id currently has a layout is server-side state this SDK does\n * not — and must not — cache and re-derive locally (the whole point of a\n * board read is that the server is the source of truth for it). Encoding the\n * rule here would mean either accepting a vehicle object just to read one\n * field, which no other write on this surface does, or building a second,\n * client-side copy of `seatMapped` that could drift from what the server\n * actually enforces. So `seatLabel` stays `string | null | undefined` on every\n * vehicle unconditionally, and the rule is enforced where the truth lives:\n * the server accepts a `seatLabel` for a seat-less vehicle and silently\n * ignores it into `null`; the honest type-level statement of this surface is\n * that `seatLabel` is ALWAYS optional and ALWAYS nullable, never that it\n * varies by vehicle. Read a vehicle's own `seatMapped` (`SeatingBoardResponse`\n * / `SeatingVehicleResponse`) before deciding whether to show a seat picker.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype SeatingBoardResponse = components['schemas']['SeatingBoardResponse'];\ntype SeatingVehicleResponse = components['schemas']['SeatingVehicleResponse'];\ntype SeatingDeleteVehicleResponse = components['schemas']['SeatingDeleteVehicleResponse'];\ntype SeatingAssignResponse = components['schemas']['SeatingAssignResponse'];\ntype SeatingAutoAssignResponse = components['schemas']['SeatingAutoAssignResponse'];\ntype SeatingManagerLinkResponse = components['schemas']['SeatingManagerLinkResponse'];\ntype CreateSeatingVehicleRequest = components['schemas']['CreateSeatingVehicleRequest'];\ntype PatchSeatingVehicleRequest = components['schemas']['PatchSeatingVehicleRequest'];\ntype AssignSeatingRequest = components['schemas']['AssignSeatingRequest'];\ntype AutoAssignSeatingRequest = components['schemas']['AutoAssignSeatingRequest'];\ntype LinkSeatingManagerRequest = components['schemas']['LinkSeatingManagerRequest'];\n\n/**\n * One row of the board's `vehicles[]`: a live vehicle, or the tombstone for\n * one deleted since the cursor. Aliased off the response type, never\n * restated.\n */\nexport type SeatingVehicleDeltaRow = SeatingBoardResponse['vehicles'][number];\n\n/** One traveller's chip in `unassignedPool[]`, or (per vehicle) in\n * `occupants[]`/`unseatedOnVehicle[]`/a seat's `occupant`. */\nexport type SeatingOccupant = SeatingBoardResponse['unassignedPool'][number];\n\n/**\n * `autoAssign`'s rules block, named so a caller can build one and hold it in\n * a variable. Indexed off the request type, so the three knobs stay whatever\n * the contract says they are.\n */\nexport type SeatingAutoAssignRules = NonNullable<AutoAssignSeatingRequest['rules']>;\n\n// --- date-time widening --------------------------------------------------\n//\n// Nothing on this surface takes a date: vehicles, seats and assignments are\n// all identified by id and label, and the board itself is read with `?since=`\n// (a cursor string, not a caller-built date). No `*Input` widening applies\n// here — unlike `rooming` and `itinerary`, this file has no\n// `normalizeDateTimeInput` call site for a request body.\n\n// --- seating.read ----------------------------------------------------------\n\nexport interface ReadSeatingBoardOptions {\n readonly tripRef: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit it for the full board. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the boundary is the\n * one thing that silently loses rows, and that module owns it.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- seating.vehicles --------------------------------------------------------\n\nexport interface CreateSeatingVehicleOptions extends CreateSeatingVehicleRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchSeatingVehicleOptions extends PatchSeatingVehicleRequest {\n readonly tripRef: string;\n readonly vehicleId: string;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this\n * method makes forgetting it impossible instead of merely discouraged.\n * Pass the `version` from the vehicle as last read. The SDK builds the\n * `If-Match` header itself; never set it in `headers`.\n *\n * A capacity-down or a `layout` change that would orphan a recorded seat\n * label is refused with `422 SEATING_CAPACITY_ORPHAN` rather than silently\n * dropping whoever held that label — see this file's header for the three\n * forms of the guard.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteSeatingVehicleOptions {\n readonly tripRef: string;\n readonly vehicleId: string;\n /** See `PatchSeatingVehicleOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface LinkSeatingManagerOptions extends LinkSeatingManagerRequest {\n readonly tripRef: string;\n readonly vehicleId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UnlinkSeatingManagerOptions {\n readonly tripRef: string;\n readonly vehicleId: string;\n /** See `PatchSeatingVehicleOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface SeatingVehicleManagerResource {\n /** `POST …/seating/vehicles/{vehicleId}/manager` — links a manager to this\n * vehicle. Demotes whichever vehicle that manager was previously linked to,\n * atomically: a manager only ever rides one vehicle. */\n link(options: LinkSeatingManagerOptions): Promise<KaafilResponse<SeatingManagerLinkResponse>>;\n unlink(options: UnlinkSeatingManagerOptions): Promise<KaafilResponse<SeatingManagerLinkResponse>>;\n}\n\nexport interface SeatingVehiclesResource {\n create(options: CreateSeatingVehicleOptions): Promise<KaafilResponse<SeatingVehicleResponse>>;\n patch(options: PatchSeatingVehicleOptions): Promise<KaafilResponse<SeatingVehicleResponse>>;\n /** Clears every occupant on this vehicle back to the unassigned pool and\n * unlinks its manager, then deletes it. */\n remove(\n options: DeleteSeatingVehicleOptions,\n ): Promise<KaafilResponse<SeatingDeleteVehicleResponse>>;\n readonly manager: SeatingVehicleManagerResource;\n}\n\n// --- seating.assign / seating.autoAssign -------------------------------------\n\nexport interface AssignSeatingOptions extends AssignSeatingRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AutoAssignSeatingOptions extends AutoAssignSeatingRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- seating -----------------------------------------------------------------\n\nexport interface SeatingResource {\n /** `GET /api/v1/trips/{ref}/seating` — vehicles with their seats and\n * occupants, the unassigned pool, and the summary counters. */\n read(options: ReadSeatingBoardOptions): Promise<KaafilResponse<SeatingBoardResponse>>;\n /**\n * `POST …/seating/assign` — puts one traveller in one vehicle (and, on a\n * seat-mapped vehicle, one seat). `vehicleId: null` moves them to the\n * unassigned pool. If the target seat is taken the occupant is displaced,\n * and the response names them in `displacedTravellerId` (plus\n * `displacedVehicleId`/`displacedSeatLabel`) rather than leaving the caller\n * to diff two boards to notice a second person moved.\n */\n assign(options: AssignSeatingOptions): Promise<KaafilResponse<SeatingAssignResponse>>;\n /**\n * `POST …/seating/auto-assign`. `dryRun: true` returns the plan without\n * writing it; `dryRun: false` returns the plan it actually applied. The two\n * are the SAME computation — the solver is pure and the only difference is\n * whether the result is also written — so a preview and its apply agree by\n * construction.\n *\n * Every rule reports an outcome in `perRule`: `applied`, `relaxed`, or\n * `noop` with `noopReason: 'no_seat_map'` — the third outcome seating has\n * that rooming does not, because `medicalFirst` and `gender` are\n * seat-adjacency heuristics with nothing to do on a seat-less vehicle. A\n * `noop` and a relaxed rule are different facts (a heuristic that could not\n * apply vs. one that applied a weaker version of itself), so both are\n * reported rather than one masquerading as the other.\n */\n autoAssign(options: AutoAssignSeatingOptions): Promise<KaafilResponse<SeatingAutoAssignResponse>>;\n readonly vehicles: SeatingVehiclesResource;\n}\n\nexport function createSeatingResource(client: KaafilHttpClient): SeatingResource {\n return {\n async read(options) {\n const { tripRef, since, signal } = options;\n return client.execute<SeatingBoardResponse>({\n method: 'GET',\n operationId: OperationId.ReadSeatingBoard,\n path: '/api/v1/trips/{ref}/seating',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async assign(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<SeatingAssignResponse>({\n method: 'POST',\n operationId: OperationId.AssignSeating,\n path: '/api/v1/trips/{ref}/seating/assign',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async autoAssign(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<SeatingAutoAssignResponse>({\n method: 'POST',\n operationId: OperationId.AutoAssignSeating,\n path: '/api/v1/trips/{ref}/seating/auto-assign',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n vehicles: {\n async create(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<SeatingVehicleResponse>({\n method: 'POST',\n operationId: OperationId.CreateSeatingVehicle,\n path: '/api/v1/trips/{ref}/seating/vehicles',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, vehicleId, version, signal, ...body } = options;\n return client.execute<SeatingVehicleResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchSeatingVehicle,\n path: '/api/v1/trips/{ref}/seating/vehicles/{vehicleId}',\n pathParams: { ref: tripRef, vehicleId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, vehicleId, version, signal } = options;\n return client.execute<SeatingDeleteVehicleResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteSeatingVehicle,\n path: '/api/v1/trips/{ref}/seating/vehicles/{vehicleId}',\n pathParams: { ref: tripRef, vehicleId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n manager: {\n async link(options) {\n const { tripRef, vehicleId, idempotencyKey, signal, ...body } = options;\n return client.execute<SeatingManagerLinkResponse>({\n method: 'POST',\n operationId: OperationId.LinkSeatingManager,\n path: '/api/v1/trips/{ref}/seating/vehicles/{vehicleId}/manager',\n pathParams: { ref: tripRef, vehicleId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async unlink(options) {\n const { tripRef, vehicleId, version, signal } = options;\n return client.execute<SeatingManagerLinkResponse>({\n method: 'DELETE',\n operationId: OperationId.UnlinkSeatingManager,\n path: '/api/v1/trips/{ref}/seating/vehicles/{vehicleId}/manager',\n pathParams: { ref: tripRef, vehicleId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n },\n };\n}\n","/**\n * `shareTokens` — create, read, revoke, patch, regenerate.\n * `architecture/08-sdk.md §3.3, §4`; every operation here is `apiKeyAuth`-only\n * in the spec (server-side mint, matching `03-auth-and-tokens.md §1`:\n * browsers only ever hold the *minted* token, never the key that mints it).\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype MintShareTokenRequest = components['schemas']['MintShareTokenRequest'];\ntype MintedShareTokenViewResponse = components['schemas']['MintedShareTokenViewResponse'];\ntype ShareTokenViewResponse = components['schemas']['ShareTokenViewResponse'];\ntype PatchShareTokenRequest = components['schemas']['PatchShareTokenRequest'];\ntype RegenerateShareTokenRequest = components['schemas']['RegenerateShareTokenRequest'];\ntype RevealedShareTokenViewResponse = components['schemas']['RevealedShareTokenViewResponse'];\n\nexport interface CreateShareTokenOptions extends Omit<MintShareTokenRequest, 'expiresAt'> {\n /** Optional on the wire (`ttlDays` is the other way to set expiry) — see\n * `../datetime` for the coercion contract; a full ISO string with an\n * offset still passes through unchanged. */\n readonly expiresAt?: DateTimeInput;\n /** Stable across retries — reused as-is, never re-minted per attempt. */\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadShareTokenOptions {\n readonly id: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ListShareTokensOptions {\n /** REQUIRED — a bare list would enumerate every live link in the agency. */\n readonly tripRef: string;\n /** Omit for the whole trip, INCLUDING the subject-less family link. */\n readonly travellerRef?: string;\n /** Adds revoked and expired links. Defaults to live only. */\n readonly includeRevoked?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface RevokeShareTokenOptions {\n readonly id: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchShareTokenOptions extends Omit<PatchShareTokenRequest, 'expiresAt'> {\n readonly id: string;\n /** Optional on the wire (`ttlDays` is the other way to set expiry) — see\n * `../datetime` for the coercion contract; a full ISO string with an\n * offset still passes through unchanged. */\n readonly expiresAt?: DateTimeInput;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both\n * answer the same version-conflict error, so this method makes forgetting\n * it impossible instead of merely discouraged. Pass the `version` from\n * the token as last read. The SDK builds the `If-Match` header itself;\n * never set it in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface RegenerateShareTokenOptions extends RegenerateShareTokenRequest {\n readonly id: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ShareTokensResource {\n /**\n * `POST /api/v1/share-tokens` — mints a config-scoped, expiring share\n * token. Expiry is top-level (`ttlDays` OR `expiresAt` on this options\n * object — never inside `config`); the server clamps it as documented on\n * `MintShareTokenRequest`. The CRM builds its own link around the returned\n * `token`; this SDK never constructs one.\n */\n create(options: CreateShareTokenOptions): Promise<KaafilResponse<MintedShareTokenViewResponse>>;\n /** `GET /api/v1/share-tokens/{id}` — a share token's metadata, never its plaintext value. */\n read(options: ReadShareTokenOptions): Promise<KaafilResponse<ShareTokenViewResponse>>;\n /**\n * `GET /api/v1/share-tokens?tripRef=` — the links on one trip, metadata\n * only, newest first.\n *\n * The read that makes revoking possible for a caller that did not mint:\n * before it, an id could only be held by whoever called `create`, so a\n * surface that reloads had no way to revoke a link it had already handed\n * out. `tripRef` is required by design.\n */\n list(options: ListShareTokensOptions): Promise<KaafilResponse<readonly ShareTokenViewResponse[]>>;\n /** `DELETE /api/v1/share-tokens/{id}`. */\n revoke(options: RevokeShareTokenOptions): Promise<KaafilResponse<ShareTokenViewResponse>>;\n /** `PATCH /api/v1/share-tokens/{id}` — update a share token's section\n * config and/or expiry. `config.sections`, if sent, REPLACES the whole\n * map; a partial PATCH is not a partial write. */\n patch(options: PatchShareTokenOptions): Promise<KaafilResponse<ShareTokenViewResponse>>;\n /** `POST /api/v1/share-tokens/{id}/regenerate` — mints a fresh token for\n * the same subject, superseding the old one. By default the old token is\n * revoked in the same transaction; pass `keepOld: true` to retain it. */\n regenerate(\n options: RegenerateShareTokenOptions,\n ): Promise<KaafilResponse<MintedShareTokenViewResponse>>;\n /**\n * `GET /api/v1/share-tokens/{id}/reveal` — show an EXISTING link's address\n * again, so a desk can re-send it instead of calling `regenerate`, which\n * revokes the copy the family is already using.\n *\n * `token` is `null` with `reason: 'not_recoverable'` for a link minted\n * before Kaafil kept a recoverable copy: those rows hold only a digest, so\n * the address is gone for good and the caller should offer `regenerate`\n * rather than a retry. That is a 200, not an error.\n */\n reveal(options: ReadShareTokenOptions): Promise<KaafilResponse<RevealedShareTokenViewResponse>>;\n}\n\nexport function createShareTokensResource(client: KaafilHttpClient): ShareTokensResource {\n return {\n async list(options) {\n const { tripRef, travellerRef, includeRevoked, signal } = options;\n return client.execute<readonly ShareTokenViewResponse[]>({\n method: 'GET',\n operationId: OperationId.ListShareTokens,\n path: '/api/v1/share-tokens',\n query: { tripRef, travellerRef, includeRevoked },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { idempotencyKey, signal, expiresAt, ...rest } = options;\n const body: MintShareTokenRequest = {\n ...rest,\n ...(expiresAt !== undefined\n ? { expiresAt: normalizeDateTimeInput(expiresAt, 'expiresAt') }\n : {}),\n };\n return client.execute<MintedShareTokenViewResponse>({\n method: 'POST',\n operationId: OperationId.MintShareToken,\n path: '/api/v1/share-tokens',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async read(options) {\n const { id, signal } = options;\n return client.execute<ShareTokenViewResponse>({\n method: 'GET',\n operationId: OperationId.ReadShareToken,\n path: '/api/v1/share-tokens/{id}',\n pathParams: { id },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reveal(options) {\n const { id, signal } = options;\n return client.execute<RevealedShareTokenViewResponse>({\n method: 'GET',\n operationId: OperationId.RevealShareToken,\n path: '/api/v1/share-tokens/{id}/reveal',\n pathParams: { id },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async revoke(options) {\n const { id, signal } = options;\n return client.execute<ShareTokenViewResponse>({\n method: 'DELETE',\n operationId: OperationId.RevokeShareToken,\n path: '/api/v1/share-tokens/{id}',\n pathParams: { id },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { id, version, signal, expiresAt, ...rest } = options;\n const body: PatchShareTokenRequest = {\n ...rest,\n ...(expiresAt !== undefined\n ? { expiresAt: normalizeDateTimeInput(expiresAt, 'expiresAt') }\n : {}),\n };\n return client.execute<ShareTokenViewResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchShareToken,\n path: '/api/v1/share-tokens/{id}',\n pathParams: { id },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async regenerate(options) {\n const { id, idempotencyKey, signal, ...rest } = options;\n const body: RegenerateShareTokenRequest = { ...rest };\n return client.execute<MintedShareTokenViewResponse>({\n method: 'POST',\n operationId: OperationId.RegenerateShareToken,\n path: '/api/v1/share-tokens/{id}/regenerate',\n pathParams: { id },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `sync` — the batched transport's three routes.\n * `architecture/06-offline-first.md §4.1`, `08-sdk.md §5`.\n *\n * This is a WIRE-SHAPE resource, not a semantic one. Every op inside a push\n * is defined, validated and versioned by its OWN endpoint; the batch changes\n * how many round trips it takes to deliver them and nothing else. That is why\n * this module has no per-module knowledge at all — an op is a method, a path,\n * an idempotency key and a body, exactly as `SyncPushRequest` declares them.\n *\n * ── `pushShare` AND A GAP IN THE VENDORED SPEC ─────────────────────────────\n *\n * `POST /api/v1/sync/push/share` is the traveller surface's drain route\n * (`06 §8`), and it must be authorized by the share token — the ops inside it\n * are that traveller's queued form writes. In the vendored spec as it stands,\n * that operation declares NO security scheme at all: `OPERATION_SECURITY\n * .syncPushShare` is `[]`, which `../auth/credentials.ts` correctly reads as\n * \"public operation, no header is due\" and sends with no credential.\n *\n * That is not something this package can paper over by attaching a header\n * behind the resolver's back — the resolver is the single place a credential\n * becomes a header, and a second path would be exactly the kind of drift this\n * SDK does not carry. So `pushShare` REFUSES, locally and by name, when the\n * spec declares no scheme for it: shipping an unauthenticated POST carrying a\n * traveller's submissions would be worse than not shipping the route. The\n * offline engine reads the same fact from the same table and simply keeps the\n * share lane on the single-op endpoints (`shareSaveForm`/`shareSubmitForm`,\n * both `['shareAuth']`), which work today. When the engine's spec declares\n * `shareAuth` here, re-vendoring turns the batch on with no code change.\n */\n\nimport type { components } from '../generated/schema';\nimport { OPERATION_SECURITY, OperationId, SecuritySchemeId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { KaafilInvalidRequestError } from '../http/errors';\nimport type { KaafilResponse } from '../types/meta';\n\ntype SyncPushRequest = components['schemas']['SyncPushRequest'];\ntype SyncPushShareRequest = components['schemas']['SyncPushShareRequest'];\ntype SyncPushResponse = components['schemas']['SyncPushResponse'];\ntype SyncPullResponse = components['schemas']['SyncPullResponse'];\ntype SyncDigestRow = components['schemas']['SyncDigestRow'];\n\n/** One op on the wire — the spec's own element type, never restated. */\nexport type SyncPushOp = SyncPushRequest['ops'][number];\n\n/** One verdict — likewise. */\nexport type SyncPushVerdict = SyncPushResponse['verdicts'][number];\n\nexport interface SyncPushOptions {\n readonly ops: readonly SyncPushOp[];\n readonly signal?: AbortSignal;\n}\n\nexport interface SyncPullTripOptions {\n readonly tripRef: string;\n /** The last successful pull's `meta.serverTime`. Omitted on a cold start,\n * which is a full snapshot with no tombstones (`06 §5`). */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface SyncDigestOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\n/** Thrown by `pushShare` when the vendored spec declares no security scheme\n * for `syncPushShare` — see this module's header. */\nexport class KaafilShareBatchUnauthenticatedError extends KaafilInvalidRequestError {\n constructor() {\n super(\n 'The vendored spec declares no security scheme for \"syncPushShare\", so a batched ' +\n \"share push would be sent with no credential at all, carrying a traveller's queued \" +\n 'writes. Refused locally. Drain share ops through their own endpoints ' +\n '(shareSaveForm / shareSubmitForm) until the engine declares shareAuth on ' +\n 'POST /api/v1/sync/push/share.',\n );\n this.name = 'KaafilShareBatchUnauthenticatedError';\n Object.setPrototypeOf(this, KaafilShareBatchUnauthenticatedError.prototype);\n }\n}\n\n/**\n * Whether the batched SHARE push is usable at all, read from the generated\n * security table rather than assumed. Exported so the offline engine can make\n * the same call without duplicating the reasoning, and so the fact is\n * inspectable from a gate.\n */\nexport function isShareBatchPushAvailable(): boolean {\n return (OPERATION_SECURITY[OperationId.SyncPushShare] as readonly SecuritySchemeId[]).includes(\n SecuritySchemeId.ShareAuth,\n );\n}\n\nexport interface SyncResource {\n /** `POST /api/v1/sync/push` — an ordered array of ops, one verdict each.\n * One op's `409` or `423` never fails the batch. */\n push(options: SyncPushOptions): Promise<KaafilResponse<SyncPushResponse>>;\n /** `GET /api/v1/trips/{ref}/sync` — every list a trip snapshot needs, in\n * one response. A section this tenant is not entitled to, or that this trip\n * leaves dark, is ABSENT from `sections` — never a `402` in the payload. */\n pullTrip(options: SyncPullTripOptions): Promise<KaafilResponse<SyncPullResponse>>;\n /** `POST /api/v1/sync/push/share` — the traveller surface's drain route.\n * See this module's header for why this can refuse locally today. */\n pushShare(options: SyncPushOptions): Promise<KaafilResponse<SyncPushResponse>>;\n /** `GET /api/v1/sync/digest` — one row per active trip, with a stable hash\n * for cheap drift detection. Compare each trip's `hash` against your own\n * and re-push only the trips that differ, instead of blind re-pushes of\n * the whole book. */\n digest(options: SyncDigestOptions): Promise<KaafilResponse<readonly SyncDigestRow[]>>;\n}\n\nexport function createSyncResource(client: KaafilHttpClient): SyncResource {\n return {\n async push(options) {\n const { ops, signal } = options;\n const body: SyncPushRequest = { ops: [...ops] };\n return client.execute<SyncPushResponse>({\n method: 'POST',\n operationId: OperationId.SyncPush,\n path: '/api/v1/sync/push',\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n async pullTrip(options) {\n const { tripRef, since, signal } = options;\n return client.execute<SyncPullResponse>({\n method: 'GET',\n operationId: OperationId.SyncPullTrip,\n path: '/api/v1/trips/{ref}/sync',\n pathParams: { ref: tripRef },\n // A `since` of `undefined` is omitted by `RequestDescriptor`'s own\n // rule, which is exactly the cold-start shape: no `?since=` at all.\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n async pushShare(options) {\n if (!isShareBatchPushAvailable()) {\n throw new KaafilShareBatchUnauthenticatedError();\n }\n const { ops, signal } = options;\n const body: SyncPushShareRequest = { ops: [...ops] };\n return client.execute<SyncPushResponse>({\n method: 'POST',\n operationId: OperationId.SyncPushShare,\n path: '/api/v1/sync/push/share',\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n async digest(options) {\n const { agencyRef, signal } = options;\n return client.execute<readonly SyncDigestRow[]>({\n method: 'GET',\n operationId: OperationId.SyncDigest,\n path: '/api/v1/sync/digest',\n query: { agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `test` — the sandbox toolkit: the simulated clock, fixture rebuilds, and\n * the sandbox tenant's fixed quota. `architecture/12-testing-sandbox.md\n * §2/§4`.\n *\n * `kaafil-engine/src/modules/test/test.routes.ts`'s own header explains the\n * SERVER-side half of this: every one of the six `/api/v1/test/*` routes is\n * `auth: 'apiKey'` — reachable by either key prefix — and then a SECOND,\n * explicit `guardTestPlane` middleware 404s a LIVE-prefixed key against the\n * resolved tenant's own `Tenant.plane`, no existence hint given. That check\n * is the engine's, runs against the ACTUAL tenant a key resolves to, and\n * this module cannot see or duplicate it — a construction-time `apiKey`\n * prefix and a resolver-supplied one are exactly the case\n * `guardApiKeyEnvironment` (`../config.ts`) already handles honestly by\n * deferring to the resolved value, and this module has no narrower fact to\n * add.\n *\n * What THIS module adds is a courtesy this package already extends to every\n * multi-scheme resource `UnsatisfiableSchemeError` covers\n * (`../auth/credentials.ts`'s header, `../client-entry.ts`'s browser-entry\n * doc comment): a client's `environment` IS known at construction, so a\n * client built `{ environment: 'live' }` and pointed at these six operations\n * refuses LOCALLY, before any request exists, the same shape of mistake\n * `UnsatisfiableSchemeError` refuses for a credential that cannot satisfy an\n * operation's scheme — a `TestEnvironmentRequiredError` below, thrown by\n * every leaf method here before `client.execute()` is ever called. This is a\n * courtesy on top of the engine's own 404, not a replacement for it: a\n * resolver-supplied key that turns out to be LIVE despite `environment:\n * 'test'` still reaches the engine and still gets 404'd there, exactly like\n * `ApiKeyEnvironmentMismatchError` is a courtesy on top of, never a\n * substitute for, the engine's own tenant-plane checks.\n *\n * There used to be a would-be extra operation here, `webhooks.sendTest`\n * (`testWebhookEndpoint`) — removed because the vendored spec declares THAT\n * one `['consoleAuth']` alone, and no scheme this package's\n * `CredentialResolver` ever holds can satisfy it (see\n * `../auth/credentials.ts`'s `CREDENTIAL_KIND_SCHEME`: no kind maps to\n * `consoleAuth`, on purpose — \"the SDK does not serve the console\"). It has\n * NOT come back here, and should not. The engine now publishes an API-key\n * entry point onto the same controller — `POST\n * /api/v1/webhooks/endpoints/{id}/test`, `testWebhookEndpointApiKey`,\n * `['apiKeyAuth']` — and that one lives on `webhooks.testEvent()`\n * (`./webhooks.ts`), not in this module. Deliberately: it is a webhooks\n * operation that happens to send a canned event, it works on BOTH planes,\n * and it must therefore NOT be gated by `TestEnvironmentRequiredError` — a\n * LIVE client proving its own LIVE endpoint verifies signatures is the\n * normal case for it, not a mistake to refuse.\n *\n * The sixth operation this module actually gained is `readFixtures()`, the\n * read-only counterpart of `fixtures()`.\n */\n\nimport type { Environment } from '../config';\nimport { Environment as EnvironmentValues } from '../config';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { KaafilInvalidRequestError } from '../http/errors';\nimport type { KaafilResponse } from '../types/meta';\n\ntype TestClockResponse = components['schemas']['TestClockResponse'];\ntype AdvanceTimeResponse = components['schemas']['AdvanceTimeResponse'];\ntype FixtureRefMapResponse = components['schemas']['FixtureRefMapResponse'];\ntype SandboxQuotaResponse = components['schemas']['SandboxQuotaResponse'];\n\n/**\n * Thrown by every `test.*` method, before `client.execute()` is ever called,\n * when the client was constructed with `environment: 'live'`. Mirrors\n * `UnsatisfiableSchemeError`'s shape (`../auth/credentials.ts`) on purpose:\n * a non-retryable `KaafilInvalidRequestError`, so a consumer's `isRetryable`\n * check (or an outbox's own class lookup) never spends a retry ladder on a\n * mistake that is permanent by construction, and `catch (e) { e instanceof\n * TestEnvironmentRequiredError }` works the same way the documented\n * `UnsatisfiableSchemeError` pattern does — never a bare `Error` a consumer's\n * `KaafilError` hierarchy check would miss.\n *\n * Named for what it enforces, not for the plane it enforces against: the\n * engine's own vocabulary is TEST/LIVE \"planes\" (`architecture/\n * 12-testing-sandbox.md`), but this class's job is narrower and purely\n * client-side — refusing before a request exists for a client whose\n * `KaafilOptions.environment` is `'live'` — so it names the environment\n * field a caller actually passed, not the engine-side concept this module\n * cannot itself observe (see this file's header for why the engine's own\n * `guardTestPlane` 404 is the check that actually matters for a\n * resolver-supplied key).\n */\nexport class TestEnvironmentRequiredError extends KaafilInvalidRequestError {\n readonly operationId: OperationId;\n readonly environment: Environment;\n\n constructor(operationId: OperationId, environment: Environment) {\n super(\n `\"${operationId}\" is a TEST-plane sandbox operation and refuses to run against a ` +\n `client constructed with environment: \"${environment}\". Construct a client with ` +\n 'environment: \"test\" to use the sandbox toolkit.',\n );\n this.name = 'TestEnvironmentRequiredError';\n // Same reason every class in `../http/errors.ts` and\n // `../auth/credentials.ts`'s `UnsatisfiableSchemeError` does this: an ES5\n // target loses the prototype chain through `super()`, and without it\n // `instanceof` fails for the one class whose whole purpose is to be\n // caught by name.\n Object.setPrototypeOf(this, TestEnvironmentRequiredError.prototype);\n this.operationId = operationId;\n this.environment = environment;\n }\n}\n\nexport interface AdvanceTestTimeOptions {\n /** The exact instant to advance the sandbox clock to. Mutually exclusive\n * with `byHours` — exactly one is required (`AdvanceTestTimeRequest`).\n *\n * Bounded at BOTH ends. At or before the clock's current `simulatedNow` is\n * `422 TEST_CLOCK_BACKWARDS`; more than one year past `simulatedNow` is\n * `422 TEST_CLOCK_TOO_FAR`; more than one year past REAL time is refused\n * earlier still, as a `422 VALIDATION_ERROR` on this field — the same\n * one-year horizon, measured from the other anchor. */\n readonly to?: string;\n /** Hours to advance the sandbox clock by, from its current `simulatedNow`.\n * Mutually exclusive with `to`. Capped at `8760` (one year) by the schema\n * itself, so this field hits the horizon as a `422 VALIDATION_ERROR`\n * rather than as `TEST_CLOCK_TOO_FAR`. */\n readonly byHours?: number;\n /** Pins the `Idempotency-Key` this call sends. Omitting it does not mean\n * \"no key\": `advanceTestTime` is now idempotent-capable\n * (`OPERATION_ACCEPTS_IDEMPOTENCY_KEY`, `../generated/security.ts`), so\n * `../http/client.ts` mints one per call and reuses it across the retry\n * ladder either way. Pass your own when the KEY itself has to survive\n * something this client does not — a process restart, a re-run of the same\n * suite step — because a forward-only advance is exactly the write a lost\n * response cannot be safely repeated for: with no key in common, the\n * repeat advances the clock a SECOND time instead of replaying the first\n * advance. A replay whose body differs is `422 IDEMPOTENCY_KEY_REUSED`. */\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadTestClockOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface ResetTestClockOptions {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface BuildTestFixturesOptions {\n /** Which fixture scenario to (re)build. v1 ships exactly one: `\"default\"`. */\n readonly scenario?: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadTestFixturesOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadTestQuotaOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface TestResource {\n /** `POST /api/v1/test/advance-time` — advances the sandbox clock and\n * replays every scheduled evaluation in between.\n *\n * Forward only AND bounded: `422 TEST_CLOCK_BACKWARDS` for a target at or\n * before `simulatedNow`, `422 TEST_CLOCK_TOO_FAR` for one more than a year\n * past it — that one's `details` carry `simulatedNow`, `requestedTo` and\n * `maxHorizonHours`. `byHours` is capped at `8760`, and a `to` beyond a\n * year from REAL time is refused as `422 VALIDATION_ERROR`. All of these\n * are non-retryable (`../generated/error-codes.ts`), so a suite clamps its\n * own horizon rather than backing off — read `maxHorizonHours` off the\n * refusal and re-aim.\n *\n * Idempotent-capable and rate-limited. The SDK always sends an\n * `Idempotency-Key` (see `AdvanceTestTimeOptions.idempotencyKey` for why\n * it matters more here than elsewhere), and the per-tenant sandbox\n * mutation limiter answers `429 RATE_LIMITED` with `Retry-After` when a\n * suite advances the clock in a tight loop — that one IS retryable, and\n * `../http/retry.ts` honours the header so the caller never sleeps by\n * hand. */\n advanceTime(options: AdvanceTestTimeOptions): Promise<KaafilResponse<AdvanceTimeResponse>>;\n /** `GET /api/v1/test/clock` — reads the sandbox's simulated clock. */\n clock(options?: ReadTestClockOptions): Promise<KaafilResponse<TestClockResponse>>;\n /** `POST /api/v1/test/clock/reset` — resets the sandbox clock to wall\n * time. Does not touch fixtures. */\n resetClock(options?: ResetTestClockOptions): Promise<KaafilResponse<TestClockResponse>>;\n /** `GET /api/v1/test/fixtures` — reads the current fixture's external\n * reference map and DOES NOT REBUILD IT. The read-only counterpart of\n * `fixtures()` below (identical `FixtureRefMapResponse`), assembled from\n * the rows that exist right now: nothing is written, no clock moves, no\n * row is created. That is the whole point — a suite can ask \"is my fixture\n * there?\" without the act of asking resetting it, which calling\n * `fixtures()` to find out would. `clock()`/`resetClock()` name the GET\n * plainly and the mutation with a verb; this pair reads the other way\n * round only because `fixtures()` already shipped as the POST.\n *\n * `404 RESOURCE_NOT_FOUND` (`KaafilNotFoundError`, `resource:\n * \"TestFixture\"`) when this tenant has never called `fixtures()`, or when\n * a previous rebuild was interrupted after the wipe. Deliberately a 404\n * rather than an empty `200`: the refs are deterministic constants, so a\n * `200` assembled from them would answer \"yes, it's there\"\n * unconditionally, and existence — not the strings — is the only thing\n * this route is actually asked. Read this 404 as \"build it first\" (call\n * `fixtures()`), not as the loss-of-access a generic 404 usually means.\n *\n * `travellerRefs`/`managerRefs` come from the live rows and are ordered by\n * external id, so an interrupted rebuild reports the manifest that\n * actually survived rather than the one that was intended. */\n readFixtures(options?: ReadTestFixturesOptions): Promise<KaafilResponse<FixtureRefMapResponse>>;\n /** `POST /api/v1/test/fixtures` — (re)builds a fixture scenario to\n * pristine, with the same external refs on every call. Reach for\n * `readFixtures()` instead when you only need to know whether it is\n * already there. */\n fixtures(options?: BuildTestFixturesOptions): Promise<KaafilResponse<FixtureRefMapResponse>>;\n /** `GET /api/v1/test/quota` — reads the sandbox tenant's fixed caps and\n * current usage. Independent of the partner's plan tier: TEST-plane trip\n * ingest is never metered against the plan.\n *\n * All three caps are ENFORCED, each on its own path and with its own\n * refusal, and each is `null` when UNCAPPED — render that as \"No limit\",\n * never as a fallback number:\n * - `tripSlots.limit` — the effective per-tenant ceiling, refused by trip\n * ingest as `422 TEST_TRIP_LIMIT`.\n * - `travellersPerTripLimit` — a PER-TRIP roster ceiling, refused on the\n * manifest ingest path as `422 TEST_TRAVELLER_LIMIT` with `details:\n * { limit, resulting }` (`resulting` is the roster size the push would\n * have produced, so a caller can split the batch instead of guessing).\n * `travellers` beside it is a tenant-wide COUNT, deliberately not\n * comparable with this limit.\n * - `storageBytesLimit` — refused at file-confirm time as\n * `402 PLAN_FEATURE_DISABLED` with `reason: 'storageQuota'`\n * (`KaafilEntitlementError.reason`, `../http/errors.ts`). On this plane\n * that refusal's `details.includedBytes` is `null`: the sandbox has no\n * soft rung to bill overage against, only the hard cap — do not render\n * a `null` `includedBytes` as zero. `storageBytes` counts `READY` files\n * only, the same rows the enforcing side counts, so THAT pair is\n * directly comparable.\n *\n * `filePurgeDays` is not a limit at all: it is the retention window a\n * sandbox upload survives before the purge sweep removes it. */\n quota(options?: ReadTestQuotaOptions): Promise<KaafilResponse<SandboxQuotaResponse>>;\n}\n\n/**\n * `environment` is threaded in alongside the transport — the one piece of\n * construction-time state this resource needs that `KaafilHttpClient` itself\n * carries no opinion about (it serves every environment identically; the\n * refusal below is this module's own, not the transport's).\n */\nexport function createTestResource(\n client: KaafilHttpClient,\n environment: Environment,\n): TestResource {\n function assertTestEnvironment(operationId: OperationId): void {\n if (environment !== EnvironmentValues.Test) {\n throw new TestEnvironmentRequiredError(operationId, environment);\n }\n }\n\n return {\n async advanceTime(options) {\n assertTestEnvironment(OperationId.AdvanceTestTime);\n const { to, byHours, idempotencyKey, signal } = options;\n return client.execute<AdvanceTimeResponse>({\n method: 'POST',\n operationId: OperationId.AdvanceTestTime,\n path: '/api/v1/test/advance-time',\n body: {\n ...(to !== undefined ? { to } : {}),\n ...(byHours !== undefined ? { byHours } : {}),\n },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async clock(options = {}) {\n assertTestEnvironment(OperationId.ReadTestClock);\n const { signal } = options;\n return client.execute<TestClockResponse>({\n method: 'GET',\n operationId: OperationId.ReadTestClock,\n path: '/api/v1/test/clock',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async resetClock(options = {}) {\n assertTestEnvironment(OperationId.ResetTestClock);\n const { idempotencyKey, signal } = options;\n return client.execute<TestClockResponse>({\n method: 'POST',\n operationId: OperationId.ResetTestClock,\n path: '/api/v1/test/clock/reset',\n body: {},\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async readFixtures(options = {}) {\n assertTestEnvironment(OperationId.ReadTestFixtures);\n const { signal } = options;\n return client.execute<FixtureRefMapResponse>({\n method: 'GET',\n operationId: OperationId.ReadTestFixtures,\n path: '/api/v1/test/fixtures',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async fixtures(options = {}) {\n assertTestEnvironment(OperationId.BuildTestFixtures);\n const { scenario, idempotencyKey, signal } = options;\n return client.execute<FixtureRefMapResponse>({\n method: 'POST',\n operationId: OperationId.BuildTestFixtures,\n path: '/api/v1/test/fixtures',\n body: { ...(scenario !== undefined ? { scenario } : {}) },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async quota(options = {}) {\n assertTestEnvironment(OperationId.ReadTestQuota);\n const { signal } = options;\n return client.execute<SandboxQuotaResponse>({\n method: 'GET',\n operationId: OperationId.ReadTestQuota,\n path: '/api/v1/test/quota',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `travellers` — the traveller-identity endpoints that live outside any one\n * trip: DPDP erasure and DSAR export, plus the two cross-trip/cross-agency\n * traveller reads. `architecture/08-sdk.md §4`.\n *\n * `erase`/`export_` (`eraseTraveller`/`exportTraveller`, `../generated/security.ts`'s\n * `OPERATION_SECURITY`) declare `apiKeyAuth` as their ONLY accepted scheme —\n * no manager or agency-admin session can ever satisfy them.\n *\n * `listForTrip`/`listForAgency` (`getTripManifest`/`searchTravellerDirectory`)\n * accept `apiKeyAuth`, `managerAuth`, OR `agencyAdminAuth` — the same\n * multi-scheme shape `./vendors.ts`'s `listTripVendors` has — so, following\n * that file's precedent, this whole resource (erase/export_ included) is\n * exposed unchanged from both `../client.ts` and `../client-entry.ts`; a\n * manager- or agency-admin-opened `KaafilClient` calling `erase`/`export_`\n * simply fails at the point of use with `UnsatisfiableSchemeError`, the same\n * way a `shareToken`-opened client calling `vendors`/`journey` already does.\n *\n * `listForTrip` mirrors `listTripVendors`: no `cursor`/`limit` query\n * parameters on `getTripManifest`, so it returns the full manifest directly\n * rather than a `KaafilPaginator`. `listForAgency` wraps\n * `searchTravellerDirectory`, which is cursor-paginated — `q` is now\n * OPTIONAL engine-side (a deliberate reversal of the previous \"search-only,\n * never browsable\" posture; when supplied it must be non-empty). Omitting\n * `q` lists every traveller in the agency, so `TravellerDirectoryFilters`\n * carries no required field.\n *\n * `create` (`createTraveller`, `POST /api/v1/agencies/{ref}/travellers`,\n * GAP-008) accepts `apiKeyAuth` OR `agencyAdminAuth` — NEVER `managerAuth`: a\n * manager acts on one trip on the ground and reaches the roster through a\n * trip's manifest or a trek's walk-in, not the agency-wide directory this\n * route writes into directly. `externalTravellerId` is optional — omitted,\n * Kaafil mints the traveller with `externalId: null`, reconciled later by\n * phone, the same shape `treks.walkIns.create` already takes. A supplied id\n * that already resolves within the SAME agency returns the EXISTING\n * directory row rather than a conflict; a ref that resolves in a DIFFERENT\n * agency is the ordinary `404` isolation refusal. `fullName` is the only\n * required body field. Because it lacks `managerAuth`, it is agencyRef-BOUND\n * on `../client-entry.ts` alongside `listForAgency`/`listForAgencyPage` — see\n * that file's \"agencyRef-bound option types\" section.\n *\n * `getAgencyProfile` (`getTravellerAgencyProfile`,\n * `GET /api/v1/agencies/{ref}/travellers/{travellerRef}`, GAP-016) — the\n * traveller-wide profile a host needs after selecting a row from\n * `listForAgency`/`listForAgencyPage`, which carries no trip reference at\n * all. Accepts `apiKeyAuth` OR `agencyAdminAuth`, NEVER `managerAuth` — the\n * identical posture `create` above already takes, for the identical reason\n * (no trip in the URL for a manager bearer's own per-trip gate to check\n * against). Also agencyRef-BOUND on `../client-entry.ts` alongside `create`.\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype EraseResponse = components['schemas']['EraseResponse'];\ntype DsarBundleResponse = components['schemas']['DsarBundleResponse'];\ntype TripManifestItemResponse = components['schemas']['TripManifestItemResponse'];\ntype TravellerDirectoryItemResponse = components['schemas']['TravellerDirectoryItemResponse'];\ntype CreateTravellerRequest = components['schemas']['CreateTravellerRequest'];\ntype TravellerDetailResponse = components['schemas']['TravellerDetailResponse'];\ntype TravellerNoteResponse = components['schemas']['TravellerNoteResponse'];\ntype AddTravellerNoteRequest = components['schemas']['AddTravellerNoteRequest'];\nexport type TravellerAgencyProfileResponse =\n components['schemas']['TravellerAgencyProfileResponse'];\n\nexport interface EraseTravellerOptions {\n readonly ref: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ExportTravellerOptions {\n readonly ref: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ListForTripOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- travellers.getDetail / .addNote (manager-facing profile) ------------\n\nexport interface GetTravellerDetailOptions {\n readonly tripRef: string;\n readonly travellerRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AddTravellerNoteOptions extends AddTravellerNoteRequest {\n readonly tripRef: string;\n readonly travellerRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\ntype SearchTravellerDirectoryQuery = NonNullable<\n operations['searchTravellerDirectory']['parameters']['query']\n>;\n/** The filterable half of `searchTravellerDirectory`'s query params —\n * `cursor`/`limit` are the paginator's job; `q` is required, never a filter\n * the caller can omit. */\nexport type TravellerDirectoryFilters = Omit<SearchTravellerDirectoryQuery, 'cursor' | 'limit'>;\n\nasync function fetchAgencyDirectoryPage(\n client: KaafilHttpClient,\n agencyRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: TravellerDirectoryFilters;\n },\n) {\n const response = await client.execute<readonly TravellerDirectoryItemResponse[]>({\n method: 'GET',\n operationId: OperationId.SearchTravellerDirectory,\n path: '/api/v1/agencies/{ref}/travellers',\n pathParams: { ref: agencyRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListForAgencyOptions {\n readonly agencyRef: string;\n readonly filters: TravellerDirectoryFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListForAgencyPageOptions extends TravellerDirectoryFilters {\n readonly agencyRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\n// --- travellers.create ---------------------------------------------------\n\nexport interface CreateTravellerOptions extends CreateTravellerRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- travellers.getAgencyProfile (GAP-016) --------------------------------\n\nexport interface GetTravellerAgencyProfileOptions {\n readonly agencyRef: string;\n readonly travellerRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TravellersResource {\n /** `POST /api/v1/travellers/{ref}/erase` — DPDP right to erasure,\n * anonymize in place. Idempotent on `Traveller.erasedAt`. */\n erase(options: EraseTravellerOptions): Promise<KaafilResponse<EraseResponse>>;\n /** `GET /api/v1/travellers/{ref}/export` — DSAR export, generated fresh\n * on every call. Named `export_` because `export` is a reserved word. */\n export_(options: ExportTravellerOptions): Promise<KaafilResponse<DsarBundleResponse>>;\n /** `GET /api/v1/trips/{ref}/travellers` — the trip's manifest. Not\n * cursor-paginated, same as `./vendors.ts`'s `listTripVendors`. */\n listForTrip(\n options: ListForTripOptions,\n ): Promise<KaafilResponse<readonly TripManifestItemResponse[]>>;\n /** `GET /api/v1/trips/{ref}/travellers/{travellerRef}` — a manager-facing\n * profile: identity, booking status, party, profile-sourced attributes\n * (email/DOB/meal preference/dietary/allergies/medical notes/emergency\n * contact), current room/seat assignment, this trip's balance (`null`\n * when the agency's plan doesn't carry `collections` — a server-side\n * gate), and the note thread. */\n getDetail(options: GetTravellerDetailOptions): Promise<KaafilResponse<TravellerDetailResponse>>;\n /** `POST /api/v1/trips/{ref}/travellers/{travellerRef}/notes` — adds a\n * free-text note to a traveller's profile, scoped to this trip. */\n addNote(options: AddTravellerNoteOptions): Promise<KaafilResponse<TravellerNoteResponse>>;\n /** `GET /api/v1/agencies/{ref}/travellers` as a `KaafilPaginator` — the\n * agency-wide traveller directory search/browse. `q` is optional; omit it\n * to page through every traveller in the agency. */\n listForAgency(\n options: ListForAgencyOptions,\n ): KaafilPaginator<TravellerDirectoryItemResponse, TravellerDirectoryFilters>;\n /** The manual single-page escape hatch for `listForAgency`. */\n listForAgencyPage(\n options: ListForAgencyPageOptions,\n ): Promise<KaafilPagedResponse<readonly TravellerDirectoryItemResponse[]>>;\n /** `POST /api/v1/agencies/{ref}/travellers` (GAP-008) — adds a traveller\n * to the agency's directory directly. See this file's header for the\n * `externalTravellerId`-optional and existing-row-return behaviour. */\n create(options: CreateTravellerOptions): Promise<KaafilResponse<TravellerDirectoryItemResponse>>;\n /** `GET /api/v1/agencies/{ref}/travellers/{travellerRef}` (GAP-016) — the\n * agency-wide profile: identity, cross-trip `profile.*` attributes, every\n * trip this traveller has been on (each with its own balance, `null` when\n * none exists yet), a computed lifetime-finance total across those trips,\n * and every trip-scoped note, read-only. See this file's header for the\n * full citation. */\n getAgencyProfile(\n options: GetTravellerAgencyProfileOptions,\n ): Promise<KaafilResponse<TravellerAgencyProfileResponse>>;\n}\n\nexport function createTravellersResource(client: KaafilHttpClient): TravellersResource {\n return {\n async erase(options) {\n const { ref, idempotencyKey, signal } = options;\n return client.execute<EraseResponse>({\n method: 'POST',\n operationId: OperationId.EraseTraveller,\n path: '/api/v1/travellers/{ref}/erase',\n pathParams: { ref },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async export_(options) {\n const { ref, signal } = options;\n return client.execute<DsarBundleResponse>({\n method: 'GET',\n operationId: OperationId.ExportTraveller,\n path: '/api/v1/travellers/{ref}/export',\n pathParams: { ref },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async listForTrip(options) {\n const { tripRef, signal } = options;\n return client.execute<readonly TripManifestItemResponse[]>({\n method: 'GET',\n operationId: OperationId.GetTripManifest,\n path: '/api/v1/trips/{ref}/travellers',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async getDetail(options) {\n const { tripRef, travellerRef, signal } = options;\n return client.execute<TravellerDetailResponse>({\n method: 'GET',\n operationId: OperationId.GetTravellerDetail,\n path: '/api/v1/trips/{ref}/travellers/{travellerRef}',\n pathParams: { ref: tripRef, travellerRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async addNote(options) {\n const { tripRef, travellerRef, idempotencyKey, signal, ...body } = options;\n return client.execute<TravellerNoteResponse>({\n method: 'POST',\n operationId: OperationId.AddTravellerNote,\n path: '/api/v1/trips/{ref}/travellers/{travellerRef}/notes',\n pathParams: { ref: tripRef, travellerRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n listForAgency(options) {\n const { agencyRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchAgencyDirectoryPage(client, agencyRef, request),\n filters,\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listForAgencyPage(options) {\n const { agencyRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly TravellerDirectoryItemResponse[]>({\n method: 'GET',\n operationId: OperationId.SearchTravellerDirectory,\n path: '/api/v1/agencies/{ref}/travellers',\n pathParams: { ref: agencyRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<TravellerDirectoryItemResponse>({\n method: 'POST',\n operationId: OperationId.CreateTraveller,\n path: '/api/v1/agencies/{ref}/travellers',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async getAgencyProfile(options) {\n const { agencyRef, travellerRef, signal } = options;\n return client.execute<TravellerAgencyProfileResponse>({\n method: 'GET',\n operationId: OperationId.GetTravellerAgencyProfile,\n path: '/api/v1/agencies/{ref}/travellers/{travellerRef}',\n pathParams: { ref: agencyRef, travellerRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `treks` — the boarding-day board, walk-ins, and postpone. `architecture/08-\n * sdk.md §4`. Deliberately small: board/close/reopen belong to `pickups`, and\n * this module contributes only trek POLICY on top of them.\n *\n * All six operations — `board`, `walkIns.meta`, `walkIns.create`,\n * `walkIns.list` (GAP-006), `walkIns.reconcile`, and `postpone` — accept the\n * SAME three alternatives: a manager session, an agency-admin session, OR an\n * API key (`managerAuth`, `apiKeyAuth`, `agencyAdminAuth`; never an AND) —\n * see `../generated/security.ts`'s `OPERATION_SECURITY`, the source of truth\n * for all of this. The `ACTIVE_TREK_REF` sentinel (below) narrows this\n * further at the semantic layer for EVERY ONE of the six, `walkIns.list`/\n * `walkIns.reconcile` included: resolving `trekRef: 'active'` is\n * manager-only regardless of which of the above credentials the request\n * carries — an apiKey or agencyAdmin caller passing the sentinel gets\n * `422 ACTIVE_REQUIRES_MANAGER`, not the trek (`assertActiveSentinelResolvable`,\n * called by every one of these six engine-side).\n *\n * ── THE `active` SENTINEL ────────────────────────────────────────────────────\n *\n * `trekRef` in these paths is a dual-mode identity like every other `ref` in\n * this SDK — Kaafil id or the CRM's external id — PLUS one reserved word,\n * `ACTIVE_TREK_REF` (`'active'`), which resolves to the manager's CURRENT\n * trek rather than being looked up as an id at all. `RESERVED_TREK_REF` in the\n * engine already guards the ingest direction (an external trip id can never\n * literally be `\"active\"`); this path position is a second, distinct place\n * the same reservation applies, and the engine's own docblock says a new path\n * position \"must opt in explicitly\" rather than inheriting the ingest guard\n * for free. Exposed here as a named constant rather than left for a caller to\n * type the string, so `treks.board({ trekRef: ACTIVE_TREK_REF })` reads as\n * \"whichever trek this manager is on\" at the call site instead of a magic\n * string that happens to mean something special.\n *\n * The consequence for a real external trip id: one literally equal to\n * `\"active\"` can NEVER be addressed through any of these four routes — it\n * would always resolve as the sentinel instead. That is a property of the\n * contract, not a bug in this SDK; a CRM minting external ids should treat\n * `\"active\"` as unusable here the same way it would a reserved keyword in any\n * other system.\n *\n * When no trek is currently assigned, `board` still answers `200` with an\n * `emptyState` block (`{ reason: 'no_trek_assigned', message }`) rather than\n * `404` — the manager stays where they tapped instead of hitting an error\n * screen. Every OTHER trek endpoint (`walkIns.*`, `postpone`) answers `404`\n * for \"no such trek\" the normal way.\n *\n * A trek endpoint reached on an `eventType: 'TRIP'` trip is `422 NOT_A_TREK`\n * — wrong kind, not missing. Unknown or cross-scope stays `404`, the same\n * not-found used everywhere else in this SDK (`../http/errors.ts`'s standing\n * argument for why there is exactly one not-found class applies here too).\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype TrekBoardResponse = components['schemas']['TrekBoardResponse'];\ntype WalkInMetaResponse = components['schemas']['WalkInMetaResponse'];\ntype WalkInResponse = components['schemas']['WalkInResponse'];\ntype WalkInListItemResponse = components['schemas']['WalkInListItemResponse'];\ntype WalkInReconcileResponse = components['schemas']['WalkInReconcileResponse'];\ntype PostponeResponse = components['schemas']['PostponeResponse'];\ntype CreateTrekWalkInRequest = components['schemas']['CreateTrekWalkInRequest'];\ntype ReconcileTrekWalkInRequest = components['schemas']['ReconcileTrekWalkInRequest'];\ntype PostponeTrekRequest = components['schemas']['PostponeTrekRequest'];\n\n/**\n * The reserved `trekRef` value meaning \"the manager's current trek\" — see\n * this file's header. Never a real external trip id: the engine refuses to\n * ingest one equal to this string (`RESERVED_TREK_REF` in\n * `shared/ingest/external-ref.resolver.ts`), so no trip that reaches this SDK\n * can ever collide with it.\n */\nexport const ACTIVE_TREK_REF = 'active';\n\n// --- date-time widening --------------------------------------------------\n//\n// `newStartDate`/`newEndDate` are `string` (`Format: date-time`) in the\n// generated schema, because the schema is a faithful mirror of the spec and\n// the wire format really is a string. `PostponeTrekOptions` widens exactly\n// those two fields to `DateTimeInput` (see `../datetime`) by indexing off the\n// generated type and overriding — never restating a request body by hand.\n// The factory normalizes back down to `string` before the body reaches the\n// wire.\n\n// --- treks.board -----------------------------------------------------------\n\nexport interface ReadTrekBoardOptions {\n /** A trek's dual-mode ref, or `ACTIVE_TREK_REF` for the manager's current\n * one — see this file's header. */\n readonly trekRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- treks.walkIns -----------------------------------------------------------\n\nexport interface ReadTrekWalkInMetaOptions {\n readonly trekRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CreateTrekWalkInOptions extends CreateTrekWalkInRequest {\n readonly trekRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n/** `listTrekWalkIns` takes no filter query params beyond `cursor`/`limit` —\n * this is the paginator's `F` type parameter, kept as an explicit empty\n * shape (never `object`, which would also accept a stray non-empty value\n * unintentionally) so `setFilters({})` is the only value that ever\n * type-checks. */\ntype TrekWalkInFilters = Record<string, never>;\n\nasync function fetchTrekWalkInsPage(\n client: KaafilHttpClient,\n trekRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: TrekWalkInFilters;\n },\n) {\n const response = await client.execute<readonly WalkInListItemResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTrekWalkIns,\n path: '/api/v1/treks/{trekRef}/walk-ins',\n pathParams: { trekRef },\n query: { cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListTrekWalkInsOptions {\n /** A trek's dual-mode ref, or `ACTIVE_TREK_REF` for the manager's current\n * one — see this file's header. Same manager-only sentinel gate as\n * `board`/`walkIns.meta`/`walkIns.create`/`postpone`: an apiKey or\n * agencyAdmin caller passing `ACTIVE_TREK_REF` here gets\n * `422 ACTIVE_REQUIRES_MANAGER`, not the trek. */\n readonly trekRef: string;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListTrekWalkInsPageOptions {\n readonly trekRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReconcileTrekWalkInOptions extends ReconcileTrekWalkInRequest {\n readonly trekRef: string;\n readonly walkInId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TrekWalkInsResource {\n /** `GET /api/v1/treks/{trekRef}/walk-ins/meta` — the open pickup points a\n * walk-in may be assigned to, plus field hints for the intake form. */\n meta(options: ReadTrekWalkInMetaOptions): Promise<KaafilResponse<WalkInMetaResponse>>;\n /**\n * `POST /api/v1/treks/{trekRef}/walk-ins` — mints a Kaafil-owned traveller\n * (no `externalId`) plus a `WalkIn` row, and upserts the manifest so\n * rooming, seating and this trek's own board see them immediately. Name and\n * phone live on the traveller, never on the walk-in row — one PII home.\n * Reconciliation against a later CRM upsert happens by normalised phone and\n * emits no event of its own; a walk-in on a `CLOSED` stop auto-reopens it\n * through `pickups.reopen` in-process, so the eventual re-close carries the\n * corrective event, not this call.\n */\n create(options: CreateTrekWalkInOptions): Promise<KaafilResponse<WalkInResponse>>;\n /** `GET /api/v1/treks/{trekRef}/walk-ins` (GAP-006) as a `KaafilPaginator`\n * — the sibling read of `create`, one row per recorded walk-in. */\n list(options: ListTrekWalkInsOptions): KaafilPaginator<WalkInListItemResponse, TrekWalkInFilters>;\n /** The manual single-page escape hatch for `list`. */\n listPage(\n options: ListTrekWalkInsPageOptions,\n ): Promise<KaafilPagedResponse<readonly WalkInListItemResponse[]>>;\n /**\n * `POST /api/v1/treks/{trekRef}/walk-ins/{walkInId}/reconcile` — the human\n * fallback `create`'s own `needsReconciliation` notice promises: a\n * name-only walk-in (no phone) has nothing for the automatic CRM-phone\n * match to compare against, so it stays flagged until claimed by hand.\n * `travellerRef` must resolve to a traveller your CRM already knows (one\n * carrying an external id) — linking to another still-unreconciled\n * Kaafil-minted traveller just trades one unclaimed row for two, so the\n * engine refuses it. Writes the same two columns the automatic path\n * writes; `WalkIn.travellerId` itself is unchanged.\n */\n reconcile(options: ReconcileTrekWalkInOptions): Promise<KaafilResponse<WalkInReconcileResponse>>;\n}\n\n// --- treks.postpone ----------------------------------------------------------\n\nexport interface PostponeTrekOptions\n extends Omit<PostponeTrekRequest, 'newStartDate' | 'newEndDate'> {\n readonly trekRef: string;\n /** Must be in the future AND after the trek's current `startDate` — a\n * postpone moves the trip forward, never back. `CANCELLED`/`COMPLETED`\n * trips answer `422 CANNOT_POSTPONE`; a write racing the close-out lock\n * answers `423 LOCKED`. */\n readonly newStartDate: DateTimeInput;\n readonly newEndDate: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- treks -----------------------------------------------------------------\n\nexport interface TreksResource {\n /** `GET /api/v1/treks/{trekRef}/board` — stops with expected-vs-boarded,\n * the running head-count, and the current phase. See this file's header\n * for the sentinel and the no-trek `emptyState`. */\n board(options: ReadTrekBoardOptions): Promise<KaafilResponse<TrekBoardResponse>>;\n readonly walkIns: TrekWalkInsResource;\n /**\n * `POST /api/v1/treks/{trekRef}/postpone`. Shifts every `ItineraryDay` and\n * `StayWindow` by the same delta in ONE transaction; `sortOrder` and bed/seat\n * assignments are untouched throughout. Pickup `scheduledTime` is\n * DELIBERATELY NOT shifted — stop times are re-confirmed by the manager on\n * the ground, because they usually change with the new departure — so\n * `ripple` on the response reports itinerary and stay-window counts only,\n * never a pickup count. `postponedFromDate` on the response always holds the\n * FIRST original start date, even across a second postpone.\n */\n postpone(options: PostponeTrekOptions): Promise<KaafilResponse<PostponeResponse>>;\n}\n\nexport function createTreksResource(client: KaafilHttpClient): TreksResource {\n return {\n async board(options) {\n const { trekRef, signal } = options;\n return client.execute<TrekBoardResponse>({\n method: 'GET',\n operationId: OperationId.ReadTrekBoard,\n path: '/api/v1/treks/{trekRef}/board',\n pathParams: { trekRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async postpone(options) {\n const { trekRef, idempotencyKey, signal, newStartDate, newEndDate, ...rest } = options;\n const body: PostponeTrekRequest = {\n ...rest,\n newStartDate: normalizeDateTimeInput(newStartDate, 'newStartDate'),\n newEndDate: normalizeDateTimeInput(newEndDate, 'newEndDate'),\n };\n return client.execute<PostponeResponse>({\n method: 'POST',\n operationId: OperationId.PostponeTrek,\n path: '/api/v1/treks/{trekRef}/postpone',\n pathParams: { trekRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n walkIns: {\n async meta(options) {\n const { trekRef, signal } = options;\n return client.execute<WalkInMetaResponse>({\n method: 'GET',\n operationId: OperationId.ReadTrekWalkInMeta,\n path: '/api/v1/treks/{trekRef}/walk-ins/meta',\n pathParams: { trekRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { trekRef, idempotencyKey, signal, ...body } = options;\n return client.execute<WalkInResponse>({\n method: 'POST',\n operationId: OperationId.CreateTrekWalkIn,\n path: '/api/v1/treks/{trekRef}/walk-ins',\n pathParams: { trekRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n list(options) {\n const { trekRef, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchTrekWalkInsPage(client, trekRef, request),\n filters: {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { trekRef, cursor, limit, signal } = options;\n const response = await client.execute<readonly WalkInListItemResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTrekWalkIns,\n path: '/api/v1/treks/{trekRef}/walk-ins',\n pathParams: { trekRef },\n query: { cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n async reconcile(options) {\n const { trekRef, walkInId, idempotencyKey, signal, ...body } = options;\n return client.execute<WalkInReconcileResponse>({\n method: 'POST',\n operationId: OperationId.ReconcileTrekWalkIn,\n path: '/api/v1/treks/{trekRef}/walk-ins/{walkInId}/reconcile',\n pathParams: { trekRef, walkInId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `trips` — upsert, get, cancel, plus `travellers`, `managers`, `parties`,\n * `balance`, and the bulk push. `architecture/08-sdk.md §4`. MOST operations\n * here are `apiKeyAuth`-only in the spec (CRM-backend ingest,\n * `03-auth-and-tokens.md §1`) — `upsert`/`get`/`cancel`, `travellers.upsert`,\n * `bulk.push`, and `managers.upsert`/`assign`/`unassign`.\n *\n * `parties.*` (`listParties`/`createParty`/`patchParty`/`deleteParty`),\n * `managers.list`/`managers.patch` (`listTripManagers`/`patchTripManager`),\n * `travellers.pushManifest`/`travellers.remove`\n * (`pushManifest`/`removeFromManifest`), and `balance.push`\n * (`pushTripBalances`) are the exception: each accepts `managerAuth`,\n * `apiKeyAuth`, OR `agencyAdminAuth` in the spec (`../generated/security.ts`'s\n * `OPERATION_SECURITY`) — the same multi-scheme shape `./vendors.ts`'s\n * `listTripVendors` has. Following that file's precedent, this WHOLE\n * resource is exposed unchanged from both `../client.ts` and\n * `../client-entry.ts`; a manager- or agency-admin-opened `KaafilClient`\n * calling any of the `apiKeyAuth`-only members above simply fails at the\n * point of use with `UnsatisfiableSchemeError`, the same way a\n * `shareToken`-opened client calling `vendors`/`journey` already does. (Note:\n * `patchTripManager` also authenticates a manager bearer at the HTTP layer,\n * then REFUSES the act itself with `422 BUSINESS_RULE_VIOLATION` — see the\n * spec's own operation doc — which is a business rule this SDK does not\n * pre-empt client-side, the same posture every other role-gated write here\n * takes.)\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so a two-parameter route (`travellers.remove` takes a\n * trip ref AND a traveller ref; `managers.unassign`/`managers.patch` take a\n * trip ref AND a manager ref; `parties.patch`/`parties.remove` take a trip\n * ref AND a party id) can't be called with its arguments swapped.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype UpsertTripRequest = components['schemas']['UpsertTripRequest'];\ntype TripUpsertResponse = components['schemas']['TripUpsertResponse'];\ntype TripEchoResponse = components['schemas']['TripEchoResponse'];\ntype TripCancelResponse = components['schemas']['TripCancelResponse'];\ntype UpsertTravellerProfileRequest = components['schemas']['UpsertTravellerProfileRequest'];\ntype TravellerUpsertResponse = components['schemas']['TravellerUpsertResponse'];\ntype PushManifestRequest = components['schemas']['PushManifestRequest'];\ntype ManifestPushResponse = components['schemas']['ManifestPushResponse'];\ntype ManifestRemoveResponse = components['schemas']['ManifestRemoveResponse'];\ntype UpsertManagerRequest = components['schemas']['UpsertManagerRequest'];\ntype ManagerResponse = components['schemas']['ManagerResponse'];\ntype AssignManagerRequest = components['schemas']['AssignManagerRequest'];\ntype TripManagerResponse = components['schemas']['TripManagerResponse'];\ntype TripManagerRowResponse = components['schemas']['TripManagerRowResponse'];\ntype PatchTripManagerRequest = components['schemas']['PatchTripManagerRequest'];\ntype PartyDeltaResponse = components['schemas']['PartyDeltaResponse'];\ntype PartyResponse = components['schemas']['PartyResponse'];\ntype PartyDeleteResponse = components['schemas']['PartyDeleteResponse'];\ntype CreatePartyRequest = components['schemas']['CreatePartyRequest'];\ntype PatchPartyRequest = components['schemas']['PatchPartyRequest'];\n/** `PushTripBalancesRequest` is itself an array in the spec — there is no wrapper object. */\ntype PushTripBalancesRow = components['schemas']['PushTripBalancesRequest'][number];\ntype BalancePushResponse = components['schemas']['BalancePushResponse'];\n/** Likewise `PushBulkTripsRequest`. */\ntype PushBulkTripsItem = components['schemas']['PushBulkTripsRequest'][number];\ntype BulkTripsPushResponse = components['schemas']['BulkTripsPushResponse'];\n\n// --- date-time widening --------------------------------------------------\n//\n// Every field below is `string` (with `Format: date-time`) in the generated\n// schema, because the schema is a faithful mirror of the OpenAPI spec, and\n// the wire format really is a string. The `*Input` types here widen just\n// those fields to `DateTimeInput` (see `../datetime`) by indexing off the\n// generated type and overriding — never restating a whole request body by\n// hand — so a spec change to any *other* field on these shapes still flows\n// through untouched. The `create*Resource` functions below normalize back\n// down to the schema's `string` shape before the body reaches the wire.\n\ntype UpsertTripSegment = NonNullable<UpsertTripRequest['segments']>[number];\ntype UpsertTripSegmentInput = Omit<UpsertTripSegment, 'startDate' | 'endDate'> & {\n readonly startDate: DateTimeInput;\n readonly endDate: DateTimeInput;\n};\n\ntype PushManifestTraveller = PushManifestRequest['travellers'][number];\n/**\n * `sourceUpdatedAt` is OPTIONAL here, unlike every sibling below, because the\n * wire made it optional for this one entry shape: a desk adding a traveller to\n * a trip has no \"when my system last changed this\" instant to send, and the\n * server stamps the write when it is omitted. A CRM mirroring its own records\n * still sends its real instant and still wins or loses a race on it.\n */\ntype PushManifestTravellerInput = Omit<PushManifestTraveller, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt?: DateTimeInput;\n};\n\ntype PushBulkTripsTraveller = NonNullable<PushBulkTripsItem['travellers']>[number];\ntype PushBulkTripsTravellerInput = Omit<PushBulkTripsTraveller, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt: DateTimeInput;\n};\n\ntype PushBulkTripsBalanceRow = NonNullable<PushBulkTripsItem['balance']>[number];\ntype PushBulkTripsBalanceRowInput = Omit<PushBulkTripsBalanceRow, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt: DateTimeInput;\n};\n\ntype PushBulkTripsManager = NonNullable<PushBulkTripsItem['managers']>[number];\ntype PushBulkTripsManagerInput = Omit<PushBulkTripsManager, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt: DateTimeInput;\n};\n\ntype PushBulkTripsItemInput = Omit<\n PushBulkTripsItem,\n 'startDate' | 'endDate' | 'sourceUpdatedAt' | 'travellers' | 'balance' | 'managers'\n> & {\n readonly startDate: DateTimeInput;\n readonly endDate: DateTimeInput;\n readonly sourceUpdatedAt: DateTimeInput;\n readonly travellers?: readonly PushBulkTripsTravellerInput[];\n readonly balance?: readonly PushBulkTripsBalanceRowInput[];\n readonly managers?: readonly PushBulkTripsManagerInput[];\n};\n\n// --- trips.{upsert,get,cancel} ---------------------------------------------\n\nexport interface UpsertTripOptions\n extends Omit<UpsertTripRequest, 'startDate' | 'endDate' | 'sourceUpdatedAt' | 'segments'> {\n readonly startDate: DateTimeInput;\n readonly endDate: DateTimeInput;\n /** The CRM's own record-updated timestamp, used for last-write-wins\n * staleness detection (`06-offline-first.md §6`). Deliberately still\n * required, with no \"defaults to now\" — defaulting it would make every\n * write look like the newest write and silently defeat the staleness\n * check on out-of-order delivery. Accepting a `Date` here (via\n * `DateTimeInput`) is the correct amount of help: the caller still\n * supplies the CRM's real timestamp, just without hand-formatting it. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly segments?: readonly UpsertTripSegmentInput[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface GetTripOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CancelTripOptions {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- trips.travellers -------------------------------------------------------\n\nexport interface UpsertTravellerProfileOptions\n extends Omit<UpsertTravellerProfileRequest, 'sourceUpdatedAt'> {\n /** The traveller's own ref — dual-mode identity (Kaafil id or the CRM's\n * `externalTravellerId`); resolution is the engine's job. */\n readonly travellerRef: string;\n /** See the comment on `UpsertTripOptions.sourceUpdatedAt` — same contract,\n * required, never defaulted. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PushManifestOptions extends Omit<PushManifestRequest, 'travellers'> {\n readonly tripRef: string;\n readonly travellers: readonly PushManifestTravellerInput[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface RemoveFromManifestOptions {\n readonly tripRef: string;\n readonly travellerRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripTravellersResource {\n upsert(options: UpsertTravellerProfileOptions): Promise<KaafilResponse<TravellerUpsertResponse>>;\n pushManifest(options: PushManifestOptions): Promise<KaafilResponse<ManifestPushResponse>>;\n remove(options: RemoveFromManifestOptions): Promise<KaafilResponse<ManifestRemoveResponse>>;\n}\n\n// --- trips.managers ----------------------------------------------------------\n\nexport interface UpsertManagerOptions extends Omit<UpsertManagerRequest, 'sourceUpdatedAt'> {\n /** See the comment on `UpsertTripOptions.sourceUpdatedAt` — same contract,\n * required, never defaulted. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AssignManagerOptions extends Omit<AssignManagerRequest, 'sourceUpdatedAt'> {\n readonly tripRef: string;\n /** OPTIONAL, unlike every other `sourceUpdatedAt` in this file, and only\n * because this route now accepts an agency admin as well as an API key. A\n * CRM sends its own last-changed instant and should keep doing so — that\n * is what orders concurrent writes. A desk operator assigning a manager\n * by hand has no such instant, so omitting it lets the SERVER stamp the\n * write, which beats a client inventing one from its own clock.\n *\n * See the comment on `UpsertTripOptions.sourceUpdatedAt` — same contract,\n * required, never defaulted. */\n readonly sourceUpdatedAt?: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UnassignManagerOptions {\n readonly tripRef: string;\n readonly managerRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ListTripManagersOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchTripManagerOptions extends PatchTripManagerRequest {\n readonly tripRef: string;\n readonly managerRef: string;\n /** Required, not optional — see `../resources/itinerary.ts`'s\n * `PatchItineraryItemOptions.version` for why a missing `If-Match` and a\n * stale one are deliberately the same `409 CONFLICT_VERSION`. Pass the\n * `version` from `managers.list`'s (or `managers.assign`'s) row. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripManagersResource {\n /** Not trip-scoped — `POST /api/v1/managers` upserts the manager entity\n * itself (dual-mode identity), independent of any one trip assignment. */\n upsert(options: UpsertManagerOptions): Promise<KaafilResponse<ManagerResponse>>;\n assign(options: AssignManagerOptions): Promise<KaafilResponse<TripManagerResponse>>;\n unassign(options: UnassignManagerOptions): Promise<KaafilResponse<TripManagerResponse>>;\n /** `GET /api/v1/trips/{ref}/managers` — every live manager assigned to\n * this trip, leads first. Not cursor-paginated, same posture as\n * `./vendors.ts`'s `listTripVendors`.\n *\n * Each row also carries the manager's vehicle on this trip (`vehicleReg`/\n * `vehicleType`, `null`/`null` when they own none), a few admin-panel\n * display fields (`contactLine`, `label`, `assignedOnLabel`), and two\n * per-request permission hints computed against the calling credential\n * (`canSetPrimary`, `canRemove` — the latter `false` only for a `manager`\n * bearer; unassign now accepts an agency admin too). */\n list(\n options: ListTripManagersOptions,\n ): Promise<KaafilResponse<readonly TripManagerRowResponse[]>>;\n /** `PATCH /api/v1/trips/{ref}/managers/{managerRef}` — changes `role` and/\n * or promotes/demotes the trip lead. See this file's header for the\n * `managerAuth`-authenticated-but-business-rule-refused case. */\n patch(options: PatchTripManagerOptions): Promise<KaafilResponse<TripManagerRowResponse>>;\n}\n\n// --- trips.parties -------------------------------------------------------------\n\nexport interface ListPartiesOptions {\n readonly tripRef: string;\n /** See `./itinerary.ts`'s `ReadItineraryOptions.since` — the identical\n * shared delta-sync cursor contract. Omit for every LIVE party; supply a\n * previous response's own cursor for a delta (live + newly-retired,\n * tombstones for the latter). */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n/** One row of `parties.list`'s result: a live party, or the tombstone for\n * one retired since the cursor. Aliased off the response type rather than\n * restated, so the union stays whatever the contract says it is — see\n * `./itinerary.ts`'s `ItineraryItemDeltaRow` for the identical pattern. */\nexport type PartyDeltaRow = PartyDeltaResponse;\n\nexport interface AddPartyOptions extends CreatePartyRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchPartyOptions extends PatchPartyRequest {\n readonly tripRef: string;\n readonly partyId: string;\n /** Required, not optional — same contract as\n * `PatchTripManagerOptions.version`. Pass the `version` from `parties.list`\n * (or a prior `add`/`patch`). */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface RemovePartyOptions {\n readonly tripRef: string;\n readonly partyId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripPartiesResource {\n /** `GET /api/v1/trips/{ref}/parties` — every live party and its current\n * members, or, with `?since=`, the delta since a prior cursor. */\n list(options: ListPartiesOptions): Promise<KaafilResponse<readonly PartyDeltaRow[]>>;\n /** `POST /api/v1/trips/{ref}/parties` — creates a PINNED party (the\n * manager override). */\n add(options: AddPartyOptions): Promise<KaafilResponse<PartyResponse>>;\n patch(options: PatchPartyOptions): Promise<KaafilResponse<PartyResponse>>;\n /** Retires the party. No `If-Match`/`version` — idempotent on an\n * already-retired party, the same `{ id, deleted: true }` ack, never a\n * `404`. */\n remove(options: RemovePartyOptions): Promise<KaafilResponse<PartyDeleteResponse>>;\n}\n\n// --- trips.balance / trips.bulk ----------------------------------------------\n\ntype PushTripBalancesRowInput = Omit<PushTripBalancesRow, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt: DateTimeInput;\n};\n\nexport interface PushTripBalancesOptions {\n readonly tripRef: string;\n readonly balances: readonly PushTripBalancesRowInput[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripBalanceResource {\n push(options: PushTripBalancesOptions): Promise<KaafilResponse<BalancePushResponse>>;\n}\n\nexport interface PushBulkTripsOptions {\n readonly trips: readonly PushBulkTripsItemInput[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripsBulkResource {\n /** `POST /api/v1/bulk/trips` — a batch of full trip bundles (trip +\n * manifest + balance + managers) in one call. */\n push(options: PushBulkTripsOptions): Promise<KaafilResponse<BulkTripsPushResponse>>;\n}\n\n// --- trips -------------------------------------------------------------------\n\nexport interface TripsResource {\n upsert(options: UpsertTripOptions): Promise<KaafilResponse<TripUpsertResponse>>;\n get(options: GetTripOptions): Promise<KaafilResponse<TripEchoResponse>>;\n cancel(options: CancelTripOptions): Promise<KaafilResponse<TripCancelResponse>>;\n readonly travellers: TripTravellersResource;\n readonly managers: TripManagersResource;\n readonly parties: TripPartiesResource;\n readonly balance: TripBalanceResource;\n readonly bulk: TripsBulkResource;\n}\n\n/**\n * `trips.bulk.push` carries the same four date-time fields as `upsert`,\n * `pushManifest`, `balance.push` and `managers.assign` combined — trip,\n * travellers, balance and managers rows all riding in one bundle — which is\n * exactly why hand-writing ISO strings there is the most painful and most\n * error-prone spot on the whole ingest surface. Pulled out to its own\n * function rather than inlined in `bulk.push` because there are four\n * separately-optional nested collections to walk.\n */\nfunction normalizeBulkTripsItem(\n item: PushBulkTripsItemInput,\n tripIndex: number,\n): PushBulkTripsItem {\n const { startDate, endDate, sourceUpdatedAt, travellers, balance, managers, ...rest } = item;\n return {\n ...rest,\n startDate: normalizeDateTimeInput(startDate, `trips[${tripIndex}].startDate`),\n endDate: normalizeDateTimeInput(endDate, `trips[${tripIndex}].endDate`),\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, `trips[${tripIndex}].sourceUpdatedAt`),\n ...(travellers !== undefined\n ? {\n travellers: travellers.map((traveller, index) => ({\n ...traveller,\n sourceUpdatedAt: normalizeDateTimeInput(\n traveller.sourceUpdatedAt,\n `trips[${tripIndex}].travellers[${index}].sourceUpdatedAt`,\n ),\n })),\n }\n : {}),\n ...(balance !== undefined\n ? {\n balance: balance.map((row, index) => ({\n ...row,\n sourceUpdatedAt: normalizeDateTimeInput(\n row.sourceUpdatedAt,\n `trips[${tripIndex}].balance[${index}].sourceUpdatedAt`,\n ),\n })),\n }\n : {}),\n ...(managers !== undefined\n ? {\n managers: managers.map((manager, index) => ({\n ...manager,\n sourceUpdatedAt: normalizeDateTimeInput(\n manager.sourceUpdatedAt,\n `trips[${tripIndex}].managers[${index}].sourceUpdatedAt`,\n ),\n })),\n }\n : {}),\n };\n}\n\nexport function createTripsResource(client: KaafilHttpClient): TripsResource {\n return {\n async upsert(options) {\n const { idempotencyKey, signal, startDate, endDate, sourceUpdatedAt, segments, ...rest } =\n options;\n const body: UpsertTripRequest = {\n ...rest,\n startDate: normalizeDateTimeInput(startDate, 'startDate'),\n endDate: normalizeDateTimeInput(endDate, 'endDate'),\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n ...(segments !== undefined\n ? {\n segments: segments.map((segment, index) => ({\n ...segment,\n startDate: normalizeDateTimeInput(\n segment.startDate,\n `segments[${index}].startDate`,\n ),\n endDate: normalizeDateTimeInput(segment.endDate, `segments[${index}].endDate`),\n })),\n }\n : {}),\n };\n return client.execute<TripUpsertResponse>({\n method: 'POST',\n operationId: OperationId.UpsertTrip,\n path: '/api/v1/trips',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async get(options) {\n const { tripRef, signal } = options;\n return client.execute<TripEchoResponse>({\n method: 'GET',\n operationId: OperationId.GetTrip,\n path: '/api/v1/trips/{ref}',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async cancel(options) {\n const { tripRef, idempotencyKey, signal } = options;\n return client.execute<TripCancelResponse>({\n method: 'DELETE',\n operationId: OperationId.CancelTrip,\n path: '/api/v1/trips/{ref}',\n pathParams: { ref: tripRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n travellers: {\n async upsert(options) {\n const { travellerRef, idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n const body: UpsertTravellerProfileRequest = {\n ...rest,\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n };\n return client.execute<TravellerUpsertResponse>({\n method: 'POST',\n operationId: OperationId.UpsertTravellerProfile,\n path: '/api/v1/travellers/{ref}',\n pathParams: { ref: travellerRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async pushManifest(options) {\n const { tripRef, idempotencyKey, signal, travellers, ...rest } = options;\n const body: PushManifestRequest = {\n ...rest,\n // `sourceUpdatedAt` is optional on this entry shape. Omitted, the\n // key is left OFF the body entirely rather than sent as `undefined`\n // — the server stamps the write itself, and an explicit `undefined`\n // would serialise as a missing key anyway but read, in this file, as\n // though a value had been intended.\n travellers: travellers.map((traveller, index) => {\n const { sourceUpdatedAt, ...entry } = traveller;\n return sourceUpdatedAt === undefined\n ? entry\n : {\n ...entry,\n sourceUpdatedAt: normalizeDateTimeInput(\n sourceUpdatedAt,\n `travellers[${index}].sourceUpdatedAt`,\n ),\n };\n }),\n };\n return client.execute<ManifestPushResponse>({\n method: 'POST',\n operationId: OperationId.PushManifest,\n path: '/api/v1/trips/{ref}/travellers',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, travellerRef, idempotencyKey, signal } = options;\n return client.execute<ManifestRemoveResponse>({\n method: 'DELETE',\n operationId: OperationId.RemoveFromManifest,\n path: '/api/v1/trips/{ref}/travellers/{travellerRef}',\n pathParams: { ref: tripRef, travellerRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n managers: {\n async upsert(options) {\n const { idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n const body: UpsertManagerRequest = {\n ...rest,\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n };\n return client.execute<ManagerResponse>({\n method: 'POST',\n operationId: OperationId.UpsertManager,\n path: '/api/v1/managers',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async assign(options) {\n const { tripRef, idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n // Omitted entirely rather than sent as `null`/`undefined`: the\n // server's own default only applies to an ABSENT key, and a desk\n // caller has no stamp to send. A CRM still passes one.\n const body: AssignManagerRequest = {\n ...rest,\n ...(sourceUpdatedAt === undefined\n ? {}\n : { sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt') }),\n };\n return client.execute<TripManagerResponse>({\n method: 'POST',\n operationId: OperationId.AssignManager,\n path: '/api/v1/trips/{ref}/managers',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async unassign(options) {\n const { tripRef, managerRef, idempotencyKey, signal } = options;\n return client.execute<TripManagerResponse>({\n method: 'DELETE',\n operationId: OperationId.UnassignManager,\n path: '/api/v1/trips/{ref}/managers/{managerRef}',\n pathParams: { ref: tripRef, managerRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { tripRef, signal } = options;\n return client.execute<readonly TripManagerRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTripManagers,\n path: '/api/v1/trips/{ref}/managers',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, managerRef, version, signal, ...body } = options;\n return client.execute<TripManagerRowResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchTripManager,\n path: '/api/v1/trips/{ref}/managers/{managerRef}',\n pathParams: { ref: tripRef, managerRef },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n parties: {\n async list(options) {\n const { tripRef, since, signal } = options;\n return client.execute<readonly PartyDeltaRow[]>({\n method: 'GET',\n operationId: OperationId.ListParties,\n path: '/api/v1/trips/{ref}/parties',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async add(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<PartyResponse>({\n method: 'POST',\n operationId: OperationId.CreateParty,\n path: '/api/v1/trips/{ref}/parties',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, partyId, version, signal, ...body } = options;\n return client.execute<PartyResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchParty,\n path: '/api/v1/trips/{ref}/parties/{partyId}',\n pathParams: { ref: tripRef, partyId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, partyId, idempotencyKey, signal } = options;\n return client.execute<PartyDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteParty,\n path: '/api/v1/trips/{ref}/parties/{partyId}',\n pathParams: { ref: tripRef, partyId },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n balance: {\n async push(options) {\n const { tripRef, balances, idempotencyKey, signal } = options;\n const body: readonly PushTripBalancesRow[] = balances.map((row, index) => ({\n ...row,\n sourceUpdatedAt: normalizeDateTimeInput(\n row.sourceUpdatedAt,\n `balances[${index}].sourceUpdatedAt`,\n ),\n }));\n return client.execute<BalancePushResponse>({\n method: 'POST',\n operationId: OperationId.PushTripBalances,\n path: '/api/v1/trips/{ref}/balance',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n bulk: {\n async push(options) {\n const { trips, idempotencyKey, signal } = options;\n const body: readonly PushBulkTripsItem[] = trips.map((item, index) =>\n normalizeBulkTripsItem(item, index),\n );\n return client.execute<BulkTripsPushResponse>({\n method: 'POST',\n operationId: OperationId.PushBulkTrips,\n path: '/api/v1/bulk/trips',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `vendors` — the trip vendor list, plus the agency's own vendor directory\n * CRUD (GAP-005). `architecture/08-sdk.md §4` (\"`managers` / `vendors` …\n * `list` (vendors optional)\").\n *\n * `list` (`listTripVendors`) accepts `apiKeyAuth`, `managerAuth`, OR\n * `agencyAdminAuth` in the spec (`../generated/security.ts`'s\n * `OPERATION_SECURITY`) — an API key, a manager session, or an agency-admin\n * session all read the same agency vendor directory. Not cursor-paginated:\n * `listTripVendors` declares no `cursor`/`limit` query parameters, so this\n * returns the full list directly rather than a `KaafilPaginator`.\n *\n * `upsert`/`remove` (`upsertVendor`/`deleteVendor`,\n * `PUT`/`DELETE /api/v1/agencies/{ref}/vendors/{externalVendorId}`) accept\n * `apiKeyAuth` OR `agencyAdminAuth` — NEVER `managerAuth`: the vendor\n * directory is an agency-wide CRM-fed record, not something worked from a\n * trip on the ground, the same posture `./travellers.ts`'s `create` takes.\n * `Vendor.externalId` is REQUIRED and, on those two calls, never\n * Kaafil-minted — so `externalVendorId` is a path parameter on both, not an\n * optional body field. `create` (`createVendor`, `POST /api/v1/agencies/\n * {ref}/vendors`) is the one form that DOES let Kaafil mint one, prefixed\n * `kf-`, for a vendor an agency admin adds by hand and therefore has no CRM\n * id for; the minted value is an ordinary `externalId` afterwards, so\n * `upsert`/`remove` address such a vendor exactly like a CRM-fed one using\n * the `externalId` the trip vendor list now returns.\n * `upsert` is LWW on `sourceUpdatedAt`, the same \"stamp not newer than\n * stored → `200 ignored_stale`\" contract every other CRM-ingest upsert in\n * this SDK uses — though that field is now OPTIONAL: omit it and the server\n * stamps its own clock, which is what an admin editing by hand needs, since\n * they have no CRM stamp and a stale one would silently drop the edit; `created: true` only on the vendor's first sighting.\n * `remove` requires `If-Match` and soft-deletes (`deletedAt`); it REFUSES\n * with `422 BUSINESS_RULE_VIOLATION` (`details.rule:\n * \"vendor.deleteBlockedByReferences\"`) rather than nulling either reference\n * when a live `Vehicle.vendorId` or `Expense.vendorId` still points at the\n * vendor. Its success body is a literal `data: false` — not a deleted-row\n * echo — so this file types it as `KaafilResponse<false>`, the same\n * convention `./forms.ts`'s header documents for its own delete calls.\n * Because neither `upsert` nor `remove` accepts `managerAuth`, both are\n * agencyRef-BOUND on `../client-entry.ts` — see that file's \"agencyRef-bound\n * option types\" section.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype VendorSummaryResponse = components['schemas']['VendorSummaryResponse'];\ntype UpsertVendorRequest = components['schemas']['UpsertVendorRequest'];\ntype CreateVendorRequest = components['schemas']['CreateVendorRequest'];\ntype VendorUpsertResponse = components['schemas']['VendorUpsertResponse'];\n\nexport interface ListTripVendorsOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UpsertVendorOptions extends UpsertVendorRequest {\n readonly agencyRef: string;\n readonly externalVendorId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n/**\n * `POST /api/v1/agencies/{ref}/vendors` — no `externalVendorId` and no\n * `sourceUpdatedAt`, deliberately: the server mints the first (prefixed\n * `kf-`) and stamps the second. This is the create path for a vendor the\n * AGENCY authored rather than one a CRM pushed; see this file's header.\n */\nexport interface CreateVendorOptions extends CreateVendorRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteVendorOptions {\n readonly agencyRef: string;\n readonly externalVendorId: string;\n /** Required — see this file's header, \"the agency's own vendor directory\"\n * section. */\n readonly version: number;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface VendorsResource {\n /** `GET /api/v1/trips/{ref}/vendors`. */\n list(options: ListTripVendorsOptions): Promise<KaafilResponse<readonly VendorSummaryResponse[]>>;\n /** `POST /api/v1/agencies/{ref}/vendors` — Kaafil mints the external id. */\n create(options: CreateVendorOptions): Promise<KaafilResponse<VendorUpsertResponse>>;\n /** `PUT /api/v1/agencies/{ref}/vendors/{externalVendorId}` (GAP-005). */\n upsert(options: UpsertVendorOptions): Promise<KaafilResponse<VendorUpsertResponse>>;\n /** `DELETE /api/v1/agencies/{ref}/vendors/{externalVendorId}` (GAP-005).\n * Success body is a literal `data: false` — see this file's header. */\n remove(options: DeleteVendorOptions): Promise<KaafilResponse<false>>;\n}\n\nexport function createVendorsResource(client: KaafilHttpClient): VendorsResource {\n return {\n async list(options) {\n const { tripRef, signal } = options;\n return client.execute<readonly VendorSummaryResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTripVendors,\n path: '/api/v1/trips/{ref}/vendors',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<VendorUpsertResponse>({\n method: 'POST',\n operationId: OperationId.CreateVendor,\n path: '/api/v1/agencies/{ref}/vendors',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async upsert(options) {\n const { agencyRef, externalVendorId, idempotencyKey, signal, ...body } = options;\n return client.execute<VendorUpsertResponse>({\n method: 'PUT',\n operationId: OperationId.UpsertVendor,\n path: '/api/v1/agencies/{ref}/vendors/{externalVendorId}',\n pathParams: { ref: agencyRef, externalVendorId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { agencyRef, externalVendorId, version, idempotencyKey, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteVendor,\n path: '/api/v1/agencies/{ref}/vendors/{externalVendorId}',\n pathParams: { ref: agencyRef, externalVendorId },\n headers: { 'If-Match': String(version) },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `webhooks` — the API-key-reachable operations only: list deliveries, read\n * a delivery, redeliver, replay, and send one test event.\n * `architecture/08-sdk.md §4`, amended `C-028`: \"the delivery-facing\n * operations … and `replayEndpoint` are API-key\" —\n * `configure`/`rotateSecret` (console-session, endpoint CRUD) are a\n * different auth model entirely and are out of this lane's scope by the\n * brief's own instruction.\n *\n * `testEvent` joined the group when the engine published an API-key entry\n * point onto the operation that used to be console-only. There are now TWO\n * routes onto the same controller and this SDK can only ever call one of\n * them: `POST /api/v1/webhooks/endpoints/{id}/test`\n * (`testWebhookEndpointApiKey`, `['apiKeyAuth']`) is the one below, and\n * `POST /api/v1/webhooks/endpoints/{id}/test-event` (`testWebhookEndpoint`)\n * is `['consoleAuth']` alone — unreachable by any credential a\n * `CredentialResolver` holds (`../auth/credentials.ts`), so it is\n * deliberately absent here. Do not repoint `testEvent` at `/test-event`\n * \"because it looks the same\": it would fail with\n * `UnsatisfiableSchemeError` before a request was built.\n *\n * `listWebhookDeliveries` is cursor-paginated (`cursor`+`limit` query params,\n * `meta.page.hasNext`); `deliveries.list()` returns a `KaafilPaginator` and\n * `deliveries.listPage()` is the manual single-page escape hatch for a\n * caller who wants to drive paging itself (`../pagination/paginator.ts`).\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype DeliveryResponse = components['schemas']['DeliveryResponse'];\ntype DeliveryDetailResponse = components['schemas']['DeliveryDetailResponse'];\ntype RedeliverResponse = components['schemas']['RedeliverResponse'];\ntype ReplayResponse = components['schemas']['ReplayResponse'];\ntype ReplayWebhookEndpointRequest = components['schemas']['ReplayWebhookEndpointRequest'];\ntype TestEventResponse = components['schemas']['TestEventResponse'];\ntype TestWebhookEndpointApiKeyRequest = components['schemas']['TestWebhookEndpointApiKeyRequest'];\n\ntype ListWebhookDeliveriesQuery = NonNullable<\n operations['listWebhookDeliveries']['parameters']['query']\n>;\n/** The filterable half of `listWebhookDeliveries`'s query params — `cursor`\n * and `limit` are the paginator's job, never the caller's to hold. */\nexport type WebhookDeliveryFilters = Omit<ListWebhookDeliveriesQuery, 'cursor' | 'limit'>;\n\nasync function fetchDeliveriesPage(\n client: KaafilHttpClient,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: WebhookDeliveryFilters;\n },\n) {\n const response = await client.execute<readonly DeliveryResponse[]>({\n method: 'GET',\n operationId: OperationId.ListWebhookDeliveries,\n path: '/api/v1/webhooks/deliveries',\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListWebhookDeliveriesOptions {\n readonly filters?: WebhookDeliveryFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListWebhookDeliveriesPageOptions extends WebhookDeliveryFilters {\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadWebhookDeliveryOptions {\n readonly id: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface RedeliverWebhookDeliveryOptions {\n readonly id: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReplayWebhookEndpointOptions extends ReplayWebhookEndpointRequest {\n /** The endpoint to replay against — `replayWebhookEndpoint`'s path\n * parameter is the webhook endpoint id, not a delivery id. */\n readonly endpointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TestWebhookEndpointOptions extends TestWebhookEndpointApiKeyRequest {\n /** The endpoint to send the test event to — `testWebhookEndpointApiKey`'s\n * path parameter is the webhook endpoint id, same as `replay`'s. */\n readonly endpointId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface WebhookDeliveriesResource {\n /** `GET /api/v1/webhooks/deliveries` as a `KaafilPaginator` — the SDK holds\n * the cursor; the consumer never sees or stores one. */\n list(\n options?: ListWebhookDeliveriesOptions,\n ): KaafilPaginator<DeliveryResponse, WebhookDeliveryFilters>;\n /** The manual single-page escape hatch: fetches exactly one page and\n * returns it directly, for a caller who wants to drive paging itself\n * rather than use the paginator `list()` returns. */\n listPage(\n options?: ListWebhookDeliveriesPageOptions,\n ): Promise<KaafilPagedResponse<readonly DeliveryResponse[]>>;\n read(options: ReadWebhookDeliveryOptions): Promise<KaafilResponse<DeliveryDetailResponse>>;\n redeliver(options: RedeliverWebhookDeliveryOptions): Promise<KaafilResponse<RedeliverResponse>>;\n}\n\nexport interface WebhooksResource {\n readonly deliveries: WebhookDeliveriesResource;\n /** `POST /api/v1/webhooks/endpoints/{id}/replay` — re-delivers every event\n * since `from` to one endpoint. */\n replay(options: ReplayWebhookEndpointOptions): Promise<KaafilResponse<ReplayResponse>>;\n /** `POST /api/v1/webhooks/endpoints/{id}/test` — sends ONE fabricated,\n * signed sample event of `eventType` (one concrete type, never the `\"*\"`\n * wildcard) to that endpoint, through the real delivery worker.\n *\n * Called directly rather than queued, so the response is the ONE attempt's\n * real result — `statusCode` (`null` on a timeout, network error or\n * blocked destination), `latencyMs`, the `signatureHeaderSample` headers\n * signed with the CURRENT secret (verify against those to prove your\n * receiver end-to-end), and `deliveryId` — not a fire-and-forget `202`.\n *\n * Never touches tenant state. The minted id is always `evt_test_`-prefixed\n * — never a real event id — and the payload carries fabricated `TEST-*`\n * `externalRefs` rather than any of your rows, so nothing here can be\n * mistaken for, or corrupt, production data. The attempt is also excluded\n * from every delivery health metric (`health`/`stats` on the endpoint\n * reads), so probing your own endpoint cannot tank its own success rate.\n *\n * Works on BOTH planes: it targets the named endpoint directly instead of\n * going through the plane-matched fan-out, so a LIVE-keyed client testing\n * a LIVE endpoint is the normal case — this is not a TEST-plane sandbox\n * tool and nothing gates it on `environment` (contrast `./test.ts`, whose\n * `TestEnvironmentRequiredError` covers only the six `/api/v1/test/*`\n * operations).\n *\n * Not idempotent-capable — every call sends a fresh event by design, so\n * there is no `idempotencyKey` to pass\n * (`OPERATION_ACCEPTS_IDEMPOTENCY_KEY.testWebhookEndpointApiKey` is\n * `false`). */\n testEvent(options: TestWebhookEndpointOptions): Promise<KaafilResponse<TestEventResponse>>;\n}\n\nexport function createWebhooksResource(client: KaafilHttpClient): WebhooksResource {\n return {\n deliveries: {\n list(options = {}) {\n return createPaginator({\n fetchPage: (request) => fetchDeliveriesPage(client, request),\n filters: options.filters ?? {},\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n });\n },\n async listPage(options = {}) {\n const { cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly DeliveryResponse[]>({\n method: 'GET',\n operationId: OperationId.ListWebhookDeliveries,\n path: '/api/v1/webhooks/deliveries',\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n async read(options) {\n const { id, signal } = options;\n return client.execute<DeliveryDetailResponse>({\n method: 'GET',\n operationId: OperationId.ReadWebhookDelivery,\n path: '/api/v1/webhooks/deliveries/{id}',\n pathParams: { id },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async redeliver(options) {\n const { id, idempotencyKey, signal } = options;\n return client.execute<RedeliverResponse>({\n method: 'POST',\n operationId: OperationId.RedeliverWebhookDelivery,\n path: '/api/v1/webhooks/deliveries/{id}/redeliver',\n pathParams: { id },\n body: {},\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n async replay(options) {\n const { endpointId, idempotencyKey, signal, ...body } = options;\n return client.execute<ReplayResponse>({\n method: 'POST',\n operationId: OperationId.ReplayWebhookEndpoint,\n path: '/api/v1/webhooks/endpoints/{id}/replay',\n pathParams: { id: endpointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async testEvent(options) {\n const { endpointId, signal, ...body } = options;\n return client.execute<TestEventResponse>({\n method: 'POST',\n operationId: OperationId.TestWebhookEndpointApiKey,\n path: '/api/v1/webhooks/endpoints/{id}/test',\n pathParams: { id: endpointId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `Kaafil` — the server client, exported from `src/index.ts`\n * (`kaafil-js`). Constructed with the partner API key; carries every\n * resource group an API key can reach. `architecture/08-sdk.md §2, §3.1`.\n *\n * This module is the ONLY place an API-key credential is ever assembled and\n * checked — `guardApiKeyEnvironment`/`assertApiKeyMatchesEnvironment`\n * (`./config.ts`) and the `{ kind: 'apiKey', apiKey }` config object below.\n * `./client-entry.ts` (the browser entry) does not import this file, does\n * not import those two guards, and builds no credential of this shape —\n * see that file's header comment for the structural argument, not just a\n * convention, for why a bundler following only the browser entry's import\n * graph has no path to this one.\n */\n\nimport type { Resolvable } from './auth/credentials';\nimport { CredentialResolver } from './auth/credentials';\nimport {\n assertValidMaxAttempts,\n assertValidTimeout,\n type Environment,\n guardApiKeyEnvironment,\n resolveBaseUrl,\n} from './config';\nimport type { KaafilHttpClient } from './http/client';\nimport { createHttpClient } from './http/client';\nimport { newIdempotencyKey } from './idempotency';\nimport type { AgenciesResource } from './resources/agencies';\nimport { createAgenciesResource } from './resources/agencies';\nimport type { AgencyAdminsResource } from './resources/agency-admins';\nimport { createAgencyAdminsResource } from './resources/agency-admins';\nimport type { AuthResource } from './resources/auth';\nimport { createAuthResource } from './resources/auth';\nimport type { BookingsResource } from './resources/bookings';\nimport { createBookingsResource } from './resources/bookings';\nimport type { ChecklistsResource } from './resources/checklists';\nimport { createChecklistsResource } from './resources/checklists';\nimport type { CloseoutResource } from './resources/closeout';\nimport { createCloseoutResource } from './resources/closeout';\nimport type { CollectionsResource } from './resources/collections';\nimport { createCollectionsResource } from './resources/collections';\nimport type { CommsResource } from './resources/comms';\nimport { createCommsResource } from './resources/comms';\nimport type { EventsResource } from './resources/events';\nimport { createEventsResource } from './resources/events';\nimport type { ExpensesResource } from './resources/expenses';\nimport { createExpensesResource } from './resources/expenses';\nimport type { FeedbackNpsResource } from './resources/feedback-nps';\nimport { createFeedbackNpsResource } from './resources/feedback-nps';\nimport type { FilesResource } from './resources/files';\nimport { createFilesResource } from './resources/files';\nimport type { FloatResource } from './resources/float';\nimport { createFloatResource } from './resources/float';\nimport type { FormsResource } from './resources/forms';\nimport { createFormsResource } from './resources/forms';\nimport type { ItineraryResource } from './resources/itinerary';\nimport { createItineraryResource } from './resources/itinerary';\nimport type { JourneyResource } from './resources/journey';\nimport { createJourneyResource } from './resources/journey';\nimport type { ManagerTodayResource } from './resources/manager-today';\nimport { createManagerTodayResource } from './resources/manager-today';\nimport type { PickupsResource } from './resources/pickups';\nimport { createPickupsResource } from './resources/pickups';\nimport type { RoomingResource } from './resources/rooming';\nimport { createRoomingResource } from './resources/rooming';\nimport type { SeatingResource } from './resources/seating';\nimport { createSeatingResource } from './resources/seating';\nimport type { ShareTokensResource } from './resources/share-tokens';\nimport { createShareTokensResource } from './resources/share-tokens';\nimport type { SyncResource } from './resources/sync';\nimport { createSyncResource } from './resources/sync';\nimport type { TestResource } from './resources/test';\nimport { createTestResource } from './resources/test';\nimport type { TravellersResource } from './resources/travellers';\nimport { createTravellersResource } from './resources/travellers';\nimport type { TreksResource } from './resources/treks';\nimport { createTreksResource } from './resources/treks';\nimport type { TripsResource } from './resources/trips';\nimport { createTripsResource } from './resources/trips';\nimport type { VendorsResource } from './resources/vendors';\nimport { createVendorsResource } from './resources/vendors';\nimport type { WebhooksResource } from './resources/webhooks';\nimport { createWebhooksResource } from './resources/webhooks';\n\nexport interface KaafilOptions {\n /** `kf_live_…` / `kf_test_…`, checked against `environment` at\n * construction for a literal key, or on every resolution for a resolver\n * (`./config.ts`'s `guardApiKeyEnvironment`). */\n readonly apiKey: Resolvable<string>;\n readonly environment: Environment;\n /** Overrides the environment's default base URL outright — see\n * `./config.ts`'s `resolveBaseUrl` for why the two are never merged. */\n readonly baseUrl?: string;\n readonly timeoutMs?: number;\n readonly maxAttempts?: number;\n readonly userAgent?: string;\n readonly random?: () => number;\n}\n\n/**\n * Thrown by any resource method called after `close()`. Every resource\n * getter reads through `#requireState()`, so a stale reference to\n * `kaafil.trips` obtained before `close()` still throws this on its next\n * call — there is no way to keep using a closed client's credential.\n */\nexport class KaafilClosedError extends Error {\n constructor() {\n super('This Kaafil client has been closed; construct a new one to keep making requests.');\n this.name = 'KaafilClosedError';\n Object.setPrototypeOf(this, KaafilClosedError.prototype);\n }\n}\n\n/**\n * Every piece of this client's live state, in one object. `close()` is the\n * single `this.#state = null` below — structurally impossible to forget a\n * field, because there is no second field anywhere else to forget.\n */\ninterface KaafilState {\n readonly http: KaafilHttpClient;\n readonly auth: AuthResource;\n readonly agencies: AgenciesResource;\n readonly agencyAdmins: AgencyAdminsResource;\n readonly shareTokens: ShareTokensResource;\n readonly trips: TripsResource;\n readonly itinerary: ItineraryResource;\n readonly managerToday: ManagerTodayResource;\n readonly rooming: RoomingResource;\n readonly seating: SeatingResource;\n readonly pickups: PickupsResource;\n readonly treks: TreksResource;\n readonly checklists: ChecklistsResource;\n readonly vendors: VendorsResource;\n readonly travellers: TravellersResource;\n readonly journey: JourneyResource;\n readonly webhooks: WebhooksResource;\n readonly events: EventsResource;\n readonly files: FilesResource;\n readonly collections: CollectionsResource;\n readonly expenses: ExpensesResource;\n readonly float: FloatResource;\n readonly forms: FormsResource;\n readonly bookings: BookingsResource;\n readonly feedbackNps: FeedbackNpsResource;\n readonly comms: CommsResource;\n readonly closeout: CloseoutResource;\n /** The batched transport's routes (`./resources/sync.ts`) — `digest()` is\n * the apiKey-scoped route on this shared resource; `push()`/`pullTrip()`\n * are manager-session-scoped and remain wired only on `./client-entry.ts`. */\n readonly sync: SyncResource;\n /** The sandbox toolkit (`./resources/test.ts`) — refuses locally, before\n * any request exists, for a client constructed with `environment: 'live'`.\n * See that module's header for why `environment` is threaded into its\n * factory alone among every other resource here. */\n readonly test: TestResource;\n}\n\nexport class Kaafil {\n #state: KaafilState | null;\n\n constructor(options: KaafilOptions) {\n assertValidTimeout(options.timeoutMs);\n assertValidMaxAttempts(options.maxAttempts);\n const baseUrl = resolveBaseUrl(options.environment, options.baseUrl);\n const apiKey = guardApiKeyEnvironment(options.apiKey, options.environment);\n\n const credentials = new CredentialResolver({ kind: 'apiKey', apiKey });\n const http = createHttpClient({\n baseUrl,\n credentials,\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n ...(options.maxAttempts !== undefined ? { maxAttempts: options.maxAttempts } : {}),\n ...(options.userAgent !== undefined ? { userAgent: options.userAgent } : {}),\n ...(options.random !== undefined ? { random: options.random } : {}),\n });\n\n this.#state = {\n http,\n auth: createAuthResource(http),\n agencies: createAgenciesResource(http),\n agencyAdmins: createAgencyAdminsResource(http),\n shareTokens: createShareTokensResource(http),\n trips: createTripsResource(http),\n itinerary: createItineraryResource(http),\n managerToday: createManagerTodayResource(http),\n rooming: createRoomingResource(http),\n seating: createSeatingResource(http),\n pickups: createPickupsResource(http),\n treks: createTreksResource(http),\n checklists: createChecklistsResource(http),\n vendors: createVendorsResource(http),\n travellers: createTravellersResource(http),\n journey: createJourneyResource(http),\n webhooks: createWebhooksResource(http),\n events: createEventsResource(http),\n files: createFilesResource(http),\n collections: createCollectionsResource(http),\n expenses: createExpensesResource(http),\n float: createFloatResource(http),\n forms: createFormsResource(http),\n bookings: createBookingsResource(http),\n feedbackNps: createFeedbackNpsResource(http),\n comms: createCommsResource(http),\n closeout: createCloseoutResource(http),\n sync: createSyncResource(http),\n test: createTestResource(http, options.environment),\n };\n }\n\n get auth(): AuthResource {\n return this.#requireState().auth;\n }\n\n get agencies(): AgenciesResource {\n return this.#requireState().agencies;\n }\n\n get agencyAdmins(): AgencyAdminsResource {\n return this.#requireState().agencyAdmins;\n }\n\n get shareTokens(): ShareTokensResource {\n return this.#requireState().shareTokens;\n }\n\n get trips(): TripsResource {\n return this.#requireState().trips;\n }\n\n get itinerary(): ItineraryResource {\n return this.#requireState().itinerary;\n }\n\n get managerToday(): ManagerTodayResource {\n return this.#requireState().managerToday;\n }\n\n get rooming(): RoomingResource {\n return this.#requireState().rooming;\n }\n\n get seating(): SeatingResource {\n return this.#requireState().seating;\n }\n\n get pickups(): PickupsResource {\n return this.#requireState().pickups;\n }\n\n get treks(): TreksResource {\n return this.#requireState().treks;\n }\n\n get checklists(): ChecklistsResource {\n return this.#requireState().checklists;\n }\n\n get vendors(): VendorsResource {\n return this.#requireState().vendors;\n }\n\n get travellers(): TravellersResource {\n return this.#requireState().travellers;\n }\n\n get journey(): JourneyResource {\n return this.#requireState().journey;\n }\n\n get webhooks(): WebhooksResource {\n return this.#requireState().webhooks;\n }\n\n get events(): EventsResource {\n return this.#requireState().events;\n }\n\n get files(): FilesResource {\n return this.#requireState().files;\n }\n\n get collections(): CollectionsResource {\n return this.#requireState().collections;\n }\n\n get expenses(): ExpensesResource {\n return this.#requireState().expenses;\n }\n\n get float(): FloatResource {\n return this.#requireState().float;\n }\n\n get forms(): FormsResource {\n return this.#requireState().forms;\n }\n\n get bookings(): BookingsResource {\n return this.#requireState().bookings;\n }\n\n get feedbackNps(): FeedbackNpsResource {\n return this.#requireState().feedbackNps;\n }\n\n get comms(): CommsResource {\n return this.#requireState().comms;\n }\n\n get closeout(): CloseoutResource {\n return this.#requireState().closeout;\n }\n\n get sync(): SyncResource {\n return this.#requireState().sync;\n }\n\n get test(): TestResource {\n return this.#requireState().test;\n }\n\n /**\n * Total teardown. One assignment, no field to forget — see `KaafilState`\n * above. Every subsequent call through any resource getter throws\n * `KaafilClosedError` instead of quietly continuing to work off a\n * credential this client no longer considers live.\n */\n close(): void {\n this.#state = null;\n }\n\n /**\n * Mints an idempotency key outside the normal per-call flow. Every\n * mutating method already mints and reuses one automatically\n * (`http/client.ts`) — this exists for the rare case of pinning a key\n * ahead of time, to replay the exact same logical operation across a\n * process restart.\n */\n static newIdempotencyKey(): string {\n return newIdempotencyKey();\n }\n\n #requireState(): KaafilState {\n if (this.#state === null) {\n throw new KaafilClosedError();\n }\n return this.#state;\n }\n}\n","/**\n * The `?since=` delta cursor. `architecture/06-offline-first.md §1, §5`.\n *\n * ── WHY THE CURSOR IS THE SERVER'S OWN CLOCK, AND NOTHING ELSE ──────────────\n *\n * Every delta read on this API answers with `meta.serverTime`. That value —\n * the timestamp of the response you are holding, taken by the machine that ran\n * the query — is the ONLY correct cursor to send back as the next `?since=`.\n * The two tempting alternatives both lose rows, silently, and only under load:\n *\n * - **A local clock** (`new Date()` when the response arrived) is skewed\n * against the server's by an unknown amount and drifts. Skew in the wrong\n * direction advances the cursor past rows the server had not committed yet\n * when it answered, and those rows are then never in any window again.\n * - **A row's own `updatedAt`** (the newest row in the page) is worse: it is a\n * bound on the rows you RECEIVED, not on the interval the server READ. Any\n * row committed between the query's snapshot and the response being stamped\n * sits after your cursor and before the server's, and is lost permanently.\n * An empty page also leaves you with no cursor at all.\n *\n * This module exists so that reasoning happens once, here, instead of at every\n * integrator's call site. `pull()` takes the cursor from the response's own\n * `meta.serverTime` and nothing else, and it advances it only after a\n * successful read — a failed pull leaves the cursor exactly where it was, so\n * the next attempt re-reads the same interval rather than skipping it.\n *\n * ── WHY DUPLICATES ARE EXPECTED, AND WHY THEY ARE FREE ──────────────────────\n *\n * The server window is deliberately AT-LEAST-ONCE: it matches\n * `updatedAt >= since - 5s`, and a cursor in the future clamps to now rather\n * than erroring. So a pull normally re-delivers rows you already have. That is\n * the design, not a defect, and the asymmetry is the reason:\n *\n * - A DUPLICATED row costs nothing. Every row — live or tombstone — carries\n * `id` and `version`, so re-applying one is a no-op rebase onto the state\n * you already hold. `mergeDeltaRows` below does exactly that, by version.\n * - A SKIPPED row is DATA LOSS. It is a hotel booking, a cancelled activity or\n * a deleted bed that the offline client never learns about and never asks\n * for again, because the cursor has already moved past it. Nothing detects\n * it; the client is simply, quietly wrong.\n *\n * A strict `> since` boundary would be exactly that trade in reverse — no\n * duplicates, and permanent loss from three separate mechanisms (the interval\n * between reading rows and stamping the response, clock skew between replicas,\n * and millisecond truncation). The engine chose the overlap; a consumer must\n * not undo it by narrowing the window on the client side.\n *\n * ── WHY A DELTA ROW IS A UNION ──────────────────────────────────────────────\n *\n * A delta read returns `Row | DeltaTombstone` in ONE array, never a second\n * `deleted[]` array, so a consumer cannot forget the drop case: the union does\n * not typecheck until the tombstone branch is handled. Ordering is\n * `(updatedAt asc, id asc)`, so each id appears at most once per page and at\n * its final state — \"deleted before or after updated\" is already answered\n * server-side.\n */\n\nimport { normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport type { KaafilResponse, ResponseMeta } from '../types/meta';\n\n/**\n * The drop marker on a delta read.\n *\n * Aliased off the generated schema rather than hand-restated. The spec uses\n * one tombstone shape for every delta read (itinerary items, rooming rooms,\n * rooming stay windows) and `ItineraryItemTombstoneResponse` is the single\n * place it appears as a NAMED component — the others inline it inside their\n * own `anyOf`, so there is no more general name to alias. If the engine ever\n * gives the shape its own component, this alias moves; the four fields are\n * still never typed by hand here.\n */\nexport type DeltaTombstone = components['schemas']['ItineraryItemTombstoneResponse'];\n\n/** One row from a delta read: the live row, or the marker saying it is gone. */\nexport type DeltaRow<TRow> = TRow | DeltaTombstone;\n\n/**\n * Narrows a delta row to the drop case.\n *\n * Structural, and provably safe rather than conventional: every response\n * schema in this contract is `additionalProperties: false`, so a live row can\n * never carry a `_tombstone` key and the two branches of the union are\n * disjoint.\n */\nexport function isTombstone<TRow extends object>(row: DeltaRow<TRow>): row is DeltaTombstone {\n return (row as { _tombstone?: unknown })._tombstone === true;\n}\n\n/**\n * What `mergeDeltaRows` requires of a live row, and what makes a duplicate\n * free: an identity and a version. Both delta variants carry them.\n */\nexport interface DeltaIdentity {\n readonly id: string;\n readonly version: number;\n}\n\n/** What one `mergeDeltaRows` call actually changed. */\nexport interface DeltaMergeStats {\n /** Rows written that the store had not seen before. */\n readonly added: number;\n /** Rows written over an older version of a row already held. */\n readonly updated: number;\n /** Rows dropped because a tombstone arrived for them. */\n readonly removed: number;\n /**\n * Rows the store already held at this version or newer. This is the\n * at-least-once overlap doing its job — a non-zero count is normal on every\n * pull after the first and is not worth reporting to a user.\n */\n readonly unchanged: number;\n}\n\n/**\n * Rebases one delta page onto a local store, keyed by `id`.\n *\n * Version-guarded in both directions, which is what makes re-applying a\n * duplicated row a genuine no-op instead of merely a harmless-looking one: a\n * row whose `version` is not NEWER than the held one is left alone, and a\n * tombstone whose `version` is older than the held row is ignored rather than\n * deleting a row that has since been recreated or updated. The store is\n * mutated in place — a caller's `Map` is its own cache, and returning a fresh\n * copy per page would make a long offline catch-up quadratic.\n */\nexport function mergeDeltaRows<TRow extends DeltaIdentity>(\n store: Map<string, TRow>,\n rows: readonly DeltaRow<TRow>[],\n): DeltaMergeStats {\n let added = 0;\n let updated = 0;\n let removed = 0;\n let unchanged = 0;\n\n for (const row of rows) {\n const held = store.get(row.id);\n if (isTombstone(row)) {\n if (held === undefined || held.version > row.version) {\n unchanged += 1;\n continue;\n }\n store.delete(row.id);\n removed += 1;\n continue;\n }\n if (held === undefined) {\n store.set(row.id, row);\n added += 1;\n continue;\n }\n if (held.version >= row.version) {\n unchanged += 1;\n continue;\n }\n store.set(row.id, row);\n updated += 1;\n }\n\n return { added, updated, removed, unchanged };\n}\n\n/**\n * Runs one delta read for a given cursor. A caller supplies this as a thin\n * closure over a resource method — this module knows nothing about operation\n * ids, paths or query-param names, only that a read takes a `since` and\n * answers with an envelope carrying `meta.serverTime`.\n *\n * `since` is `undefined` on a cold start, which is a full read: the server\n * emits no tombstones without a cursor, because a client that has never\n * synced has nothing to drop.\n */\nexport type FetchDelta<T> = (request: {\n readonly since: string | undefined;\n readonly signal: AbortSignal | undefined;\n}) => Promise<KaafilResponse<T>>;\n\n/** One completed pull, with the cursor bookkeeping made visible. */\nexport interface DeltaPull<T> {\n readonly data: T;\n readonly meta: ResponseMeta;\n /** The cursor now stored: THIS response's `meta.serverTime`. */\n readonly cursor: string;\n /** What was sent as `?since=` — `undefined` on the cold start. */\n readonly previousCursor: string | undefined;\n}\n\n/** `pull()` was re-entered while a previous pull on the same cursor was in flight. */\nexport class KaafilDeltaCursorInFlightError extends Error {\n constructor() {\n super(\n 'pull() was called while a previous pull on this delta cursor was still in flight. ' +\n 'Two concurrent pulls would settle in an unknown order and leave the cursor at ' +\n \"whichever response landed last, not the newest — await the first one's result.\",\n );\n this.name = 'KaafilDeltaCursorInFlightError';\n Object.setPrototypeOf(this, KaafilDeltaCursorInFlightError.prototype);\n }\n}\n\nexport interface KaafilDeltaCursor<T> {\n /**\n * The cursor that will be sent as `?since=` on the next `pull()`, or\n * `undefined` before the first successful one. Read this to PERSIST it; a\n * durable consumer stores it beside its rows and hands it back to\n * `restore()` after a restart, so a process death costs one overlapping\n * window rather than a full resync.\n */\n readonly cursor: string | undefined;\n readonly isLoading: boolean;\n /** Whether any pull has succeeded yet — i.e. whether the next one is a cold start. */\n readonly hasSynced: boolean;\n /**\n * Reads everything that changed since the stored cursor, then advances the\n * cursor to this response's own `meta.serverTime`. On failure the cursor is\n * left untouched, so a retry re-reads the same interval instead of stepping\n * over it.\n */\n pull(options?: { readonly signal?: AbortSignal }): Promise<DeltaPull<T>>;\n /**\n * Adopts a cursor persisted from an earlier session. Takes a `string`\n * only — deliberately not a `Date` or an epoch number, the two things that\n * would let a local clock become a cursor, which is the failure this whole\n * module exists to prevent. Must be a value some response's\n * `meta.serverTime` actually carried.\n */\n restore(cursor: string): void;\n /**\n * Discards the cursor, so the next `pull()` is a cold start: a full read,\n * with no tombstones. The honest recovery when a local store is corrupt or\n * of unknown provenance — cheaper to re-read the trip than to reconcile a\n * cache you cannot vouch for.\n */\n reset(): void;\n}\n\nexport interface CreateDeltaCursorConfig<T> {\n readonly fetchDelta: FetchDelta<T>;\n /** A cursor persisted from an earlier session, as `restore()` would take it. */\n readonly cursor?: string;\n}\n\nexport function createDeltaCursor<T>(config: CreateDeltaCursorConfig<T>): KaafilDeltaCursor<T> {\n const { fetchDelta } = config;\n const state: { cursor: string | undefined; isLoading: boolean } = {\n cursor: undefined,\n isLoading: false,\n };\n\n function restore(cursor: string): void {\n // Routed through the same validator every date-time field on the ingest\n // surface uses, so a malformed cursor (an empty string read back from an\n // empty cache row, a date-only string) fails locally and by name instead\n // of becoming a `?since=` the server has to reject — or worse, clamp.\n state.cursor = normalizeDateTimeInput(cursor, 'cursor');\n }\n\n if (config.cursor !== undefined) {\n restore(config.cursor);\n }\n\n async function pull(options: { readonly signal?: AbortSignal } = {}): Promise<DeltaPull<T>> {\n if (state.isLoading) {\n throw new KaafilDeltaCursorInFlightError();\n }\n const previousCursor = state.cursor;\n state.isLoading = true;\n try {\n const response = await fetchDelta({ since: previousCursor, signal: options.signal });\n // The one assignment that matters in this file. `meta.serverTime`, from\n // this very response — never `Date.now()`, never a row's `updatedAt`.\n state.cursor = response.meta.serverTime;\n return {\n data: response,\n meta: response.meta,\n cursor: response.meta.serverTime,\n previousCursor,\n };\n } finally {\n state.isLoading = false;\n }\n }\n\n return {\n get cursor() {\n return state.cursor;\n },\n get isLoading() {\n return state.isLoading;\n },\n get hasSynced() {\n return state.cursor !== undefined;\n },\n pull,\n restore,\n reset() {\n state.cursor = undefined;\n },\n };\n}\n","/**\n * This file was auto-generated by `scripts/gen-meta.mjs` from\n * `openapi/openapi.json`. Do not make direct changes to the file — re-run\n * `pnpm gen:types` instead.\n *\n * @generated src/generated/enums.ts\n */\n\n// Every distinct request-body enum value set in the vendored spec, as a\n// runtime `as const` object plus its matching type — the same pattern\n// `Environment` uses in `src/config.ts`. `openapi-typescript` already\n// types these fields as string-literal unions; this gives a caller something\n// to import, autocomplete from, and check an incoming string against, so\n// `tripMode: TripMode.Personalized` replaces `tripMode: 'PERSONALIZED'`\n// without changing what a caller may still write literally — a bare string\n// literal keeps working, unchanged, because the field's type is still the\n// union, not this object.\n//\n// Named per value set, not per property path: the same set\n// (`GROUP|PERSONALIZED`) appears under several different fields across\n// several request schemas, and this file exports it once. See\n// `REQUEST_ENUM_NAMES` in `scripts/gen-meta.mjs` for the explicit mapping.\n\nexport const BoardStatus = {\n Boarded: 'BOARDED',\n NoShow: 'NO_SHOW',\n} as const;\nexport type BoardStatus = (typeof BoardStatus)[keyof typeof BoardStatus];\n\nexport const BookingStatus = {\n Confirmed: 'CONFIRMED',\n Tentative: 'TENTATIVE',\n Cancelled: 'CANCELLED',\n} as const;\nexport type BookingStatus = (typeof BookingStatus)[keyof typeof BookingStatus];\n\nexport const ChecklistAudience = {\n Internal: 'INTERNAL',\n External: 'EXTERNAL',\n} as const;\nexport type ChecklistAudience = (typeof ChecklistAudience)[keyof typeof ChecklistAudience];\n\nexport const ChecklistGate = {\n None: 'NONE',\n PreToActive: 'PRE_TO_ACTIVE',\n ActiveToClosedOut: 'ACTIVE_TO_CLOSED_OUT',\n} as const;\nexport type ChecklistGate = (typeof ChecklistGate)[keyof typeof ChecklistGate];\n\nexport const ChecklistItemStatus = {\n Open: 'OPEN',\n Complete: 'COMPLETE',\n} as const;\nexport type ChecklistItemStatus = (typeof ChecklistItemStatus)[keyof typeof ChecklistItemStatus];\n\nexport const ChecklistPhase = {\n PreDeparture: 'PRE_DEPARTURE',\n InTrip: 'IN_TRIP',\n PostTrip: 'POST_TRIP',\n} as const;\nexport type ChecklistPhase = (typeof ChecklistPhase)[keyof typeof ChecklistPhase];\n\nexport const ChecklistPullTemplateMode = {\n Append: 'append',\n Replace: 'replace',\n} as const;\nexport type ChecklistPullTemplateMode = (typeof ChecklistPullTemplateMode)[keyof typeof ChecklistPullTemplateMode];\n\nexport const ClaimStatusIngest = {\n Approved: 'APPROVED',\n Paid: 'PAID',\n Rejected: 'REJECTED',\n} as const;\nexport type ClaimStatusIngest = (typeof ClaimStatusIngest)[keyof typeof ClaimStatusIngest];\n\nexport const CloseoutPackSection = {\n Summary: 'summary',\n Blockers: 'blockers',\n Handover: 'handover',\n Collections: 'collections',\n Expenses: 'expenses',\n Float: 'float',\n Checklists: 'checklists',\n Forms: 'forms',\n Rooming: 'rooming',\n Seating: 'seating',\n Pickups: 'pickups',\n Vendors: 'vendors',\n Itinerary: 'itinerary',\n} as const;\nexport type CloseoutPackSection = (typeof CloseoutPackSection)[keyof typeof CloseoutPackSection];\n\nexport const CollectionMode = {\n Cash: 'CASH',\n Upi: 'UPI',\n Card: 'CARD',\n Bank: 'BANK',\n} as const;\nexport type CollectionMode = (typeof CollectionMode)[keyof typeof CollectionMode];\n\nexport const CommsEmailProvider = {\n Sendgrid: 'SENDGRID',\n Brevo: 'BREVO',\n Resend: 'RESEND',\n} as const;\nexport type CommsEmailProvider = (typeof CommsEmailProvider)[keyof typeof CommsEmailProvider];\n\nexport const CommsMode = {\n KaafilSend: 'KAAFIL_SEND',\n CrmSend: 'CRM_SEND',\n} as const;\nexport type CommsMode = (typeof CommsMode)[keyof typeof CommsMode];\n\nexport const Currency = {\n Inr: 'INR',\n} as const;\nexport type Currency = (typeof Currency)[keyof typeof Currency];\n\nexport const EventType = {\n Trip: 'TRIP',\n Trek: 'TREK',\n} as const;\nexport type EventType = (typeof EventType)[keyof typeof EventType];\n\nexport const ExpenseCategory = {\n Accom: 'ACCOM',\n Food: 'FOOD',\n Transport: 'TRANSPORT',\n Activity: 'ACTIVITY',\n Misc: 'MISC',\n} as const;\nexport type ExpenseCategory = (typeof ExpenseCategory)[keyof typeof ExpenseCategory];\n\nexport const ExpensePaymentMode = {\n FloatCash: 'FLOAT_CASH',\n Personal: 'PERSONAL',\n Other: 'OTHER',\n} as const;\nexport type ExpensePaymentMode = (typeof ExpensePaymentMode)[keyof typeof ExpensePaymentMode];\n\nexport const FileContentType = {\n ImageJpeg: 'image/jpeg',\n ImagePng: 'image/png',\n ImageWebp: 'image/webp',\n ImageHeic: 'image/heic',\n ApplicationPdf: 'application/pdf',\n} as const;\nexport type FileContentType = (typeof FileContentType)[keyof typeof FileContentType];\n\nexport const FilePurpose = {\n ExpenseReceipt: 'expense_receipt',\n FormAttachment: 'form_attachment',\n BookingVoucher: 'booking_voucher',\n TripDocument: 'trip_document',\n} as const;\nexport type FilePurpose = (typeof FilePurpose)[keyof typeof FilePurpose];\n\nexport const FloatDirection = {\n In: 'IN',\n Out: 'OUT',\n} as const;\nexport type FloatDirection = (typeof FloatDirection)[keyof typeof FloatDirection];\n\nexport const FormAnchor = {\n TripStart: 'TRIP_START',\n TripEnd: 'TRIP_END',\n ManifestJoin: 'MANIFEST_JOIN',\n Dispatch: 'DISPATCH',\n ItineraryDay: 'ITINERARY_DAY',\n Absolute: 'ABSOLUTE',\n} as const;\nexport type FormAnchor = (typeof FormAnchor)[keyof typeof FormAnchor];\n\nexport const FormAnonymity = {\n Identified: 'IDENTIFIED',\n Optional: 'OPTIONAL',\n Anonymous: 'ANONYMOUS',\n} as const;\nexport type FormAnonymity = (typeof FormAnonymity)[keyof typeof FormAnonymity];\n\nexport const FormDispatchMode = {\n Journey: 'JOURNEY',\n Manual: 'MANUAL',\n None: 'NONE',\n} as const;\nexport type FormDispatchMode = (typeof FormDispatchMode)[keyof typeof FormDispatchMode];\n\nexport const FormDispatchReason = {\n Journey: 'journey',\n Manual: 'manual',\n} as const;\nexport type FormDispatchReason = (typeof FormDispatchReason)[keyof typeof FormDispatchReason];\n\nexport const FormFieldKind = {\n Heading: 'HEADING',\n InfoBlock: 'INFO_BLOCK',\n ShortText: 'SHORT_TEXT',\n LongText: 'LONG_TEXT',\n Email: 'EMAIL',\n Phone: 'PHONE',\n Url: 'URL',\n Number: 'NUMBER',\n Currency: 'CURRENCY',\n Rating: 'RATING',\n Nps: 'NPS',\n Date: 'DATE',\n Datetime: 'DATETIME',\n Time: 'TIME',\n Select: 'SELECT',\n Multiselect: 'MULTISELECT',\n Checkbox: 'CHECKBOX',\n Consent: 'CONSENT',\n Signature: 'SIGNATURE',\n FileUpload: 'FILE_UPLOAD',\n Address: 'ADDRESS',\n} as const;\nexport type FormFieldKind = (typeof FormFieldKind)[keyof typeof FormFieldKind];\n\nexport const FormFieldSensitivity = {\n Normal: 'NORMAL',\n SelfOnly: 'SELF_ONLY',\n} as const;\nexport type FormFieldSensitivity = (typeof FormFieldSensitivity)[keyof typeof FormFieldSensitivity];\n\nexport const FormPhase = {\n PreDeparture: 'PRE_DEPARTURE',\n OnTrip: 'ON_TRIP',\n PostTrip: 'POST_TRIP',\n} as const;\nexport type FormPhase = (typeof FormPhase)[keyof typeof FormPhase];\n\nexport const FormResponseExportFormat = {\n Csv: 'csv',\n Pdf: 'pdf',\n} as const;\nexport type FormResponseExportFormat = (typeof FormResponseExportFormat)[keyof typeof FormResponseExportFormat];\n\nexport const FormResponsePolicy = {\n Single: 'SINGLE',\n Multiple: 'MULTIPLE',\n} as const;\nexport type FormResponsePolicy = (typeof FormResponsePolicy)[keyof typeof FormResponsePolicy];\n\nexport const FormVisibilityOperator = {\n Answered: 'answered',\n Empty: 'empty',\n Eq: 'eq',\n Ne: 'ne',\n Gt: 'gt',\n Gte: 'gte',\n Lt: 'lt',\n Lte: 'lte',\n In: 'in',\n Nin: 'nin',\n Contains: 'contains',\n} as const;\nexport type FormVisibilityOperator = (typeof FormVisibilityOperator)[keyof typeof FormVisibilityOperator];\n\nexport const Gender = {\n Male: 'MALE',\n Female: 'FEMALE',\n Other: 'OTHER',\n Unknown: 'UNKNOWN',\n} as const;\nexport type Gender = (typeof Gender)[keyof typeof Gender];\n\nexport const ItineraryItemStatusUpdate = {\n Planned: 'PLANNED',\n Completed: 'COMPLETED',\n Skipped: 'SKIPPED',\n} as const;\nexport type ItineraryItemStatusUpdate = (typeof ItineraryItemStatusUpdate)[keyof typeof ItineraryItemStatusUpdate];\n\nexport const ItineraryItemType = {\n Accommodation: 'ACCOMMODATION',\n Transport: 'TRANSPORT',\n Activity: 'ACTIVITY',\n Meal: 'MEAL',\n Other: 'OTHER',\n} as const;\nexport type ItineraryItemType = (typeof ItineraryItemType)[keyof typeof ItineraryItemType];\n\nexport const ManagerRole = {\n Manager: 'MANAGER',\n Coordinator: 'COORDINATOR',\n} as const;\nexport type ManagerRole = (typeof ManagerRole)[keyof typeof ManagerRole];\n\nexport const ManifestMode = {\n Merge: 'merge',\n Replace: 'replace',\n} as const;\nexport type ManifestMode = (typeof ManifestMode)[keyof typeof ManifestMode];\n\nexport const MessageChannel = {\n Email: 'EMAIL',\n Sms: 'SMS',\n Whatsapp: 'WHATSAPP',\n} as const;\nexport type MessageChannel = (typeof MessageChannel)[keyof typeof MessageChannel];\n\nexport const MessageTemplateStatus = {\n Draft: 'DRAFT',\n Active: 'ACTIVE',\n Archived: 'ARCHIVED',\n} as const;\nexport type MessageTemplateStatus = (typeof MessageTemplateStatus)[keyof typeof MessageTemplateStatus];\n\nexport const PartyKind = {\n Family: 'FAMILY',\n Couple: 'COUPLE',\n Friends: 'FRIENDS',\n Corporate: 'CORPORATE',\n Other: 'OTHER',\n} as const;\nexport type PartyKind = (typeof PartyKind)[keyof typeof PartyKind];\n\nexport const PersonKind = {\n Traveller: 'TRAVELLER',\n Manager: 'MANAGER',\n} as const;\nexport type PersonKind = (typeof PersonKind)[keyof typeof PersonKind];\n\nexport const PickupKind = {\n Pickup: 'PICKUP',\n Drop: 'DROP',\n} as const;\nexport type PickupKind = (typeof PickupKind)[keyof typeof PickupKind];\n\nexport const RoomingFillOrder = {\n LargestRoomFirst: 'LARGEST_ROOM_FIRST',\n Sequential: 'SEQUENTIAL',\n Balanced: 'BALANCED',\n} as const;\nexport type RoomingFillOrder = (typeof RoomingFillOrder)[keyof typeof RoomingFillOrder];\n\nexport const RoomingGenderPolicy = {\n StrictSeparate: 'STRICT_SEPARATE',\n GroupMixedOk: 'GROUP_MIXED_OK',\n Off: 'OFF',\n} as const;\nexport type RoomingGenderPolicy = (typeof RoomingGenderPolicy)[keyof typeof RoomingGenderPolicy];\n\nexport const RoomingHeuristicKey = {\n MedicalFirst: 'medicalFirst',\n Couples: 'couples',\n Parties: 'parties',\n Gender: 'gender',\n Diet: 'diet',\n SpreadSolos: 'spreadSolos',\n PartyGenderPolicy: 'partyGenderPolicy',\n SameBus: 'sameBus',\n} as const;\nexport type RoomingHeuristicKey = (typeof RoomingHeuristicKey)[keyof typeof RoomingHeuristicKey];\n\nexport const RoomType = {\n Single: 'SINGLE',\n Twin: 'TWIN',\n Shared: 'SHARED',\n Dorm: 'DORM',\n} as const;\nexport type RoomType = (typeof RoomType)[keyof typeof RoomType];\n\nexport const SeatingFillOrder = {\n Balanced: 'BALANCED',\n FillFirst: 'FILL_FIRST',\n ByStop: 'BY_STOP',\n} as const;\nexport type SeatingFillOrder = (typeof SeatingFillOrder)[keyof typeof SeatingFillOrder];\n\nexport const SeatingGenderAdjacency = {\n Off: 'OFF',\n AvoidUnrelated: 'AVOID_UNRELATED',\n StrictRows: 'STRICT_ROWS',\n} as const;\nexport type SeatingGenderAdjacency = (typeof SeatingGenderAdjacency)[keyof typeof SeatingGenderAdjacency];\n\nexport const SeatingHeuristicKey = {\n MedicalFirst: 'medicalFirst',\n Parties: 'parties',\n SameStop: 'sameStop',\n Gender: 'gender',\n BalanceVehicles: 'balanceVehicles',\n} as const;\nexport type SeatingHeuristicKey = (typeof SeatingHeuristicKey)[keyof typeof SeatingHeuristicKey];\n\nexport const SettingsExpenseWindow = {\n Anytime: 'ANYTIME',\n TripPlusDays: 'TRIP_PLUS_DAYS',\n} as const;\nexport type SettingsExpenseWindow = (typeof SettingsExpenseWindow)[keyof typeof SettingsExpenseWindow];\n\nexport const SettingsPickupTreatment = {\n Advisory: 'ADVISORY',\n Strict: 'STRICT',\n} as const;\nexport type SettingsPickupTreatment = (typeof SettingsPickupTreatment)[keyof typeof SettingsPickupTreatment];\n\nexport const SyncOpMethod = {\n Post: 'POST',\n Patch: 'PATCH',\n Put: 'PUT',\n Delete: 'DELETE',\n} as const;\nexport type SyncOpMethod = (typeof SyncOpMethod)[keyof typeof SyncOpMethod];\n\nexport const TriggerAnchor = {\n Start: 'START',\n End: 'END',\n} as const;\nexport type TriggerAnchor = (typeof TriggerAnchor)[keyof typeof TriggerAnchor];\n\nexport const TripMode = {\n Group: 'GROUP',\n Personalized: 'PERSONALIZED',\n} as const;\nexport type TripMode = (typeof TripMode)[keyof typeof TripMode];\n\nexport const TripStatus = {\n Confirmed: 'CONFIRMED',\n InProgress: 'IN_PROGRESS',\n Completed: 'COMPLETED',\n Postponed: 'POSTPONED',\n Cancelled: 'CANCELLED',\n} as const;\nexport type TripStatus = (typeof TripStatus)[keyof typeof TripStatus];\n\nexport const VehicleLayout = {\n TwoTwo: 'TWO_TWO',\n TwoOne: 'TWO_ONE',\n Flat: 'FLAT',\n} as const;\nexport type VehicleLayout = (typeof VehicleLayout)[keyof typeof VehicleLayout];\n\nexport const VehicleType = {\n Bus: 'BUS',\n TempoTraveller: 'TEMPO_TRAVELLER',\n Car: 'CAR',\n Flight: 'FLIGHT',\n Train: 'TRAIN',\n Other: 'OTHER',\n} as const;\nexport type VehicleType = (typeof VehicleType)[keyof typeof VehicleType];\n\nexport const VendorCategory = {\n Hotel: 'HOTEL',\n Transport: 'TRANSPORT',\n Activity: 'ACTIVITY',\n Guide: 'GUIDE',\n Food: 'FOOD',\n Misc: 'MISC',\n} as const;\nexport type VendorCategory = (typeof VendorCategory)[keyof typeof VendorCategory];\n","/**\n * The rooming vocabulary a client needs to RENDER what\n * `rooming.autoAssign` and `rooming.read` answer — and which is deliberately\n * not on the wire.\n *\n * Two things live here, for the same reason: each is a property of the RULE or\n * of the CANON, not of a particular run, so shipping either inside every\n * response would put a second copy of one judgement in every payload and let\n * the two disagree after a contract change. The engine states this in\n * `src/modules/rooming/index.ts`, which re-exports both explicitly \"for the\n * SDK\". This file is that re-export's other end, so a client renders\n * relaxations and traveller chips without inventing its own severity map or\n * its own colour maths.\n *\n * ── HOW THIS STAYS HONEST ────────────────────────────────────────────────────\n *\n * These values are not in `openapi.json`, so `gen:check` cannot police them.\n * What does: both maps are typed as TOTAL `Record`s over GENERATED key types\n * (`RoomingHeuristicKey` and `Gender`, from `../generated/enums.ts`, which\n * `scripts/gen-meta.mjs` builds out of the vendored spec's own request enums).\n * Add a heuristic or a gender to the contract and re-vendor, and this file\n * stops compiling until someone decides what the new member's severity or hue\n * family is. A `Record<string, …>` here would have accepted the drift\n * silently, which is exactly the failure a hand-maintained mirror invites.\n */\n\nimport { Gender, type RoomingHeuristicKey } from '../generated/enums';\n\n/**\n * How loudly to render a rule's relaxation.\n *\n * - `warn` — the manager should look: a preference they set was given up.\n * - `split` — a group was broken up. Louder than `warn`; it is the complaint\n * the trip will actually generate.\n * - `info` — a soft preference, worth showing but not worth interrupting for.\n * - `never` — this rule is never relaxed at all. It exists so the map is TOTAL:\n * a missing entry would be indistinguishable from a rule nobody had\n * classified yet.\n */\nexport type RoomingHeuristicSeverity = 'warn' | 'split' | 'info' | 'never';\n\n/**\n * The frozen severity map, mirroring the engine's `HEURISTIC_SEVERITY`.\n *\n * `gender` is `'never'` because a gender rule is never relaxed — the traveller\n * stays unassigned instead, and turns up in `autoAssign`'s `unassigned[]` with\n * a reason. So a `perRule` entry for `gender` with `outcome: 'relaxed'` is not\n * something to render loudly; it is a contract violation, and a client is\n * entitled to treat it as a bug rather than as a user-facing warning.\n */\nexport const HEURISTIC_SEVERITY: Readonly<Record<RoomingHeuristicKey, RoomingHeuristicSeverity>> =\n Object.freeze({\n medicalFirst: 'warn',\n couples: 'warn',\n parties: 'split',\n gender: 'never',\n diet: 'info',\n spreadSolos: 'info',\n partyGenderPolicy: 'info',\n sameBus: 'info',\n });\n\n/**\n * Whether a string is one of the heuristic keys this SDK knows about.\n *\n * Exists because `autoAssign`'s `perRule[].rule` is an open `string` on the\n * wire, not the closed enum `strategyOrder` is on the request side — so a\n * response may name a rule a given SDK build has never heard of, and a client\n * must be able to ask.\n */\nexport function isRoomingHeuristicKey(rule: string): rule is RoomingHeuristicKey {\n return Object.hasOwn(HEURISTIC_SEVERITY, rule);\n}\n\n/**\n * How loudly to render one `perRule` entry's relaxation.\n *\n * ── WHY THIS FUNCTION EXISTS AND THE MAP IS NOT ENOUGH ──────────────────────\n *\n * `HEURISTIC_SEVERITY[entry.rule]` does not compile, and that is correct\n * rather than an oversight to paper over: `entry.rule` is `string` in the\n * contract, and a total `Record` over a closed key set legitimately refuses a\n * `string` index. The two possible fixes are not equivalent. Loosening the map\n * to `Record<string, …>` would also throw away the compile-time drift gate\n * described in this file's header, which is the only thing keeping this\n * hand-maintained mirror honest against a re-vendored spec. So the map stays\n * total and this accessor takes the wire's `string`.\n *\n * Returns `undefined` for a rule this build does not know. A caller should\n * render that entry rather than drop it — an unrecognised rule that was\n * RELAXED is still a relaxation the manager needs to see, and hiding it\n * because the severity lookup missed is the silent-relaxation failure the\n * `perRule` array exists to prevent. `'info'` is a reasonable default to draw\n * it at; `undefined` is deliberately not pre-defaulted here, so that choice is\n * visible at the call site instead of buried in this function.\n */\nexport function roomingHeuristicSeverity(rule: string): RoomingHeuristicSeverity | undefined {\n return isRoomingHeuristicKey(rule) ? HEURISTIC_SEVERITY[rule] : undefined;\n}\n\n// ── The identity-mark canon ──────────────────────────────────────────────────\n\n/**\n * The hue FAMILIES a `tone` token is built from, keyed by the occupant's\n * `gender`.\n *\n * `null` gender and `UNKNOWN` map to the SAME family: the field is nullable\n * AND the enum has an `UNKNOWN` member, so unknown-ness arrives two ways and\n * means one thing. Rendering them in two palettes would show the same fact\n * twice over as two different facts.\n */\nexport const TONE_FAMILIES: Readonly<Record<Gender, string>> = Object.freeze({\n [Gender.Male]: 'male',\n [Gender.Female]: 'female',\n [Gender.Other]: 'other',\n [Gender.Unknown]: 'unknown',\n});\n\n/** The family for a `null` gender. Identical to `UNKNOWN`'s, by the reasoning above. */\nexport const UNKNOWN_TONE_FAMILY: string = TONE_FAMILIES[Gender.Unknown];\n\n/**\n * How many shades each family has, so a client's palette knows how many to\n * define: `shade` in a `tone` token is always `0 .. SHADES_PER_FAMILY - 1`.\n *\n * It equals the maximum room capacity, and that is the whole argument. The\n * promise is that two same-gender travellers IN ONE ROOM still look different —\n * a room being the only place two chips sit side by side and have to be told\n * apart. A room holds at most 8 people, so with 8 shades per family a\n * collision is never FORCED inside that scope. It is frozen rather than\n * configurable because the mark is a property of the TRAVELLER, not of the\n * viewer: two agencies with different values would render the same person in\n * two different shades, and `transport-seating` — which draws the same chip\n * from the same canon — would have to know whose grid it was on to agree with\n * the rooming board.\n */\nexport const SHADES_PER_FAMILY = 8;\n\n/**\n * The glyph the engine sends for a traveller whose `fullName` has no\n * renderable characters at all. Reachable, because the name is CRM-supplied,\n * and an unnameable traveller must still get a chip rather than vanish off the\n * board.\n */\nexport const FALLBACK_GLYPH = '?';\n\n/** A parsed `tone` token. */\nexport interface RoomingTone {\n /** One of `TONE_FAMILIES`' values. */\n readonly family: string;\n /** `0 .. SHADES_PER_FAMILY - 1`. */\n readonly shade: number;\n}\n\n/**\n * Splits an occupant's `tone` into its family and shade.\n *\n * ── `tone` IS A TOKEN, NEVER A COLOUR ───────────────────────────────────────\n *\n * The engine sends `\"male.3\"`, not `\"#3B82F6\"`, and that is deliberate: the\n * engine must not own brand colour values. If it did, an agency re-theme would\n * be an engine deploy, and the same traveller would render in two different\n * palettes depending on which module's copy of the hex table was newer. What\n * the engine owns is the CONSISTENCY claim — `rooming` and `transport-seating`\n * handing you the same string for the same person IS the consistency —\n * and what you paint it is entirely yours. So the shape a consumer wants is\n * `palette[family][shade]`, with `palette` living in your own design system,\n * and this function is how you get the two indices out without string-slicing\n * by hand.\n *\n * Returns `undefined` rather than throwing for anything that is not a\n * recognisable token, because this runs while drawing a board: a chip with an\n * unreadable tone should fall back to a neutral swatch, not take the screen\n * down. The family is NOT checked against `TONE_FAMILIES` — a family added to\n * the contract before your palette knows about it should still parse, so you\n * can fall back on the family you do not recognise instead of on every chip.\n */\nexport function parseRoomingTone(tone: string): RoomingTone | undefined {\n const separator = tone.lastIndexOf('.');\n if (separator <= 0 || separator === tone.length - 1) {\n return undefined;\n }\n const family = tone.slice(0, separator);\n const rawShade = tone.slice(separator + 1);\n // `Number` and not `parseInt`: `parseInt('3x')` is 3, which would silently\n // accept a malformed token as a valid one.\n const shade = Number(rawShade);\n if (!Number.isInteger(shade) || shade < 0) {\n return undefined;\n }\n return { family, shade };\n}\n"]}
1
+ {"version":3,"sources":["../src/generated/security.ts","../src/generated/error-codes.ts","../src/http/errors.ts","../src/auth/credentials.ts","../src/config.ts","../src/http/retry.ts","../src/http/client.ts","../src/idempotency.ts","../src/datetime.ts","../src/pagination/paginator.ts","../src/resources/internal.ts","../src/resources/agencies.ts","../src/resources/agency-admins.ts","../src/resources/auth.ts","../src/resources/bookings.ts","../src/resources/checklists.ts","../src/resources/closeout.ts","../src/resources/collections.ts","../src/resources/comms.ts","../src/resources/events.ts","../src/resources/expenses.ts","../src/resources/feedback-nps.ts","../src/resources/files.ts","../src/resources/float.ts","../src/resources/forms.ts","../src/resources/itinerary.ts","../src/resources/journey.ts","../src/resources/manager-today.ts","../src/resources/pickups.ts","../src/resources/rooming.ts","../src/resources/seating.ts","../src/resources/share-tokens.ts","../src/resources/sync.ts","../src/resources/test.ts","../src/resources/travellers.ts","../src/resources/treks.ts","../src/resources/trips.ts","../src/resources/vendors.ts","../src/resources/webhooks.ts","../src/client.ts","../src/delta/cursor.ts","../src/generated/enums.ts","../src/rooming/vocabulary.ts"],"names":["createInitialState"],"mappings":";AAmBO,IAAM,gBAAA,GAAmB;AAAA,EAC9B,eAAA,EAAiB,iBAAA;AAAA,EACjB,UAAA,EAAY,YAAA;AAAA,EAEZ,WAAA,EAAa,aAAA;AAAA,EAEb,SAAA,EAAW;AACb,CAAA;AAGO,IAAM,wBAAA,GAAkF;AAAA,EAC7F,eAAA,EAAiB,EAAE,IAAA,EAAM,QAAA,EAAS;AAAA,EAClC,UAAA,EAAY,EAAE,IAAA,EAAM,QAAA,EAAU,YAAY,WAAA,EAAY;AAAA,EACtD,WAAA,EAAa,EAAE,IAAA,EAAM,QAAA,EAAU,YAAY,wBAAA,EAAyB;AAAA,EACpE,WAAA,EAAa,EAAE,IAAA,EAAM,QAAA,EAAS;AAAA,EAC9B,iBAAA,EAAmB,EAAE,IAAA,EAAM,QAAA,EAAS;AAAA,EACpC,SAAA,EAAW,EAAE,IAAA,EAAM,QAAA;AACrB,CAAA;AAEO,IAAM,WAAA,GAAc;AAAA,EAGzB,gBAAA,EAAkB,kBAAA;A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U,KAAK,CAAA,IAAK,QAAQ,CAAA,EAAG;AACzC,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAO,EAAE,QAAQ,KAAA,EAAM;AACzB","file":"index.js","sourcesContent":["/**\n * This file was auto-generated by `scripts/gen-meta.mjs` from\n * `openapi/openapi.json`. Do not make direct changes to the file — re-run\n * `pnpm gen:types` instead.\n *\n * @generated src/generated/security.ts\n */\n\n// `security` on an operation is a list of alternatives (OR), never an AND —\n// enforced by `gen-meta.mjs`, which throws if any requirement names more\n// than one scheme. The order below is the order declared in the spec: the\n// transport must try schemes in this order and use the first one the client\n// is actually configured for.\n\nexport type CredentialCarrier =\n | { readonly kind: 'header'; readonly headerName: string }\n | { readonly kind: 'bearer' }\n | { readonly kind: 'cookie'; readonly cookieName: string };\n\nexport const SecuritySchemeId = {\n AgencyAdminAuth: 'agencyAdminAuth',\n ApiKeyAuth: 'apiKeyAuth',\n ConsoleAuth: 'consoleAuth',\n ManagerAuth: 'managerAuth',\n PlatformAdminAuth: 'platformAdminAuth',\n ShareAuth: 'shareAuth',\n} as const;\nexport type SecuritySchemeId = (typeof SecuritySchemeId)[keyof typeof SecuritySchemeId];\n\nexport const SECURITY_SCHEME_CARRIERS: Readonly<Record<SecuritySchemeId, CredentialCarrier>> = {\n agencyAdminAuth: { kind: 'bearer' },\n apiKeyAuth: { kind: 'header', headerName: 'X-API-Key' },\n consoleAuth: { kind: 'cookie', cookieName: 'kaafil_console_session' },\n managerAuth: { kind: 'bearer' },\n platformAdminAuth: { kind: 'bearer' },\n shareAuth: { kind: 'bearer' },\n};\n\nexport const OperationId = {\n AcceptConsoleInvite: 'acceptConsoleInvite',\n AcceptPlatformAdminInvite: 'acceptPlatformAdminInvite',\n AddChecklistItem: 'addChecklistItem',\n AddItineraryItem: 'addItineraryItem',\n AddPlatformIncidentUpdate: 'addPlatformIncidentUpdate',\n AddTravellerNote: 'addTravellerNote',\n AdjustFloat: 'adjustFloat',\n AdvanceTestTime: 'advanceTestTime',\n AdvanceTestTimeConsole: 'advanceTestTimeConsole',\n ArchiveForm: 'archiveForm',\n AssignManager: 'assignManager',\n AssignPickupTraveller: 'assignPickupTraveller',\n AssignRoomingBed: 'assignRoomingBed',\n AssignSeating: 'assignSeating',\n AutoAssignRooming: 'autoAssignRooming',\n AutoAssignSeating: 'autoAssignSeating',\n BoardPickupTraveller: 'boardPickupTraveller',\n BuildTestFixtures: 'buildTestFixtures',\n BuildTestFixturesConsole: 'buildTestFixturesConsole',\n BulkUpsertBookings: 'bulkUpsertBookings',\n CancelTrip: 'cancelTrip',\n ChangeMyConsolePassword: 'changeMyConsolePassword',\n ChangeOwnPlatformPassword: 'changeOwnPlatformPassword',\n ClaimStatusIngest: 'claimStatusIngest',\n CloneForm: 'cloneForm',\n CloseForm: 'closeForm',\n ClosePickupStop: 'closePickupStop',\n ConfirmFileUpload: 'confirmFileUpload',\n ConsoleLogin: 'consoleLogin',\n ConsoleLogout: 'consoleLogout',\n ConsoleSwitchPlane: 'consoleSwitchPlane',\n CopyAgencyEntitlement: 'copyAgencyEntitlement',\n CorrectPickupBoardStatus: 'correctPickupBoardStatus',\n CreateAgencyConsole: 'createAgencyConsole',\n CreateApiKey: 'createApiKey',\n CreateChecklistTemplate: 'createChecklistTemplate',\n CreateCommsProviderCredential: 'createCommsProviderCredential',\n CreateCommsProviderCredentialConsole: 'createCommsProviderCredentialConsole',\n CreateConsoleUser: 'createConsoleUser',\n CreateForm: 'createForm',\n CreateFormField: 'createFormField',\n CreateFormSection: 'createFormSection',\n CreateMessageTemplate: 'createMessageTemplate',\n CreateParty: 'createParty',\n CreatePickupStop: 'createPickupStop',\n CreatePlatformAdmin: 'createPlatformAdmin',\n CreatePlatformIncident: 'createPlatformIncident',\n CreatePlatformPartner: 'createPlatformPartner',\n CreatePlatformPartnerConsoleUser: 'createPlatformPartnerConsoleUser',\n CreateRoomingRoom: 'createRoomingRoom',\n CreateRoomingStayWindow: 'createRoomingStayWindow',\n CreateSeatingVehicle: 'createSeatingVehicle',\n CreateSupportGrant: 'createSupportGrant',\n CreateTraveller: 'createTraveller',\n CreateTrekWalkIn: 'createTrekWalkIn',\n CreateVendor: 'createVendor',\n DeleteBooking: 'deleteBooking',\n DeleteChecklistItem: 'deleteChecklistItem',\n DeleteChecklistTemplate: 'deleteChecklistTemplate',\n DeleteFile: 'deleteFile',\n DeleteForm: 'deleteForm',\n DeleteFormField: 'deleteFormField',\n DeleteFormSection: 'deleteFormSection',\n DeleteItineraryItem: 'deleteItineraryItem',\n DeleteParty: 'deleteParty',\n DeletePickupStop: 'deletePickupStop',\n DeletePlatformPartnerPlan: 'deletePlatformPartnerPlan',\n DeleteRoomingRoom: 'deleteRoomingRoom',\n DeleteRoomingStayWindow: 'deleteRoomingStayWindow',\n DeleteSeatingVehicle: 'deleteSeatingVehicle',\n DeleteVendor: 'deleteVendor',\n DispatchForm: 'dispatchForm',\n EditWebhookEndpoint: 'editWebhookEndpoint',\n EraseTraveller: 'eraseTraveller',\n ExportCloseoutPack: 'exportCloseoutPack',\n ExportFormResponses: 'exportFormResponses',\n ExportTraveller: 'exportTraveller',\n GetAgencyAdminMe: 'getAgencyAdminMe',\n GetAgencySettings: 'getAgencySettings',\n GetAgencySettingsSelf: 'getAgencySettingsSelf',\n GetAgencyTrip: 'getAgencyTrip',\n GetForm: 'getForm',\n GetFormAggregate: 'getFormAggregate',\n GetFormConsentReceipt: 'getFormConsentReceipt',\n GetFormResponse: 'getFormResponse',\n GetFormsCompletionMatrix: 'getFormsCompletionMatrix',\n GetFormsCrossModuleAnswers: 'getFormsCrossModuleAnswers',\n GetManagerAgencyProfile: 'getManagerAgencyProfile',\n GetManagerInbox: 'getManagerInbox',\n GetNotificationDetail: 'getNotificationDetail',\n GetShareManifest: 'getShareManifest',\n GetShareSnapshot: 'getShareSnapshot',\n GetTravellerAgencyProfile: 'getTravellerAgencyProfile',\n GetTravellerDetail: 'getTravellerDetail',\n GetTrip: 'getTrip',\n GetTripManifest: 'getTripManifest',\n Health: 'health',\n HealthV1: 'healthV1',\n InspectConsoleInvite: 'inspectConsoleInvite',\n InspectPlatformAdminInvite: 'inspectPlatformAdminInvite',\n IssueFloat: 'issueFloat',\n LinkExpenseReceipt: 'linkExpenseReceipt',\n LinkSeatingManager: 'linkSeatingManager',\n ListAgencies: 'listAgencies',\n ListAgencyManagers: 'listAgencyManagers',\n ListAgencyTrips: 'listAgencyTrips',\n ListApiKeys: 'listApiKeys',\n ListBookings: 'listBookings',\n ListChecklistTemplates: 'listChecklistTemplates',\n ListChecklistTemplatesAdmin: 'listChecklistTemplatesAdmin',\n ListCollections: 'listCollections',\n ListConsoleUsers: 'listConsoleUsers',\n ListEligibleCollections: 'listEligibleCollections',\n ListEvents: 'listEvents',\n ListExpenses: 'listExpenses',\n ListFiles: 'listFiles',\n ListFormBindings: 'listFormBindings',\n ListForms: 'listForms',\n ListJourneyTriggers: 'listJourneyTriggers',\n ListJourneyTriggersConsole: 'listJourneyTriggersConsole',\n ListManagerExpenses: 'listManagerExpenses',\n ListManagerNotifications: 'listManagerNotifications',\n ListMessages: 'listMessages',\n ListMessagesConsole: 'listMessagesConsole',\n ListMessageTemplates: 'listMessageTemplates',\n ListMyConsoleSessions: 'listMyConsoleSessions',\n ListOwnManagerTrips: 'listOwnManagerTrips',\n ListParties: 'listParties',\n ListPickupStops: 'listPickupStops',\n ListPlatformAdmins: 'listPlatformAdmins',\n ListPlatformAudit: 'listPlatformAudit',\n ListPlatformIncidents: 'listPlatformIncidents',\n ListPlatformPartnerApiKeys: 'listPlatformPartnerApiKeys',\n ListPlatformPartnerConsoleUsers: 'listPlatformPartnerConsoleUsers',\n ListPlatformPartners: 'listPlatformPartners',\n ListPlatformPlanTiers: 'listPlatformPlanTiers',\n ListRoomingStayWindows: 'listRoomingStayWindows',\n ListShareTokens: 'listShareTokens',\n ListSupportIngestLog: 'listSupportIngestLog',\n ListSupportWebhookDeliveries: 'listSupportWebhookDeliveries',\n ListTravellerFormResponses: 'listTravellerFormResponses',\n ListTrekWalkIns: 'listTrekWalkIns',\n ListTripFormResponses: 'listTripFormResponses',\n ListTripForms: 'listTripForms',\n ListTripManagers: 'listTripManagers',\n ListTripManifest: 'listTripManifest',\n ListTripVendors: 'listTripVendors',\n ListWebhookDeliveries: 'listWebhookDeliveries',\n ListWebhookDeliveriesConsole: 'listWebhookDeliveriesConsole',\n ListWebhookEndpoints: 'listWebhookEndpoints',\n LockCloseout: 'lockCloseout',\n LogExpense: 'logExpense',\n ManagerCreateFormResponse: 'managerCreateFormResponse',\n MarkNotificationRead: 'markNotificationRead',\n MintAgencyAdminTokens: 'mintAgencyAdminTokens',\n MintManagerTokens: 'mintManagerTokens',\n MintShareToken: 'mintShareToken',\n NudgeConsoleInvite: 'nudgeConsoleInvite',\n PatchAgencyEntitlement: 'patchAgencyEntitlement',\n PatchAgencySettings: 'patchAgencySettings',\n PatchAgencySettingsSelf: 'patchAgencySettingsSelf',\n PatchChecklistItem: 'patchChecklistItem',\n PatchChecklistTemplate: 'patchChecklistTemplate',\n PatchConsoleUser: 'patchConsoleUser',\n PatchForm: 'patchForm',\n PatchFormField: 'patchFormField',\n PatchFormSection: 'patchFormSection',\n PatchItineraryDay: 'patchItineraryDay',\n PatchItineraryItem: 'patchItineraryItem',\n PatchJourneyTrigger: 'patchJourneyTrigger',\n PatchJourneyTriggerConsole: 'patchJourneyTriggerConsole',\n PatchMessageTemplate: 'patchMessageTemplate',\n PatchParty: 'patchParty',\n PatchPickupStop: 'patchPickupStop',\n PatchPlatformAdmin: 'patchPlatformAdmin',\n PatchPlatformPartnerConsoleUser: 'patchPlatformPartnerConsoleUser',\n PatchRoomingRoom: 'patchRoomingRoom',\n PatchRoomingStayWindow: 'patchRoomingStayWindow',\n PatchSeatingVehicle: 'patchSeatingVehicle',\n PatchShareToken: 'patchShareToken',\n PatchTripManager: 'patchTripManager',\n PlatformHealth: 'platformHealth',\n PlatformLogin: 'platformLogin',\n PlatformLogout: 'platformLogout',\n PlatformMe: 'platformMe',\n PlatformRefreshTokens: 'platformRefreshTokens',\n PlatformWebhookHealth: 'platformWebhookHealth',\n PostponeTrek: 'postponeTrek',\n PublishChecklistTemplate: 'publishChecklistTemplate',\n PublishForm: 'publishForm',\n PullChecklistTemplate: 'pullChecklistTemplate',\n PushBulkTrips: 'pushBulkTrips',\n PushManifest: 'pushManifest',\n PushTripBalances: 'pushTripBalances',\n PutCommsConfig: 'putCommsConfig',\n PutCommsConfigConsole: 'putCommsConfigConsole',\n PutPlatformPartnerPlan: 'putPlatformPartnerPlan',\n ReadAgencyEntitlement: 'readAgencyEntitlement',\n ReadAgencyFeedbackSummary: 'readAgencyFeedbackSummary',\n ReadApiKey: 'readApiKey',\n ReadChecklistAggregate: 'readChecklistAggregate',\n ReadChecklistItem: 'readChecklistItem',\n ReadCloseout: 'readCloseout',\n ReadCommsConfig: 'readCommsConfig',\n ReadCommsConfigConsole: 'readCommsConfigConsole',\n ReadConsoleAudit: 'readConsoleAudit',\n ReadConsoleCertification: 'readConsoleCertification',\n ReadConsoleMe: 'readConsoleMe',\n ReadConsoleUserInvite: 'readConsoleUserInvite',\n ReadEndpointDeliveries: 'readEndpointDeliveries',\n ReadEndpointDelivery: 'readEndpointDelivery',\n ReadEntitlementCatalog: 'readEntitlementCatalog',\n ReadExpense: 'readExpense',\n ReadFile: 'readFile',\n ReadFileUrl: 'readFileUrl',\n ReadFloatLedger: 'readFloatLedger',\n ReadFloatSummary: 'readFloatSummary',\n ReadIngestLog: 'readIngestLog',\n ReadIngestLogSummary: 'readIngestLogSummary',\n ReadItinerary: 'readItinerary',\n ReadItineraryChangeLog: 'readItineraryChangeLog',\n ReadJourney: 'readJourney',\n ReadJourneyCapabilities: 'readJourneyCapabilities',\n ReadManagerExpense: 'readManagerExpense',\n ReadManagerExpenseLogMeta: 'readManagerExpenseLogMeta',\n ReadManagerFileView: 'readManagerFileView',\n ReadManagerToday: 'readManagerToday',\n ReadManifestByPickup: 'readManifestByPickup',\n ReadPlan: 'readPlan',\n ReadPlatformPartner: 'readPlatformPartner',\n ReadRoomingBoard: 'readRoomingBoard',\n ReadRoomingRoom: 'readRoomingRoom',\n ReadSeatingBoard: 'readSeatingBoard',\n ReadShareToken: 'readShareToken',\n ReadSupportJourneyState: 'readSupportJourneyState',\n ReadSupportWebhookDeliveryDetail: 'readSupportWebhookDeliveryDetail',\n ReadTenantDefaultCommsConfig: 'readTenantDefaultCommsConfig',\n ReadTenantDefaultCommsConfigConsole: 'readTenantDefaultCommsConfigConsole',\n ReadTestClock: 'readTestClock',\n ReadTestClockConsole: 'readTestClockConsole',\n ReadTestFixtures: 'readTestFixtures',\n ReadTestFixturesConsole: 'readTestFixturesConsole',\n ReadTestQuota: 'readTestQuota',\n ReadTestQuotaConsole: 'readTestQuotaConsole',\n ReadTrekBoard: 'readTrekBoard',\n ReadTrekWalkInMeta: 'readTrekWalkInMeta',\n ReadTripFeedbackSummary: 'readTripFeedbackSummary',\n ReadUsage: 'readUsage',\n ReadWebhookDelivery: 'readWebhookDelivery',\n ReadWebhookDeliveryConsole: 'readWebhookDeliveryConsole',\n ReadWebhookEndpoint: 'readWebhookEndpoint',\n ReadWebhookEventCatalog: 'readWebhookEventCatalog',\n ReassignPickupStopTravellers: 'reassignPickupStopTravellers',\n RebuildJourney: 'rebuildJourney',\n RecheckConsoleCertification: 'recheckConsoleCertification',\n ReconcileTrekWalkIn: 'reconcileTrekWalkIn',\n RecordCollection: 'recordCollection',\n RedeliverEndpointDelivery: 'redeliverEndpointDelivery',\n RedeliverWebhookDelivery: 'redeliverWebhookDelivery',\n RedeliverWebhookDeliveryConsole: 'redeliverWebhookDeliveryConsole',\n RedriveSupportWebhookDelivery: 'redriveSupportWebhookDelivery',\n RefreshAgencyAdminTokens: 'refreshAgencyAdminTokens',\n RefreshConsoleSession: 'refreshConsoleSession',\n RefreshManagerTokens: 'refreshManagerTokens',\n RegenerateShareToken: 'regenerateShareToken',\n RegisterWebhookEndpoint: 'registerWebhookEndpoint',\n ReissueConsoleUserInvite: 'reissueConsoleUserInvite',\n ReissuePlatformAdminInvite: 'reissuePlatformAdminInvite',\n ReissuePlatformPartnerConsoleUserInvite: 'reissuePlatformPartnerConsoleUserInvite',\n RemoveFromManifest: 'removeFromManifest',\n RenamePlatformPartner: 'renamePlatformPartner',\n ReopenForm: 'reopenForm',\n ReopenPickupStop: 'reopenPickupStop',\n ReorderForm: 'reorderForm',\n ReorderItineraryItem: 'reorderItineraryItem',\n ReorderPickupStops: 'reorderPickupStops',\n ReplaceBookingVouchers: 'replaceBookingVouchers',\n ReplaySupportWebhookRange: 'replaySupportWebhookRange',\n ReplayWebhookEndpoint: 'replayWebhookEndpoint',\n ReplayWebhookEndpointConsole: 'replayWebhookEndpointConsole',\n RequestFileUpload: 'requestFileUpload',\n ResetPlatformPartnerConsoleUser: 'resetPlatformPartnerConsoleUser',\n ResetTestClock: 'resetTestClock',\n ResetTestClockConsole: 'resetTestClockConsole',\n ResolvePlatformCredential: 'resolvePlatformCredential',\n ReturnFloat: 'returnFloat',\n RevealShareToken: 'revealShareToken',\n RevokeApiKey: 'revokeApiKey',\n RevokeMyConsoleSession: 'revokeMyConsoleSession',\n RevokePlatformPartnerApiKey: 'revokePlatformPartnerApiKey',\n RevokeShareToken: 'revokeShareToken',\n RotateApiKey: 'rotateApiKey',\n RotateWebhookEndpointSecret: 'rotateWebhookEndpointSecret',\n RunJourneyStep: 'runJourneyStep',\n SaveCloseoutHandover: 'saveCloseoutHandover',\n SearchTravellerDirectory: 'searchTravellerDirectory',\n SendCommsTestMessage: 'sendCommsTestMessage',\n SendCommsTestMessageConsole: 'sendCommsTestMessageConsole',\n SendMessage: 'sendMessage',\n SetPlatformPartnerStatus: 'setPlatformPartnerStatus',\n ShareListForms: 'shareListForms',\n ShareRenderForm: 'shareRenderForm',\n ShareSaveForm: 'shareSaveForm',\n ShareSubmitForm: 'shareSubmitForm',\n SubmitExpenseClaim: 'submitExpenseClaim',\n SyncDigest: 'syncDigest',\n SyncPullTrip: 'syncPullTrip',\n SyncPush: 'syncPush',\n SyncPushShare: 'syncPushShare',\n TestCommsProviderCredential: 'testCommsProviderCredential',\n TestCommsProviderCredentialConsole: 'testCommsProviderCredentialConsole',\n TestWebhookEndpoint: 'testWebhookEndpoint',\n TestWebhookEndpointApiKey: 'testWebhookEndpointApiKey',\n ToggleChecklistItem: 'toggleChecklistItem',\n UnarchiveForm: 'unarchiveForm',\n UnassignManager: 'unassignManager',\n UnlinkSeatingManager: 'unlinkSeatingManager',\n UnlockCloseout: 'unlockCloseout',\n UpsertAgency: 'upsertAgency',\n UpsertAgencyAdmin: 'upsertAgencyAdmin',\n UpsertManager: 'upsertManager',\n UpsertTravellerProfile: 'upsertTravellerProfile',\n UpsertTrip: 'upsertTrip',\n UpsertVendor: 'upsertVendor',\n VoidCollection: 'voidCollection',\n VoidExpense: 'voidExpense',\n WithdrawExpenseClaim: 'withdrawExpenseClaim',\n} as const;\nexport type OperationId = (typeof OperationId)[keyof typeof OperationId];\n\n// Ordered list of accepted credential schemes per operation. An empty array\n// means the operation is public (no security requirement in the spec).\nexport const OPERATION_SECURITY: Readonly<Record<OperationId, readonly SecuritySchemeId[]>> = {\n acceptConsoleInvite: [],\n acceptPlatformAdminInvite: [],\n addChecklistItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n addItineraryItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n addPlatformIncidentUpdate: ['platformAdminAuth'],\n addTravellerNote: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n adjustFloat: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n advanceTestTime: ['apiKeyAuth'],\n advanceTestTimeConsole: ['consoleAuth'],\n archiveForm: ['apiKeyAuth', 'agencyAdminAuth'],\n assignManager: ['apiKeyAuth', 'agencyAdminAuth'],\n assignPickupTraveller: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n assignRoomingBed: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n assignSeating: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n autoAssignRooming: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n autoAssignSeating: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n boardPickupTraveller: ['managerAuth'],\n buildTestFixtures: ['apiKeyAuth'],\n buildTestFixturesConsole: ['consoleAuth'],\n bulkUpsertBookings: ['apiKeyAuth'],\n cancelTrip: ['apiKeyAuth'],\n changeMyConsolePassword: ['consoleAuth'],\n changeOwnPlatformPassword: ['platformAdminAuth'],\n claimStatusIngest: ['apiKeyAuth'],\n cloneForm: ['apiKeyAuth', 'agencyAdminAuth'],\n closeForm: ['apiKeyAuth', 'agencyAdminAuth'],\n closePickupStop: ['managerAuth'],\n confirmFileUpload: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n consoleLogin: [],\n consoleLogout: ['consoleAuth'],\n consoleSwitchPlane: ['consoleAuth'],\n copyAgencyEntitlement: ['consoleAuth'],\n correctPickupBoardStatus: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createAgencyConsole: ['consoleAuth'],\n createApiKey: ['consoleAuth'],\n createChecklistTemplate: ['apiKeyAuth', 'agencyAdminAuth'],\n createCommsProviderCredential: ['apiKeyAuth'],\n createCommsProviderCredentialConsole: ['consoleAuth'],\n createConsoleUser: ['consoleAuth'],\n createForm: ['apiKeyAuth', 'agencyAdminAuth'],\n createFormField: ['apiKeyAuth', 'agencyAdminAuth'],\n createFormSection: ['apiKeyAuth', 'agencyAdminAuth'],\n createMessageTemplate: ['apiKeyAuth'],\n createParty: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createPickupStop: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createPlatformAdmin: ['platformAdminAuth'],\n createPlatformIncident: ['platformAdminAuth'],\n createPlatformPartner: ['platformAdminAuth'],\n createPlatformPartnerConsoleUser: ['platformAdminAuth'],\n createRoomingRoom: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createRoomingStayWindow: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createSeatingVehicle: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createSupportGrant: ['platformAdminAuth'],\n createTraveller: ['apiKeyAuth', 'agencyAdminAuth'],\n createTrekWalkIn: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n createVendor: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteBooking: ['apiKeyAuth'],\n deleteChecklistItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteChecklistTemplate: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteFile: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteForm: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteFormField: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteFormSection: ['apiKeyAuth', 'agencyAdminAuth'],\n deleteItineraryItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteParty: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deletePickupStop: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deletePlatformPartnerPlan: ['platformAdminAuth'],\n deleteRoomingRoom: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteRoomingStayWindow: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteSeatingVehicle: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n deleteVendor: ['apiKeyAuth', 'agencyAdminAuth'],\n dispatchForm: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n editWebhookEndpoint: ['consoleAuth'],\n eraseTraveller: ['apiKeyAuth'],\n exportCloseoutPack: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n exportFormResponses: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n exportTraveller: ['apiKeyAuth'],\n getAgencyAdminMe: ['agencyAdminAuth'],\n getAgencySettings: ['consoleAuth'],\n getAgencySettingsSelf: ['apiKeyAuth', 'agencyAdminAuth'],\n getAgencyTrip: ['apiKeyAuth', 'agencyAdminAuth'],\n getForm: ['apiKeyAuth', 'agencyAdminAuth', 'managerAuth'],\n getFormAggregate: ['apiKeyAuth'],\n getFormConsentReceipt: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n getFormResponse: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n getFormsCompletionMatrix: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n getFormsCrossModuleAnswers: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n getManagerAgencyProfile: ['apiKeyAuth', 'agencyAdminAuth'],\n getManagerInbox: ['managerAuth'],\n getNotificationDetail: ['managerAuth'],\n getShareManifest: ['shareAuth'],\n getShareSnapshot: ['shareAuth'],\n getTravellerAgencyProfile: ['apiKeyAuth', 'agencyAdminAuth'],\n getTravellerDetail: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n getTrip: ['apiKeyAuth'],\n getTripManifest: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n health: [],\n healthV1: [],\n inspectConsoleInvite: [],\n inspectPlatformAdminInvite: [],\n issueFloat: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n linkExpenseReceipt: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n linkSeatingManager: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listAgencies: ['consoleAuth'],\n listAgencyManagers: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listAgencyTrips: ['apiKeyAuth', 'agencyAdminAuth'],\n listApiKeys: ['consoleAuth'],\n listBookings: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n listChecklistTemplates: ['managerAuth', 'apiKeyAuth'],\n listChecklistTemplatesAdmin: ['apiKeyAuth', 'agencyAdminAuth'],\n listCollections: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listConsoleUsers: ['consoleAuth'],\n listEligibleCollections: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listEvents: ['apiKeyAuth'],\n listExpenses: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listFiles: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listFormBindings: ['apiKeyAuth', 'agencyAdminAuth', 'managerAuth'],\n listForms: ['apiKeyAuth', 'agencyAdminAuth'],\n listJourneyTriggers: ['apiKeyAuth', 'agencyAdminAuth'],\n listJourneyTriggersConsole: ['consoleAuth'],\n listManagerExpenses: ['managerAuth'],\n listManagerNotifications: ['managerAuth'],\n listMessages: ['apiKeyAuth'],\n listMessagesConsole: ['consoleAuth'],\n listMessageTemplates: ['apiKeyAuth'],\n listMyConsoleSessions: ['consoleAuth'],\n listOwnManagerTrips: ['managerAuth'],\n listParties: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n listPickupStops: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n listPlatformAdmins: ['platformAdminAuth'],\n listPlatformAudit: ['platformAdminAuth'],\n listPlatformIncidents: ['platformAdminAuth'],\n listPlatformPartnerApiKeys: ['platformAdminAuth'],\n listPlatformPartnerConsoleUsers: ['platformAdminAuth'],\n listPlatformPartners: ['platformAdminAuth'],\n listPlatformPlanTiers: ['platformAdminAuth'],\n listRoomingStayWindows: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n listShareTokens: ['apiKeyAuth', 'agencyAdminAuth'],\n listSupportIngestLog: ['platformAdminAuth'],\n listSupportWebhookDeliveries: ['platformAdminAuth'],\n listTravellerFormResponses: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTrekWalkIns: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTripFormResponses: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTripForms: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTripManagers: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n listTripManifest: ['apiKeyAuth', 'agencyAdminAuth'],\n listTripVendors: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n listWebhookDeliveries: ['apiKeyAuth'],\n listWebhookDeliveriesConsole: ['consoleAuth'],\n listWebhookEndpoints: ['consoleAuth'],\n lockCloseout: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n logExpense: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n managerCreateFormResponse: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n markNotificationRead: ['managerAuth'],\n mintAgencyAdminTokens: ['apiKeyAuth'],\n mintManagerTokens: ['apiKeyAuth'],\n mintShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n nudgeConsoleInvite: [],\n patchAgencyEntitlement: ['consoleAuth'],\n patchAgencySettings: ['consoleAuth'],\n patchAgencySettingsSelf: ['agencyAdminAuth'],\n patchChecklistItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchChecklistTemplate: ['apiKeyAuth', 'agencyAdminAuth'],\n patchConsoleUser: ['consoleAuth'],\n patchForm: ['apiKeyAuth', 'agencyAdminAuth'],\n patchFormField: ['apiKeyAuth', 'agencyAdminAuth'],\n patchFormSection: ['apiKeyAuth', 'agencyAdminAuth'],\n patchItineraryDay: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchItineraryItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchJourneyTrigger: ['apiKeyAuth', 'agencyAdminAuth'],\n patchJourneyTriggerConsole: ['consoleAuth'],\n patchMessageTemplate: ['apiKeyAuth'],\n patchParty: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchPickupStop: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchPlatformAdmin: ['platformAdminAuth'],\n patchPlatformPartnerConsoleUser: ['platformAdminAuth'],\n patchRoomingRoom: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchRoomingStayWindow: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchSeatingVehicle: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n patchShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n patchTripManager: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n platformHealth: ['platformAdminAuth'],\n platformLogin: [],\n platformLogout: ['platformAdminAuth'],\n platformMe: ['platformAdminAuth'],\n platformRefreshTokens: ['platformAdminAuth'],\n platformWebhookHealth: ['platformAdminAuth'],\n postponeTrek: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n publishChecklistTemplate: ['apiKeyAuth', 'agencyAdminAuth'],\n publishForm: ['apiKeyAuth', 'agencyAdminAuth'],\n pullChecklistTemplate: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n pushBulkTrips: ['apiKeyAuth'],\n pushManifest: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n pushTripBalances: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n putCommsConfig: ['apiKeyAuth'],\n putCommsConfigConsole: ['consoleAuth'],\n putPlatformPartnerPlan: ['platformAdminAuth'],\n readAgencyEntitlement: ['consoleAuth'],\n readAgencyFeedbackSummary: ['agencyAdminAuth', 'apiKeyAuth'],\n readApiKey: ['consoleAuth'],\n readChecklistAggregate: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readChecklistItem: ['managerAuth', 'apiKeyAuth'],\n readCloseout: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readCommsConfig: ['apiKeyAuth'],\n readCommsConfigConsole: ['consoleAuth'],\n readConsoleAudit: ['consoleAuth'],\n readConsoleCertification: ['consoleAuth'],\n readConsoleMe: ['consoleAuth'],\n readConsoleUserInvite: ['consoleAuth'],\n readEndpointDeliveries: ['consoleAuth'],\n readEndpointDelivery: ['consoleAuth'],\n readEntitlementCatalog: ['consoleAuth'],\n readExpense: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readFile: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readFileUrl: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readFloatLedger: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readFloatSummary: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readIngestLog: ['consoleAuth'],\n readIngestLogSummary: ['consoleAuth'],\n readItinerary: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readItineraryChangeLog: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readJourney: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readJourneyCapabilities: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readManagerExpense: ['managerAuth'],\n readManagerExpenseLogMeta: ['managerAuth'],\n readManagerFileView: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readManagerToday: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readManifestByPickup: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readPlan: ['consoleAuth'],\n readPlatformPartner: ['platformAdminAuth'],\n readRoomingBoard: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readRoomingRoom: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readSeatingBoard: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n readSupportJourneyState: ['platformAdminAuth'],\n readSupportWebhookDeliveryDetail: ['platformAdminAuth'],\n readTenantDefaultCommsConfig: ['apiKeyAuth'],\n readTenantDefaultCommsConfigConsole: ['consoleAuth'],\n readTestClock: ['apiKeyAuth'],\n readTestClockConsole: ['consoleAuth'],\n readTestFixtures: ['apiKeyAuth'],\n readTestFixturesConsole: ['consoleAuth'],\n readTestQuota: ['apiKeyAuth'],\n readTestQuotaConsole: ['consoleAuth'],\n readTrekBoard: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readTrekWalkInMeta: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n readTripFeedbackSummary: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readUsage: ['consoleAuth'],\n readWebhookDelivery: ['apiKeyAuth'],\n readWebhookDeliveryConsole: ['consoleAuth'],\n readWebhookEndpoint: ['consoleAuth'],\n readWebhookEventCatalog: ['consoleAuth'],\n reassignPickupStopTravellers: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n rebuildJourney: ['apiKeyAuth'],\n recheckConsoleCertification: ['consoleAuth'],\n reconcileTrekWalkIn: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n recordCollection: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n redeliverEndpointDelivery: ['consoleAuth'],\n redeliverWebhookDelivery: ['apiKeyAuth'],\n redeliverWebhookDeliveryConsole: ['consoleAuth'],\n redriveSupportWebhookDelivery: ['platformAdminAuth'],\n refreshAgencyAdminTokens: ['agencyAdminAuth'],\n refreshConsoleSession: ['consoleAuth'],\n refreshManagerTokens: ['managerAuth'],\n regenerateShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n registerWebhookEndpoint: ['consoleAuth'],\n reissueConsoleUserInvite: ['consoleAuth'],\n reissuePlatformAdminInvite: ['platformAdminAuth'],\n reissuePlatformPartnerConsoleUserInvite: ['platformAdminAuth'],\n removeFromManifest: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n renamePlatformPartner: ['platformAdminAuth'],\n reopenForm: ['apiKeyAuth', 'agencyAdminAuth'],\n reopenPickupStop: ['managerAuth'],\n reorderForm: ['apiKeyAuth', 'agencyAdminAuth'],\n reorderItineraryItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n reorderPickupStops: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n replaceBookingVouchers: ['apiKeyAuth', 'agencyAdminAuth'],\n replaySupportWebhookRange: ['platformAdminAuth'],\n replayWebhookEndpoint: ['apiKeyAuth'],\n replayWebhookEndpointConsole: ['consoleAuth'],\n requestFileUpload: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n resetPlatformPartnerConsoleUser: ['platformAdminAuth'],\n resetTestClock: ['apiKeyAuth'],\n resetTestClockConsole: ['consoleAuth'],\n resolvePlatformCredential: ['platformAdminAuth'],\n returnFloat: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n revealShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n revokeApiKey: ['consoleAuth'],\n revokeMyConsoleSession: ['consoleAuth'],\n revokePlatformPartnerApiKey: ['platformAdminAuth'],\n revokeShareToken: ['apiKeyAuth', 'agencyAdminAuth'],\n rotateApiKey: ['consoleAuth'],\n rotateWebhookEndpointSecret: ['consoleAuth'],\n runJourneyStep: ['apiKeyAuth'],\n saveCloseoutHandover: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n searchTravellerDirectory: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n sendCommsTestMessage: ['apiKeyAuth'],\n sendCommsTestMessageConsole: ['consoleAuth'],\n sendMessage: ['apiKeyAuth'],\n setPlatformPartnerStatus: ['platformAdminAuth'],\n shareListForms: ['shareAuth'],\n shareRenderForm: ['shareAuth'],\n shareSaveForm: ['shareAuth'],\n shareSubmitForm: ['shareAuth'],\n submitExpenseClaim: ['managerAuth', 'apiKeyAuth'],\n syncDigest: ['apiKeyAuth'],\n syncPullTrip: ['managerAuth', 'apiKeyAuth'],\n syncPush: ['managerAuth', 'apiKeyAuth'],\n syncPushShare: [],\n testCommsProviderCredential: ['apiKeyAuth'],\n testCommsProviderCredentialConsole: ['consoleAuth'],\n testWebhookEndpoint: ['consoleAuth'],\n testWebhookEndpointApiKey: ['apiKeyAuth'],\n toggleChecklistItem: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n unarchiveForm: ['apiKeyAuth', 'agencyAdminAuth'],\n unassignManager: ['apiKeyAuth', 'agencyAdminAuth'],\n unlinkSeatingManager: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n unlockCloseout: ['apiKeyAuth'],\n upsertAgency: ['apiKeyAuth'],\n upsertAgencyAdmin: ['apiKeyAuth'],\n upsertManager: ['apiKeyAuth'],\n upsertTravellerProfile: ['apiKeyAuth'],\n upsertTrip: ['apiKeyAuth'],\n upsertVendor: ['apiKeyAuth', 'agencyAdminAuth'],\n voidCollection: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n voidExpense: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n withdrawExpenseClaim: ['managerAuth', 'apiKeyAuth'],\n};\n\n// 110 of 327 operations accept an `Idempotency-Key` header, per each\n// operation's `parameters` in the vendored spec.\nexport const OPERATION_ACCEPTS_IDEMPOTENCY_KEY: Readonly<Record<OperationId, boolean>> = {\n acceptConsoleInvite: true,\n acceptPlatformAdminInvite: true,\n addChecklistItem: true,\n addItineraryItem: true,\n addPlatformIncidentUpdate: false,\n addTravellerNote: true,\n adjustFloat: true,\n advanceTestTime: true,\n advanceTestTimeConsole: true,\n archiveForm: false,\n assignManager: true,\n assignPickupTraveller: true,\n assignRoomingBed: true,\n assignSeating: true,\n autoAssignRooming: true,\n autoAssignSeating: true,\n boardPickupTraveller: true,\n buildTestFixtures: true,\n buildTestFixturesConsole: true,\n bulkUpsertBookings: true,\n cancelTrip: true,\n changeMyConsolePassword: true,\n changeOwnPlatformPassword: false,\n claimStatusIngest: true,\n cloneForm: true,\n closeForm: false,\n closePickupStop: true,\n confirmFileUpload: true,\n consoleLogin: false,\n consoleLogout: false,\n consoleSwitchPlane: false,\n copyAgencyEntitlement: true,\n correctPickupBoardStatus: false,\n createAgencyConsole: false,\n createApiKey: true,\n createChecklistTemplate: true,\n createCommsProviderCredential: true,\n createCommsProviderCredentialConsole: true,\n createConsoleUser: true,\n createForm: true,\n createFormField: false,\n createFormSection: false,\n createMessageTemplate: true,\n createParty: true,\n createPickupStop: true,\n createPlatformAdmin: false,\n createPlatformIncident: false,\n createPlatformPartner: false,\n createPlatformPartnerConsoleUser: false,\n createRoomingRoom: true,\n createRoomingStayWindow: true,\n createSeatingVehicle: true,\n createSupportGrant: false,\n createTraveller: true,\n createTrekWalkIn: true,\n createVendor: true,\n deleteBooking: true,\n deleteChecklistItem: false,\n deleteChecklistTemplate: false,\n deleteFile: true,\n deleteForm: false,\n deleteFormField: false,\n deleteFormSection: false,\n deleteItineraryItem: false,\n deleteParty: true,\n deletePickupStop: false,\n deletePlatformPartnerPlan: false,\n deleteRoomingRoom: false,\n deleteRoomingStayWindow: false,\n deleteSeatingVehicle: false,\n deleteVendor: true,\n dispatchForm: true,\n editWebhookEndpoint: true,\n eraseTraveller: true,\n exportCloseoutPack: false,\n exportFormResponses: false,\n exportTraveller: false,\n getAgencyAdminMe: false,\n getAgencySettings: false,\n getAgencySettingsSelf: false,\n getAgencyTrip: false,\n getForm: false,\n getFormAggregate: false,\n getFormConsentReceipt: false,\n getFormResponse: false,\n getFormsCompletionMatrix: false,\n getFormsCrossModuleAnswers: false,\n getManagerAgencyProfile: false,\n getManagerInbox: false,\n getNotificationDetail: false,\n getShareManifest: false,\n getShareSnapshot: false,\n getTravellerAgencyProfile: false,\n getTravellerDetail: false,\n getTrip: false,\n getTripManifest: false,\n health: false,\n healthV1: false,\n inspectConsoleInvite: false,\n inspectPlatformAdminInvite: false,\n issueFloat: true,\n linkExpenseReceipt: true,\n linkSeatingManager: true,\n listAgencies: false,\n listAgencyManagers: false,\n listAgencyTrips: false,\n listApiKeys: false,\n listBookings: false,\n listChecklistTemplates: false,\n listChecklistTemplatesAdmin: false,\n listCollections: false,\n listConsoleUsers: false,\n listEligibleCollections: false,\n listEvents: false,\n listExpenses: false,\n listFiles: false,\n listFormBindings: false,\n listForms: false,\n listJourneyTriggers: false,\n listJourneyTriggersConsole: false,\n listManagerExpenses: false,\n listManagerNotifications: false,\n listMessages: false,\n listMessagesConsole: false,\n listMessageTemplates: false,\n listMyConsoleSessions: false,\n listOwnManagerTrips: false,\n listParties: false,\n listPickupStops: false,\n listPlatformAdmins: false,\n listPlatformAudit: false,\n listPlatformIncidents: false,\n listPlatformPartnerApiKeys: false,\n listPlatformPartnerConsoleUsers: false,\n listPlatformPartners: false,\n listPlatformPlanTiers: false,\n listRoomingStayWindows: false,\n listShareTokens: false,\n listSupportIngestLog: false,\n listSupportWebhookDeliveries: false,\n listTravellerFormResponses: false,\n listTrekWalkIns: false,\n listTripFormResponses: false,\n listTripForms: false,\n listTripManagers: false,\n listTripManifest: false,\n listTripVendors: false,\n listWebhookDeliveries: false,\n listWebhookDeliveriesConsole: false,\n listWebhookEndpoints: false,\n lockCloseout: true,\n logExpense: true,\n managerCreateFormResponse: true,\n markNotificationRead: true,\n mintAgencyAdminTokens: false,\n mintManagerTokens: false,\n mintShareToken: true,\n nudgeConsoleInvite: false,\n patchAgencyEntitlement: true,\n patchAgencySettings: false,\n patchAgencySettingsSelf: false,\n patchChecklistItem: false,\n patchChecklistTemplate: false,\n patchConsoleUser: true,\n patchForm: false,\n patchFormField: false,\n patchFormSection: false,\n patchItineraryDay: false,\n patchItineraryItem: false,\n patchJourneyTrigger: true,\n patchJourneyTriggerConsole: true,\n patchMessageTemplate: false,\n patchParty: true,\n patchPickupStop: false,\n patchPlatformAdmin: false,\n patchPlatformPartnerConsoleUser: false,\n patchRoomingRoom: false,\n patchRoomingStayWindow: false,\n patchSeatingVehicle: false,\n patchShareToken: false,\n patchTripManager: false,\n platformHealth: false,\n platformLogin: true,\n platformLogout: false,\n platformMe: false,\n platformRefreshTokens: true,\n platformWebhookHealth: false,\n postponeTrek: true,\n publishChecklistTemplate: false,\n publishForm: false,\n pullChecklistTemplate: true,\n pushBulkTrips: true,\n pushManifest: true,\n pushTripBalances: true,\n putCommsConfig: false,\n putCommsConfigConsole: false,\n putPlatformPartnerPlan: false,\n readAgencyEntitlement: false,\n readAgencyFeedbackSummary: false,\n readApiKey: false,\n readChecklistAggregate: false,\n readChecklistItem: false,\n readCloseout: false,\n readCommsConfig: false,\n readCommsConfigConsole: false,\n readConsoleAudit: false,\n readConsoleCertification: false,\n readConsoleMe: false,\n readConsoleUserInvite: false,\n readEndpointDeliveries: false,\n readEndpointDelivery: false,\n readEntitlementCatalog: false,\n readExpense: false,\n readFile: false,\n readFileUrl: false,\n readFloatLedger: false,\n readFloatSummary: false,\n readIngestLog: false,\n readIngestLogSummary: false,\n readItinerary: false,\n readItineraryChangeLog: false,\n readJourney: false,\n readJourneyCapabilities: false,\n readManagerExpense: false,\n readManagerExpenseLogMeta: false,\n readManagerFileView: false,\n readManagerToday: false,\n readManifestByPickup: false,\n readPlan: false,\n readPlatformPartner: false,\n readRoomingBoard: false,\n readRoomingRoom: false,\n readSeatingBoard: false,\n readShareToken: false,\n readSupportJourneyState: false,\n readSupportWebhookDeliveryDetail: false,\n readTenantDefaultCommsConfig: false,\n readTenantDefaultCommsConfigConsole: false,\n readTestClock: false,\n readTestClockConsole: false,\n readTestFixtures: false,\n readTestFixturesConsole: false,\n readTestQuota: false,\n readTestQuotaConsole: false,\n readTrekBoard: false,\n readTrekWalkInMeta: false,\n readTripFeedbackSummary: false,\n readUsage: false,\n readWebhookDelivery: false,\n readWebhookDeliveryConsole: false,\n readWebhookEndpoint: false,\n readWebhookEventCatalog: false,\n reassignPickupStopTravellers: true,\n rebuildJourney: true,\n recheckConsoleCertification: false,\n reconcileTrekWalkIn: true,\n recordCollection: true,\n redeliverEndpointDelivery: true,\n redeliverWebhookDelivery: true,\n redeliverWebhookDeliveryConsole: true,\n redriveSupportWebhookDelivery: false,\n refreshAgencyAdminTokens: false,\n refreshConsoleSession: false,\n refreshManagerTokens: false,\n regenerateShareToken: true,\n registerWebhookEndpoint: true,\n reissueConsoleUserInvite: true,\n reissuePlatformAdminInvite: false,\n reissuePlatformPartnerConsoleUserInvite: false,\n removeFromManifest: true,\n renamePlatformPartner: false,\n reopenForm: false,\n reopenPickupStop: true,\n reorderForm: false,\n reorderItineraryItem: true,\n reorderPickupStops: true,\n replaceBookingVouchers: false,\n replaySupportWebhookRange: false,\n replayWebhookEndpoint: true,\n replayWebhookEndpointConsole: true,\n requestFileUpload: true,\n resetPlatformPartnerConsoleUser: false,\n resetTestClock: true,\n resetTestClockConsole: true,\n resolvePlatformCredential: false,\n returnFloat: true,\n revealShareToken: false,\n revokeApiKey: true,\n revokeMyConsoleSession: true,\n revokePlatformPartnerApiKey: false,\n revokeShareToken: false,\n rotateApiKey: true,\n rotateWebhookEndpointSecret: true,\n runJourneyStep: true,\n saveCloseoutHandover: true,\n searchTravellerDirectory: false,\n sendCommsTestMessage: true,\n sendCommsTestMessageConsole: true,\n sendMessage: true,\n setPlatformPartnerStatus: false,\n shareListForms: false,\n shareRenderForm: false,\n shareSaveForm: true,\n shareSubmitForm: true,\n submitExpenseClaim: true,\n syncDigest: false,\n syncPullTrip: false,\n syncPush: false,\n syncPushShare: false,\n testCommsProviderCredential: true,\n testCommsProviderCredentialConsole: true,\n testWebhookEndpoint: false,\n testWebhookEndpointApiKey: false,\n toggleChecklistItem: true,\n unarchiveForm: false,\n unassignManager: true,\n unlinkSeatingManager: false,\n unlockCloseout: true,\n upsertAgency: true,\n upsertAgencyAdmin: true,\n upsertManager: true,\n upsertTravellerProfile: true,\n upsertTrip: true,\n upsertVendor: true,\n voidCollection: false,\n voidExpense: false,\n withdrawExpenseClaim: false,\n};\n","/**\n * This file was auto-generated by `scripts/gen-meta.mjs` from\n * `openapi/openapi.json`. Do not make direct changes to the file — re-run\n * `pnpm gen:types` instead.\n *\n * @generated src/generated/error-codes.ts\n */\n\n// `status` is `null` for a code that no operation's `responses` declares in\n// the vendored spec — the code exists in the `ErrorCode` enum and in both\n// `x-kaafil-*` maps, but no current operation returns it. Never backfilled by\n// hand: when an operation starts declaring it, re-running `pnpm gen:types`\n// fills the real status in.\n\nexport const KaafilErrorCode = {\n ActiveRequiresManager: 'ACTIVE_REQUIRES_MANAGER',\n BusinessRuleViolation: 'BUSINESS_RULE_VIOLATION',\n CannotPostpone: 'CANNOT_POSTPONE',\n CapabilityUnavailable: 'CAPABILITY_UNAVAILABLE',\n ConflictVersion: 'CONFLICT_VERSION',\n ConsentRequired: 'CONSENT_REQUIRED',\n FieldNotVisible: 'FIELD_NOT_VISIBLE',\n FileOrphaned: 'FILE_ORPHANED',\n FilePurged: 'FILE_PURGED',\n FormClosed: 'FORM_CLOSED',\n FormDefinitionChanged: 'FORM_DEFINITION_CHANGED',\n FormLockedByResponses: 'FORM_LOCKED_BY_RESPONSES',\n FormNotOpen: 'FORM_NOT_OPEN',\n FormNotPublishable: 'FORM_NOT_PUBLISHABLE',\n FormWindowInvalid: 'FORM_WINDOW_INVALID',\n IdempotencyKeyReused: 'IDEMPOTENCY_KEY_REUSED',\n InternalError: 'INTERNAL_ERROR',\n Locked: 'LOCKED',\n NotATrek: 'NOT_A_TREK',\n NotImplemented: 'NOT_IMPLEMENTED',\n OutOfTripWindow: 'OUT_OF_TRIP_WINDOW',\n PlanFeatureDisabled: 'PLAN_FEATURE_DISABLED',\n RateLimited: 'RATE_LIMITED',\n ReadOnlyRole: 'READ_ONLY_ROLE',\n ResourceNotFound: 'RESOURCE_NOT_FOUND',\n ResponseClosed: 'RESPONSE_CLOSED',\n ResponseLimitReached: 'RESPONSE_LIMIT_REACHED',\n SeatingCapacityOrphan: 'SEATING_CAPACITY_ORPHAN',\n SecretNotReplayable: 'SECRET_NOT_REPLAYABLE',\n ShareTokenExpired: 'SHARE_TOKEN_EXPIRED',\n ShareTokenRevoked: 'SHARE_TOKEN_REVOKED',\n ShareWriteGraceExpired: 'SHARE_WRITE_GRACE_EXPIRED',\n StayWindowHasAssignments: 'STAY_WINDOW_HAS_ASSIGNMENTS',\n StayWindowOverlap: 'STAY_WINDOW_OVERLAP',\n StopHasPending: 'STOP_HAS_PENDING',\n SubjectRequired: 'SUBJECT_REQUIRED',\n SupportGrantRequired: 'SUPPORT_GRANT_REQUIRED',\n SyncTargetRefused: 'SYNC_TARGET_REFUSED',\n TenantScopeMissing: 'TENANT_SCOPE_MISSING',\n TestClockBackwards: 'TEST_CLOCK_BACKWARDS',\n TestClockTooFar: 'TEST_CLOCK_TOO_FAR',\n TestFixtureScenarioUnknown: 'TEST_FIXTURE_SCENARIO_UNKNOWN',\n TestTravellerLimit: 'TEST_TRAVELLER_LIMIT',\n TestTripLimit: 'TEST_TRIP_LIMIT',\n Unauthenticated: 'UNAUTHENTICATED',\n UploadMismatch: 'UPLOAD_MISMATCH',\n ValidationError: 'VALIDATION_ERROR',\n} as const;\nexport type KaafilErrorCode = (typeof KaafilErrorCode)[keyof typeof KaafilErrorCode];\n\nexport const Retryability = {\n No: 'no',\n Yes: 'yes',\n AfterRefresh: 'after-refresh',\n HonourRetryAfter: 'honour-retry-after',\n} as const;\nexport type Retryability = (typeof Retryability)[keyof typeof Retryability];\n\nexport const OutboxClass = {\n Transient: 'TRANSIENT',\n Conflict: 'CONFLICT',\n Fatal: 'FATAL',\n} as const;\nexport type OutboxClass = (typeof OutboxClass)[keyof typeof OutboxClass];\n\nexport interface ErrorCodeTableEntry {\n /** Always present: every code's status comes from the catalog, not from\n * whichever operations happen to declare the code. */\n readonly status: number;\n readonly retryability: Retryability;\n readonly outboxClass: OutboxClass;\n}\n\nexport const ERROR_CODE_TABLE: Readonly<Record<KaafilErrorCode, ErrorCodeTableEntry>> = {\n ACTIVE_REQUIRES_MANAGER: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n BUSINESS_RULE_VIOLATION: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n CANNOT_POSTPONE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n CAPABILITY_UNAVAILABLE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n CONFLICT_VERSION: { status: 409, retryability: 'no', outboxClass: 'CONFLICT' },\n CONSENT_REQUIRED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FIELD_NOT_VISIBLE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FILE_ORPHANED: { status: 409, retryability: 'no', outboxClass: 'FATAL' },\n FILE_PURGED: { status: 410, retryability: 'no', outboxClass: 'FATAL' },\n FORM_CLOSED: { status: 409, retryability: 'no', outboxClass: 'FATAL' },\n FORM_DEFINITION_CHANGED: { status: 409, retryability: 'no', outboxClass: 'FATAL' },\n FORM_LOCKED_BY_RESPONSES: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FORM_NOT_OPEN: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FORM_NOT_PUBLISHABLE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n FORM_WINDOW_INVALID: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n IDEMPOTENCY_KEY_REUSED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n INTERNAL_ERROR: { status: 500, retryability: 'yes', outboxClass: 'TRANSIENT' },\n LOCKED: { status: 423, retryability: 'no', outboxClass: 'FATAL' },\n NOT_A_TREK: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n NOT_IMPLEMENTED: { status: 501, retryability: 'no', outboxClass: 'FATAL' },\n OUT_OF_TRIP_WINDOW: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n PLAN_FEATURE_DISABLED: { status: 402, retryability: 'no', outboxClass: 'FATAL' },\n RATE_LIMITED: { status: 429, retryability: 'honour-retry-after', outboxClass: 'TRANSIENT' },\n READ_ONLY_ROLE: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n RESOURCE_NOT_FOUND: { status: 404, retryability: 'no', outboxClass: 'FATAL' },\n RESPONSE_CLOSED: { status: 409, retryability: 'no', outboxClass: 'FATAL' },\n RESPONSE_LIMIT_REACHED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n SEATING_CAPACITY_ORPHAN: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n SECRET_NOT_REPLAYABLE: { status: 409, retryability: 'no', outboxClass: 'CONFLICT' },\n SHARE_TOKEN_EXPIRED: { status: 401, retryability: 'no', outboxClass: 'FATAL' },\n SHARE_TOKEN_REVOKED: { status: 401, retryability: 'no', outboxClass: 'FATAL' },\n SHARE_WRITE_GRACE_EXPIRED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n STAY_WINDOW_HAS_ASSIGNMENTS: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n STAY_WINDOW_OVERLAP: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n STOP_HAS_PENDING: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n SUBJECT_REQUIRED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n SUPPORT_GRANT_REQUIRED: { status: 403, retryability: 'no', outboxClass: 'FATAL' },\n SYNC_TARGET_REFUSED: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TENANT_SCOPE_MISSING: { status: 500, retryability: 'yes', outboxClass: 'TRANSIENT' },\n TEST_CLOCK_BACKWARDS: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TEST_CLOCK_TOO_FAR: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TEST_FIXTURE_SCENARIO_UNKNOWN: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TEST_TRAVELLER_LIMIT: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n TEST_TRIP_LIMIT: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n UNAUTHENTICATED: { status: 401, retryability: 'after-refresh', outboxClass: 'FATAL' },\n UPLOAD_MISMATCH: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n VALIDATION_ERROR: { status: 422, retryability: 'no', outboxClass: 'FATAL' },\n};\n","import { ERROR_CODE_TABLE, KaafilErrorCode, Retryability } from '../generated/error-codes';\nimport type { ResponseMeta } from '../types/meta';\n\n// Error semantics cited, never restated: `architecture/08-sdk.md §6`\n// (retries & error handling), `architecture/06-offline-first.md §7` (FATAL /\n// CONFLICT / TRANSIENT classification), `architecture/10-conventions.md §7`\n// (the master error catalog) and `architecture/03-auth-and-tokens.md §2`\n// (manager token rotation / `READ_ONLY_ROLE`).\n\n/**\n * Distinguishes a real API response (has a catalog `.code`) from a\n * transport-level failure (network, timeout, abort — never reached a\n * catalog code because no response envelope was ever parsed). Present on\n * the base class, not just inferable via `instanceof`, so a consumer whose\n * bundler duplicated this package across two copies can still branch —\n * `instanceof` across two module instances of the same package is a real,\n * if rare, hazard.\n */\nexport type KaafilErrorKind = 'api' | 'transport';\n\ninterface KaafilErrorInit {\n readonly code?: KaafilErrorCode;\n readonly status?: number;\n readonly details?: Record<string, unknown>;\n readonly requestId?: string;\n readonly meta?: ResponseMeta;\n readonly cause?: unknown;\n}\n\n/**\n * Base of every error this SDK throws. Carries the fields a consumer needs\n * to branch on (`code`, `kind`) and the fields support needs to trace a\n * request (`status`, `requestId`, `meta`).\n *\n * Subclassing `Error` and relying on `instanceof` later breaks once a build\n * step downlevels the output (the prototype chain gets rebuilt incorrectly\n * by some ES5 target transforms) — every concrete leaf class below restores\n * its own prototype with `Object.setPrototypeOf` after calling `super()`.\n */\nexport abstract class KaafilError extends Error {\n abstract readonly kind: KaafilErrorKind;\n readonly code: KaafilErrorCode | undefined;\n readonly status: number | undefined;\n readonly details: Record<string, unknown> | undefined;\n readonly requestId: string | undefined;\n readonly meta: ResponseMeta | undefined;\n\n protected constructor(message: string, init: KaafilErrorInit = {}) {\n super(message, init.cause !== undefined ? { cause: init.cause } : undefined);\n this.name = 'KaafilError';\n this.code = init.code;\n this.status = init.status;\n this.details = init.details;\n this.requestId = init.requestId;\n this.meta = init.meta;\n }\n}\n\n/**\n * A response the server actually answered, carrying a catalog `.code`. Also\n * the fallback for a catalog code that has no dedicated subclass below —\n * every one of the 24 cross-cutting codes in `ERROR_CODE_TABLE` produces at\n * least a typed `KaafilApiError`, even the ones a consumer rarely needs to\n * branch on by name (`BUSINESS_RULE_VIOLATION`, `TENANT_SCOPE_MISSING`, …).\n *\n * ── WHY 10B's FIVE MODULE-LOCAL CODES DID NOT EARN A DEDICATED SUBCLASS ─────\n *\n * `SEATING_CAPACITY_ORPHAN`, `NOT_A_TREK`, `CANNOT_POSTPONE`,\n * `STAY_WINDOW_OVERLAP` and `STAY_WINDOW_HAS_ASSIGNMENTS` all resolve to a\n * plain `KaafilApiError` through `fromEnvelope`'s `default` branch, same as\n * `BUSINESS_RULE_VIOLATION`. The temptation, having just built the module-\n * local registry that lets a module publish its OWN named code, is to give\n * each one its own class to match — but the twelve codes that DO have a\n * dedicated class below (`ResourceNotFound`, `PlanFeatureDisabled`,\n * `CapabilityUnavailable`, `ReadOnlyRole`, `ValidationError`,\n * `ConflictVersion`, `Locked`, `RateLimited`, `Unauthenticated`,\n * `ShareTokenExpired`, `ShareTokenRevoked`, `NotImplemented`) share a trait\n * none of these five have: each is part of the SDK's OWN cross-module\n * machinery — auth, retry, offline sync, idempotency — reused with an\n * IDENTICAL meaning everywhere it appears, which is exactly why `errors.ts`\n * (a `shared/`-level file) is the right place to name it once. A\n * module-local code is, by the registry's own rule, owned by exactly one\n * module and defined once in that module's FRD; giving it a class in this\n * shared file would start coupling the shared error hierarchy to one\n * module's business specifics — the identical boundary violation\n * `module-error-codes.ts` (engine-side) already refuses for the opposite\n * direction (\"`shared/` may never import a module\").\n *\n * Nor does branching need it: `error.code === KaafilErrorCode.NotATrek` is\n * already fully typed (`KaafilErrorCode` is a real union, not a bare\n * string), so a UI that branches on `NOT_A_TREK` or `SEATING_CAPACITY_ORPHAN`\n * — and the plan for this phase says explicitly that a UI does — gets that\n * from `.code` alone, no `instanceof` required. That is precisely the\n * precedent `STOP_HAS_PENDING` and `OUT_OF_TRIP_WINDOW` already set: both are\n * equally single-meaning, equally UI-branchable codes from earlier phases,\n * and neither got a class either. Multiplying subclasses per code the moment\n * a caller might name-check one would eventually turn this file into a\n * mirror of the whole catalog — which is the same \"just add a 25th entry\"\n * instinct the module-local registry was built specifically to avoid on the\n * engine side (see `module-error-codes.ts`'s header). `SEATING_CAPACITY_ORPHAN`\n * carries an orphaned count and labels in `details` — read those\n * defensively off `.details`, the same as `KaafilValidationError.fields`\n * would if this file ever decides the getter is worth adding; it does not\n * change which class the error is.\n *\n * This is not a permanent ruling. If a module-local code later needs a typed\n * getter over `details` the way `KaafilVersionConflictError.currentVersion`\n * does, that is the trigger to add ONE dedicated class for THAT code — not a\n * reason to add all five at once pre-emptively.\n */\nexport class KaafilApiError extends KaafilError {\n override readonly kind = 'api' as const;\n override readonly code: KaafilErrorCode;\n\n constructor(code: KaafilErrorCode, message: string, init: Omit<KaafilErrorInit, 'code'> = {}) {\n super(message, { ...init, code });\n this.name = 'KaafilApiError';\n this.code = code;\n Object.setPrototypeOf(this, KaafilApiError.prototype);\n }\n}\n\ntype ApiErrorInit = Omit<KaafilErrorInit, 'code'>;\n\n/**\n * `404 RESOURCE_NOT_FOUND` — the **only** not-found class this SDK has, on\n * purpose. Tenant isolation and genuine absence answer the identical `404`\n * by design: a distinguishing code would itself be an existence leak (a\n * cross-tenant probe could tell \"wrong tenant\" apart from \"never existed\").\n * Do not add a second not-found class — the ambiguity is the contract, not\n * a gap in it (`10-conventions.md §7`, `06-offline-first.md §7`).\n */\nexport class KaafilNotFoundError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ResourceNotFound'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ResourceNotFound, message, init);\n this.name = 'KaafilNotFoundError';\n this.code = KaafilErrorCode.ResourceNotFound;\n Object.setPrototypeOf(this, KaafilNotFoundError.prototype);\n }\n}\n\n/**\n * Every `details.reason` a `402 PLAN_FEATURE_DISABLED` refusal can carry —\n * mirrors the engine's `PlanRefusalReason`\n * (`shared/errors/error-factory.ts`). Not generated from the vendored spec:\n * `ErrorEnvelope.error.details` is `{ additionalProperties: {} }` there —\n * deliberately untyped, because `details`' shape varies by code — so this\n * one field, on this one code, is hand-declared rather than produced by\n * `gen-meta.mjs`. Different people act on the four values: the CRM flips\n * its own switch (`agencyFlag`), Kaafil sells an upgrade (`partnerTier`),\n * nobody does anything until the billing period rolls (`tripQuota`), or\n * someone frees storage or upgrades — a storage cap never resets\n * (`storageQuota`) — a bare `402` cannot tell a caller which.\n */\nexport type PlanRefusalReason = 'agencyFlag' | 'partnerTier' | 'tripQuota' | 'storageQuota';\n\nconst PLAN_REFUSAL_REASONS: ReadonlySet<string> = new Set<PlanRefusalReason>([\n 'agencyFlag',\n 'partnerTier',\n 'tripQuota',\n 'storageQuota',\n]);\n\n/**\n * `402 PLAN_FEATURE_DISABLED` — an entitlement gap. Never retried.\n *\n * `details`' shape is per-`reason`, and the one field worth calling out is\n * `storageQuota`'s `includedBytes`: it is `number | null`, not a number.\n * `null` is what the TEST plane sends — a sandbox has no soft, billable rung\n * to overshoot, only the hard cap (`hardCapBytes`) — so a UI must not render\n * a `null` `includedBytes` as `0`, and must not compute \"bytes remaining\"\n * from it without a null check. On LIVE it is the plan's included figure,\n * and usage above it but under `hardCapBytes` is billed as overage rather\n * than refused. See `../resources/test.ts`'s `quota()` for the sandbox side\n * of the same cap.\n */\nexport class KaafilEntitlementError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['PlanFeatureDisabled'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.PlanFeatureDisabled, message, init);\n this.name = 'KaafilEntitlementError';\n this.code = KaafilErrorCode.PlanFeatureDisabled;\n Object.setPrototypeOf(this, KaafilEntitlementError.prototype);\n }\n\n /**\n * `details.reason` — which person (or which wait) fixes this. Read\n * defensively, like `.fields`/`.currentVersion` below: `details` is\n * untyped at the transport boundary, so a value this SDK does not\n * recognise (an engine that ships a fifth reason before this SDK knows\n * about it) surfaces as `undefined` rather than a wrong branch. The guard\n * reads the same set the type is declared from, so adding a reason is one\n * edit, not two that can drift — `storageQuota` shipped on the engine\n * before this guard knew it, and every storage refusal read as `undefined`.\n */\n get reason(): PlanRefusalReason | undefined {\n const value = this.details?.reason;\n return typeof value === 'string' && PLAN_REFUSAL_REASONS.has(value)\n ? (value as PlanRefusalReason)\n : undefined;\n }\n\n /**\n * `details.requiredTier` — the cheapest tier that would lift this refusal,\n * carried on `partnerTier` and `tripQuota`; `null` on `agencyFlag` (no tier\n * would help — the agency never asked) and absent on `storageQuota`.\n */\n get requiredTier(): string | null | undefined {\n const value = this.details?.requiredTier;\n return value === null || typeof value === 'string' ? value : undefined;\n }\n}\n\n/**\n * `422 CAPABILITY_UNAVAILABLE` — a dark capability (ingested data absent or\n * mode-inapplicable for the trip). Shares HTTP status 422 with several other\n * codes; `.code` is the discriminant, never the status.\n */\nexport class KaafilCapabilityUnavailableError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['CapabilityUnavailable'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.CapabilityUnavailable, message, init);\n this.name = 'KaafilCapabilityUnavailableError';\n this.code = KaafilErrorCode.CapabilityUnavailable;\n Object.setPrototypeOf(this, KaafilCapabilityUnavailableError.prototype);\n }\n}\n\n/**\n * `422 READ_ONLY_ROLE` — a `COORDINATOR` manager token attempted a write on\n * a `PERSONALIZED` trip; the role reads everything and writes nothing, with\n * no exception (`03-auth-and-tokens.md §2`). Also shares status 422.\n */\nexport class KaafilReadOnlyRoleError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ReadOnlyRole'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ReadOnlyRole, message, init);\n this.name = 'KaafilReadOnlyRoleError';\n this.code = KaafilErrorCode.ReadOnlyRole;\n Object.setPrototypeOf(this, KaafilReadOnlyRoleError.prototype);\n }\n}\n\n/**\n * `422 VALIDATION_ERROR` — body/params failed schema validation. `.fields`\n * reads `details.fields` defensively, since `details` is untyped at the\n * transport boundary.\n */\nexport class KaafilValidationError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ValidationError'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ValidationError, message, init);\n this.name = 'KaafilValidationError';\n this.code = KaafilErrorCode.ValidationError;\n Object.setPrototypeOf(this, KaafilValidationError.prototype);\n }\n\n get fields(): Record<string, unknown> | undefined {\n const value = this.details?.fields;\n return typeof value === 'object' && value !== null\n ? (value as Record<string, unknown>)\n : undefined;\n }\n}\n\n/**\n * `409 CONFLICT_VERSION` — `If-Match`/`expectedVersion` went stale.\n * `.currentVersion` reads `details.currentVersion` (`06-offline-first.md\n * §6`); the SDK's sync engine re-pulls and reconciles rather than\n * blind-retrying.\n */\nexport class KaafilVersionConflictError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ConflictVersion'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ConflictVersion, message, init);\n this.name = 'KaafilVersionConflictError';\n this.code = KaafilErrorCode.ConflictVersion;\n Object.setPrototypeOf(this, KaafilVersionConflictError.prototype);\n }\n\n get currentVersion(): number | undefined {\n const value = this.details?.currentVersion;\n return typeof value === 'number' ? value : undefined;\n }\n}\n\n/**\n * `423 LOCKED` — a write raced past trip close-out. Terminal: park the op,\n * never retry (`08-sdk.md §6`, `06-offline-first.md §7`).\n */\nexport class KaafilLockedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['Locked'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.Locked, message, init);\n this.name = 'KaafilLockedError';\n this.code = KaafilErrorCode.Locked;\n Object.setPrototypeOf(this, KaafilLockedError.prototype);\n }\n}\n\n/**\n * `429 RATE_LIMITED`. `.retryAfterSeconds` is a transport fact (the\n * `Retry-After` header), not part of the error envelope schema — the\n * factory that builds this error is responsible for supplying it from the\n * response headers.\n */\nexport class KaafilRateLimitedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['RateLimited'];\n readonly retryAfterSeconds: number | undefined;\n\n constructor(message: string, init: ApiErrorInit & { readonly retryAfterSeconds?: number } = {}) {\n const { retryAfterSeconds, ...rest } = init;\n super(KaafilErrorCode.RateLimited, message, rest);\n this.name = 'KaafilRateLimitedError';\n this.code = KaafilErrorCode.RateLimited;\n this.retryAfterSeconds = retryAfterSeconds;\n Object.setPrototypeOf(this, KaafilRateLimitedError.prototype);\n }\n}\n\n/**\n * `401 UNAUTHENTICATED` — missing/expired credential. The SDK attempts\n * exactly one token refresh before surfacing this (`03-auth-and-tokens.md\n * §2`); by the time a consumer sees it, that attempt already failed.\n */\nexport class KaafilUnauthenticatedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['Unauthenticated'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.Unauthenticated, message, init);\n this.name = 'KaafilUnauthenticatedError';\n this.code = KaafilErrorCode.Unauthenticated;\n Object.setPrototypeOf(this, KaafilUnauthenticatedError.prototype);\n }\n}\n\n/**\n * `401 SHARE_TOKEN_EXPIRED` — terminal, unlike `UNAUTHENTICATED`: there is\n * no refresh to attempt for a share token. Purges the cached snapshot\n * (`06-offline-first.md §8`).\n */\nexport class KaafilShareTokenExpiredError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ShareTokenExpired'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ShareTokenExpired, message, init);\n this.name = 'KaafilShareTokenExpiredError';\n this.code = KaafilErrorCode.ShareTokenExpired;\n Object.setPrototypeOf(this, KaafilShareTokenExpiredError.prototype);\n }\n}\n\n/** `401 SHARE_TOKEN_REVOKED` — terminal, same purge behaviour as expiry. */\nexport class KaafilShareTokenRevokedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['ShareTokenRevoked'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.ShareTokenRevoked, message, init);\n this.name = 'KaafilShareTokenRevokedError';\n this.code = KaafilErrorCode.ShareTokenRevoked;\n Object.setPrototypeOf(this, KaafilShareTokenRevokedError.prototype);\n }\n}\n\n/**\n * `501 NOT_IMPLEMENTED` — a reserved surface: the route is real and\n * validates its body, but the behaviour behind it lands in a later phase.\n * Deliberately distinct from `404` (`10-conventions.md §7`).\n */\nexport class KaafilNotImplementedError extends KaafilApiError {\n override readonly code: (typeof KaafilErrorCode)['NotImplemented'];\n\n constructor(message: string, init: ApiErrorInit = {}) {\n super(KaafilErrorCode.NotImplemented, message, init);\n this.name = 'KaafilNotImplementedError';\n this.code = KaafilErrorCode.NotImplemented;\n Object.setPrototypeOf(this, KaafilNotImplementedError.prototype);\n }\n}\n\n/**\n * A failure that never produced a server response to parse — timeout,\n * abort, DNS/connection failure. These have no catalog `.code`: inventing\n * one would claim a server actually answered when it did not.\n */\nexport abstract class KaafilTransportError extends KaafilError {\n override readonly kind = 'transport' as const;\n override readonly code: undefined;\n\n protected constructor(message: string, init: Omit<KaafilErrorInit, 'code'> = {}) {\n super(message, init);\n this.code = undefined;\n }\n}\n\ntype TransportErrorInit = Omit<KaafilErrorInit, 'code'>;\n\n/** The request exceeded the SDK's own timeout budget. Retryable (transient). */\nexport class KaafilTimeoutError extends KaafilTransportError {\n constructor(message = 'Request timed out', init: TransportErrorInit = {}) {\n super(message, init);\n this.name = 'KaafilTimeoutError';\n Object.setPrototypeOf(this, KaafilTimeoutError.prototype);\n }\n}\n\n/**\n * The caller's own `AbortController` fired. Deliberately not retryable —\n * unlike a timeout, this is the caller cancelling, not a transient failure.\n */\nexport class KaafilAbortError extends KaafilTransportError {\n constructor(message = 'Request aborted', init: TransportErrorInit = {}) {\n super(message, init);\n this.name = 'KaafilAbortError';\n Object.setPrototypeOf(this, KaafilAbortError.prototype);\n }\n}\n\n/** `fetch` itself rejected — offline, DNS failure, connection reset. Retryable. */\nexport class KaafilNetworkError extends KaafilTransportError {\n constructor(message = 'Network request failed', init: TransportErrorInit = {}) {\n super(message, init);\n this.name = 'KaafilNetworkError';\n Object.setPrototypeOf(this, KaafilNetworkError.prototype);\n }\n}\n\n/**\n * The caller built an impossible request — a missing path parameter, say.\n *\n * A programmer error, not a transport one, and the distinction is not cosmetic:\n * before this class existed, a missing path parameter escaped as a bare `Error`\n * from inside a send attempt, got wrapped as a `KaafilNetworkError`, and was\n * therefore **retried across the whole ladder** while reporting \"Unexpected\n * transport failure\". A typo in an argument name spent minutes backing off and\n * then blamed the network. It is `NEVER` retryable, because trying the same\n * malformed request again cannot make it well-formed.\n *\n * It extends `KaafilTransportError` only to inherit the \"no server response, so\n * no catalog code\" shape. `isRetryable` special-cases it — see there.\n */\nexport class KaafilInvalidRequestError extends KaafilTransportError {\n constructor(message: string, init: TransportErrorInit = {}) {\n super(message, init);\n this.name = 'KaafilInvalidRequestError';\n Object.setPrototypeOf(this, KaafilInvalidRequestError.prototype);\n }\n}\n\n/**\n * Structural guard, not `instanceof`-only: a consumer whose bundler ended up\n * with two copies of this package (a real, if rare, hazard) still gets a\n * correct answer, because it falls back to checking the shape every\n * `KaafilError` instance carries.\n */\nexport function isKaafilError(error: unknown): error is KaafilError {\n if (error instanceof KaafilError) {\n return true;\n }\n if (typeof error !== 'object' || error === null) {\n return false;\n }\n const candidate = error as { kind?: unknown; message?: unknown };\n return (\n (candidate.kind === 'api' || candidate.kind === 'transport') &&\n typeof candidate.message === 'string'\n );\n}\n\nconst RETRYABLE_CODES: ReadonlySet<KaafilErrorCode> = new Set(\n (Object.keys(ERROR_CODE_TABLE) as KaafilErrorCode[]).filter(\n (code) => ERROR_CODE_TABLE[code].retryability !== Retryability.No,\n ),\n);\n\n/**\n * Whether the retry ladder (`08-sdk.md §6`) should ever re-attempt this\n * failure. Driven entirely by the generated `ERROR_CODE_TABLE` — retryability\n * is an allowlist there, and this function is the one place that allowlist\n * gets read, so a code the table marks non-retryable can never sneak back in\n * via a hand-written switch here.\n *\n * Transport failures are retryable except a caller-initiated abort, which is\n * not a transient condition to retry through.\n */\nexport function isRetryable(error: unknown): boolean {\n if (!isKaafilError(error)) {\n return false;\n }\n if (error.kind === 'transport') {\n // Two transport failures are NOT transient and must not be retried: an abort\n // the caller asked for, and a request the caller built wrongly. Retrying a\n // malformed request cannot make it well-formed, and doing so once cost a\n // full backoff ladder while reporting a network fault.\n return !(error instanceof KaafilAbortError) && !(error instanceof KaafilInvalidRequestError);\n }\n return error.code !== undefined && RETRYABLE_CODES.has(error.code);\n}\n\ninterface ParsedErrorEnvelope {\n readonly code: KaafilErrorCode;\n readonly message: string;\n readonly details: Record<string, unknown> | undefined;\n}\n\nconst KAAFIL_ERROR_CODE_VALUES: ReadonlySet<string> = new Set(Object.values(KaafilErrorCode));\n\nfunction isKaafilErrorCode(value: string): value is KaafilErrorCode {\n return KAAFIL_ERROR_CODE_VALUES.has(value);\n}\n\n/**\n * Parses `{ error: { code, message, details? } }` defensively — an\n * intermediary (gateway, proxy) can return anything as a body, so every\n * field is checked before use rather than cast. Returns `undefined` for\n * anything that isn't a recognizable error envelope, which `fromEnvelope`\n * treats as a transport failure rather than guessing a catalog code.\n */\nfunction parseErrorEnvelope(body: unknown): ParsedErrorEnvelope | undefined {\n if (typeof body !== 'object' || body === null) {\n return undefined;\n }\n const errorField = (body as Record<string, unknown>).error;\n if (typeof errorField !== 'object' || errorField === null) {\n return undefined;\n }\n const errorRecord = errorField as Record<string, unknown>;\n const code = errorRecord.code;\n const message = errorRecord.message;\n if (typeof code !== 'string' || !isKaafilErrorCode(code) || typeof message !== 'string') {\n return undefined;\n }\n const details = errorRecord.details;\n return {\n code,\n message,\n details:\n typeof details === 'object' && details !== null\n ? (details as Record<string, unknown>)\n : undefined,\n };\n}\n\nexport interface FromEnvelopeInit {\n readonly status: number;\n readonly requestId?: string;\n readonly meta?: ResponseMeta;\n readonly retryAfterSeconds?: number;\n readonly cause?: unknown;\n}\n\nfunction buildApiErrorInit(\n init: FromEnvelopeInit,\n details: Record<string, unknown> | undefined,\n): ApiErrorInit {\n return {\n status: init.status,\n ...(details !== undefined ? { details } : {}),\n ...(init.requestId !== undefined ? { requestId: init.requestId } : {}),\n ...(init.meta !== undefined ? { meta: init.meta } : {}),\n ...(init.cause !== undefined ? { cause: init.cause } : {}),\n };\n}\n\n/**\n * Turns a parsed HTTP body plus the transport-level facts about the\n * response into the right `KaafilError` subclass. Guards its own parse: a\n * gateway `502` with an HTML or empty body has no `{ error: { code, ... } }`\n * shape to read, so this returns a `KaafilNetworkError` for it rather than\n * throwing a `TypeError` from inside error handling or inventing a fake\n * catalog code for a response the engine never actually sent.\n */\nexport function fromEnvelope(body: unknown, init: FromEnvelopeInit): KaafilError {\n const parsed = parseErrorEnvelope(body);\n if (parsed === undefined) {\n return new KaafilNetworkError(\n `Received an unrecognizable error body for HTTP ${init.status}`,\n buildApiErrorInit(init, undefined),\n );\n }\n\n const commonInit = buildApiErrorInit(init, parsed.details);\n\n switch (parsed.code) {\n case KaafilErrorCode.ResourceNotFound:\n return new KaafilNotFoundError(parsed.message, commonInit);\n case KaafilErrorCode.PlanFeatureDisabled:\n return new KaafilEntitlementError(parsed.message, commonInit);\n case KaafilErrorCode.CapabilityUnavailable:\n return new KaafilCapabilityUnavailableError(parsed.message, commonInit);\n case KaafilErrorCode.ReadOnlyRole:\n return new KaafilReadOnlyRoleError(parsed.message, commonInit);\n case KaafilErrorCode.ValidationError:\n return new KaafilValidationError(parsed.message, commonInit);\n case KaafilErrorCode.ConflictVersion:\n return new KaafilVersionConflictError(parsed.message, commonInit);\n case KaafilErrorCode.Locked:\n return new KaafilLockedError(parsed.message, commonInit);\n case KaafilErrorCode.RateLimited:\n return new KaafilRateLimitedError(parsed.message, {\n ...commonInit,\n ...(init.retryAfterSeconds !== undefined\n ? { retryAfterSeconds: init.retryAfterSeconds }\n : {}),\n });\n case KaafilErrorCode.Unauthenticated:\n return new KaafilUnauthenticatedError(parsed.message, commonInit);\n case KaafilErrorCode.ShareTokenExpired:\n return new KaafilShareTokenExpiredError(parsed.message, commonInit);\n case KaafilErrorCode.ShareTokenRevoked:\n return new KaafilShareTokenRevokedError(parsed.message, commonInit);\n case KaafilErrorCode.NotImplemented:\n return new KaafilNotImplementedError(parsed.message, commonInit);\n default:\n return new KaafilApiError(parsed.code, parsed.message, commonInit);\n }\n}\n","/**\n * Credential resolution for `kaafil-js`: the discriminated credential\n * model, scheme selection against an operation's accepted schemes, and the\n * single-flight manager-session refresh. See\n * `architecture/03-auth-and-tokens.md §2` and `architecture/08-sdk.md §6`.\n */\n\nimport type { components } from '../generated/schema';\nimport {\n type OperationId,\n SECURITY_SCHEME_CARRIERS,\n SecuritySchemeId,\n} from '../generated/security';\n// A value import, and safe in the browser bundle: `../http/errors.ts` reaches\n// only the generated code table and type-only `types/meta`, never a credential\n// path, and every class in it is already re-exported from the browser entry.\nimport { KaafilInvalidRequestError } from '../http/errors';\n\n/**\n * A credential value the host may supply as a literal or as a resolver\n * invoked at header-assembly time, on every request — never captured once\n * and reused, which is how a stale credential gets sent.\n */\nexport type Resolvable<T> = T | (() => T | Promise<T>);\n\nasync function resolveValue<T>(value: Resolvable<T>): Promise<T> {\n return typeof value === 'function' ? await (value as () => T | Promise<T>)() : value;\n}\n\n/**\n * The credential kind is declared by the caller, never derived from which\n * field happens to be populated.\n *\n * `agencyAdmin` is named after the engine's own JWT `kind` claim\n * (`kaafil-engine`'s `CLAIM_DISCRIMINATED_AUTH_KINDS`), the same way `apiKey`\n * and `shareToken` are named after what identifies the credential rather\n * than the flow that produced it — unlike `managerSession`, which predates\n * this convention. It rotates exactly like `managerSession` does (see\n * `RotatingSessionCredentialConfig` below): a bearer access/refresh pair\n * minted by `mintAgencyAdminTokens` and rotated forward by\n * `refreshAgencyAdminTokens`.\n */\nexport const CredentialKind = {\n AgencyAdmin: 'agencyAdmin',\n ApiKey: 'apiKey',\n ManagerSession: 'managerSession',\n ShareToken: 'shareToken',\n} as const;\nexport type CredentialKind = (typeof CredentialKind)[keyof typeof CredentialKind];\n\nexport interface ApiKeyCredentialConfig {\n readonly kind: typeof CredentialKind.ApiKey;\n readonly apiKey: Resolvable<string>;\n}\n\nexport interface ShareTokenCredentialConfig {\n readonly kind: typeof CredentialKind.ShareToken;\n readonly token: Resolvable<string>;\n}\n\n/** `refreshManagerTokens`'s success shape, straight out of the generated\n * schema — never hand-typed, so a spec change surfaces here as a type error\n * rather than a silently-stale hand-written interface. */\ntype ManagerSessionResponseShape = components['schemas']['ManagerSessionResponse'];\n\n/** `refreshAgencyAdminTokens`'s success shape, straight out of the generated\n * schema, for the same reason as `ManagerSessionResponseShape` above. */\ntype AgencyAdminSessionResponseShape = components['schemas']['AgencyAdminSessionResponse'];\n\n/**\n * The result of a manager-session refresh exchange. Only this shape may\n * ever rotate the manager-session credential — never a value sniffed out of\n * an unrelated response body.\n */\nexport type ManagerRefreshResult = Pick<\n ManagerSessionResponseShape,\n 'accessToken' | 'refreshToken' | 'expiresAt'\n>;\n\n/**\n * The result of an agency-admin session refresh exchange — the\n * agency-admin analogue of `ManagerRefreshResult` above, derived\n * independently from its own generated response shape rather than reused\n * from the manager one, so the two are only ever accidentally identical,\n * never structurally coupled: a future spec revision that adds a field to\n * one and not the other surfaces here as a type error, not a silent share.\n */\nexport type AgencyAdminRefreshResult = Pick<\n AgencyAdminSessionResponseShape,\n 'accessToken' | 'refreshToken' | 'expiresAt'\n>;\n\n/**\n * The shape both rotating credentials' refresh results happen to share —\n * `ManagerRefreshResult` and `AgencyAdminRefreshResult` are each already\n * structurally assignable to this, so the single-flight machinery below can\n * be written once, generically, against this shape instead of against\n * either concrete one.\n */\nexport interface RotatingRefreshResult {\n readonly accessToken: string;\n readonly refreshToken: string;\n readonly expiresAt: string;\n}\n\n/**\n * The one HTTP call a rotating-session resolver is allowed to make. Typed as\n * this single narrow function — not the whole `KaafilHttpClient` — so\n * whatever this resolver is given cannot be used to make any other request.\n * Shared by both rotating kinds (`managerSession`, `agencyAdmin`): the two\n * differ only in which endpoint the exchange hits, not in this shape.\n *\n * `credentials.ts` cannot import `./http/client.ts` to build this itself:\n * that module already imports `CredentialKind`/`CredentialResolver` from\n * here to drive its own 401-triggered refresh, and the reverse import would\n * make a cycle. So the concrete implementation is built in `http/client.ts`\n * (which already knows how to talk to the engine and parse its envelope) and\n * handed down through `CredentialResolver`'s constructor by whichever entry\n * point (`../client-entry.ts`) opens the session — the top of the graph is\n * where both sides are already in scope.\n */\nexport type RotatingSessionExchange = (\n accessToken: string,\n refreshToken: string,\n) => Promise<RotatingRefreshResult>;\n\n/** @deprecated Kept as an alias of {@link RotatingSessionExchange} for\n * existing call sites that name it for the manager kind specifically —\n * both rotating kinds now share the one type. */\nexport type ManagerSessionExchange = RotatingSessionExchange;\n\n/**\n * Access-token skew window: refresh pre-emptively once fewer than this many\n * milliseconds remain, instead of waiting to learn from a `401` what the\n * mint response already told us. Shared by both rotating kinds — a manager\n * or agency-admin access token each live 15 minutes\n * (`architecture/03-auth-and-tokens.md §2`); 30s is generous next to typical\n * request latency (so a request built just inside the window still lands\n * before the server's own clock expires it) and small next to the 900s\n * lifetime (so it only ever preempts the closing seconds, never meaningfully\n * shortening the token's usable life).\n */\nconst ROTATING_ACCESS_TOKEN_REFRESH_SKEW_MS = 30_000;\n\n/**\n * The shape shared by both rotating credential kinds — everything about a\n * `managerSession`/`agencyAdmin` config except the discriminant `kind`\n * itself. `ManagerSessionCredentialConfig` and `AgencyAdminCredentialConfig`\n * below are each this shape plus their own literal `kind`, so the\n * single-flight refresh machinery can take either without a second copy of\n * itself per kind.\n */\ninterface RotatingSessionCredentialConfig<\n TKind extends CredentialKind,\n TResult extends RotatingRefreshResult,\n> {\n readonly kind: TKind;\n readonly accessToken: Resolvable<string>;\n readonly refreshToken: Resolvable<string>;\n /**\n * The access token's absolute expiry (the mint/refresh response's\n * `expiresAt`), if the host has it. Enables the pre-emptive refresh above\n * — without it the resolver only learns a token is dead from a `401`.\n */\n readonly expiresAt?: Resolvable<string>;\n /**\n * Overrides the default exchange (a direct call to this kind's own\n * refresh endpoint, authorised by the session's own access token —\n * `architecture/03-auth-and-tokens.md §2`) with an integrator-supplied\n * one, for a host that wants the rotation to pass through its own backend\n * instead. Most hosts never set this: the default path handles the\n * exchange without it. Called at most once per pre-emptive-or-401\n * trigger, and single-flighted across concurrent callers by\n * `CredentialResolver.refreshRotatingSession` — the refresh token\n * rotates, and presenting a rotated one twice revokes the whole family\n * (same section).\n */\n readonly refresh?: (refreshToken: string) => Promise<TResult>;\n /**\n * Fires once per successful rotation so a host can persist the new\n * refresh token. Never fires on a failed refresh. This SDK has no\n * persistence in this version, so surviving a reload is the one other\n * thing it cannot do for the consumer — this callback is that hand-off.\n */\n readonly onRefresh?: (result: TResult) => void | Promise<void>;\n}\n\nexport interface ManagerSessionCredentialConfig\n extends RotatingSessionCredentialConfig<\n typeof CredentialKind.ManagerSession,\n ManagerRefreshResult\n > {}\n\nexport interface AgencyAdminCredentialConfig\n extends RotatingSessionCredentialConfig<\n typeof CredentialKind.AgencyAdmin,\n AgencyAdminRefreshResult\n > {}\n\nexport type CredentialConfig =\n | AgencyAdminCredentialConfig\n | ApiKeyCredentialConfig\n | ManagerSessionCredentialConfig\n | ShareTokenCredentialConfig;\n\n/** Either rotating kind's config — the shape `CredentialResolver`'s\n * single-flight machinery actually operates on, once the discriminant has\n * narrowed `CredentialConfig` down to one of these two. */\ntype AnyRotatingCredentialConfig = AgencyAdminCredentialConfig | ManagerSessionCredentialConfig;\n\n/**\n * `true` for the two credential kinds that rotate (`managerSession`,\n * `agencyAdmin`) — the ones `refreshRotatingSession` and the pre-emptive\n * skew check apply to. `apiKey`/`shareToken` never rotate: an API key is\n * revoked out of band and a share token simply expires, so neither has a\n * refresh endpoint to call.\n */\nexport function isRotatingCredentialKind(\n kind: CredentialKind,\n): kind is typeof CredentialKind.AgencyAdmin | typeof CredentialKind.ManagerSession {\n return kind === CredentialKind.AgencyAdmin || kind === CredentialKind.ManagerSession;\n}\n\n/** Same test as `isRotatingCredentialKind`, narrowing the whole config\n * rather than just its `kind` — what `refreshRotatingSession` needs to hand\n * a properly-typed config down to `performRotatingRefresh`. */\nfunction isRotatingConfig(config: CredentialConfig): config is AnyRotatingCredentialConfig {\n return isRotatingCredentialKind(config.kind);\n}\n\n/**\n * Exactly one accepted scheme per credential kind. No kind maps to\n * `consoleAuth` — the SDK does not serve the console, and its cookie is\n * never a client-wide default (see `headersForCarrier`'s `cookie` branch).\n */\nconst CREDENTIAL_KIND_SCHEME: Readonly<Record<CredentialKind, SecuritySchemeId>> = {\n agencyAdmin: SecuritySchemeId.AgencyAdminAuth,\n apiKey: SecuritySchemeId.ApiKeyAuth,\n managerSession: SecuritySchemeId.ManagerAuth,\n shareToken: SecuritySchemeId.ShareAuth,\n};\n\nexport interface ResolvedCredentialHeaders {\n /** `null` for a public operation (no accepted schemes) — no header is due. */\n readonly schemeId: SecuritySchemeId | null;\n readonly headers: Readonly<Record<string, string>>;\n}\n\n/**\n * Thrown before any HTTP round trip when the configured credential cannot\n * satisfy any scheme an operation accepts. Never let a missing credential\n * surface as a `404`, which on this API means tenant isolation or genuine\n * absence (`architecture/10-conventions.md §7`).\n *\n * Extends `KaafilInvalidRequestError` — it is not merely an `Error` — because\n * `execute()` normalises any throw outside the `KaafilError` hierarchy into a\n * retryable `KaafilNetworkError`. As a bare `Error` this class never escaped:\n * a consumer following the documented `catch (e) { e instanceof\n * UnsatisfiableSchemeError }` pattern got `false`, saw \"Unexpected transport\n * failure\" for a call that made no request at all, and `isRetryable` said\n * `true` — so a retry queue burned the whole backoff ladder on a condition\n * that is permanent by construction. Choosing this parent rather than\n * `KaafilTransportError` directly is what keeps it non-retryable: `isRetryable`\n * already excludes `KaafilInvalidRequestError`, so there is no second\n * special case to keep in step with this one. The classification is right\n * on the merits too — the wrong credential for an operation is a request the\n * caller built wrongly, and re-sending it cannot make it satisfiable.\n */\nexport class UnsatisfiableSchemeError extends KaafilInvalidRequestError {\n readonly operationId: OperationId;\n readonly acceptedSchemes: readonly SecuritySchemeId[];\n readonly credentialKind: CredentialKind;\n\n constructor(\n operationId: OperationId,\n acceptedSchemes: readonly SecuritySchemeId[],\n credentialKind: CredentialKind,\n ) {\n const schemeList =\n acceptedSchemes.length > 0 ? acceptedSchemes.join(', ') : '(no scheme declared)';\n super(\n `\"${operationId}\" accepts [${schemeList}], but the configured \"${credentialKind}\" ` +\n 'credential cannot satisfy any of them.',\n );\n this.name = 'UnsatisfiableSchemeError';\n // Same reason every class in `../http/errors.ts` does this: an ES5 target\n // loses the prototype chain through `super()`, and without it `instanceof`\n // fails for the one class whose whole purpose is to be caught by name.\n Object.setPrototypeOf(this, UnsatisfiableSchemeError.prototype);\n this.operationId = operationId;\n this.acceptedSchemes = acceptedSchemes;\n this.credentialKind = credentialKind;\n }\n}\n\nfunction headersForCarrier(\n schemeId: SecuritySchemeId,\n value: string,\n): Readonly<Record<string, string>> {\n const carrier = SECURITY_SCHEME_CARRIERS[schemeId];\n switch (carrier.kind) {\n case 'header':\n return { [carrier.headerName]: value };\n case 'bearer':\n return { Authorization: `Bearer ${value}` };\n case 'cookie':\n // No entry in `CREDENTIAL_KIND_SCHEME` maps to a cookie-borne scheme —\n // the SDK does not serve the console, so this branch is unreachable\n // through `CredentialResolver`. Kept explicit (never a bare `false`)\n // so an SDK-side scheme added later without a credential kind fails\n // loudly instead of silently attaching a cookie.\n throw new Error(`Scheme \"${schemeId}\" is cookie-borne and has no SDK-side credential kind.`);\n }\n}\n\ninterface RotatingSessionState {\n current: { accessToken: string; refreshToken: string; expiresAt: string | undefined } | null;\n refreshPromise: Promise<RotatingRefreshResult> | null;\n}\n\n/**\n * Every piece of this resolver's per-session state, in one object, so\n * `reset()` is a single assignment that cannot forget a field. Only a\n * rotating kind (`managerSession`, `agencyAdmin`) has anything to hold —\n * `apiKey`/`shareToken` values are read fresh from their resolver on every\n * call and never cached here. One `rotating` slot, not one per kind: a\n * config is exactly one kind, so it never needs both at once.\n */\ninterface CredentialResolverState {\n rotating: RotatingSessionState | null;\n}\n\nfunction createInitialState(config: CredentialConfig): CredentialResolverState {\n return {\n rotating: isRotatingCredentialKind(config.kind)\n ? { current: null, refreshPromise: null }\n : null,\n };\n}\n\n/**\n * `true` once fewer than `ROTATING_ACCESS_TOKEN_REFRESH_SKEW_MS` remain\n * before `expiresAt`, or once it has already passed. `undefined` (no\n * `expiresAt` known yet) is never treated as expiring — the resolver simply\n * has nothing to preempt with and falls back to learning from a `401`.\n */\nfunction isExpiringSoon(expiresAt: string | undefined, nowMs: number): boolean {\n if (expiresAt === undefined) {\n return false;\n }\n const expiryMs = Date.parse(expiresAt);\n if (Number.isNaN(expiryMs)) {\n return false;\n }\n return expiryMs - nowMs <= ROTATING_ACCESS_TOKEN_REFRESH_SKEW_MS;\n}\n\n/**\n * Resolves headers for one immutable, declared credential. Constructed once\n * per client with no credential baked into the transport; every header is\n * assembled from the current credential value at call time.\n */\nexport class CredentialResolver {\n private readonly config: CredentialConfig;\n private state: CredentialResolverState;\n /**\n * The default exchange for a rotating (`managerSession`/`agencyAdmin`)\n * credential — `undefined` for the two non-rotating kinds, and for a\n * rotating config that always uses its own `refresh` override instead.\n * See `RotatingSessionExchange`'s doc comment for why this arrives as a\n * constructor argument rather than an import.\n */\n private readonly rotatingSessionExchange: RotatingSessionExchange | undefined;\n\n constructor(config: CredentialConfig, rotatingSessionExchange?: RotatingSessionExchange) {\n this.config = config;\n this.state = createInitialState(config);\n this.rotatingSessionExchange = rotatingSessionExchange;\n }\n\n get kind(): CredentialKind {\n return this.config.kind;\n }\n\n /**\n * Picks the first scheme in `acceptedSchemes` (spec declaration order)\n * the configured credential can satisfy and returns its headers. Throws\n * `UnsatisfiableSchemeError` — never makes the doomed round trip — if\n * none match. An empty `acceptedSchemes` (a public operation) needs no\n * credential and returns no headers.\n */\n async resolveHeaders(\n operationId: OperationId,\n acceptedSchemes: readonly SecuritySchemeId[],\n ): Promise<ResolvedCredentialHeaders> {\n if (acceptedSchemes.length === 0) {\n return { schemeId: null, headers: {} };\n }\n\n const config = this.config;\n const mySchemeId = CREDENTIAL_KIND_SCHEME[config.kind];\n if (!acceptedSchemes.includes(mySchemeId)) {\n throw new UnsatisfiableSchemeError(operationId, acceptedSchemes, config.kind);\n }\n\n const value = await this.currentValue(config);\n return { schemeId: mySchemeId, headers: headersForCarrier(mySchemeId, value) };\n }\n\n private async currentValue(config: CredentialConfig): Promise<string> {\n switch (config.kind) {\n case CredentialKind.ApiKey:\n return resolveValue(config.apiKey);\n case CredentialKind.ShareToken:\n return resolveValue(config.token);\n case CredentialKind.ManagerSession:\n case CredentialKind.AgencyAdmin:\n return this.currentRotatingAccessToken(config);\n }\n }\n\n private async currentRotatingAccessToken(config: AnyRotatingCredentialConfig): Promise<string> {\n const state = this.rotatingSessionState();\n if (!state.current) {\n const [accessToken, refreshToken, expiresAt] = await Promise.all([\n resolveValue(config.accessToken),\n resolveValue(config.refreshToken),\n config.expiresAt !== undefined\n ? resolveValue(config.expiresAt)\n : Promise.resolve(undefined),\n ]);\n state.current = { accessToken, refreshToken, expiresAt };\n }\n\n // Pre-emptive refresh: act on what the mint response already told us\n // instead of spending a round trip to relearn it via a `401`. Routed\n // through the same single-flight path as the reactive 401-triggered\n // refresh in `http/client.ts` — two refresh paths would defeat the\n // single-flight guarantee the rotating refresh token depends on.\n if (isExpiringSoon(state.current.expiresAt, Date.now())) {\n const result = await this.refreshRotatingSession();\n return result.accessToken;\n }\n return state.current.accessToken;\n }\n\n /**\n * Single-flight refresh: concurrent triggers (N simultaneous `401`s, or a\n * pre-emptive check racing a `401`) share one in-flight promise, so the\n * rotating refresh token is presented exactly once. The promise is\n * cleared on both success and failure — a rejected refresh never stays\n * sticky, and the next trigger always starts a fresh exchange\n * (`architecture/03-auth-and-tokens.md §2`). Callers make one attempt per\n * request and surface the failure; this method does not loop. Shared by\n * both rotating kinds — see the module header's argument for why this is\n * one implementation, not one per kind.\n */\n async refreshRotatingSession(): Promise<RotatingRefreshResult> {\n const config = this.config;\n if (!isRotatingConfig(config)) {\n throw new Error(\n 'refreshRotatingSession() is only valid for a rotating (\"managerSession\" or ' +\n '\"agencyAdmin\") credential.',\n );\n }\n\n const state = this.rotatingSessionState();\n if (state.refreshPromise) {\n return state.refreshPromise;\n }\n\n const promise = this.performRotatingRefresh(config, state);\n state.refreshPromise = promise;\n try {\n return await promise;\n } finally {\n state.refreshPromise = null;\n }\n }\n\n private async performRotatingRefresh(\n config: AnyRotatingCredentialConfig,\n state: RotatingSessionState,\n ): Promise<RotatingRefreshResult> {\n const refreshToken = state.current?.refreshToken ?? (await resolveValue(config.refreshToken));\n const result =\n config.refresh !== undefined\n ? await config.refresh(refreshToken)\n : await this.defaultRotatingRefresh(config, state, refreshToken);\n state.current = {\n accessToken: result.accessToken,\n refreshToken: result.refreshToken,\n expiresAt: result.expiresAt,\n };\n await config.onRefresh?.(result);\n return result;\n }\n\n private async defaultRotatingRefresh(\n config: AnyRotatingCredentialConfig,\n state: RotatingSessionState,\n refreshToken: string,\n ): Promise<RotatingRefreshResult> {\n if (this.rotatingSessionExchange === undefined) {\n throw new Error(\n 'invariant: a rotating credential without a \"refresh\" override needs the exchange ' +\n 'function the entry point constructs it with — see \"./client-entry.ts\".',\n );\n }\n // The bearer's job here is to identify WHICH session is being rotated,\n // not to be current — the engine accepts it even once expired, bounded\n // by the refresh token's own lifetime (`03-auth-and-tokens.md §2`). So\n // the possibly-stale `state.current.accessToken` is exactly what this\n // call is supposed to send, not a reason to resolve a fresh one first.\n const accessToken = state.current?.accessToken ?? (await resolveValue(config.accessToken));\n return this.rotatingSessionExchange(accessToken, refreshToken);\n }\n\n private rotatingSessionState(): RotatingSessionState {\n const state = this.state.rotating;\n if (!state) {\n throw new Error('invariant: rotating-session state missing for a rotating credential.');\n }\n return state;\n }\n\n /**\n * Resets every piece of per-session state in one assignment — teardown\n * that cannot forget a field because the state is rebuilt from scratch,\n * not cleared field by field.\n */\n reset(): void {\n this.state = createInitialState(this.config);\n }\n}\n","/**\n * Construction-time configuration for `kaafil-js`: environment → base URL\n * mapping, and every check that can be made before the first request goes\n * out. `architecture/08-sdk.md §2` (\"Environments are selected at init and\n * pinned to the key prefix\"), `architecture/03-auth-and-tokens.md §1`.\n *\n * A mistake this module can catch at construction is caught here, with a\n * message naming the offending field — never turned into a confusing HTTP\n * failure three requests later.\n */\n\nimport type { Resolvable } from './auth/credentials';\n\nexport const Environment = {\n Live: 'live',\n Test: 'test',\n} as const;\nexport type Environment = (typeof Environment)[keyof typeof Environment];\n\n/**\n * Default base URL per environment. There is exactly one real engine host,\n * `https://engine.kaafil.in` — `live` and `test` are Tenants reached through\n * that same host and distinguished by which credential resolves, never by a\n * different domain (`environments.mdx §\"LIVE and TEST are Tenants\"`). Both\n * entries below point at it on purpose, not by coincidence: an integrator\n * never needs to pass `baseUrl` for a real deployment, and should not be\n * told to. `baseUrl` remains available on `KaafilOptions` purely for\n * self-hosted/local-engine development against a non-production host.\n */\nconst ENVIRONMENT_BASE_URLS: Readonly<Record<Environment, string>> = {\n live: 'https://engine.kaafil.in',\n test: 'https://engine.kaafil.in',\n};\n\n/**\n * `kf_live_…` / `kf_test_…` — verified against the engine's own key\n * material generator (`kaafil-engine/src/shared/auth/constants.ts`:\n * `API_KEY_PREFIX_LIVE = 'kf_live_'`, `API_KEY_PREFIX_TEST = 'kf_test_'`),\n * never trusted from the spec's prose alone.\n */\nconst API_KEY_ENVIRONMENT_PREFIX: Readonly<Record<Environment, string>> = {\n live: 'kf_live_',\n test: 'kf_test_',\n};\n\n/** Every construction-time configuration mistake this module can catch,\n * in one class, so a consumer can `instanceof`-branch on \"my init call was\n * wrong\" without also catching a runtime/HTTP failure. */\nexport class KaafilConfigError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'KaafilConfigError';\n }\n}\n\n/**\n * An API key whose prefix doesn't match the `environment` it was configured\n * against. Thrown at construction for a literal key, or the first time a\n * resolver-supplied key actually resolves (see `guardApiKeyEnvironment`) —\n * either way, before the doomed request that a live key against a test\n * tenant (or vice versa) would otherwise produce.\n */\nexport class ApiKeyEnvironmentMismatchError extends KaafilConfigError {\n readonly environment: Environment;\n readonly keyPrefix: string;\n\n constructor(environment: Environment, apiKey: string) {\n const keyPrefix = apiKey.includes('_') ? `${apiKey.split('_').slice(0, 2).join('_')}_` : apiKey;\n super(\n `environment: \"${environment}\" expects an API key prefixed ` +\n `\"${API_KEY_ENVIRONMENT_PREFIX[environment]}\", but the configured key is prefixed ` +\n `\"${keyPrefix}\".`,\n );\n this.name = 'ApiKeyEnvironmentMismatchError';\n this.environment = environment;\n this.keyPrefix = keyPrefix;\n }\n}\n\n/** Renders an offending config value for a message: a string quoted as the\n * caller typed it, anything else (including `undefined`) as itself. */\nfunction describeConfigValue(value: unknown): string {\n return typeof value === 'string' ? `\"${value}\"` : String(value);\n}\n\n/**\n * `environment` is required and has exactly two values. Checked before any\n * per-environment table is indexed with it, because an absent or misspelled\n * `environment` otherwise reaches `assertApiKeyMatchesEnvironment`, where\n * the expected-prefix lookup misses and the resulting\n * `ApiKeyEnvironmentMismatchError` tells the caller their key should have\n * been prefixed `\"undefined\"` — blaming `apiKey` for a mistake that is in\n * `environment`.\n */\nexport function assertValidEnvironment(environment: Environment): void {\n if (environment !== Environment.Live && environment !== Environment.Test) {\n throw new KaafilConfigError(\n `\"environment\" is required and must be \"${Environment.Live}\" or \"${Environment.Test}\"; ` +\n `received ${describeConfigValue(environment)}.`,\n );\n }\n}\n\nfunction isValidAbsoluteUrl(value: string): boolean {\n try {\n const url = new URL(value);\n return url.protocol === 'http:' || url.protocol === 'https:';\n } catch {\n return false;\n }\n}\n\n/**\n * `environment` selects a default; an explicit `baseUrl` overrides it\n * outright (self-hosted / proxied / sandbox deployment) — the two are never\n * merged or partially applied. Construction-time and immutable: there is no\n * setter, callers re-construct a client to point elsewhere.\n *\n * `environment` is validated here rather than in each constructor because\n * this is the one call every client entry point makes before anything else\n * reads `environment` — including the `baseUrl`-override path, where the\n * value is otherwise never looked at and would go on to mis-shape the API\n * key guard and the sandbox-only `test` resource.\n */\nexport function resolveBaseUrl(environment: Environment, baseUrl?: string): string {\n assertValidEnvironment(environment);\n if (baseUrl === undefined) {\n return ENVIRONMENT_BASE_URLS[environment];\n }\n if (!isValidAbsoluteUrl(baseUrl)) {\n throw new KaafilConfigError(\n `\"baseUrl\" must be an absolute http(s) URL; received \"${baseUrl}\".`,\n );\n }\n return baseUrl;\n}\n\n/** Throws `KaafilConfigError` naming the field if `timeoutMs` is present and\n * not a positive, finite number. `undefined` is valid — the transport\n * applies its own default (`http/client.ts`'s `DEFAULT_TIMEOUT_MS`). */\nexport function assertValidTimeout(timeoutMs: number | undefined): void {\n if (timeoutMs === undefined) {\n return;\n }\n if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n throw new KaafilConfigError(`\"timeoutMs\" must be a positive number; received ${timeoutMs}.`);\n }\n}\n\n/** Throws `KaafilConfigError` naming the field if `maxAttempts` is present\n * and not a positive integer. `undefined` is valid — the retry ladder\n * applies its own default (`http/retry.ts`). */\nexport function assertValidMaxAttempts(maxAttempts: number | undefined): void {\n if (maxAttempts === undefined) {\n return;\n }\n if (!Number.isInteger(maxAttempts) || maxAttempts <= 0) {\n throw new KaafilConfigError(\n `\"maxAttempts\" must be a positive integer; received ${maxAttempts}.`,\n );\n }\n}\n\n/**\n * Checks one API key's prefix against `environment`, throwing\n * `ApiKeyEnvironmentMismatchError` naming both sides on a mismatch, and\n * `KaafilConfigError` if the key doesn't even look like a Kaafil key (wrong\n * shape is a construction mistake in its own right, not just a wrong\n * environment).\n */\nexport function assertApiKeyMatchesEnvironment(apiKey: string, environment: Environment): void {\n const expectedPrefix = API_KEY_ENVIRONMENT_PREFIX[environment];\n const isKnownPrefix =\n apiKey.startsWith(API_KEY_ENVIRONMENT_PREFIX.live) ||\n apiKey.startsWith(API_KEY_ENVIRONMENT_PREFIX.test);\n if (!isKnownPrefix) {\n throw new KaafilConfigError(\n `\"apiKey\" does not look like a Kaafil API key (expected a \"${API_KEY_ENVIRONMENT_PREFIX.live}\" ` +\n `or \"${API_KEY_ENVIRONMENT_PREFIX.test}\" prefix).`,\n );\n }\n if (!apiKey.startsWith(expectedPrefix)) {\n throw new ApiKeyEnvironmentMismatchError(environment, apiKey);\n }\n}\n\n/**\n * Guards an `apiKey` against `environment`, honestly, for both shapes\n * `Resolvable<string>` allows:\n *\n * - A literal key is known now, so it is checked now — the whole point of\n * catching a construction mistake at construction.\n * - A resolver's value is not known until it first resolves (that's what\n * \"resolver\" means), so it genuinely cannot be checked any earlier than\n * that. This wraps the resolver so the check runs against every resolved\n * value, starting with the first — cheap (a string-prefix comparison) and\n * correct even though `CredentialResolver` never caches a resolver's\n * value: a resolver's whole contract is that its answer may legitimately\n * change between calls (`credentials.ts`'s `Resolvable<T>`), so a\n * check-once-then-trust would miss a later swap to a key from the wrong\n * environment.\n *\n * Returns a `Resolvable<string>` suitable to hand straight to an\n * `ApiKeyCredentialConfig`.\n */\nexport function guardApiKeyEnvironment(\n apiKey: Resolvable<string>,\n environment: Environment,\n): Resolvable<string> {\n if (typeof apiKey !== 'function') {\n assertApiKeyMatchesEnvironment(apiKey, environment);\n return apiKey;\n }\n const resolver = apiKey as () => string | Promise<string>;\n return async () => {\n const value = await resolver();\n assertApiKeyMatchesEnvironment(value, environment);\n return value;\n };\n}\n","/**\n * The retry ladder and retry policy — architecture/08-sdk.md §6.\n *\n * Retryability is an allowlist: a failure is only retried when the\n * generated `ERROR_CODE_TABLE` (`src/generated/error-codes.ts`) marks its\n * code retryable, or when there is no code at all because the request never\n * got an HTTP response (a genuine transport failure). A denylist would\n * default to retrying anything not explicitly excluded — including outcomes\n * that can never succeed — and hoard requests forever with no way out.\n */\n\nimport { ERROR_CODE_TABLE, type KaafilErrorCode, Retryability } from '../generated/error-codes';\n\n/** `1s → 5s → 15s → 1m → 5m → 15m → 1h`, then hold at the last rung. */\nexport const RETRY_LADDER_MS = [1_000, 5_000, 15_000, 60_000, 300_000, 900_000, 3_600_000] as const;\n\n/**\n * A per-request cap, never a client-global one: this counter is a local\n * variable inside a single `executeWithRetry()` call and starts fresh for\n * every request. A client-global counter would let one unlucky endpoint\n * poison retries for every other call sharing it. The default covers the\n * full ladder (six escalating rungs) plus roughly a day of holding at the\n * last rung; pass `maxAttempts` to change it per call.\n */\nexport const DEFAULT_MAX_ATTEMPTS = 24;\n\nexport interface RetryClassificationInput {\n /** `null` means no HTTP response reached the client at all. */\n readonly status: number | null;\n readonly code?: KaafilErrorCode;\n}\n\n/**\n * Whether a failure is eligible for the backoff ladder at all. This is the\n * allowlist: retryable only if the generated table says so for a\n * recognized `code`, or if there was no response to key a code off of.\n */\nexport function isRetryableFailure(input: RetryClassificationInput): boolean {\n if (input.status === null) {\n return true;\n }\n\n const entry = input.code !== undefined ? ERROR_CODE_TABLE[input.code] : undefined;\n if (entry !== undefined) {\n return (\n entry.retryability === Retryability.Yes ||\n entry.retryability === Retryability.HonourRetryAfter\n );\n }\n\n // No recognized code: allow only the same statuses the table's retryable\n // entries all share — 5xx and 429. `after-refresh` (401) is deliberately\n // excluded here: it is one refresh-then-replay attempt owned by the\n // credential layer (03-auth-and-tokens.md §2), not a ladder retry.\n return input.status === 429 || (input.status >= 500 && input.status <= 599);\n}\n\nexport interface DelayOptions {\n /** Present only for a 429 that carried `Retry-After`. Integer seconds,\n * exposed cross-origin and readable in a browser; never below 1. */\n readonly retryAfterSeconds?: number;\n readonly random?: () => number;\n}\n\n/**\n * Pure backoff computation — exported standalone so the ladder is\n * inspectable without actually waiting. `attempt` is 1 for the first retry\n * (the call that failed once already), 2 for the second, and so on; values\n * beyond the ladder's length clamp to its last rung (\"then hold\").\n *\n * Uses equal jitter (half the rung is guaranteed, half is random) rather\n * than full jitter, so the wait still holds near the top of the ladder\n * instead of collapsing back toward zero on every attempt.\n */\nexport function computeRetryDelayMs(attempt: number, options: DelayOptions = {}): number {\n if (options.retryAfterSeconds !== undefined) {\n return Math.max(1, Math.floor(options.retryAfterSeconds)) * 1000;\n }\n\n const index = Math.min(Math.max(attempt - 1, 0), RETRY_LADDER_MS.length - 1);\n const base = RETRY_LADDER_MS[index];\n if (base === undefined) {\n throw new Error('unreachable: index is clamped to RETRY_LADDER_MS bounds');\n }\n const random = options.random ?? Math.random;\n const half = base / 2;\n return Math.floor(half + random() * half);\n}\n\n/**\n * Sleeps for `ms`, but rejects with the signal's abort reason immediately\n * if `signal` fires while waiting — a caller who aborts must not be held\n * through a 15-minute backoff just because the timer was already running.\n */\nexport function delayWithAbort(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted === true) {\n return Promise.reject(signal.reason);\n }\n return new Promise<void>((resolve, reject) => {\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(signal?.reason);\n };\n const timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\nexport interface RetryFailure {\n readonly status: number | null;\n readonly code?: KaafilErrorCode;\n readonly retryAfterSeconds?: number;\n}\n\nexport type AttemptOutcome<T> =\n | { readonly ok: true; readonly value: T }\n | ({ readonly ok: false } & RetryFailure);\n\nexport class RetryExhaustedError extends Error {\n readonly failure: RetryFailure;\n readonly attempts: number;\n\n constructor(failure: RetryFailure, attempts: number) {\n super(`retry exhausted after ${attempts} attempt(s), last status ${String(failure.status)}`);\n this.name = 'RetryExhaustedError';\n this.failure = failure;\n this.attempts = attempts;\n }\n}\n\nexport interface RetryOptions {\n readonly maxAttempts?: number;\n readonly signal?: AbortSignal;\n readonly random?: () => number;\n /**\n * The stable idempotency key for this logical operation, if the\n * underlying request carries a body (`architecture/08-sdk.md §5`). The\n * caller mints it once and must pass the *same* value on every attempt —\n * this module never mints or rotates one itself, it only reads whether\n * one was supplied.\n */\n readonly idempotencyKey?: string;\n /**\n * True when the underlying request carries a body that isn't safely\n * replayable on its own (a write). Leave false/omitted for GET/HEAD-style\n * calls with no body, which are always safe to retry. A body-bearing\n * request with no `idempotencyKey` is treated as unsafe to replay and is\n * attempted once, never retried, regardless of `maxAttempts`.\n */\n readonly hasBody?: boolean;\n}\n\n/**\n * Runs `attempt` against the retry ladder, honouring `Retry-After` on 429s,\n * an `AbortSignal` while sleeping, and a per-request attempt cap. Resolves\n * with the first successful value, or throws `RetryExhaustedError` once the\n * failure is non-retryable or the cap is reached.\n */\nexport async function executeWithRetry<T>(\n attempt: (attemptNumber: number) => Promise<AttemptOutcome<T>>,\n options: RetryOptions = {},\n): Promise<T> {\n const unsafeToReplay = options.hasBody === true && options.idempotencyKey === undefined;\n const maxAttempts = unsafeToReplay ? 1 : (options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);\n const random = options.random ?? Math.random;\n\n for (let attemptNumber = 1; attemptNumber <= maxAttempts; attemptNumber += 1) {\n if (options.signal?.aborted === true) {\n throw options.signal.reason;\n }\n\n const outcome = await attempt(attemptNumber);\n if (outcome.ok) {\n return outcome.value;\n }\n\n const retryable = isRetryableFailure(outcome);\n if (!retryable || attemptNumber === maxAttempts) {\n throw new RetryExhaustedError(outcome, attemptNumber);\n }\n\n const delayMs = computeRetryDelayMs(attemptNumber, {\n ...(outcome.retryAfterSeconds !== undefined\n ? { retryAfterSeconds: outcome.retryAfterSeconds }\n : {}),\n random,\n });\n await delayWithAbort(delayMs, options.signal);\n }\n\n // Unreachable: maxAttempts is always >= 1, so the loop above always\n // returns or throws before falling out the bottom.\n throw new Error('unreachable: executeWithRetry loop exited without returning or throwing');\n}\n","/**\n * The single HTTP choke point for `kaafil-js` — every request, from every\n * module method on either entry point, passes through `execute()`.\n * `architecture/08-sdk.md §5, §6`, `architecture/06-offline-first.md §7`,\n * `architecture/03-auth-and-tokens.md §2`.\n *\n * `execute()` is the one exported entry point: it takes a fully-described\n * `RequestDescriptor` and returns a typed `KaafilResponse<T>`. The actual\n * network call lives in the separately named `sendOnce()`, which knows\n * nothing about retries, refresh, or ladders — that split is deliberate.\n * A later offline-outbox phase decorates this exact seam (queue a write\n * durably, then call through) by wrapping `execute()` or splicing into the\n * `attempt` closure that calls `sendOnce()`; neither this file's public\n * shape nor `sendOnce()`'s signature needs to change for that phase to land.\n */\n\nimport {\n type CredentialResolver,\n isRotatingCredentialKind,\n type RotatingRefreshResult,\n type RotatingSessionExchange,\n} from '../auth/credentials';\nimport { KaafilErrorCode } from '../generated/error-codes';\nimport type { components } from '../generated/schema';\nimport {\n OPERATION_ACCEPTS_IDEMPOTENCY_KEY,\n OPERATION_SECURITY,\n type OperationId,\n} from '../generated/security';\nimport type {\n BinaryResponseMeta,\n KaafilBinaryResponse,\n KaafilResponse,\n ResponseMeta,\n} from '../types/meta';\nimport {\n fromEnvelope,\n isKaafilError,\n isRetryable,\n KaafilAbortError,\n type KaafilError,\n KaafilInvalidRequestError,\n KaafilNetworkError,\n KaafilRateLimitedError,\n KaafilTimeoutError,\n} from './errors';\nimport { type AttemptOutcome, executeWithRetry, RetryExhaustedError } from './retry';\n\ntype EnvelopeMetaShape = components['schemas']['EnvelopeMeta'];\n\nexport type HttpMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE';\n\n/**\n * The SDK's own request shape — deliberately not `extends RequestInit`.\n * Inheriting the transport's option bag would make swapping `fetch` for a\n * different transport a breaking change to this type, and would let an\n * unrecognized caller-supplied key ride straight through to `fetch`.\n */\nexport interface RequestDescriptor {\n readonly method: HttpMethod;\n readonly operationId: OperationId;\n /** e.g. `/v1/trips/{tripId}` — every `{name}` is replaced from `pathParams`. */\n readonly path: string;\n readonly pathParams?: Readonly<Record<string, string | number>>;\n /** A value of `undefined` is omitted — it never becomes the string `\"undefined\"`. */\n readonly query?: Readonly<Record<string, string | number | boolean | undefined>>;\n readonly body?: unknown;\n /** Extra headers a specific method needs (`If-Match` on a versioned write,\n * `08-sdk.md §5`) — merged in last, after the credential and idempotency\n * headers this module owns. */\n readonly headers?: Readonly<Record<string, string>>;\n /**\n * A caller-supplied idempotency key, for resuming a logical operation\n * across a process restart. Omitted lets this module mint one — either\n * way, the same value rides every retry attempt for this call, which is\n * the entire point of the header.\n */\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n /**\n * The `Accept` header for this one request. Defaults to\n * `application/json`, which is what every enveloped operation wants and\n * what this field existed to leave alone. Set by `executeBinary()`'s\n * callers for the handful of operations the engine answers with bytes —\n * see that method on {@link KaafilHttpClient}.\n */\n readonly accept?: string;\n}\n\nexport interface KaafilClientConfig {\n /** Fixed at construction — no runtime `setBaseUrl` (module header). */\n readonly baseUrl: string;\n readonly credentials: CredentialResolver;\n /** Per-attempt network timeout. Default 30s. */\n readonly timeoutMs?: number;\n /** Per-call attempt cap passed through to the retry ladder. */\n readonly maxAttempts?: number;\n /** Sent as `User-Agent` where the platform permits setting one. */\n readonly userAgent?: string;\n readonly random?: () => number;\n}\n\nexport interface KaafilHttpClient {\n execute<T>(request: RequestDescriptor): Promise<KaafilResponse<T>>;\n /**\n * For the operations whose SUCCESS body is bytes, not a\n * `{ ok, data, meta }` envelope. Same credential resolution, same\n * idempotency handling, same retry-and-refresh ladder as `execute()` —\n * the only difference is how a `2xx` body is read.\n *\n * This exists because `execute()` structurally cannot serve these: it\n * calls `response.text()` and then requires `isSuccessEnvelope`, so a PDF\n * arrives as a `KaafilNetworkError('Received an unrecognizable success\n * body')` — a transport-shaped error for a response that was completely\n * fine. Only the SUCCESS path differs: the engine's error middleware\n * still emits a JSON `ErrorEnvelope` on every non-2xx, so failures come\n * back through the identical `fromEnvelope` mapping and the identical\n * typed error classes.\n *\n * Returns a {@link KaafilBinaryResponse} wrapper rather than the\n * `KaafilResponse<T>` intersection, because there is no envelope to take\n * a `meta` from — see that type's own doc for what is and is not known\n * about an envelope-less response.\n */\n executeBinary(request: RequestDescriptor): Promise<KaafilBinaryResponse>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\ninterface ClientContext {\n readonly baseUrl: string;\n readonly credentials: CredentialResolver;\n readonly timeoutMs: number;\n readonly maxAttempts: number | undefined;\n readonly userAgent: string | undefined;\n readonly random: (() => number) | undefined;\n}\n\n/** Public constructor. Everything below `execute()` is this module's private machinery. */\nexport function createHttpClient(config: KaafilClientConfig): KaafilHttpClient {\n const ctx: ClientContext = {\n baseUrl: config.baseUrl,\n credentials: config.credentials,\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n maxAttempts: config.maxAttempts,\n userAgent: config.userAgent,\n random: config.random,\n };\n return {\n execute: <T>(request: RequestDescriptor) => execute<T>(ctx, request),\n executeBinary: (request: RequestDescriptor) => executeBinary(ctx, request),\n };\n}\n\n// --- URL composition --------------------------------------------------\n\nfunction renderPath(\n template: string,\n params: Readonly<Record<string, string | number>> | undefined,\n): string {\n return template.replace(/\\{([^}]+)\\}/g, (_match, name: string) => {\n const raw = params?.[name];\n if (raw === undefined) {\n // Typed, and deliberately not a bare `Error`: an untyped throw from here\n // was wrapped as a retryable `KaafilNetworkError` and spent the whole\n // backoff ladder before reporting \"Unexpected transport failure\" for what\n // is a mistake in the call itself.\n throw new KaafilInvalidRequestError(\n `Missing path parameter \"${name}\" for \"${template}\". Pass it in the call's options.`,\n );\n }\n return encodeURIComponent(String(raw));\n });\n}\n\nfunction buildUrl(\n baseUrl: string,\n renderedPath: string,\n query: Readonly<Record<string, string | number | boolean | undefined>> | undefined,\n): URL {\n const normalizedBase = baseUrl.endsWith('/') ? baseUrl : `${baseUrl}/`;\n const relativePath = renderedPath.startsWith('/') ? renderedPath.slice(1) : renderedPath;\n const url = new URL(relativePath, normalizedBase);\n if (query !== undefined) {\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) {\n continue;\n }\n url.searchParams.set(key, String(value));\n }\n }\n return url;\n}\n\n// --- Abort + timeout combination ---------------------------------------\n\n/** Identity sentinel, never surfaced — only used to tell \"our own timeout\n * fired\" apart from \"the caller's signal fired\" once `combined.signal` aborts. */\nconst TIMEOUT_REASON = Symbol('kaafil-timeout');\n\ninterface CombinedSignal {\n readonly signal: AbortSignal;\n readonly isTimeout: () => boolean;\n readonly cleanup: () => void;\n}\n\n/**\n * Combines the caller's `AbortSignal` with this module's own timeout so\n * whichever fires first wins, without ever mutating or replacing the\n * caller's signal — a single client-wide \"next request\" abort slot binds to\n * whichever request happens to run next, which is the footgun this avoids.\n */\nfunction combineSignals(callerSignal: AbortSignal | undefined, timeoutMs: number): CombinedSignal {\n const controller = new AbortController();\n const cleanupFns: Array<() => void> = [];\n\n if (callerSignal !== undefined) {\n if (callerSignal.aborted) {\n controller.abort(callerSignal.reason);\n } else {\n const onAbort = (): void => controller.abort(callerSignal.reason);\n callerSignal.addEventListener('abort', onAbort, { once: true });\n cleanupFns.push(() => callerSignal.removeEventListener('abort', onAbort));\n }\n }\n\n const timer = setTimeout(() => controller.abort(TIMEOUT_REASON), timeoutMs);\n cleanupFns.push(() => clearTimeout(timer));\n\n return {\n signal: controller.signal,\n isTimeout: () => controller.signal.reason === TIMEOUT_REASON,\n cleanup: () => {\n for (const fn of cleanupFns) {\n fn();\n }\n },\n };\n}\n\n// --- Header assembly -----------------------------------------------------\n\nasync function buildHeaders(\n ctx: ClientContext,\n request: RequestDescriptor,\n idempotencyKey: string | undefined,\n hasBody: boolean,\n): Promise<Headers> {\n const acceptedSchemes = OPERATION_SECURITY[request.operationId];\n const credential = await ctx.credentials.resolveHeaders(request.operationId, acceptedSchemes);\n\n const headers = new Headers();\n headers.set('Accept', request.accept ?? 'application/json');\n if (hasBody) {\n headers.set('Content-Type', 'application/json');\n }\n for (const [key, value] of Object.entries(credential.headers)) {\n headers.set(key, value);\n }\n if (idempotencyKey !== undefined) {\n headers.set('Idempotency-Key', idempotencyKey);\n }\n if (ctx.userAgent !== undefined) {\n try {\n headers.set('User-Agent', ctx.userAgent);\n } catch {\n // Some fetch implementations (browsers) forbid setting `User-Agent` on\n // outgoing requests. A build stamp is a nice-to-have for support, never\n // load-bearing for the request itself — fail silently.\n }\n }\n if (request.headers !== undefined) {\n for (const [key, value] of Object.entries(request.headers)) {\n headers.set(key, value);\n }\n }\n return headers;\n}\n\n// --- Response parsing ------------------------------------------------\n\nfunction tryParseJson(text: string): unknown {\n try {\n return JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\nfunction isSuccessEnvelope(\n body: unknown,\n): body is { ok: true; data: unknown; meta: EnvelopeMetaShape; facets?: unknown } {\n if (typeof body !== 'object' || body === null) {\n return false;\n }\n const record = body as Record<string, unknown>;\n if (record.ok !== true) {\n return false;\n }\n if (typeof record.data !== 'object' || record.data === null) {\n return false;\n }\n const meta = record.meta;\n if (typeof meta !== 'object' || meta === null) {\n return false;\n }\n return typeof (meta as Record<string, unknown>).serverTime === 'string';\n}\n\nfunction buildResponseMeta(\n status: number,\n requestId: string | undefined,\n meta: EnvelopeMetaShape,\n): ResponseMeta {\n return {\n status,\n serverTime: meta.serverTime,\n requestId,\n page: meta.page,\n };\n}\n\nfunction parseRetryAfterSeconds(headerValue: string | null): number | undefined {\n if (headerValue === null) {\n return undefined;\n }\n const seconds = Number(headerValue);\n return Number.isFinite(seconds) && seconds >= 0 ? seconds : undefined;\n}\n\n/**\n * Attaches `meta` to a successful payload. `data` is `object`-typed by\n * `isSuccessEnvelope`'s guard, but that includes arrays — several operations\n * in this API return `data: T[]` directly (`listTripVendors`,\n * `listWebhookDeliveries`, …), and spreading an array with `{ ...data }`\n * copies its indices into a plain `{0: ..., 1: ...}` object, silently\n * discarding `Array.isArray`/`.length`/`.map` for every caller. `Object.assign`\n * mutates and returns the freshly-parsed body in place instead, which\n * preserves array-ness when `data` is an array and behaves identically to\n * the previous spread when it's a plain object.\n */\n/**\n * Attach the envelope's out-of-band values onto the payload.\n *\n * `facets` rides along the same way `meta` does, and ONLY when the envelope\n * actually carried one — which is every response's behaviour today except the\n * two operations whose engine-side schema declares it (`listAgencyTrips`,\n * `listWebhookDeliveries*`). Without this the key was read off the wire and\n * then thrown away here, so an aggregate the engine computed over the whole\n * filtered set could never reach a caller: exactly the \"extra key disappears\n * without anyone deciding that\" hazard the engine's own response wrapper\n * documents on its `KNOWN_PAGINATED_EXTRA_KEYS` allowlist, one layer further\n * out.\n *\n * The intersection is collision-safe for the same reason `meta`'s is\n * (`types/meta.ts`'s own note): `facets` appears only on envelope-shaped\n * schemas in the catalog, never as a property of a payload DTO — and a\n * paginated payload is an array, which owns no such key.\n */\nfunction attachMeta<T>(data: unknown, meta: ResponseMeta, facets: unknown): KaafilResponse<T> {\n // ── `data` CAN BE ABSENT, AND `Object.assign` THROWS ON IT ────────────────\n //\n // A `204 No Content` has no envelope and so no `data`. `Object.assign(\n // undefined, …)` raises a TypeError, and because a TypeError is not a\n // `KaafilError` the layer above classified it as a TRANSPORT failure and\n // RETRIED — so a delete that had already succeeded ran a second time against\n // a row that no longer existed, and the caller was handed the retry's `404`\n // for an operation that worked. The bytes really were gone; the answer was\n // simply the wrong request's.\n //\n // `null` gets the same treatment for the same reason: it is equally\n // impossible to hang a property off, and an enveloped `data: null` is a\n // shape the server is free to send.\n const base = data === undefined || data === null ? {} : (data as object);\n const withMeta = Object.assign(base, { meta });\n return (\n facets === undefined ? withMeta : Object.assign(withMeta, { facets })\n ) as KaafilResponse<T>;\n}\n\n// --- Cross-origin diagnostic (browser only) -------------------------------\n\n/**\n * Heuristic-only classification of a rejected `fetch` as a likely in-browser\n * CORS block, never a determination. From inside the page, `fetch` rejecting\n * with no status is indistinguishable between \"the network is down\" and \"the\n * browser withheld a cross-origin response because the API has not\n * allowlisted this page's origin\" — the browser hides the real reason either\n * way, so this can only name the more likely cause, not confirm it. A\n * genuine network outage produces the exact same rejection.\n *\n * Returns `undefined` outside a browser: `globalThis.location` does not\n * exist in Node, there is no same-origin policy to violate there, and this\n * must neither fire nor throw for a server-side caller.\n */\nfunction describeCrossOriginSuspect(url: URL): string | undefined {\n const loc = (globalThis as { location?: unknown }).location;\n if (typeof loc !== 'object' || loc === null) {\n return undefined;\n }\n const origin = (loc as { origin?: unknown }).origin;\n if (typeof origin !== 'string' || origin === url.origin) {\n return undefined;\n }\n return (\n `Request failed while calling a different origin (${url.origin}) than the page's own origin ` +\n `(${origin}). The most likely cause is that the API has not allowlisted this origin for CORS — ` +\n 'but the browser withholds the actual reason from JavaScript when it blocks a cross-origin ' +\n 'response, so the SDK cannot confirm this; a genuine network outage produces the same ' +\n \"rejection. If this is unexpected, the fix is server-side: add this origin to the API's CORS \" +\n 'allowlist.'\n );\n}\n\n// --- The one place a request is actually sent -----------------------------\n\n/**\n * Reads a non-2xx response and throws the right typed `KaafilError`. Shared\n * verbatim by both success readers below, and that sharing is the load-bearing\n * part: an operation whose SUCCESS body is bytes still fails through the\n * engine's ordinary JSON `ErrorEnvelope`, so its `404`/`422`/`423`/`429` must\n * land in exactly the same typed classes as every other operation's. Never\n * returns.\n */\nasync function throwFromErrorResponse(\n response: Response,\n status: number,\n requestId: string | undefined,\n): Promise<never> {\n // Guarded end to end: an empty body, or a non-JSON body from an\n // intermediary (a `502` with an HTML page), must never throw out of\n // `response.text()`/`JSON.parse` — `fromEnvelope` turns an unrecognizable\n // body into a coherent typed error on its own.\n const text = await response.text();\n const body = text.length > 0 ? tryParseJson(text) : undefined;\n const retryAfterSeconds = parseRetryAfterSeconds(response.headers.get('retry-after'));\n throw fromEnvelope(body, {\n status,\n ...(requestId !== undefined ? { requestId } : {}),\n ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),\n });\n}\n\n/**\n * Sends exactly one HTTP attempt and hands the 2xx `Response` to\n * `readSuccess`, or throws the right typed `KaafilError`. Knows nothing\n * about retries, ladders, or refresh — `execute()`/`executeBinary()` own all\n * of that and call this once per attempt.\n *\n * Generic over how a success body is READ, and over nothing else: the URL,\n * the credential, the idempotency header, the abort/timeout combination and\n * the whole error path are identical whether the answer is an envelope or a\n * PDF, and duplicating them for the binary case is how the two drift.\n */\nasync function sendOnceWith<R>(\n ctx: ClientContext,\n request: RequestDescriptor,\n idempotencyKey: string | undefined,\n readSuccess: (response: Response, status: number, requestId: string | undefined) => Promise<R>,\n): Promise<R> {\n const hasBody = request.body !== undefined;\n const renderedPath = renderPath(request.path, request.pathParams);\n const url = buildUrl(ctx.baseUrl, renderedPath, request.query);\n const headers = await buildHeaders(ctx, request, idempotencyKey, hasBody);\n const combined = combineSignals(request.signal, ctx.timeoutMs);\n\n try {\n const response = await fetch(url, {\n method: request.method,\n headers,\n signal: combined.signal,\n ...(hasBody ? { body: JSON.stringify(request.body) } : {}),\n });\n\n const requestId = response.headers.get('x-request-id') ?? undefined;\n const status = response.status;\n\n if (response.ok) {\n return await readSuccess(response, status, requestId);\n }\n return await throwFromErrorResponse(response, status, requestId);\n } catch (error) {\n // Errors thrown above are already the right typed `KaafilError` —\n // propagate them untouched. Anything else reaching here is a genuine\n // transport failure: `fetch()` rejecting, or `response.text()`\n // rejecting mid-stream (network drop, our own timeout, or the caller's\n // abort — `combined` tells these two apart).\n if (isKaafilError(error)) {\n throw error;\n }\n if (combined.signal.aborted) {\n if (combined.isTimeout()) {\n throw new KaafilTimeoutError('Request timed out', { cause: error });\n }\n throw new KaafilAbortError('Request aborted', { cause: error });\n }\n throw new KaafilNetworkError(describeCrossOriginSuspect(url) ?? 'Request failed', {\n cause: error,\n });\n } finally {\n combined.cleanup();\n }\n}\n\n/** The enveloped success reader — every operation but the byte-bodied few. */\nfunction sendOnce<T>(\n ctx: ClientContext,\n request: RequestDescriptor,\n idempotencyKey: string | undefined,\n): Promise<{ readonly data: T; readonly meta: ResponseMeta; readonly facets: unknown }> {\n return sendOnceWith(ctx, request, idempotencyKey, async (response, status, requestId) => {\n const text = await response.text();\n const body = text.length > 0 ? tryParseJson(text) : undefined;\n\n // ── A 2xx WITH NO BODY IS A SUCCESS, NOT AN UNRECOGNIZABLE ONE ──────────\n //\n // Every DELETE in this API answers `204 No Content`, and HTTP forbids a\n // body on a 204 — so there is no envelope to find and demanding one turned\n // every successful delete into a thrown `KaafilNetworkError` carrying\n // `status: 204`. `vendors.remove()` and `files.remove()` were both\n // unusable because of it.\n //\n // `serverTime` is the one field a caller loses here, and it cannot be\n // recovered: it lives in the envelope the response does not have. Rather\n // than invent one from the device clock — the exact thing this SDK refuses\n // to do everywhere else — `meta.serverTime` carries the `Date` header when\n // the server sent one, and is absent otherwise.\n if (body === undefined && status >= 200 && status < 300) {\n const serverDate = response.headers.get('date');\n return {\n data: undefined as T,\n meta: {\n status,\n requestId,\n ...(serverDate === null ? {} : { serverTime: new Date(serverDate).toISOString() }),\n } as ResponseMeta,\n facets: undefined,\n };\n }\n\n if (!isSuccessEnvelope(body)) {\n throw new KaafilNetworkError(`Received an unrecognizable success body for HTTP ${status}`, {\n status,\n ...(requestId !== undefined ? { requestId } : {}),\n });\n }\n return {\n data: body.data as T,\n meta: buildResponseMeta(status, requestId, body.meta),\n facets: body.facets,\n };\n });\n}\n\n/**\n * The byte success reader. Asserts NOTHING about the payload beyond \"it\n * arrived\": no magic-number check, no `Content-Type` allowlist. A caller\n * that cares which format it got reads `meta.contentType`, which is the\n * server's own header verbatim — this SDK does not re-decide what a\n * successfully-served body is.\n *\n * `arrayBuffer()` rather than `blob()`: `Blob` is not a Node global before\n * 18 and is awkward to get bytes out of anywhere, while `ArrayBuffer` →\n * `Uint8Array` is one allocation-free wrap in every runtime.\n */\nfunction sendOnceBinary(\n ctx: ClientContext,\n request: RequestDescriptor,\n idempotencyKey: string | undefined,\n): Promise<KaafilBinaryResponse> {\n return sendOnceWith(ctx, request, idempotencyKey, async (response, status, requestId) => {\n const buffer = await response.arrayBuffer();\n const meta: BinaryResponseMeta = {\n status,\n requestId,\n contentType: response.headers.get('content-type') ?? undefined,\n };\n return { bytes: new Uint8Array(buffer), meta };\n });\n}\n\n// --- The rotating-session exchanges, standing alone from `execute()` -------\n\nconst MANAGER_TOKENS_REFRESH_PATH = '/api/v1/auth/manager-tokens/refresh';\nconst AGENCY_ADMIN_TOKENS_REFRESH_PATH = '/api/v1/auth/agency-admin-tokens/refresh';\n\n/**\n * Builds the `RotatingSessionExchange` a rotating (`managerSession`/\n * `agencyAdmin`) credential is constructed with by default\n * (`../client-entry.ts`). Deliberately its own tiny `fetch` call rather than\n * a call through `execute()`: `execute()` resolves its request's credential\n * through the very `CredentialResolver` this function is handed into, so\n * routing the refresh itself through `execute()` would recurse back into the\n * resolver mid-refresh; and `execute()`'s retry ladder is built to retry a\n * request, not to retry a single-use rotation that revokes its whole family\n * on a second presentation (`../auth/credentials.ts`'s\n * `RotatingSessionExchange` doc comment, `architecture/03-auth-and-tokens.md\n * §2`). One attempt, no ladder, no credential resolution — just the one POST\n * the session's own access token authorises.\n *\n * Shared by both `createManagerSessionRefreshExchange` and\n * `createAgencyAdminSessionRefreshExchange` below — the two differ only in\n * which endpoint they hit, and hand-rolling the fetch/parse/error-mapping\n * dance a second time for the second kind would be exactly the kind of copy\n * this lane's brief calls out for the engine's own rotation extraction.\n */\nfunction createRotatingSessionRefreshExchange(\n baseUrl: string,\n refreshPath: string,\n networkErrorMessage: string,\n): RotatingSessionExchange {\n return async (accessToken, refreshToken) => {\n const url = buildUrl(baseUrl, refreshPath, undefined);\n const headers = new Headers({\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${accessToken}`,\n });\n\n let response: Response;\n try {\n response = await fetch(url, {\n method: 'POST',\n headers,\n body: JSON.stringify({ refreshToken }),\n });\n } catch (error) {\n throw new KaafilNetworkError(networkErrorMessage, { cause: error });\n }\n\n const requestId = response.headers.get('x-request-id') ?? undefined;\n const status = response.status;\n const text = await response.text();\n const body = text.length > 0 ? tryParseJson(text) : undefined;\n\n if (!response.ok) {\n throw fromEnvelope(body, {\n status,\n ...(requestId !== undefined ? { requestId } : {}),\n });\n }\n if (!isSuccessEnvelope(body)) {\n throw new KaafilNetworkError(`Received an unrecognizable success body for HTTP ${status}`, {\n status,\n ...(requestId !== undefined ? { requestId } : {}),\n });\n }\n return body.data as RotatingRefreshResult;\n };\n}\n\nexport function createManagerSessionRefreshExchange(baseUrl: string): RotatingSessionExchange {\n return createRotatingSessionRefreshExchange(\n baseUrl,\n MANAGER_TOKENS_REFRESH_PATH,\n 'Manager-session refresh request failed',\n );\n}\n\nexport function createAgencyAdminSessionRefreshExchange(baseUrl: string): RotatingSessionExchange {\n return createRotatingSessionRefreshExchange(\n baseUrl,\n AGENCY_ADMIN_TOKENS_REFRESH_PATH,\n 'Agency-admin session refresh request failed',\n );\n}\n\n// --- Retry + refresh orchestration --------------------------------------\n\nfunction toKaafilError(error: unknown): KaafilError {\n if (isKaafilError(error)) {\n return error;\n }\n return new KaafilNetworkError('Unexpected transport failure', { cause: error });\n}\n\nfunction toFailureOutcome<T>(error: KaafilError): AttemptOutcome<T> {\n return {\n ok: false,\n status: error.status ?? null,\n ...(error.code !== undefined ? { code: error.code } : {}),\n ...(error instanceof KaafilRateLimitedError && error.retryAfterSeconds !== undefined\n ? { retryAfterSeconds: error.retryAfterSeconds }\n : {}),\n };\n}\n\n/**\n * Runs one logical call end to end: mints (or reuses) the idempotency key,\n * drives the retry ladder (`retry.ts`) whose allowlist is itself built from\n * the same `ERROR_CODE_TABLE` that `classify.ts` classifies transient /\n * conflict / fatal from (`06-offline-first.md §7`) — so a code the table\n * marks non-retryable never gets a second ladder attempt here, and grants\n * `401 UNAUTHENTICATED` exactly one refresh-then-replay outside the ladder\n * (`03-auth-and-tokens.md §2`; `after-refresh` is deliberately excluded from\n * the ladder's own allowlist in `retry.ts`, precisely so it can't also be\n * retried there).\n */\nasync function runWithLadder<R>(\n ctx: ClientContext,\n request: RequestDescriptor,\n send: (idempotencyKey: string | undefined) => Promise<R>,\n): Promise<R> {\n const idempotencyKey = OPERATION_ACCEPTS_IDEMPOTENCY_KEY[request.operationId]\n ? (request.idempotencyKey ?? globalThis.crypto.randomUUID())\n : undefined;\n\n let lastError: KaafilError | undefined;\n let refreshAttempted = false;\n\n const sendAndClassify = async (): Promise<AttemptOutcome<R>> => {\n try {\n return { ok: true, value: await send(idempotencyKey) };\n } catch (error) {\n const typed = toKaafilError(error);\n lastError = typed;\n // A malformed request never enters the ladder. `isRetryableFailure`\n // (`./retry.ts`) classifies from a bare `{ status, code }`, and a\n // usage error carries NEITHER — no response reached the client, so\n // `status` is `null`, which that function reads as \"transport blip,\n // retry\". It cannot tell a dropped connection apart from a request\n // that was rejected before it was ever built.\n //\n // This mattered concretely, and the scale of it is the point.\n // `UnsatisfiableSchemeError` — thrown by `CredentialResolver` inside\n // `buildHeaders`, i.e. before `fetch` is reached at all — is the\n // answer for every operation the open credential's scheme cannot\n // satisfy (`closeout.unlock` and `expenses.claims.ingest` from a\n // manager session; `journey.rebuild`/`journey.runStep` likewise, which\n // is how long this has been true). Classified as a null-status failure\n // it entered the full default ladder: `DEFAULT_MAX_ATTEMPTS` is 24 and\n // `RETRY_LADDER_MS` holds at its 3,600,000 ms top rung, so the 23 waits\n // sum to 62,481,000 ms before jitter — between roughly 8.7 and 17.4\n // hours of a pending promise, with ZERO requests sent, for a mistake\n // the SDK had already diagnosed completely on the first microtask.\n // Observed directly: a probe left running past 25 minutes had not yet\n // surfaced it. The eventual error was the right one; nobody is awake\n // to read it.\n //\n // `isRetryable` (`./errors.ts`) already encodes exactly this rule for\n // consumers, and its own comment names this failure — the ladder was\n // simply never consulting it. Deferring to it here rather than\n // re-testing `instanceof KaafilInvalidRequestError` keeps one\n // definition of \"retryable\", so a future change to that predicate\n // cannot leave the transport disagreeing with the package's exported\n // answer. `KaafilAbortError` comes along for the ride, correctly: the\n // caller asked to stop.\n if (typed.kind === 'transport' && !isRetryable(typed)) {\n throw typed;\n }\n return toFailureOutcome(typed);\n }\n };\n\n const attempt = async (_attemptNumber: number): Promise<AttemptOutcome<R>> => {\n const outcome = await sendAndClassify();\n if (outcome.ok) {\n return outcome;\n }\n\n const canRefresh =\n !refreshAttempted &&\n outcome.code === KaafilErrorCode.Unauthenticated &&\n isRotatingCredentialKind(ctx.credentials.kind);\n if (!canRefresh) {\n return outcome;\n }\n\n refreshAttempted = true;\n try {\n await ctx.credentials.refreshRotatingSession();\n } catch {\n // The refresh itself failed — surface the original 401, not a\n // refresh-plumbing error the consumer never asked about.\n return outcome;\n }\n return sendAndClassify();\n };\n\n // Rendered once here, BEFORE the retry loop, purely so a malformed request\n // fails on the caller's first await instead of inside an attempt. `sendOnce`\n // renders it again per attempt — the function is pure and cheap, and having\n // the validation live at the boundary is worth the duplicate call: a usage\n // error that escapes from inside `attempt` is one classification mistake away\n // from being retried.\n renderPath(request.path, request.pathParams);\n\n try {\n return await executeWithRetry(attempt, {\n ...(ctx.maxAttempts !== undefined ? { maxAttempts: ctx.maxAttempts } : {}),\n ...(request.signal !== undefined ? { signal: request.signal } : {}),\n ...(ctx.random !== undefined ? { random: ctx.random } : {}),\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n hasBody: request.body !== undefined,\n });\n } catch (error) {\n if (error instanceof RetryExhaustedError) {\n // Never replace a typed failure with a generic \"retry exhausted\"\n // message — that is precisely how a tenant-isolation 404 becomes an\n // untyped string. Throw the last real `KaafilError` we saw instead.\n throw lastError ?? error;\n }\n if (request.signal?.aborted === true) {\n throw new KaafilAbortError('Request aborted', { cause: lastError ?? error });\n }\n throw error;\n }\n}\n\n/** The enveloped call — what every resource method but `closeout.exportPdf`\n * goes through. */\n/**\n * In-flight GETs, so N callers asking the same question at the same moment\n * make ONE request. Keyed by client context first — a coalesced answer is\n * scoped to the credential that fetched it, and a client that goes away takes\n * its entries with it.\n */\nconst inFlightReads = new WeakMap<object, Map<string, Promise<unknown>>>();\n\n/**\n * What makes two reads the same read. Everything that can change the answer,\n * and nothing that cannot: `operationId` rather than `path` alone because two\n * operations can share a template, and both `pathParams` and `query` because a\n * different trip or a different cursor is a different question.\n */\nfunction readKey(request: RequestDescriptor): string {\n return [\n request.operationId,\n request.path,\n JSON.stringify(request.pathParams ?? {}),\n JSON.stringify(request.query ?? {}),\n JSON.stringify(request.headers ?? {}),\n ].join('|');\n}\n\nfunction execute<T>(ctx: ClientContext, request: RequestDescriptor): Promise<KaafilResponse<T>> {\n const run = (): Promise<KaafilResponse<T>> =>\n runWithLadder(ctx, request, async (idempotencyKey) => {\n const { data, meta, facets } = await sendOnce<T>(ctx, request, idempotencyKey);\n return attachMeta<T>(data, meta, facets);\n });\n\n // ── COALESCE IDENTICAL IN-FLIGHT READS ────────────────────────────────────\n //\n // A UI hook is an implementation shared by its callers, not an instance\n // shared by them: every component that calls one gets its own state, its own\n // effect and therefore its own request. A screen assembled from several\n // components that each need the same answer asks for it several times, at\n // the same moment — and every copy is slower than one would have been,\n // because they queue behind each other at the server.\n //\n // Measured on the manager's Now tab against a live engine: ten requests on\n // open, four of them the same capability read.\n //\n // TWO CONDITIONS, both of which matter.\n //\n // GET ONLY. A write is not idempotent by position in time — two callers\n // posting the same body mean two things happened, and they carry different\n // `Idempotency-Key`s precisely to say so. Sharing one would silently drop\n // the second.\n //\n // NO CALLER SIGNAL. `combineSignals` ties the fetch to the caller's own\n // `AbortSignal`, so a shared request would die when whichever caller\n // happened to arrive first unmounted — taking the others' results with it.\n // Rather than reference-count aborts, a request that carries a signal simply\n // opts out; the hooks that duplicate reads do not pass one.\n //\n // This is NOT a cache. The entry is dropped the moment the promise settles,\n // success or failure, so it changes how many requests a single instant\n // produces and nothing about freshness, refetch timing, or what a later\n // caller sees. A rejection is never replayed to someone who would have\n // retried.\n if (request.method !== 'GET' || request.signal !== undefined) return run();\n\n let perClient = inFlightReads.get(ctx);\n if (perClient === undefined) {\n perClient = new Map();\n inFlightReads.set(ctx, perClient);\n }\n\n const key = readKey(request);\n const existing = perClient.get(key);\n if (existing !== undefined) return existing as Promise<KaafilResponse<T>>;\n\n const started = run().finally(() => {\n perClient.delete(key);\n });\n perClient.set(key, started);\n return started;\n}\n\n/** The byte-bodied call. Same ladder, same refresh grant, same typed errors\n * — see `KaafilHttpClient.executeBinary`'s doc for why it cannot go through\n * `execute()` above. */\nfunction executeBinary(\n ctx: ClientContext,\n request: RequestDescriptor,\n): Promise<KaafilBinaryResponse> {\n return runWithLadder(ctx, request, (idempotencyKey) =>\n sendOnceBinary(ctx, request, idempotencyKey),\n );\n}\n","/**\n * Mints a fresh idempotency key. Not credential-specific and not tied to\n * either entry point — both `Kaafil` (`../client.ts`) and `KaafilClient`\n * (`../client-entry.ts`) expose this as a static `newIdempotencyKey()`, and\n * this is the one place the actual minting happens so the two never drift.\n *\n * Every mutating call already mints and reuses a key automatically\n * (`http/client.ts`'s `execute()` — `globalThis.crypto.randomUUID()` when the\n * caller didn't supply one). Calling this directly is the rare case: pinning\n * a key ahead of time so a caller can replay the exact same logical\n * operation — with the exact same key — across a process restart, which\n * `execute()` has no way to do on the caller's behalf since it has no\n * visibility into the caller's own retry-across-restart bookkeeping.\n */\nexport function newIdempotencyKey(): string {\n return globalThis.crypto.randomUUID();\n}\n","/**\n * Coercion for the caller-supplied date-time fields scattered across the\n * ingest surface (`trips.upsert`, `trips.travellers.*`, `trips.managers.*`,\n * `trips.balance.push`, `trips.bulk.push`, `shareTokens.create`). Every one\n * of those fields is, in the generated schema, a bare `string` that the API\n * requires to be a full ISO-8601 datetime WITH an offset — a caller who\n * hand-builds that string is the single most common way to fail this API's\n * validation, and JavaScript already has a `Date` for exactly this job.\n *\n * This module is the one seam every such field routes through. It is not\n * wired into the generated schema types (those stay a faithful mirror of\n * the OpenAPI spec) — it is wired into the hand-written `*Options` types in\n * `resources/trips.ts` and `resources/share-tokens.ts`, which widen the\n * relevant fields from `string` to `DateTimeInput` and normalize back down\n * to the schema's `string` shape before the body reaches `client.execute`.\n */\n\nimport { KaafilInvalidRequestError } from './http/errors';\n\n/**\n * What a caller may hand a date-time field on the ingest surface.\n *\n * - `Date` is the point of this whole module: build it however you like,\n * the SDK converts it correctly.\n * - `number` is epoch milliseconds — `Date.now()` and friends, without\n * forcing a caller to wrap it in `new Date(...)` first.\n * - `string` is the escape hatch for a caller who already has a correctly\n * formatted ISO datetime (e.g. echoed back from another system) and does\n * not want it touched — see `normalizeDateTimeInput` for why a full\n * datetime string passes through byte-for-byte instead of round-tripping\n * through `Date`.\n */\nexport type DateTimeInput = Date | number | string;\n\n// A full ISO-8601 datetime with an explicit offset — `Z` or `±HH:MM`.\n// Anchored both ends: a substring match here would let e.g. free text that\n// merely *contains* a valid datetime slip through as \"already valid\".\nconst FULL_DATETIME_WITH_OFFSET =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(Z|[+-]\\d{2}:\\d{2})$/;\n\n// `YYYY-MM-DD` — the specific, seductive wrong answer this module refuses\n// to guess its way out of. See the throw site below for why.\nconst DATE_ONLY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\nfunction invalidRequest(fieldPath: string, message: string): KaafilInvalidRequestError {\n return new KaafilInvalidRequestError(`${fieldPath}: ${message}`);\n}\n\n/**\n * Normalizes one caller-supplied date-time field to the ISO string the API\n * expects. `fieldPath` is a dotted/indexed path (e.g.\n * `\"trips[2].travellers[0].sourceUpdatedAt\"`) so a thrown error names\n * exactly which field, in which nested row, is wrong — a caller pushing a\n * bulk batch of 50 trips should not have to bisect the payload by hand.\n *\n * A `string` that is already a full ISO datetime with an offset is\n * returned UNCHANGED, not round-tripped through `new Date(...).toISOString()`.\n * `toISOString()` always normalizes to `Z`, so round-tripping would silently\n * rewrite a caller's explicit `+05:30` to `Z` — same instant, different text\n * — and change what gets echoed back to them on every read. An existing\n * caller who already builds this string correctly must see it pass through\n * byte-for-byte; this function only ever *adds* a coercion path, never\n * alters the one that already worked.\n *\n * A `string` that is date-only (`YYYY-MM-DD`) is REFUSED, not coerced to\n * midnight UTC. That coercion looks helpful and is a correctness trap: a\n * trip starting \"20 August\" in `Asia/Kolkata` does not begin at `00:00Z`,\n * and picking UTC on the caller's behalf would silently invent a timezone\n * they never chose, shifting a real trip's start by hours. Guessing wrong\n * here is worse than refusing — so this throws a `KaafilInvalidRequestError`\n * (a caller-built-it-wrong error, never retried, per `http/errors.ts`)\n * naming the field and showing the fix, and the caller finds out locally\n * and instantly instead of after a round trip to a remote `422`.\n */\nexport function normalizeDateTimeInput(value: DateTimeInput, fieldPath: string): string {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) {\n throw invalidRequest(fieldPath, 'received an invalid Date (getTime() is NaN).');\n }\n return value.toISOString();\n }\n\n if (typeof value === 'number') {\n if (!Number.isFinite(value)) {\n throw invalidRequest(\n fieldPath,\n `received a non-finite number (${String(value)}); expected epoch milliseconds.`,\n );\n }\n return new Date(value).toISOString();\n }\n\n if (FULL_DATETIME_WITH_OFFSET.test(value)) {\n return value;\n }\n\n if (DATE_ONLY.test(value)) {\n throw invalidRequest(\n fieldPath,\n `received a date-only string (\"${value}\"). This API requires a full ISO-8601 ` +\n 'datetime WITH an offset, and the SDK will not guess which timezone you meant ' +\n '(midnight UTC is rarely midnight where the trip actually starts). Pass a ' +\n '`Date` instead — e.g. `new Date(\"2026-08-20T09:00:00+05:30\")` — or add an ' +\n 'explicit offset yourself, e.g. \"2026-08-20T00:00:00+05:30\".',\n );\n }\n\n throw invalidRequest(\n fieldPath,\n `received \"${value}\", which is not a full ISO-8601 datetime with an offset. Pass a ` +\n '`Date`, an epoch-milliseconds number, or a string like \"2026-08-20T09:00:00+05:30\".',\n );\n}\n\n/**\n * Same contract as `normalizeDateTimeInput`, for a field that is optional on\n * the wire (`expiresAt?:` on `MintShareTokenRequest`, say). `undefined` in\n * means `undefined` out — the caller omitted it, so there is nothing to\n * normalize and nothing to throw about.\n */\nexport function normalizeOptionalDateTimeInput(\n value: DateTimeInput | undefined,\n fieldPath: string,\n): string | undefined {\n return value === undefined ? undefined : normalizeDateTimeInput(value, fieldPath);\n}\n\n/**\n * Same contract again, for a NULLABLE field (`startTime`/`endTime` on an\n * itinerary item, where `null` clears a time that was set).\n *\n * `null` passes through as `null`; it is never coerced to a timestamp and\n * never folded into `undefined`. On these fields the two mean opposite\n * things — `undefined` is \"leave whatever is there alone\", `null` is \"clear\n * it\" — and collapsing them would turn an attempt to clear a start time into\n * a silent no-op.\n *\n * `undefined` is deliberately NOT in this signature, unlike\n * `normalizeOptionalDateTimeInput`'s. Every field that reaches this function\n * is optional on the wire too, and `exactOptionalPropertyTypes` means an\n * omitted field must be omitted from the object literal rather than set to\n * `undefined` — so the call site already has to branch on `undefined` to build\n * its conditional spread. Accepting it here as well would let a `undefined`\n * return leak into a field typed `string | null`.\n */\nexport function normalizeNullableDateTimeInput(\n value: DateTimeInput | null,\n fieldPath: string,\n): string | null {\n return value === null ? null : normalizeDateTimeInput(value, fieldPath);\n}\n","/**\n * Cursor pagination for `kaafil-js`. Six list operations are\n * cursor-paginated (`cursor` + `limit` query params, `meta.page.hasNext` in\n * the envelope) — the SDK holds the cursor so a consumer never sees one\n * (`architecture/08-sdk.md §5`: \"pagination cursors are exposed on the\n * result\"; the cursor itself is documented OPAQUE per-operation in\n * `openapi/openapi.json`, e.g. `listApiKeys`, `listWebhookEndpoints`,\n * `listWebhookDeliveries`).\n *\n * `hasNext` is read from `meta.page.hasNext` and never inferred from \"the\n * page came back empty\" or \"fewer than `limit` rows came back\" — the server\n * already answers this question, and guessing it from row counts is exactly\n * how a reference SDK's list object gets it wrong at a page boundary that\n * lands on a multiple of `limit`.\n */\n\nimport type { PagedResponseMeta } from '../types/meta';\n\n/** One fetched page: its rows plus the envelope metadata that came with them. */\nexport interface PaginatorPage<T> {\n readonly items: readonly T[];\n readonly meta: PagedResponseMeta;\n}\n\n/**\n * Fetches one page for a given cursor/limit/filters triple. A resource\n * module supplies this as a thin closure over `KaafilHttpClient.execute` —\n * this module knows nothing about HTTP, operation ids, or query-param names,\n * only that a page has `items` and cursor-pagination `meta`.\n */\nexport type FetchPage<T, F> = (request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: F;\n}) => Promise<PaginatorPage<T>>;\n\n/**\n * Thrown by `next()` instead of ever resolving to `[]` for a state that\n * isn't \"the server returned zero rows this page\". A reference SDK resolves\n * an empty array on a re-entrant call, on exhaustion, AND on a genuinely\n * empty page — collapsing three different states into one indistinguishable\n * answer, so a double-fire on a UI mount looks exactly like \"no more data\".\n * These two named subclasses exist so a caller can `instanceof`-branch and\n * tell them apart; a real empty page still just resolves normally with\n * `items: []` and whatever `hasNext` the server said.\n */\nexport abstract class KaafilPaginationError extends Error {\n protected constructor(message: string) {\n super(message);\n this.name = 'KaafilPaginationError';\n }\n}\n\n/** `next()` was called again before the in-flight call for this paginator settled. */\nexport class KaafilPaginationInFlightError extends KaafilPaginationError {\n constructor() {\n super('next() was called while a previous call on this paginator was still in flight.');\n this.name = 'KaafilPaginationInFlightError';\n Object.setPrototypeOf(this, KaafilPaginationInFlightError.prototype);\n }\n}\n\n/** `next()` was called after `hasNext` had already gone `false`. */\nexport class KaafilPaginationExhaustedError extends KaafilPaginationError {\n constructor() {\n super('next() was called after this paginator was already exhausted (hasNext is false).');\n this.name = 'KaafilPaginationExhaustedError';\n Object.setPrototypeOf(this, KaafilPaginationExhaustedError.prototype);\n }\n}\n\n/**\n * The HTTP statuses this module treats as terminal: the server has answered\n * definitively that this call can never succeed by paging further (a plan\n * gate, a validation failure, tenant-scoped absence). On one of these, the\n * paginator sets `hasNext` to `false` and files the typed error in\n * `lastError` rather than throwing it out of `next()` or the async\n * iterator — a caller iterating a list is not the place to force a `try`\n * around a condition that means \"there is nothing more to show,\" and the\n * error is still there in `lastError` for anyone who wants to inspect why.\n * Any other failure (a 5xx, a timeout that survived the transport's own\n * retry ladder) is NOT terminal here: it is re-thrown, because the paginator\n * cannot tell whether paging further would still work.\n */\nconst TERMINAL_STATUSES: ReadonlySet<number> = new Set([402, 404, 422]);\n\nfunction isTerminalStatus(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'status' in error &&\n typeof (error as { status: unknown }).status === 'number' &&\n TERMINAL_STATUSES.has((error as { status: number }).status)\n );\n}\n\n/**\n * A `list()` call builds one of these and returns it SYNCHRONOUSLY, before\n * any request goes out: it is not a promise, and `await list()` is a no-op\n * that hands back this same object with `items: []`. The first page arrives\n * only from `await paginator.next()` or from iterating the paginator — an\n * untouched paginator reading as an empty tenant is the shape of that\n * mistake, and `meta === undefined` distinguishes \"not fetched yet\" from a\n * genuinely empty first page.\n */\nexport interface KaafilPaginator<T, F> {\n /** Every row fetched so far, across every page pulled on the current\n * filters — `[]` until `next()` (or iteration) has actually run. */\n readonly items: readonly T[];\n /** From the last page's `meta.page.hasNext` — `true` until a first fetch has run. */\n readonly hasNext: boolean;\n readonly isLoading: boolean;\n /** The typed error from the last failed fetch, if any. Cleared by `setFilters`. */\n readonly lastError: unknown;\n /** The last page's full envelope `meta`, or `undefined` before a first fetch. */\n readonly meta: PagedResponseMeta | undefined;\n /**\n * Fetches the next page and returns just that page's rows (also appended\n * to `items`). Throws `KaafilPaginationInFlightError` on a re-entrant\n * call and `KaafilPaginationExhaustedError` once `hasNext` is `false` —\n * neither case reaches the network.\n */\n next(): Promise<readonly T[]>;\n /**\n * Replaces the filters, resets the cursor to the start, clears\n * `items`/`lastError`, and sets `hasNext` back to `true`. A\n * stale-cursor-with-new-filters state is unrepresentable: there is no way\n * to change `filters` without also discarding whatever cursor was in\n * flight for the old ones.\n */\n setFilters(filters: F): void;\n /**\n * Drives `next()` until the server says `hasNext: false`, yielding one row\n * at a time so a Node backend can `for await (const row of paginator)` and\n * never think about paging. A terminal error ends the iteration quietly\n * (see `TERMINAL_STATUSES`); anything else propagates out of the loop.\n */\n [Symbol.asyncIterator](): AsyncIterator<T>;\n}\n\ninterface PaginatorState<T, F> {\n cursor: string | undefined;\n hasNext: boolean;\n isLoading: boolean;\n lastError: unknown;\n meta: PagedResponseMeta | undefined;\n items: T[];\n filters: F;\n}\n\nfunction createInitialState<T, F>(filters: F): PaginatorState<T, F> {\n return {\n cursor: undefined,\n hasNext: true,\n isLoading: false,\n lastError: undefined,\n meta: undefined,\n items: [],\n filters,\n };\n}\n\nexport interface CreatePaginatorConfig<T, F> {\n readonly fetchPage: FetchPage<T, F>;\n readonly filters: F;\n /** Page size sent as the `limit` query param. Omitted lets the server default apply. */\n readonly limit?: number;\n}\n\n/**\n * Builds a `KaafilPaginator`. A resource module's `list()` method calls this\n * once per invocation and hands back the result directly — the paginator\n * owns every subsequent page fetch.\n */\nexport function createPaginator<T, F>(config: CreatePaginatorConfig<T, F>): KaafilPaginator<T, F> {\n const { fetchPage, limit } = config;\n const state = createInitialState<T, F>(config.filters);\n\n async function next(): Promise<readonly T[]> {\n if (state.isLoading) {\n throw new KaafilPaginationInFlightError();\n }\n if (!state.hasNext) {\n throw new KaafilPaginationExhaustedError();\n }\n\n state.isLoading = true;\n try {\n const page = await fetchPage({ cursor: state.cursor, limit, filters: state.filters });\n state.items.push(...page.items);\n state.cursor = page.meta.page.cursor ?? undefined;\n state.hasNext = page.meta.page.hasNext;\n state.meta = page.meta;\n state.lastError = undefined;\n return page.items;\n } catch (error) {\n state.lastError = error;\n if (isTerminalStatus(error)) {\n state.hasNext = false;\n return [];\n }\n throw error;\n } finally {\n state.isLoading = false;\n }\n }\n\n function setFilters(filters: F): void {\n const fresh = createInitialState<T, F>(filters);\n state.cursor = fresh.cursor;\n state.hasNext = fresh.hasNext;\n state.isLoading = fresh.isLoading;\n state.lastError = fresh.lastError;\n state.meta = fresh.meta;\n state.items.length = 0;\n state.filters = filters;\n }\n\n async function* iterate(): AsyncGenerator<T> {\n while (state.hasNext) {\n const page = await next();\n for (const item of page) {\n yield item;\n }\n }\n }\n\n return {\n get items() {\n return state.items;\n },\n get hasNext() {\n return state.hasNext;\n },\n get isLoading() {\n return state.isLoading;\n },\n get lastError() {\n return state.lastError;\n },\n get meta() {\n return state.meta;\n },\n next,\n setFilters,\n [Symbol.asyncIterator]: iterate,\n };\n}\n","/**\n * Helpers shared by more than one resource file. Not a resource itself, and\n * not the barrel that assembles resources into a client — that belongs to\n * the next lane. Kept here once instead of duplicated in `webhooks.ts` and\n * `events.ts`, the two groups in this lane whose list operation is\n * cursor-paginated (`architecture/08-sdk.md §5`, `../pagination/paginator.ts`).\n */\n\nimport type { PaginatorPage } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\n\n/**\n * Narrows a response's `meta` from `ResponseMeta` (where `.page` is optional\n * because most operations aren't paginated) to `PagedResponseMeta` (where\n * it's guaranteed). Every cursor-paginated operation's envelope always\n * carries `meta.page` — this only guards the boundary between \"the generated\n * type says optional\" and \"this specific endpoint always sends it,\" so a\n * response that somehow arrived without one fails loudly here rather than\n * quietly widening to a paginator that can never learn `hasNext`.\n */\nexport function narrowPaged<T>(response: KaafilResponse<T>): KaafilPagedResponse<T> {\n if (response.meta.page === undefined) {\n throw new Error('invariant: a cursor-paginated response arrived without meta.page.');\n }\n return response as KaafilPagedResponse<T>;\n}\n\n/**\n * Adapts one already-fetched list response into the shape\n * `createPaginator`'s `fetchPage` closures return. The response value\n * itself, once narrowed, already satisfies `readonly T[]` (the transport\n * attaches `meta` onto the array in place, `../http/client.ts`'s\n * `attachMeta`), so `items` and the array are the same object.\n */\nexport function toPaginatorPage<T>(response: KaafilResponse<readonly T[]>): PaginatorPage<T> {\n const paged = narrowPaged(response);\n return { items: paged, meta: paged.meta };\n}\n","/**\n * `agencies` — the agency record itself, plus the agency-wide manager\n * directory. `architecture/08-sdk.md §4`.\n *\n * `upsert` (`upsertAgency`, `PUT /api/v1/agencies/{ref}`) is `apiKeyAuth`-only\n * in the spec (`../generated/security.ts`'s `OPERATION_SECURITY`) — the same\n * ingest credential `POST /api/v1/trips` and every other `trip-ingest` write\n * use. LWW, first-ingest-creates: `sourceUpdatedAt` is REQUIRED, with no\n * \"defaults to now\", for the same staleness-detection reason as every other\n * last-write-wins field in this SDK (see `trips.ts`'s `UpsertTripOptions`) —\n * a push whose stamp is not newer than the stored one comes back `200` with\n * `verdict: ignored_stale`, never a `409`.\n *\n * `managers.list` (`listAgencyManagers`, `GET /api/v1/agencies/{ref}/managers`)\n * accepts `apiKeyAuth`, `managerAuth`, OR `agencyAdminAuth` in the spec — the\n * same multi-scheme shape `./vendors.ts`'s `listTripVendors` has — so,\n * following that file's precedent, this resource (`upsert` included) is\n * exposed unchanged from both `../client.ts` and `../client-entry.ts`; a\n * manager- or agency-admin-opened `KaafilClient` calling `upsert` simply fails\n * at the point of use with `UnsatisfiableSchemeError`, the same way a\n * `shareToken`-opened client calling `vendors`/`journey` already does.\n * `settings.get`/`settings.patch` (below) are agency-scoped and, on\n * `../client-entry.ts`, agencyRef-BOUND — see that file's \"agencyRef-bound\n * option types\" section, the same treatment `managers.list`/`.listPage` get\n * there.\n *\n * `managers.list` is cursor-paginated (`cursor`/`limit` query params), with an\n * optional free-text `q` filter and an optional `forTripRef` that additionally\n * computes each returned manager's availability against that trip's own dates\n * (`../generated/schema.d.ts`'s `ManagerListRowResponse.availability`).\n * Modeled as a `KaafilPaginator`, the same as `./travellers.ts`'s\n * `listForAgency` — unlike that one, though, every filter here (including `q`)\n * is optional, so `filters` may be an empty object. `managers.listPage` is the\n * manual single-page escape hatch, same convention.\n *\n * ── `settings` — THE SIBLING ROUTE, NEVER A WIDENED AUTH ARRAY (GAP-002) ────\n *\n * `settings.get`/`settings.patch` wrap `GET`/`PATCH\n * /api/v1/agencies/{ref}/settings/self` (`getAgencySettingsSelf`/\n * `patchAgencySettingsSelf`) — a SEPARATE route from the console's own\n * `GET`/`PATCH /api/v1/agencies/{ref}/settings` (`getAgencySettings`/\n * `patchAgencySettings`, `consoleAuth`-only, not exposed by this package; see\n * `./checklists.ts`'s header for the same console-exclusion reasoning). The\n * engine deliberately ships two routes rather than one route with a widened\n * `security` array: `../shared/http/route-pipeline.ts`'s `pipeline()` throws\n * at import time if `'consoleAuth'` ever appears in a multi-scheme set,\n * because a cookie is ambient and a multi-kind set could silently prefer a\n * console session from another browser tab. `settings.get` accepts\n * `apiKeyAuth` OR `agencyAdminAuth`; `settings.patch` is `agencyAdminAuth`-\n * only — an API key pushes trip/booking data, never this agency's own\n * operational knobs. Both share the exact same request/response body shape\n * as the console pair (`PatchAgencySettingsRequest`/\n * `PatchAgencySettingsSelfRequest` are structurally identical in the\n * vendored spec), so nothing here is a lesser version of the console form.\n * `settings.patch` requires `If-Match`, the same optimistic-concurrency\n * contract as every other version-guarded write in this SDK.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type {\n KaafilFacetedPagedResponse,\n KaafilPagedResponse,\n KaafilResponse,\n} from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype UpsertAgencyRequest = components['schemas']['UpsertAgencyRequest'];\ntype AgencyUpsertResponse = components['schemas']['AgencyUpsertResponse'];\ntype ManagerListRowResponse = components['schemas']['ManagerListRowResponse'];\nexport type ManagerAgencyProfileResponse = components['schemas']['ManagerAgencyProfileResponse'];\ntype AgencySettingsResponse = components['schemas']['AgencySettingsResponse'];\ntype TripDirectoryRowResponse = components['schemas']['TripDirectoryRowResponse'];\ntype TripManifestRowResponse = components['schemas']['TripManifestRowResponse'];\ntype PatchAgencySettingsSelfRequest = components['schemas']['PatchAgencySettingsSelfRequest'];\n\nexport interface UpsertAgencyOptions extends Omit<UpsertAgencyRequest, 'sourceUpdatedAt'> {\n readonly agencyRef: string;\n /** The CRM's own record-updated timestamp — required, no \"defaults to\n * now\". See this file's header for why. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- agencies.managers ---------------------------------------------------\n\ntype ListAgencyManagersQuery = NonNullable<operations['listAgencyManagers']['parameters']['query']>;\n/** The filterable half of `listAgencyManagers`'s query params —\n * `cursor`/`limit` are the paginator's job. Unlike\n * `./travellers.ts`'s `TravellerDirectoryFilters`, both `q` and `forTripRef`\n * here are optional, so an empty object is a valid `filters`. */\nexport type AgencyManagerFilters = Omit<ListAgencyManagersQuery, 'cursor' | 'limit'>;\n\nasync function fetchAgencyManagersPage(\n client: KaafilHttpClient,\n agencyRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: AgencyManagerFilters;\n },\n) {\n const response = await client.execute<readonly ManagerListRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListAgencyManagers,\n path: '/api/v1/agencies/{ref}/managers',\n pathParams: { ref: agencyRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListAgencyManagersOptions {\n readonly agencyRef: string;\n readonly filters?: AgencyManagerFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListAgencyManagersPageOptions extends AgencyManagerFilters {\n readonly agencyRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface GetAgencyManagerProfileOptions {\n readonly agencyRef: string;\n readonly managerRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencyManagersResource {\n /** `GET /api/v1/agencies/{ref}/managers` as a `KaafilPaginator` — the\n * agency's whole manager directory, `q`-filterable, and, with\n * `forTripRef`, availability-annotated against that trip's dates. */\n list(\n options: ListAgencyManagersOptions,\n ): KaafilPaginator<ManagerListRowResponse, AgencyManagerFilters>;\n /** The manual single-page escape hatch for `list`. */\n listPage(\n options: ListAgencyManagersPageOptions,\n ): Promise<KaafilPagedResponse<readonly ManagerListRowResponse[]>>;\n /** `GET /api/v1/agencies/{ref}/managers/{managerRef}` — one manager's own\n * agency-wide profile: identity plus every trip they've been on. The\n * traveller-profile sibling (`./travellers.ts`'s `getAgencyProfile`,\n * GAP-016) — same `apiKeyAuth`/`agencyAdminAuth`-only posture, never\n * `managerAuth`, for the identical reason. */\n get(\n options: GetAgencyManagerProfileOptions,\n ): Promise<KaafilResponse<ManagerAgencyProfileResponse>>;\n}\n\n// --- agencies.trips -------------------------------------------------------\n\ntype ListAgencyTripsQuery = NonNullable<operations['listAgencyTrips']['parameters']['query']>;\n/** The filterable half of `listAgencyTrips`'s query params — `cursor`/`limit`\n * are the paginator's job. Every member is optional, so `{}` is valid. */\nexport type AgencyTripFilters = Omit<ListAgencyTripsQuery, 'cursor' | 'limit'>;\n\n/**\n * Per-bucket trip counts over the WHOLE agency, not the current page.\n *\n * Hand-written rather than taken from `components['schemas']` on purpose:\n * the engine's OpenAPI generator can only describe\n * `SuccessEnvelope & { data: X }`, so it has no way to declare the `facets`\n * sibling the response wrapper actually sends, and the shape therefore never\n * reaches the generated catalog. The source of truth is\n * `kaafil-engine/src/modules/trip-directory/trip-directory.dto.ts`'s\n * `tripSegmentCountsResponseSchema` — keep the two in step by hand.\n *\n * The five non-`all` buckets partition every live trip, so they sum to\n * `all`. There is no `draft` bucket: `TripStatus` has no draft member.\n */\nexport interface AgencyTripSegmentCounts {\n readonly all: number;\n /** In progress, or confirmed and inside its own date window. */\n readonly active: number;\n /** Confirmed and starting later. */\n readonly upcoming: number;\n /** Completed, or confirmed and already ended. */\n readonly past: number;\n readonly postponed: number;\n readonly cancelled: number;\n}\n\n/** What `listAgencyTrips` carries in the envelope's `facets` key. */\nexport interface AgencyTripFacets {\n readonly segments: AgencyTripSegmentCounts;\n}\n\nasync function fetchAgencyTripsPage(\n client: KaafilHttpClient,\n agencyRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: AgencyTripFilters;\n },\n) {\n const response = await client.execute<readonly TripDirectoryRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListAgencyTrips,\n path: '/api/v1/agencies/{ref}/trips',\n pathParams: { ref: agencyRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListAgencyTripsOptions {\n readonly agencyRef: string;\n readonly filters?: AgencyTripFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListAgencyTripsPageOptions extends AgencyTripFilters {\n readonly agencyRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface GetAgencyTripOptions {\n readonly agencyRef: string;\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencyTripsResource {\n /**\n * `GET /api/v1/agencies/{ref}/trips` as a `KaafilPaginator` — the agency's\n * whole trip list, filterable by `q`/`eventType`/`status`/`segment` and\n * orderable by `sort`.\n *\n * THE ONLY trip-collection read reachable by an agency admin. `managerMe.\n * listTrips` is a manager's own assignments and `managerAuth`-only; the\n * `trips` resource itself (`upsert`/`get`/`cancel`) is `apiKeyAuth`-only\n * ingest. Prefer `listPage` when you need the segment counts — a paginator\n * surfaces pages, not the envelope's `facets`.\n */\n list(\n options: ListAgencyTripsOptions,\n ): KaafilPaginator<TripDirectoryRowResponse, AgencyTripFilters>;\n /**\n * The manual single-page escape hatch for `list`, and the only way to read\n * `facets.segments` — the per-bucket counts a filter-chip row needs, which\n * are computed over the whole agency rather than the page.\n */\n listPage(\n options: ListAgencyTripsPageOptions,\n ): Promise<KaafilFacetedPagedResponse<readonly TripDirectoryRowResponse[], AgencyTripFacets>>;\n /**\n * `GET /api/v1/agencies/{ref}/trips/{tripRef}` — one trip's own console\n * read: identity, live manifest size, the FULL manager roster and a money\n * rollup.\n *\n * Distinct from `trips.get`, which is `apiKeyAuth`-only and returns the\n * ingest ECHO. `managers.get`'s (GAP-016) exact sibling, scoped to `Trip`,\n * with the same `apiKeyAuth`/`agencyAdminAuth`-only posture and never\n * `managerAuth`.\n */\n get(options: GetAgencyTripOptions): Promise<KaafilResponse<TripDirectoryRowResponse>>;\n /** That trip's manifest, for the office — see `TripManifestResource`. */\n readonly manifest: TripManifestResource;\n}\n\n// --- agencies.trips.manifest ----------------------------------------------\n\ntype ListTripManifestQuery = NonNullable<operations['listTripManifest']['parameters']['query']>;\n/** The filterable half of `listTripManifest`'s query params. Every member is\n * optional, so `{}` is valid. */\nexport type TripManifestFilters = Omit<ListTripManifestQuery, 'cursor' | 'limit'>;\n\n/**\n * Whole-set aggregates over the manifest, in the envelope's `facets` key.\n *\n * Hand-written for the same reason `AgencyTripFacets` is — the engine's\n * generator can only describe `SuccessEnvelope & { data: X }` and so cannot\n * declare the `facets` sibling the response wrapper actually sends. Kept in\n * step with `trip-directory.dto.ts#tripManifestFacetsResponseSchema` by hand.\n *\n * These describe the CURRENT FILTERED SET, unlike `AgencyTripFacets.segments`\n * which spans the whole agency: a head-count above a filtered table has to\n * describe that table.\n */\nexport interface TripManifestFacets {\n /** Rows matching the current filters, across every page. */\n readonly total: number;\n /** Head-count by booking status. Every member present, zeros included. */\n readonly byBookingStatus: {\n readonly CONFIRMED: number;\n readonly TENTATIVE: number;\n readonly CANCELLED: number;\n };\n readonly medicalCount: number;\n readonly dueCount: number;\n /**\n * Histogram over the raw, lower-cased `dietary` string — an OPEN key set,\n * because that column is free text rather than an enum. Travellers with no\n * value group under `unspecified` rather than being dropped, so these\n * always sum to `total`.\n */\n readonly dietCounts: Readonly<Record<string, number>>;\n}\n\nasync function fetchTripManifestPage(\n client: KaafilHttpClient,\n agencyRef: string,\n tripRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: TripManifestFilters;\n },\n) {\n const response = await client.execute<readonly TripManifestRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTripManifest,\n path: '/api/v1/agencies/{ref}/trips/{tripRef}/manifest',\n pathParams: { ref: agencyRef, tripRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListTripManifestOptions {\n readonly agencyRef: string;\n readonly tripRef: string;\n readonly filters?: TripManifestFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListTripManifestPageOptions extends TripManifestFilters {\n readonly agencyRef: string;\n readonly tripRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripManifestResource {\n /**\n * `GET /api/v1/agencies/{ref}/trips/{tripRef}/manifest` as a\n * `KaafilPaginator` — the office-side manifest read.\n *\n * DISTINCT FROM `travellers.listForTrip`, which is the same trip's manifest\n * for the FIELD app: that one takes no query parameters and returns the full\n * roster in one array, which is what a manager's device wants. This one is\n * filterable and paginated, and its row additionally carries `gender`,\n * `medicalFlag`, `dateOfBirth` and the traveller's `party` denormalised.\n * Neither replaces the other.\n *\n * Prefer `listPage` when you need `facets` — a paginator surfaces pages, not\n * the envelope's extras.\n */\n list(\n options: ListTripManifestOptions,\n ): KaafilPaginator<TripManifestRowResponse, TripManifestFilters>;\n /**\n * The manual single-page escape hatch for `list`, and the only way to read\n * `facets` — the head-count, booking-status split, medical count, due count\n * and diet histogram, computed over the whole FILTERED set rather than the\n * page.\n */\n listPage(\n options: ListTripManifestPageOptions,\n ): Promise<KaafilFacetedPagedResponse<readonly TripManifestRowResponse[], TripManifestFacets>>;\n}\n\n// --- agencies.settings ----------------------------------------------------\n\nexport interface ReadAgencySettingsOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchAgencySettingsOptions extends PatchAgencySettingsSelfRequest {\n readonly agencyRef: string;\n /**\n * Required, not optional — same `If-Match` contract as every other\n * version-guarded write in this SDK. Pass the `version` from a prior\n * `settings.get()`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencySettingsResource {\n /** `GET /api/v1/agencies/{ref}/settings/self` — the sibling of the\n * console's own `GET .../settings`. See this file's header, \"the sibling\n * route\" section. */\n get(options: ReadAgencySettingsOptions): Promise<KaafilResponse<AgencySettingsResponse>>;\n /** `PATCH /api/v1/agencies/{ref}/settings/self` — `agencyAdminAuth`-only.\n * See this file's header, \"the sibling route\" section. */\n patch(options: PatchAgencySettingsOptions): Promise<KaafilResponse<AgencySettingsResponse>>;\n}\n\nexport interface AgenciesResource {\n /** `PUT /api/v1/agencies/{ref}` — first sighting of `{ref}` creates the\n * agency (`created: true`); every later call re-syncs `name`/\n * `sourceUpdatedAt` on the existing row (`created: false`). */\n upsert(options: UpsertAgencyOptions): Promise<KaafilResponse<AgencyUpsertResponse>>;\n readonly managers: AgencyManagersResource;\n /** The agency's trip list and per-trip console read — the only\n * trip-collection surface an agency admin can reach. */\n readonly trips: AgencyTripsResource;\n /** The agency's own operational settings document — see this file's\n * header, \"the sibling route\" section. */\n readonly settings: AgencySettingsResource;\n}\n\nexport function createAgenciesResource(client: KaafilHttpClient): AgenciesResource {\n return {\n async upsert(options) {\n const { agencyRef, idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n const body: UpsertAgencyRequest = {\n ...rest,\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n };\n return client.execute<AgencyUpsertResponse>({\n method: 'PUT',\n operationId: OperationId.UpsertAgency,\n path: '/api/v1/agencies/{ref}',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n managers: {\n list(options) {\n const { agencyRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchAgencyManagersPage(client, agencyRef, request),\n filters: filters ?? {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { agencyRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly ManagerListRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListAgencyManagers,\n path: '/api/v1/agencies/{ref}/managers',\n pathParams: { ref: agencyRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n async get(options) {\n const { agencyRef, managerRef, signal } = options;\n return client.execute<ManagerAgencyProfileResponse>({\n method: 'GET',\n operationId: OperationId.GetManagerAgencyProfile,\n path: '/api/v1/agencies/{ref}/managers/{managerRef}',\n pathParams: { ref: agencyRef, managerRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n trips: {\n list(options) {\n const { agencyRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchAgencyTripsPage(client, agencyRef, request),\n filters: filters ?? {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { agencyRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly TripDirectoryRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListAgencyTrips,\n path: '/api/v1/agencies/{ref}/trips',\n pathParams: { ref: agencyRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response) as KaafilFacetedPagedResponse<\n readonly TripDirectoryRowResponse[],\n AgencyTripFacets\n >;\n },\n async get(options) {\n const { agencyRef, tripRef, signal } = options;\n return client.execute<TripDirectoryRowResponse>({\n method: 'GET',\n operationId: OperationId.GetAgencyTrip,\n path: '/api/v1/agencies/{ref}/trips/{tripRef}',\n pathParams: { ref: agencyRef, tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n manifest: {\n list(options) {\n const { agencyRef, tripRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchTripManifestPage(client, agencyRef, tripRef, request),\n filters: filters ?? {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { agencyRef, tripRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly TripManifestRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTripManifest,\n path: '/api/v1/agencies/{ref}/trips/{tripRef}/manifest',\n pathParams: { ref: agencyRef, tripRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response) as KaafilFacetedPagedResponse<\n readonly TripManifestRowResponse[],\n TripManifestFacets\n >;\n },\n },\n },\n\n settings: {\n async get(options) {\n const { agencyRef, signal } = options;\n return client.execute<AgencySettingsResponse>({\n method: 'GET',\n operationId: OperationId.GetAgencySettingsSelf,\n path: '/api/v1/agencies/{ref}/settings/self',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { agencyRef, version, signal, ...body } = options;\n return client.execute<AgencySettingsResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchAgencySettingsSelf,\n path: '/api/v1/agencies/{ref}/settings/self',\n pathParams: { ref: agencyRef },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `agencyAdmins` — the agency admin roster (dual-mode identity). One\n * operation, `upsertAgencyAdmin` (`POST /api/v1/agency-admins`),\n * `apiKeyAuth`-only in the spec (`../generated/security.ts`'s\n * `OPERATION_SECURITY`) — the same ingest credential `PUT\n * /api/v1/agencies/{ref}` and every other `trip-ingest` write use.\n * LWW: `sourceUpdatedAt` is REQUIRED, with no \"defaults to now\", for the\n * same staleness-detection reason as every other last-write-wins field in\n * this SDK (see `agencies.ts`'s `UpsertAgencyOptions`) — a push whose\n * stamp is not newer than the stored one comes back `200` with\n * `verdict: ignored_stale`, never a `409`.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype UpsertAgencyAdminRequest = components['schemas']['UpsertAgencyAdminRequest'];\ntype AgencyAdminResponse = components['schemas']['AgencyAdminResponse'];\n\nexport interface UpsertAgencyAdminOptions\n extends Omit<UpsertAgencyAdminRequest, 'sourceUpdatedAt'> {\n /** The CRM's own record-updated timestamp — required, no \"defaults to\n * now\". See this file's header for why. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencyAdminsResource {\n /** `POST /api/v1/agency-admins` — dual-mode identity: first sighting of\n * `externalAgencyAdminId` (or an omitted one) mints a new admin\n * (`created: true`); a later call re-syncs the existing row\n * (`created: false`). */\n upsert(options: UpsertAgencyAdminOptions): Promise<KaafilResponse<AgencyAdminResponse>>;\n}\n\nexport function createAgencyAdminsResource(client: KaafilHttpClient): AgencyAdminsResource {\n return {\n async upsert(options) {\n const { idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n const body: UpsertAgencyAdminRequest = {\n ...rest,\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n };\n return client.execute<AgencyAdminResponse>({\n method: 'POST',\n operationId: OperationId.UpsertAgencyAdmin,\n path: '/api/v1/agency-admins',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `auth` — minting a manager session or an agency-admin session.\n * `architecture/08-sdk.md §3.2, §4`.\n *\n * Rotation is deliberately absent as a public method for either kind:\n * `../auth/credentials.ts` calls each kind's own refresh endpoint itself,\n * pre-emptively and reactively, as part of resolving every request's\n * credential — a consumer never calls it directly (this wave's governing\n * principle: the SDK does the refresh, the consumer only ever hands the SDK\n * the tokens it was given).\n *\n * `08-sdk.md §4`'s table also lists a `revoke` method for this group. No such\n * operation exists anywhere in the vendored spec: the `Auth` tag in\n * `openapi/openapi.json` names exactly four operations —\n * `mintManagerTokens`, `refreshManagerTokens`, `mintAgencyAdminTokens`,\n * `refreshAgencyAdminTokens` (verified via `jq '.paths[][] | select(.tags ==\n * [\"Auth\"]) | .operationId'`) — and the two `refresh*` ones are the\n * resolver's job, not a public method here. Per this lane's brief — \"if this\n * list and the spec disagree, the spec wins, and you say so\" — no `revoke`\n * method ships. Flagged here rather than silently dropped.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype MintManagerTokenRequest = components['schemas']['MintManagerTokensRequest'];\ntype ManagerSessionResponse = components['schemas']['ManagerSessionResponse'];\ntype MintAgencyAdminTokenRequest = components['schemas']['MintAgencyAdminTokensRequest'];\ntype AgencyAdminSessionResponse = components['schemas']['AgencyAdminSessionResponse'];\n\nexport interface MintManagerTokenOptions extends MintManagerTokenRequest {\n readonly signal?: AbortSignal;\n}\n\nexport interface MintAgencyAdminTokenOptions extends MintAgencyAdminTokenRequest {\n readonly signal?: AbortSignal;\n}\n\nexport interface AuthResource {\n /**\n * `POST /api/v1/auth/manager-tokens` — opens a manager session. Server-side\n * only (API key; `mintManagerTokens` accepts only `apiKeyAuth`). The\n * returned `refreshToken` is shown exactly once, here and at every\n * subsequent rotation — hand `accessToken`, `refreshToken`, and\n * `expiresAt` straight to a `managerSession`-credentialed client\n * (`../auth/credentials.ts`'s `ManagerSessionCredentialConfig`, or the\n * browser entry's `session.open(...)`).\n *\n * Not idempotent — no `idempotencyKey` field on this options type — by the\n * operation's own design (`refreshManagerTokens`'s response carries a\n * plaintext refresh token; replaying it from an idempotency cache would\n * mean persisting that secret, which the hash-only refresh-token storage\n * rule forbids). A caller that loses this response to a network error\n * simply mints again.\n */\n mintManagerToken(\n options: MintManagerTokenOptions,\n ): Promise<KaafilResponse<ManagerSessionResponse>>;\n /**\n * `POST /api/v1/auth/agency-admin-tokens` — opens an agency-admin session,\n * the agency-admin analogue of `mintManagerToken` above. Server-side only\n * (API key; `mintAgencyAdminTokens` accepts only `apiKeyAuth`) — hand the\n * response's `accessToken`, `refreshToken`, and `expiresAt` straight to an\n * `agencyAdmin`-credentialed client (`../auth/credentials.ts`'s\n * `AgencyAdminCredentialConfig`, or the browser entry's `admin.open(...)`).\n *\n * Not idempotent, for the same reason as `mintManagerToken`: the response\n * carries a plaintext refresh token, and the hash-only refresh-token\n * storage rule forbids persisting one in an idempotency cache to replay.\n */\n mintAgencyAdminToken(\n options: MintAgencyAdminTokenOptions,\n ): Promise<KaafilResponse<AgencyAdminSessionResponse>>;\n}\n\nexport function createAuthResource(client: KaafilHttpClient): AuthResource {\n return {\n async mintManagerToken(options) {\n const { signal, ...body } = options;\n return client.execute<ManagerSessionResponse>({\n method: 'POST',\n operationId: OperationId.MintManagerTokens,\n path: '/api/v1/auth/manager-tokens',\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async mintAgencyAdminToken(options) {\n const { signal, ...body } = options;\n return client.execute<AgencyAdminSessionResponse>({\n method: 'POST',\n operationId: OperationId.MintAgencyAdminTokens,\n path: '/api/v1/auth/agency-admin-tokens',\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `bookings` — a trip's third-party reservations (accommodation, transport,\n * activity), pushed by the CRM and read back by a manager. `architecture/08-\n * sdk.md §4`. `bulkUpsert`/`delete` are `apiKeyAuth`-only (CRM-backend\n * ingest, the same reason `trips.ts`'s whole module is). Two operations are\n * wider, and this header used to claim otherwise:\n *\n * `list` `apiKeyAuth` | `managerAuth` | `agencyAdminAuth`\n * `vouchers.replace` `apiKeyAuth` | `agencyAdminAuth`\n *\n * The ground team still only READS what the CRM pushed. The desk reads too,\n * and may point a booking at a voucher file — the one write it has here —\n * because a CRM that never pushed the voucher otherwise left the desk\n * holding a document with no way to attach it. Creating, editing or removing\n * a booking remains the CRM's alone.\n *\n * `vouchers.replace` is a FULL-ARRAY REPLACE (R6), which matters more now\n * that a browser can call it: send the complete set every time, including\n * keys already attached. A client that sends only its new key DETACHES every\n * voucher the CRM had attached.\n *\n * ── `bulkUpsert`'S ITEM SHAPE IS HAND-TYPED, NOT GENERATED ──────────────────\n *\n * `BulkUpsertBookingsRequest` is declared in the vendored spec as a bare\n * `{ propertyNames: string; additionalProperties: {} }[]` — an opaque array\n * of untyped objects, unlike `trips.ts`'s `PushBulkTripsRequest` (a real,\n * fully-typed item schema this SDK indexes off of with\n * `components['schemas']['PushBulkTripsRequest'][number]`). There is no\n * generated item type to index off here, so `BulkUpsertBookingItem` below is\n * hand-typed from `BookingResponse` instead (every field the engine echoes\n * back, minus the four it derives itself: `id`, `version`, `createdAt`,\n * `updatedAt`). If the engine ever tightens `BulkUpsertBookingsRequest` to a\n * real item schema, this hand-typed shape should be re-verified against it\n * rather than assumed still correct.\n *\n * `kind` is typed off `BookingResponse['kind']` for the same reason —\n * `ACCOMMODATION|TRANSPORT|ACTIVITY` never appears in ANY request-body\n * schema this spec declares (the bulk item is opaque, so `scripts/gen-\n * meta.mjs`'s request-enum walk never reaches it), so there is no\n * `../generated/enums.ts` runtime constant for it the way `FormFieldKind`\n * or `MessageChannel` get one; a caller compares against the literal\n * strings, or against `BookingResponse.kind` read back from `list()`.\n *\n * `externalBookingId` + `sourceUpdatedAt` is the same last-write-wins pair\n * `trips.ts`'s bulk push uses — `sourceUpdatedAt` is required, with no\n * \"defaults to now\", for the identical reason: defaulting it would make\n * every write look like the newest one and defeat out-of-order staleness\n * detection. Per-item `verdict` on the response\n * (`applied`/`ignored_stale`/`rejected`) reports which of the three\n * happened; `errorCode`/`message` are populated only for `rejected`.\n *\n * `list`'s rows may be a live booking OR the tombstone shape (`_tombstone:\n * true`) for one deleted since `?since=` — the same delta shape\n * `itinerary`/`pickups`/`checklists` already use.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype BookingResponse = components['schemas']['BookingResponse'];\ntype BulkUpsertResponse = components['schemas']['BulkUpsertResponse'];\ntype ListBookingsResponse = components['schemas']['ListBookingsResponse'];\ntype BookingDeleteResponse = components['schemas']['BookingDeleteResponse'];\ntype ReplaceBookingVouchersRequest = components['schemas']['ReplaceBookingVouchersRequest'];\n\n/** `BookingResponse.kind` — see this file's header for why this is a type\n * alias off the response, not a `../generated/enums.ts` runtime constant. */\nexport type BookingKind = BookingResponse['kind'];\n\n/** One row of `list`'s response: a live booking, or the tombstone for one\n * deleted since the cursor. See this file's header. */\nexport type BookingListRow = ListBookingsResponse[number];\n\ntype ListBookingsQuery = NonNullable<operations['listBookings']['parameters']['query']>;\n/** The filterable half of `list`'s query params — `since` is the delta\n * cursor and is passed as its own option, never bundled in here. */\nexport type BookingFilters = Omit<ListBookingsQuery, 'since'>;\n\n// --- bookings.bulkUpsert ---------------------------------------------------\n\n/**\n * One item of `bulkUpsert`'s array body. Hand-typed off `BookingResponse` —\n * see this file's header for why there is no generated request-item type to\n * extend instead.\n */\nexport interface BulkUpsertBookingItem {\n readonly externalBookingId: string;\n readonly kind: BookingKind;\n readonly title: string;\n readonly confirmationRef?: string | null;\n readonly startAt: DateTimeInput;\n readonly endAt?: DateTimeInput | null;\n readonly providerName?: string | null;\n readonly providerPhone?: string | null;\n readonly locationText?: string | null;\n readonly details?: Readonly<Record<string, unknown>> | null;\n readonly voucherFileKeys?: readonly string[];\n /** The CRM's own record-updated timestamp — required, no \"defaults to\n * now\". See this file's header for why. */\n readonly sourceUpdatedAt: DateTimeInput;\n}\n\nexport interface BulkUpsertBookingsOptions {\n readonly tripRef: string;\n readonly items: readonly BulkUpsertBookingItem[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- bookings.list ----------------------------------------------------------\n\nexport interface ListBookingsOptions extends BookingFilters {\n readonly tripRef: string;\n /** The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit for the full live set. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand, same as every other\n * delta read in this SDK. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- bookings.delete / bookings.vouchers -----------------------------------\n\nexport interface DeleteBookingOptions {\n readonly tripRef: string;\n readonly bookingRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReplaceBookingVouchersOptions extends ReplaceBookingVouchersRequest {\n readonly tripRef: string;\n readonly bookingRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface BookingVouchersResource {\n /** `PATCH /api/v1/trips/{ref}/bookings/{bookingRef}/vouchers` — replaces\n * the FULL `voucherFileKeys` list; there is no add/remove-one call. Each\n * key must resolve to a `ready` file (`files.*`) with `purpose:\n * 'booking_voucher'` — an unconfirmed or wrong-purpose key is\n * `422 VALIDATION_ERROR`. */\n replace(options: ReplaceBookingVouchersOptions): Promise<KaafilResponse<BookingResponse>>;\n}\n\n// --- bookings ----------------------------------------------------------------\n\nexport interface BookingsResource {\n /**\n * `POST /api/v1/trips/{ref}/bookings` — up to 2000 items per call. See\n * this file's header for the item shape, the last-write-wins pair, and\n * the per-item `verdict`. A partial failure never fails the whole call —\n * inspect `items[].verdict`/`errorCode` on the response, never a thrown\n * error, to find a `rejected` row.\n */\n bulkUpsert(options: BulkUpsertBookingsOptions): Promise<KaafilResponse<BulkUpsertResponse>>;\n /** `GET /api/v1/trips/{ref}/bookings` — optionally filtered by `kind`. See\n * this file's header for the delta-cursor semantics and the tombstone row\n * shape. */\n list(options: ListBookingsOptions): Promise<KaafilResponse<ListBookingsResponse>>;\n /** `DELETE /api/v1/trips/{ref}/bookings/{bookingRef}` — `bookingRef` is a\n * dual-mode ref (Kaafil id or the CRM's `externalBookingId`), same as\n * every other `ref` in this SDK. */\n delete(options: DeleteBookingOptions): Promise<KaafilResponse<BookingDeleteResponse>>;\n readonly vouchers: BookingVouchersResource;\n}\n\nexport function createBookingsResource(client: KaafilHttpClient): BookingsResource {\n return {\n async bulkUpsert(options) {\n const { tripRef, items, idempotencyKey, signal } = options;\n const body = items.map((item, index) => {\n const { startAt, endAt, sourceUpdatedAt, ...rest } = item;\n return {\n ...rest,\n startAt: normalizeDateTimeInput(startAt, `items[${index}].startAt`),\n ...(endAt !== undefined\n ? {\n endAt:\n endAt === null ? null : normalizeDateTimeInput(endAt, `items[${index}].endAt`),\n }\n : {}),\n sourceUpdatedAt: normalizeDateTimeInput(\n sourceUpdatedAt,\n `items[${index}].sourceUpdatedAt`,\n ),\n };\n });\n return client.execute<BulkUpsertResponse>({\n method: 'POST',\n operationId: OperationId.BulkUpsertBookings,\n path: '/api/v1/trips/{ref}/bookings',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { tripRef, since, signal, ...filters } = options;\n return client.execute<ListBookingsResponse>({\n method: 'GET',\n operationId: OperationId.ListBookings,\n path: '/api/v1/trips/{ref}/bookings',\n pathParams: { ref: tripRef },\n query: { ...filters, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async delete(options) {\n const { tripRef, bookingRef, idempotencyKey, signal } = options;\n return client.execute<BookingDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteBooking,\n path: '/api/v1/trips/{ref}/bookings/{bookingRef}',\n pathParams: { ref: tripRef, bookingRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n vouchers: {\n async replace(options) {\n const { tripRef, bookingRef, signal, ...body } = options;\n return client.execute<BookingResponse>({\n method: 'PATCH',\n operationId: OperationId.ReplaceBookingVouchers,\n path: '/api/v1/trips/{ref}/bookings/{bookingRef}/vouchers',\n pathParams: { ref: tripRef, bookingRef },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `checklists` — sections, items, toggle, and the agency's reusable template\n * library. `architecture/08-sdk.md §4`. `checklists` FRD §3, RULES R1–R14,\n * `D-029` (pull-template copy semantics), `modules/checklists/checklists\n * .routes.ts`'s own header (the source of every auth/lock line below).\n *\n * `read` and `templates.list` accept a manager session OR an API key; every\n * WRITE (`items.add/patch/remove/toggle`, `templates.pull`) is\n * `managerAuth`-only — admin template CONFIG (`POST/PATCH` against the\n * library itself) does not exist yet (`checklists.routes.ts`'s \"ADMIN\n * TEMPLATE CONFIG IS DEFERRED\" note), so there is no write here an API key\n * could ever reach even in principle. Every write also declares\n * `closeoutLock: 'ref'` engine-side — a write racing trip close-out answers\n * `423 LOCKED` (`KaafilLockedError`), terminal, never retried.\n *\n * ── FOUR QUIRKS A CONSUMER WILL OTHERWISE GET WRONG ─────────────────────────\n *\n * 1. **`toggle`'s concurrency guard is on the item's STATUS, not its\n * `version`.** Every OTHER version-guarded write in this API takes an\n * `If-Match`/`version` and answers `409 CONFLICT_VERSION` with\n * `details.currentVersion` on staleness. `toggle` takes `expectedStatus`\n * in the BODY instead, and a stale value still answers\n * `409 CONFLICT_VERSION` — same code, `KaafilVersionConflictError` still\n * catches it — but the payload carries `details.currentStatus`, never\n * `details.currentVersion`. Reading `.currentVersion` off the caught\n * error here is silently `undefined`; read `error.details?.currentStatus`\n * (typed `ChecklistItemStatus`) instead. This file does not add a second\n * getter to `KaafilVersionConflictError` for it — `../http/errors.ts`'s\n * own header states the bar for a code-specific getter, and one class per\n * code that merely carries an unusual `details` shape is exactly what\n * that bar exists to avoid.\n * 2. **A `COMPLETE` item cannot be deleted.** `items.remove` on a `COMPLETE`\n * item answers `422 BUSINESS_RULE_VIOLATION` with\n * `details.rule: 'item_complete_delete_blocked'` — un-toggle it first.\n * Not a module-local code: the FRD only describes the refusal, never\n * names it as an identity a client branches on, so it never got minted\n * one (`checklists.constants.ts`'s own line on the point).\n * 3. **`templates.pull` COPIES (`D-029`).** Both `append` and `replace`\n * write TRIP-OWNED rows; neither creates a live link. A template edited\n * AFTER a pull never reaches the trip's copy, and an edit to the trip's\n * copy never reaches the template. `sourceSectionId` on the pulled\n * section is the only trace of where it came from, stamped once, on\n * first pull only — a second pull of the same template onto a section\n * that already exists never rewrites it.\n * 4. **Editing an item's `phase` RE-DERIVES its `gate`, unless `gate` is\n * sent in the SAME request.** `phase` is a hint only — `ChecklistItem`\n * has no `phase` column (phase is the SECTION's) — so `items.patch` never\n * echoes it back on the response, and an explicit `gate` in the same call\n * always wins over the fixed phase→gate map.\n * 5. **A `DRAFT` agency template (GAP-004) is invisible to\n * `templates.list`/`templates.pull`.** `ChecklistTemplateSectionResponse\n * .status ∈ DRAFT|PUBLISHED`; a new `agencyTemplates.create` starts\n * `DRAFT` and stays that way until `agencyTemplates.publish` flips it.\n * Only `agencyTemplates.list` (the authoring library) shows both; the\n * trip-facing `templates.list`/`templates.pull` see `PUBLISHED` only.\n *\n * Beyond those four: the aggregate's `sections[]` is always the FULL live\n * set (a trip's sections are a handful); `items[]` is the ONLY delta axis —\n * `?since=` narrows it, with a deletion arriving as the same tombstone shape\n * `itinerary`/`pickups` already use. `progress` and `hasOpenMandatoryByPhase`\n * are always computed over the full live set, independent of `?since=`. The\n * four reserved sections (`medical`/`documents`/`logistics`/`handover`) are\n * seeded at TRIP-INGEST, inside the upsert transaction — never by this\n * read — so a fresh trip's `read()` already carries them on its very first\n * call; there is no seed-on-read call to make or race against.\n *\n * ── THE SIX `console`-PLANE READS ARE NOT IN THIS PACKAGE ───────────────────\n *\n * `GET /api/v1/console/trips/{ref}/checklist` (`readConsoleChecklist`) and\n * its five siblings (`listConsoleTrips`, `…/itinerary`, `…/rooming`,\n * `…/seating`, `…/pickups`) exist in the vendored spec and are excluded from\n * this SDK on purpose — the same decision `../auth/credentials.ts` and\n * `webhooks.ts` already state for `consoleAuth` generally. They authenticate\n * with a console session cookie (`consoleAuth`), which is the partner\n * console's OWN administrative UI's credential, never something a CRM\n * integrating this package holds — a partner API key satisfies none of\n * `readConsoleChecklist`'s `security` alternatives (there is only one:\n * `consoleAuth`), so a method wrapping it would be uncallable by every\n * consumer of this package. `scripts/gen-meta.mjs`'s\n * `nonIntegrationRequestSchemaNames` already enforces the analogous exclusion\n * for request-body enums reachable only from a console/platform path; this\n * resource file is the read-side statement of the identical decision. If a\n * console read ever gains a second, API-key-satisfiable security\n * alternative, that is a spec change this SDK would need to notice and\n * decide about again — not something to pre-empt here.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype ChecklistAggregateResponse = components['schemas']['ChecklistAggregateResponse'];\ntype ChecklistItemResponse = components['schemas']['ChecklistItemResponse'];\ntype DeleteItemResponse = components['schemas']['DeleteItemResponse'];\ntype ToggleResponse = components['schemas']['ToggleResponse'];\ntype TemplatesListResponse = components['schemas']['TemplatesListResponse'];\ntype AddChecklistItemRequest = components['schemas']['AddChecklistItemRequest'];\ntype PatchChecklistItemRequest = components['schemas']['PatchChecklistItemRequest'];\ntype ToggleChecklistItemRequest = components['schemas']['ToggleChecklistItemRequest'];\ntype PullChecklistTemplateRequest = components['schemas']['PullChecklistTemplateRequest'];\ntype ChecklistTemplateAdminListResponse =\n components['schemas']['ChecklistTemplateAdminListResponse'];\ntype ChecklistTemplateSectionResponse = components['schemas']['ChecklistTemplateSectionResponse'];\ntype DeleteChecklistTemplateResponse = components['schemas']['DeleteChecklistTemplateResponse'];\ntype CreateChecklistTemplateRequest = components['schemas']['CreateChecklistTemplateRequest'];\ntype PatchChecklistTemplateRequest = components['schemas']['PatchChecklistTemplateRequest'];\n\n/**\n * One row of `read`'s `items[]`: a live item, or the tombstone for one\n * deleted since the cursor. Aliased off the response type, never restated —\n * `itinerary.ts#ItineraryItemDeltaRow`'s own reasoning applies verbatim.\n */\nexport type ChecklistItemDeltaRow = ChecklistAggregateResponse['items'][number];\n\n// --- checklists.read ---------------------------------------------------------\n\nexport interface ReadChecklistOptions {\n readonly tripRef: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit for the full aggregate — `sections[]` and the two\n * progress figures are always full regardless; only `items[]` narrows.\n * Prefer `createDeltaCursor` (`../delta/cursor.ts`) over passing this by\n * hand, same as every other delta read in this SDK.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- checklists.items ---------------------------------------------------------\n\nexport interface AddChecklistItemOptions extends AddChecklistItemRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchChecklistItemOptions extends PatchChecklistItemRequest {\n readonly tripRef: string;\n readonly itemId: string;\n /**\n * Required, not optional — `itinerary.ts#PatchItineraryItemOptions\n * .version`'s own argument for why a missing `If-Match` and a stale one\n * answering the identical `409 CONFLICT_VERSION` means this SDK should\n * make forgetting it impossible rather than merely discouraged. Pass the\n * `version` from the item as last read; the SDK builds the `If-Match`\n * header itself. NOT the same guard as `toggle`'s `expectedStatus` — see\n * this file's header, quirk 1.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface GetChecklistItemOptions {\n readonly tripRef: string;\n readonly itemId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteChecklistItemOptions {\n readonly tripRef: string;\n readonly itemId: string;\n /** See `PatchChecklistItemOptions.version` — same contract. Refused with\n * `422 BUSINESS_RULE_VIOLATION` while the item is `COMPLETE` — this file's\n * header, quirk 2. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ToggleChecklistItemOptions extends ToggleChecklistItemRequest {\n readonly tripRef: string;\n readonly itemId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ChecklistItemsResource {\n /**\n * `GET …/checklist/items/{itemId}` — one item's current state, without\n * pulling the whole trip aggregate. Same read auth as `read()` above\n * (a manager session or an API key), not the write triple the other four\n * methods on this resource use.\n */\n get(options: GetChecklistItemOptions): Promise<KaafilResponse<ChecklistItemResponse>>;\n /**\n * `POST …/checklist/items` — auto-creates the section when `sectionKey`\n * is new FOR THIS TRIP (taking `sectionTitle`/`audience` as the new\n * section's display; both are ignored on an already-existing section). An\n * omitted `key` is slugged from `title` and de-duplicated within the\n * section; an explicit colliding `key` is `422 VALIDATION_ERROR`, never a\n * silent rename. `gate` is derived from the section's `phase` — the\n * create body carries no `gate` of its own.\n */\n add(options: AddChecklistItemOptions): Promise<KaafilResponse<ChecklistItemResponse>>;\n /** See this file's header, quirk 4 — a `phase` sent here without an\n * explicit `gate` re-derives the item's `gate`. */\n patch(options: PatchChecklistItemOptions): Promise<KaafilResponse<ChecklistItemResponse>>;\n /** See this file's header, quirk 2. */\n remove(options: DeleteChecklistItemOptions): Promise<KaafilResponse<DeleteItemResponse>>;\n /**\n * `POST …/checklist/items/{itemId}/toggle` — flips OPEN↔COMPLETE. See\n * this file's header, quirk 1, before catching `KaafilVersionConflictError`\n * off this call. Returns the updated item PLUS its section's and the\n * trip's own progress, so a caller patches its local state without a\n * refetch. `checklist.item_completed` fires on every `OPEN → COMPLETE`\n * transition; `checklist.completed` fires additionally when it was the\n * LAST mandatory item trip-wide. `COMPLETE → OPEN` emits nothing.\n */\n toggle(options: ToggleChecklistItemOptions): Promise<KaafilResponse<ToggleResponse>>;\n}\n\n// --- checklists.templates ------------------------------------------------------\n\nexport interface ListChecklistTemplatesOptions {\n readonly tripRef: string;\n /** Default `\"en\"`, with `\"en\"` fallback on no exact match. */\n readonly locale?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PullChecklistTemplateOptions extends PullChecklistTemplateRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ChecklistTemplatesResource {\n /** `GET …/checklist/templates` — the agency's library (`tripId` is\n * `null`), resolved to `?locale=`. `lastUsedAt` is `null` until this\n * template is pulled onto some trip, or the pull marker has expired. */\n list(options: ListChecklistTemplatesOptions): Promise<KaafilResponse<TemplatesListResponse>>;\n /** See this file's header, quirk 3 — COPY semantics, never a live link.\n * Returns the FULL new aggregate (cold, no `?since=`) for atomic\n * replacement. */\n pull(options: PullChecklistTemplateOptions): Promise<KaafilResponse<ChecklistAggregateResponse>>;\n}\n\n// --- checklists.agencyTemplates -------------------------------------------------\n//\n// The AGENCY-level template library itself (`GET/POST/PATCH/DELETE\n// /api/v1/agencies/{ref}/checklist-templates[/{id}[/publish]]`) — distinct\n// from `templates` above, which is trip-scoped (`.../trips/{ref}/checklist\n// /templates`) and read/pull only. `list`/`create`/`patch`/`remove`/`publish`\n// here ALL accept the same pair, an API key OR an agency-admin session,\n// never `managerAuth` — the \"ADMIN TEMPLATE CONFIG IS DEFERRED\" note this\n// file's header cites for `templates` was about the TRIP-scoped surface\n// only; the agency-scoped CRUD below is a separate, already-shipped route\n// group. `publish` (GAP-004) is the DRAFT→PUBLISHED transition — see\n// `AgencyChecklistTemplatesResource.publish`'s own doc comment.\n\nexport interface ListAgencyChecklistTemplatesOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CreateAgencyChecklistTemplateOptions extends CreateChecklistTemplateRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchAgencyChecklistTemplateOptions extends PatchChecklistTemplateRequest {\n readonly agencyRef: string;\n readonly templateId: string;\n /**\n * Required, not optional — same `If-Match` contract as\n * `PatchChecklistItemOptions.version`. Pass the `version` from the\n * template as last read; the SDK builds the `If-Match` header itself.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteAgencyChecklistTemplateOptions {\n readonly agencyRef: string;\n readonly templateId: string;\n /** See `PatchAgencyChecklistTemplateOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface PublishAgencyChecklistTemplateOptions {\n readonly agencyRef: string;\n readonly templateId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AgencyChecklistTemplatesResource {\n /** `GET /api/v1/agencies/{ref}/checklist-templates` — the agency's full\n * template library, across every locale. */\n list(\n options: ListAgencyChecklistTemplatesOptions,\n ): Promise<KaafilResponse<ChecklistTemplateAdminListResponse>>;\n /** `POST /api/v1/agencies/{ref}/checklist-templates`. */\n create(\n options: CreateAgencyChecklistTemplateOptions,\n ): Promise<KaafilResponse<ChecklistTemplateSectionResponse>>;\n /** `PATCH /api/v1/agencies/{ref}/checklist-templates/{id}` — `items`, when\n * sent, is the FULL replacement list, not a delta. */\n patch(\n options: PatchAgencyChecklistTemplateOptions,\n ): Promise<KaafilResponse<ChecklistTemplateSectionResponse>>;\n /** `DELETE /api/v1/agencies/{ref}/checklist-templates/{id}`. */\n remove(\n options: DeleteAgencyChecklistTemplateOptions,\n ): Promise<KaafilResponse<DeleteChecklistTemplateResponse>>;\n /**\n * `POST /api/v1/agencies/{ref}/checklist-templates/{id}/publish` (GAP-004)\n * — moves a template `DRAFT` → `PUBLISHED`. Bodiless, no `If-Match`. A\n * `DRAFT` template is excluded from `templates.pull` and from the\n * manager-facing `templates.list`; only `PUBLISHED` is visible on either.\n * `create` above has no `status` field on its request — every new template\n * starts `DRAFT`, and this is the only way to flip it.\n */\n publish(\n options: PublishAgencyChecklistTemplateOptions,\n ): Promise<KaafilResponse<ChecklistTemplateSectionResponse>>;\n}\n\n// --- checklists ----------------------------------------------------------------\n\nexport interface ChecklistsResource {\n /** `GET …/trips/{ref}/checklist` — the full aggregate: sections, items,\n * both progress figures, and the agency's available templates. A PURE\n * READ — it never seeds; the four reserved sections are already present\n * by trip-ingest time (this file's header). */\n read(options: ReadChecklistOptions): Promise<KaafilResponse<ChecklistAggregateResponse>>;\n readonly items: ChecklistItemsResource;\n readonly templates: ChecklistTemplatesResource;\n /** The agency-level template library — see this file's `checklists\n * .agencyTemplates` section header for how it differs from `templates`. */\n readonly agencyTemplates: AgencyChecklistTemplatesResource;\n}\n\nexport function createChecklistsResource(client: KaafilHttpClient): ChecklistsResource {\n return {\n async read(options) {\n const { tripRef, since, signal } = options;\n return client.execute<ChecklistAggregateResponse>({\n method: 'GET',\n operationId: OperationId.ReadChecklistAggregate,\n path: '/api/v1/trips/{ref}/checklist',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n items: {\n async get(options) {\n const { tripRef, itemId, signal } = options;\n return client.execute<ChecklistItemResponse>({\n method: 'GET',\n operationId: OperationId.ReadChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async add(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<ChecklistItemResponse>({\n method: 'POST',\n operationId: OperationId.AddChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, itemId, version, signal, ...body } = options;\n return client.execute<ChecklistItemResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, itemId, version, signal } = options;\n return client.execute<DeleteItemResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async toggle(options) {\n const { tripRef, itemId, idempotencyKey, signal, ...body } = options;\n return client.execute<ToggleResponse>({\n method: 'POST',\n operationId: OperationId.ToggleChecklistItem,\n path: '/api/v1/trips/{ref}/checklist/items/{itemId}/toggle',\n pathParams: { ref: tripRef, itemId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n templates: {\n async list(options) {\n const { tripRef, locale, signal } = options;\n return client.execute<TemplatesListResponse>({\n method: 'GET',\n operationId: OperationId.ListChecklistTemplates,\n path: '/api/v1/trips/{ref}/checklist/templates',\n pathParams: { ref: tripRef },\n query: { locale },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async pull(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<ChecklistAggregateResponse>({\n method: 'POST',\n operationId: OperationId.PullChecklistTemplate,\n path: '/api/v1/trips/{ref}/checklist/pull-template',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n agencyTemplates: {\n async list(options) {\n const { agencyRef, signal } = options;\n return client.execute<ChecklistTemplateAdminListResponse>({\n method: 'GET',\n operationId: OperationId.ListChecklistTemplatesAdmin,\n path: '/api/v1/agencies/{ref}/checklist-templates',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<ChecklistTemplateSectionResponse>({\n method: 'POST',\n operationId: OperationId.CreateChecklistTemplate,\n path: '/api/v1/agencies/{ref}/checklist-templates',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { agencyRef, templateId, version, signal, ...body } = options;\n return client.execute<ChecklistTemplateSectionResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchChecklistTemplate,\n path: '/api/v1/agencies/{ref}/checklist-templates/{id}',\n pathParams: { ref: agencyRef, id: templateId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { agencyRef, templateId, version, signal } = options;\n return client.execute<DeleteChecklistTemplateResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteChecklistTemplate,\n path: '/api/v1/agencies/{ref}/checklist-templates/{id}',\n pathParams: { ref: agencyRef, id: templateId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async publish(options) {\n const { agencyRef, templateId, signal } = options;\n return client.execute<ChecklistTemplateSectionResponse>({\n method: 'POST',\n operationId: OperationId.PublishChecklistTemplate,\n path: '/api/v1/agencies/{ref}/checklist-templates/{id}/publish',\n pathParams: { ref: agencyRef, id: templateId },\n body: {},\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `closeout` — the closing day: what is still open, the handover note, the\n * lock that freezes the trip, the admin-only reopen, and the printed pack.\n * Five operations over `/api/v1/trips/{ref}/closeout*`.\n *\n * ── `get()`'s `?since=` IS NOT A DELTA CURSOR ───────────────────────────────\n *\n * It looks like every other `?since=` in this SDK and it is not one. The\n * aggregate is fully DERIVED — `blockers[]` is recomputed from ten modules on\n * every read and stored nowhere, so there is no `updatedAt` to window and no\n * tombstone to emit. The body is therefore ALWAYS whole and always\n * authoritative, cursor or no cursor. `?since=` narrows nothing; it answers\n * exactly one extra question, in exactly one extra field: did the STORED\n * record — the handover note, the lock, the reopen — move since that instant?\n * (`recordChangedSince`, `null` when no cursor was sent.)\n *\n * Two consequences, both easy to get wrong:\n *\n * 1. Do NOT feed this through `createDeltaCursor` (`../delta/cursor.ts`).\n * That helper merges narrowed rows into a local set and applies\n * tombstones; here it would be merging a full body into itself every\n * pull. Pass `since` by hand — a previous response's `meta.serverTime`,\n * the same value every other cursor in this SDK uses — or omit it.\n * 2. `recordChangedSince: false` does NOT mean \"nothing changed\". A balance\n * ingested a second ago moves `blockers[]` and `canLock` without touching\n * the stored row at all. It is a narrow claim about one record, and a\n * client that reads it as \"safe to skip the re-render\" will leave a lock\n * button greyed out after it has gone live.\n *\n * ── THE TWO VERSION GUARDS ARE BODY FIELDS, NOT `If-Match` ─────────────────\n *\n * Unlike `checklists.items.patch` / `expenses.void` / `collections.void`,\n * which carry their optimistic-concurrency guard in an `If-Match` header,\n * `saveHandover` and `lock` take `expectedVersion` as a REQUEST BODY field —\n * that is how the spec declares them (`SaveCloseoutHandoverRequest`,\n * `LockCloseoutRequest`), so this file passes it through as body and builds\n * no header. Read it from `handover.version` on a prior `get()`. A stale one\n * is answered `409 CONFLICT_VERSION` (`KaafilVersionConflictError`); rebase\n * against the current record and retry.\n *\n * It is REQUIRED on `saveHandover` (the spec marks it so: two managers\n * writing a closing narrative from two devices is the case it exists for) and\n * OPTIONAL on `lock` (`LockCloseoutRequest` does not require it — a lock\n * re-derives `canLock` inside the request anyway, so a stale `true` from a\n * `get()` can never win; `expectedVersion` there guards the record, not the\n * decision).\n *\n * ── `unlock` IS `apiKeyAuth`-ONLY, AND THAT IS THE POINT ───────────────────\n *\n * `OPERATION_SECURITY.unlockCloseout` is `['apiKeyAuth']` — the only one of\n * these five a manager session cannot satisfy. Reopening a locked trip is a\n * back-office act, not an on-ground one. This resource still exposes it\n * uniformly rather than branching per credential kind: a manager-session\n * client calling `unlock()` gets `UnsatisfiableSchemeError` from\n * `CredentialResolver` BEFORE any request is sent, which is a better answer\n * than a `401` from the engine and is exactly how `journey.rebuild`/\n * `journey.runStep` already behave on the browser entry.\n *\n * ── `exportPdf` RETURNS BYTES, NOT AN ENVELOPE ─────────────────────────────\n *\n * The engine sets `Content-Type: application/pdf` and sends the buffer\n * directly, so `responseWrapperMiddleware` never wraps it — there is no\n * `{ ok, data, meta }` around a closeout pack. The vendored spec describes\n * the `200` as `application/json` holding a `CloseoutPackBinaryResponse`,\n * which the generator renders as a bare `string`; that is the spec being\n * imprecise about a binary route, not the wire being JSON, and this method\n * follows the WIRE. It is the one method in this package that goes through\n * `KaafilHttpClient.executeBinary` (added for it) and the one that returns a\n * `KaafilBinaryResponse` — `{ bytes, meta }`, with `meta` carrying only\n * `status`/`requestId`/`contentType`, because an envelope-less response has\n * no `serverTime` and no `page` to report. Do not pass `meta` from here as a\n * `?since=` cursor anywhere; there is nothing in it to pass.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilBinaryResponse, KaafilResponse } from '../types/meta';\n\ntype CloseoutAggregateResponse = components['schemas']['CloseoutAggregateResponse'];\ntype SaveCloseoutHandoverRequest = components['schemas']['SaveCloseoutHandoverRequest'];\ntype LockCloseoutRequest = components['schemas']['LockCloseoutRequest'];\ntype UnlockCloseoutRequest = components['schemas']['UnlockCloseoutRequest'];\ntype ExportCloseoutPackRequest = components['schemas']['ExportCloseoutPackRequest'];\n\n/** One row of `blockers[]` — what is still open, and which screen clears it.\n * Aliased off the response type, never restated, so a spec change to the\n * closed eleven-key inventory reaches call sites as a type error rather than\n * silently widening. */\nexport type CloseoutBlocker = CloseoutAggregateResponse['blockers'][number];\n\n// --- closeout.get ----------------------------------------------------------\n\nexport interface ReadCloseoutOptions {\n readonly tripRef: string;\n /**\n * A previous response's own `meta.serverTime`, and nothing else. NOT a\n * delta cursor — see this file's header for what it does and does not\n * narrow. Omit it and `recordChangedSince` comes back `null`.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- closeout.saveHandover / .lock / .unlock -------------------------------\n\nexport interface SaveCloseoutHandoverOptions extends SaveCloseoutHandoverRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface LockCloseoutOptions extends LockCloseoutRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UnlockCloseoutOptions extends UnlockCloseoutRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- closeout.exportPdf ----------------------------------------------------\n\nexport interface ExportCloseoutPackOptions extends ExportCloseoutPackRequest {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- closeout --------------------------------------------------------------\n\nexport interface CloseoutResource {\n /** `GET /api/v1/trips/{ref}/closeout` — the whole closing-day picture:\n * the derived `stage`, `canLock` with its human `lockDisabledReason`, every\n * open `blockers[]` row hard-first, the handover note with the `version` the\n * two writes below need, and the financial summary. Always complete; see\n * this file's header for what `since` adds. */\n get(options: ReadCloseoutOptions): Promise<KaafilResponse<CloseoutAggregateResponse>>;\n /** `POST …/closeout/handover` — writes (or, with `handoverNote: null`,\n * clears) the closing narrative. `expectedVersion` is required; a stale one\n * answers `409 CONFLICT_VERSION`. Refused `423 LOCKED` once the trip is\n * locked. Returns the full re-derived aggregate. */\n saveHandover(\n options: SaveCloseoutHandoverOptions,\n ): Promise<KaafilResponse<CloseoutAggregateResponse>>;\n /** `POST …/closeout/lock` — freezes the trip. `canLock` is re-computed\n * inside this request, so a stale `true` from an earlier `get()` never wins:\n * an open hard blocker answers `422 BUSINESS_RULE_VIOLATION` however\n * confident the last read was. Returns the full re-derived aggregate. */\n lock(options: LockCloseoutOptions): Promise<KaafilResponse<CloseoutAggregateResponse>>;\n /** `POST …/closeout/unlock` — reopens a locked trip, with a `reason` that is\n * kept on the record and carried on the `closeout.reopened` event.\n * `apiKeyAuth`-ONLY: from a manager session this throws\n * `UnsatisfiableSchemeError` locally, before any request. See this file's\n * header. */\n unlock(options: UnlockCloseoutOptions): Promise<KaafilResponse<CloseoutAggregateResponse>>;\n /** `POST …/closeout/export-pdf` — the printed pack. Returns BYTES, not an\n * envelope: `{ bytes: Uint8Array, meta: { status, requestId, contentType } }`.\n * `sections` chooses which chapters print, in the array's own order (omit for\n * the agency default, which is all of them); `redactPii` reduces traveller\n * names to initials for a copy that leaves the agency. See this file's\n * header for why this one method is shaped differently from every other. */\n exportPdf(options: ExportCloseoutPackOptions): Promise<KaafilBinaryResponse>;\n}\n\nexport function createCloseoutResource(client: KaafilHttpClient): CloseoutResource {\n return {\n async get(options) {\n const { tripRef, since, signal } = options;\n return client.execute<CloseoutAggregateResponse>({\n method: 'GET',\n operationId: OperationId.ReadCloseout,\n path: '/api/v1/trips/{ref}/closeout',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async saveHandover(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<CloseoutAggregateResponse>({\n method: 'POST',\n operationId: OperationId.SaveCloseoutHandover,\n path: '/api/v1/trips/{ref}/closeout/handover',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async lock(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<CloseoutAggregateResponse>({\n method: 'POST',\n operationId: OperationId.LockCloseout,\n path: '/api/v1/trips/{ref}/closeout/lock',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async unlock(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<CloseoutAggregateResponse>({\n method: 'POST',\n operationId: OperationId.UnlockCloseout,\n path: '/api/v1/trips/{ref}/closeout/unlock',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async exportPdf(options) {\n const { tripRef, signal, ...body } = options;\n return client.executeBinary({\n method: 'POST',\n operationId: OperationId.ExportCloseoutPack,\n path: '/api/v1/trips/{ref}/closeout/export-pdf',\n pathParams: { ref: tripRef },\n body,\n // The one place a non-JSON `Accept` is sent. `exportCloseoutPack`\n // declares no `Idempotency-Key` parameter\n // (`OPERATION_ACCEPTS_IDEMPOTENCY_KEY.exportCloseoutPack` is `false`),\n // and rightly — printing the same pack twice creates nothing — so no\n // key is offered here and the transport mints none.\n accept: 'application/pdf',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `collections` — customer payments recorded against a traveller's balance,\n * who still owes, and the void correction. `architecture/08-sdk.md §4`.\n *\n * `list`/`eligible` accept a manager session OR an API key; `record`/`void`\n * are `managerAuth`-only — collecting cash and correcting a mistake both\n * happen on the ground.\n *\n * `mode ∈ CollectionMode` (`CASH|UPI|CARD|BANK`) is a CUSTOMER payment\n * mode, disjoint from `expenses`' agency-spend `paymentMode` — the two\n * enums never overlap and are never interchangeable even where a value\n * name might coincide.\n *\n * ── THE OVERPAY GUARD IS A HARD REFUSAL ──────────────────────────────────\n *\n * `record()`'s `amountMinor` must not exceed the traveller's DERIVED\n * `outstandingMinor` (computed live from the ingested `Balance`, never\n * stored) — a caller cannot record more than what is actually owed.\n * Exceeding it answers `422 BUSINESS_RULE_VIOLATION` with\n * `details.remainingMinor`, the room actually left. `eligible()` is the\n * companion read — which travellers it returns depends on its `status`\n * option, below; a traveller Kaafil cannot say anything about (no `Balance`\n * row at all) is absent regardless, though still recordable through\n * `record()` as an advance.\n *\n * `void()` is a correction, never an edit or a hard delete — there is no\n * edit-after-record. `If-Match: <version>` is required; a missing or stale\n * one answers `409 CONFLICT_VERSION` with `details.currentVersion`, never\n * silently overwriting a version the caller has not seen.\n *\n * `eligible()`'s `status` option (default `'due'`, matching the engine's own\n * default so an existing caller's response never changes underneath it):\n * `'due'` is travellers who still owe (`outstandingMinor > 0`, the original\n * behaviour); `'settled'` is travellers who are fully paid up\n * (`outstandingMinor === 0`); `'all'` is both together. A traveller Kaafil\n * cannot say anything about — no `Balance` row yet, or a credit balance — is\n * absent under every status, not folded into `'settled'`.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype CollectionResponse = components['schemas']['CollectionResponse'];\ntype CollectionDeltaResponse = components['schemas']['CollectionDeltaResponse'];\ntype EligibleRowResponse = components['schemas']['EligibleRowResponse'];\ntype RecordCollectionRequest = components['schemas']['RecordCollectionRequest'];\ntype VoidCollectionRequest = components['schemas']['VoidCollectionRequest'];\n\n/**\n * One row of `list`'s result: a live collection with its derived\n * `outstandingMinor`, or the tombstone for one deleted since the cursor.\n * Aliased off the response type rather than restated — see\n * `../delta/cursor.ts`'s `isTombstone`.\n */\nexport type CollectionDeltaRow = CollectionDeltaResponse;\n\n// --- date-time widening --------------------------------------------------\n//\n// `collectedAt` is `string` (`Format: date-time`) in the generated schema,\n// because the schema is a faithful mirror of the spec and the wire format\n// really is a string. `RecordCollectionOptions` widens exactly that field\n// to `DateTimeInput` (see `../datetime`) by indexing off the generated type\n// and overriding — never restating a request body by hand. The factory\n// normalizes back down to `string` before the body reaches the wire.\n\n// --- collections.list / collections.eligible -----------------------------\n\nexport interface ListCollectionsOptions {\n readonly tripRef: string;\n /** Narrows to one traveller. Omitted lists every traveller's rows. */\n readonly travellerId?: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit it for the full list. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the window is\n * INCLUSIVE and overlapped by five seconds, so a pull is at-least-once\n * and re-delivers rows a caller already holds; that module owns the\n * bookkeeping this endpoint's overlap assumes.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\ntype ListEligibleQuery = NonNullable<operations['listEligibleCollections']['parameters']['query']>;\n\n/** `'due' | 'settled' | 'all'` — the engine's own `?status=` enum on this route. */\nexport type EligibleCollectionsStatus = NonNullable<ListEligibleQuery['status']>;\n\nexport interface ListEligibleCollectionsOptions {\n readonly tripRef: string;\n /** Defaults to `'due'` — the endpoint's original, unwidened response. */\n readonly status?: EligibleCollectionsStatus;\n readonly signal?: AbortSignal;\n}\n\n// --- collections.record ---------------------------------------------------\n\nexport interface RecordCollectionOptions extends Omit<RecordCollectionRequest, 'collectedAt'> {\n readonly tripRef: string;\n readonly collectedAt?: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- collections.void ------------------------------------------------------\n\nexport interface VoidCollectionOptions extends VoidCollectionRequest {\n readonly tripRef: string;\n readonly collectionId: string;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both\n * answer `409 CONFLICT_VERSION` — identically confusing either way — so\n * this method makes forgetting it impossible instead of merely\n * discouraged. Pass the `version` from a collection just read via\n * `list()` or the row `record()` returned. The SDK builds the `If-Match`\n * header itself; never set it in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\n// --- collections -----------------------------------------------------------\n\nexport interface CollectionsResource {\n /** `GET /api/v1/trips/{ref}/collections` — recorded collections, each row's\n * `outstandingMinor` derived live on this read. See this file's header for\n * the delta-cursor semantics. */\n list(options: ListCollectionsOptions): Promise<KaafilResponse<readonly CollectionDeltaRow[]>>;\n /** `GET /api/v1/trips/{ref}/collections/eligible` — travellers filtered by\n * `status` (default `'due'`: `outstandingMinor > 0`, \"who has a balance to\n * chase\", not \"who may be collected from\"; `'settled'`: `outstandingMinor\n * === 0`; `'all'`: both). See this file's header for the full contract. */\n eligible(\n options: ListEligibleCollectionsOptions,\n ): Promise<KaafilResponse<readonly EligibleRowResponse[]>>;\n /** `POST /api/v1/trips/{ref}/collections` — records a customer payment.\n * See this file's header for the overpay guard. */\n record(options: RecordCollectionOptions): Promise<KaafilResponse<CollectionResponse>>;\n /** `DELETE /api/v1/trips/{ref}/collections/{id}/void` — a correction, not\n * an edit or a hard delete. `DELETE`, not the FRD table's nominal `POST`:\n * a real `If-Match` guard is unsatisfiable on a `POST` under this\n * engine's OpenAPI generator, and a version-guarded soft void is the\n * shape the generator already blesses `DELETE` for — same path, same\n * body, same response either way. */\n void(options: VoidCollectionOptions): Promise<KaafilResponse<CollectionResponse>>;\n}\n\nexport function createCollectionsResource(client: KaafilHttpClient): CollectionsResource {\n return {\n async list(options) {\n const { tripRef, travellerId, since, signal } = options;\n return client.execute<readonly CollectionDeltaRow[]>({\n method: 'GET',\n operationId: OperationId.ListCollections,\n path: '/api/v1/trips/{ref}/collections',\n pathParams: { ref: tripRef },\n query: { travellerId, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async eligible(options) {\n const { tripRef, status, signal } = options;\n return client.execute<readonly EligibleRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListEligibleCollections,\n path: '/api/v1/trips/{ref}/collections/eligible',\n pathParams: { ref: tripRef },\n query: { status },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async record(options) {\n const { tripRef, idempotencyKey, signal, collectedAt, ...rest } = options;\n const body: RecordCollectionRequest = {\n ...rest,\n ...(collectedAt !== undefined\n ? { collectedAt: normalizeDateTimeInput(collectedAt, 'collectedAt') }\n : {}),\n };\n return client.execute<CollectionResponse>({\n method: 'POST',\n operationId: OperationId.RecordCollection,\n path: '/api/v1/trips/{ref}/collections',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async void(options) {\n const { tripRef, collectionId, version, signal, ...body } = options;\n return client.execute<CollectionResponse>({\n method: 'DELETE',\n operationId: OperationId.VoidCollection,\n path: '/api/v1/trips/{ref}/collections/{id}/void',\n pathParams: { ref: tripRef, id: collectionId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `comms` — an agency's messaging config, its outbound message log, its\n * reusable template library, its BYO provider credentials, and its\n * tenant-level config default and test-send routes. `architecture/08-sdk.md\n * §4`. Every operation here is `apiKeyAuth`-only in the spec — this is a\n * CRM/agency-admin-console configuration surface, never something a manager\n * or a share-token holder reaches.\n *\n * ── `KAAFIL_SEND` vs `CRM_SEND` ───────────────────────────────────────────\n *\n * `config.read()`/`config.put()`'s `mode` (`CommsMode`) decides who actually\n * dispatches a message once `send()` (or an internal trigger elsewhere in\n * the API) requests one: `KAAFIL_SEND` has the engine deliver it through its\n * own provider, `CRM_SEND` has the engine log the request\n * (`MessageLogListResponse`/`SendMessageResponse`) WITHOUT delivering it —\n * the CRM's own systems own delivery, and this API is a record of intent,\n * not a guarantee of a provider call. `channels.*.enabled` and\n * `fallbackOrder` (`MessageChannel[]`) only matter under `KAAFIL_SEND`;\n * `quietHours` (`null` = no quiet window) suppresses a send until the\n * window ends, producing `status: 'DEFERRED_QUIET'` rather than dropping it.\n *\n * ── `send()`'S BODY CARRIES ITS OWN SCOPE, UNLIKE EVERY OTHER MODULE ─────\n *\n * Every other resource in this SDK takes its agency/trip ref as a named\n * field on the options object, resolved into the PATH\n * (`/api/v1/trips/{ref}/...`). `send()` is the one exception: the route is\n * the ref-less `POST /api/v1/messages/send`, and `agencyRef` (required) plus\n * `tripRef` (optional, for a trip-scoped template) travel in the BODY\n * instead — the spec's own shape, not a stylistic choice this file made.\n * `clientToken` is required and is this route's OWN idempotency guard,\n * DISTINCT from the `Idempotency-Key` header every mutating call in this\n * SDK already gets automatically (`08-sdk.md §5`) — both are sent, and both\n * must be supplied or minted for a retried `send()` to dedupe correctly.\n *\n * ── `templates.patch` LIVES AT A DIFFERENT PATH THAN `templates.list` ────\n *\n * `templates.create`/`templates.list` are `/api/v1/agencies/{ref}/templates`\n * (agency-scoped, matching every other agency-scoped list in this SDK);\n * `templates.patch` is the ref-less `PATCH /api/v1/templates/{id}` — the\n * template's own id already disambiguates it without an agency ref in the\n * path, the same way `forms.ts`'s `formId`-keyed routes need no agency ref\n * once a caller already holds the id. `patch` requires `If-Match` (`version`\n * on this options object), the same optimistic-concurrency contract as\n * every other versioned write in this SDK.\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\nimport { narrowPaged } from './internal';\n\ntype CommsConfigResponse = components['schemas']['CommsConfigResponse'];\ntype PutCommsConfigRequest = components['schemas']['PutCommsConfigRequest'];\ntype MessageLogListResponse = components['schemas']['MessageLogListResponse'];\ntype MessageLogRow = MessageLogListResponse['items'][number];\ntype SendMessageRequest = components['schemas']['SendMessageRequest'];\ntype SendMessageResponse = components['schemas']['SendMessageResponse'];\ntype MessageTemplateResponse = components['schemas']['MessageTemplateResponse'];\ntype MessageTemplateListResponse = components['schemas']['MessageTemplateListResponse'];\ntype CreateMessageTemplateRequest = components['schemas']['CreateMessageTemplateRequest'];\ntype PatchMessageTemplateRequest = components['schemas']['PatchMessageTemplateRequest'];\ntype CreateCommsProviderCredentialRequest =\n components['schemas']['CreateCommsProviderCredentialRequest'];\ntype CreateProviderCredentialResponse = components['schemas']['CreateProviderCredentialResponse'];\ntype TestCommsProviderCredentialRequest =\n components['schemas']['TestCommsProviderCredentialRequest'];\ntype TestProviderCredentialResponse = components['schemas']['TestProviderCredentialResponse'];\ntype SendCommsTestMessageRequest = components['schemas']['SendCommsTestMessageRequest'];\ntype TestMessageResponse = components['schemas']['TestMessageResponse'];\n\n// --- comms.config ------------------------------------------------------------\n\nexport interface ReadCommsConfigOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PutCommsConfigOptions extends PutCommsConfigRequest {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadDefaultCommsConfigOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface CommsConfigResource {\n /** `GET /api/v1/agencies/{ref}/comms-config`. */\n read(options: ReadCommsConfigOptions): Promise<KaafilResponse<CommsConfigResponse>>;\n /** `PUT /api/v1/agencies/{ref}/comms-config` — replaces the FULL config;\n * there is no PATCH for this resource. See this file's header for what\n * `mode` decides. */\n put(options: PutCommsConfigOptions): Promise<KaafilResponse<CommsConfigResponse>>;\n /** `GET /api/v1/comms/config/default` — the tenant-level comms-config\n * default, unresolved against any agency. Ref-less, unlike `read`/`put`. */\n readDefault(\n options?: ReadDefaultCommsConfigOptions,\n ): Promise<KaafilResponse<CommsConfigResponse>>;\n}\n\n// --- comms.messages ------------------------------------------------------------\n\ntype ListMessagesQuery = NonNullable<operations['listMessages']['parameters']['query']>;\n/** The filterable half of `messages.list`'s query params — `cursor` and\n * `limit` are the paginator's job, never the caller's to hold. */\nexport type MessageFilters = Omit<ListMessagesQuery, 'cursor' | 'limit'>;\n\n/**\n * `MessageLogListResponse` is `{ items, meta: { page } }` — an OBJECT, not a\n * bare array like every other cursor-paginated list in this SDK\n * (`events.ts`, `webhooks.ts`). This is also the one response DTO in the\n * whole vendored spec that declares its OWN `meta` property, alongside\n * `SuccessEnvelope`/`ErrorEnvelope` — `../types/meta.ts`'s header states\n * that invariant as verified by a `jq` query over `components.schemas`; this\n * schema now breaks it. Today the two `meta.page` shapes (this schema's own,\n * and the transport's `CursorPageMeta`) happen to be structurally identical,\n * so `http/client.ts`'s `attachMeta` — which does `Object.assign(data, {\n * meta })`, REPLACING whatever `meta` the wire payload already carried —\n * still leaves `response.meta.page` holding a valid cursor. But that is a\n * coincidence of today's two shapes matching, not a contract either schema\n * promises going forward; if the engine ever changes what\n * `MessageLogListResponse.meta` carries without changing the envelope's own\n * `EnvelopeMeta.page` to match, `attachMeta` silently drops the payload's\n * own value and this fetch keeps working only because the REPLACEMENT\n * value happens to still be usable. Flagged here rather than assumed away.\n */\nasync function fetchMessagesPage(\n client: KaafilHttpClient,\n request: {\n readonly agencyRef: string;\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: MessageFilters;\n },\n) {\n const response = await client.execute<MessageLogListResponse>({\n method: 'GET',\n operationId: OperationId.ListMessages,\n path: '/api/v1/agencies/{ref}/messages',\n pathParams: { ref: request.agencyRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n const paged = narrowPaged(response);\n return { items: paged.items, meta: paged.meta };\n}\n\nexport interface ListMessagesOptions {\n readonly agencyRef: string;\n readonly filters?: MessageFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListMessagesPageOptions extends MessageFilters {\n readonly agencyRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface SendMessageOptions extends SendMessageRequest {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface MessagesResource {\n /** `GET /api/v1/agencies/{ref}/messages` as a `KaafilPaginator` — the SDK\n * holds the cursor; the consumer never sees or stores one. See this\n * file's `fetchMessagesPage` for a caveat on this endpoint's response\n * shape. */\n list(options: ListMessagesOptions): KaafilPaginator<MessageLogRow, MessageFilters>;\n /** The manual single-page escape hatch — fetches exactly one page and\n * returns it directly, for a caller who wants to drive paging itself. */\n listPage(\n options: ListMessagesPageOptions,\n ): Promise<KaafilPagedResponse<readonly MessageLogRow[]>>;\n /** `POST /api/v1/messages/send` — one-off send outside any module's own\n * trigger. See this file's header for why `agencyRef`/`tripRef` travel in\n * the body, and for `clientToken` vs. the automatic `Idempotency-Key`. */\n send(options: SendMessageOptions): Promise<KaafilResponse<SendMessageResponse>>;\n}\n\n// --- comms.templates -----------------------------------------------------------\n\nexport interface ListMessageTemplatesOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CreateMessageTemplateOptions extends CreateMessageTemplateRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchMessageTemplateOptions extends PatchMessageTemplateRequest {\n readonly templateId: string;\n /** Required — see `checklists.ts#PatchChecklistItemOptions.version`'s own\n * argument for why this SDK never leaves `If-Match` optional on a\n * versioned write. Pass the `version` from the template as last read. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface MessageTemplatesResource {\n /** `GET /api/v1/agencies/{ref}/templates`. */\n list(options: ListMessageTemplatesOptions): Promise<KaafilResponse<MessageTemplateListResponse>>;\n /** `POST /api/v1/agencies/{ref}/templates`. */\n create(options: CreateMessageTemplateOptions): Promise<KaafilResponse<MessageTemplateResponse>>;\n /** `PATCH /api/v1/templates/{id}` — see this file's header for why this\n * one route carries no agency ref in its path. */\n patch(options: PatchMessageTemplateOptions): Promise<KaafilResponse<MessageTemplateResponse>>;\n}\n\n// --- comms.providers -------------------------------------------------------------\n\nexport interface CreateCommsProviderCredentialOptions extends CreateCommsProviderCredentialRequest {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TestCommsProviderCredentialOptions extends TestCommsProviderCredentialRequest {\n readonly providerId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CommsProvidersResource {\n /** `POST /api/v1/comms/providers` — seals a BYO email-provider API key and\n * mints a `providerRefId`. */\n create(\n options: CreateCommsProviderCredentialOptions,\n ): Promise<KaafilResponse<CreateProviderCredentialResponse>>;\n /** `POST /api/v1/comms/providers/{id}/test` — sends a real test email\n * through a saved provider credential. */\n test(\n options: TestCommsProviderCredentialOptions,\n ): Promise<KaafilResponse<TestProviderCredentialResponse>>;\n}\n\n// --- comms.sendTestMessage -------------------------------------------------------\n\nexport interface SendCommsTestMessageOptions extends SendCommsTestMessageRequest {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- comms ---------------------------------------------------------------------\n\nexport interface CommsResource {\n readonly config: CommsConfigResource;\n readonly messages: MessagesResource;\n readonly templates: MessageTemplatesResource;\n readonly providers: CommsProvidersResource;\n /** `POST /api/v1/comms/test-message` — the header action (\"Test message\n * queued to your own sender\"). */\n sendTestMessage(\n options: SendCommsTestMessageOptions,\n ): Promise<KaafilResponse<TestMessageResponse>>;\n}\n\nexport function createCommsResource(client: KaafilHttpClient): CommsResource {\n return {\n config: {\n async read(options) {\n const { agencyRef, signal } = options;\n return client.execute<CommsConfigResponse>({\n method: 'GET',\n operationId: OperationId.ReadCommsConfig,\n path: '/api/v1/agencies/{ref}/comms-config',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async put(options) {\n const { agencyRef, signal, ...body } = options;\n return client.execute<CommsConfigResponse>({\n method: 'PUT',\n operationId: OperationId.PutCommsConfig,\n path: '/api/v1/agencies/{ref}/comms-config',\n pathParams: { ref: agencyRef },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async readDefault(options) {\n const { signal } = options ?? {};\n return client.execute<CommsConfigResponse>({\n method: 'GET',\n operationId: OperationId.ReadTenantDefaultCommsConfig,\n path: '/api/v1/comms/config/default',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n messages: {\n list(options) {\n const { agencyRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchMessagesPage(client, { ...request, agencyRef }),\n filters: filters ?? {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { agencyRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<MessageLogListResponse>({\n method: 'GET',\n operationId: OperationId.ListMessages,\n path: '/api/v1/agencies/{ref}/messages',\n pathParams: { ref: agencyRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n const paged = narrowPaged(response);\n return Object.assign(paged.items, { meta: paged.meta }) as KaafilPagedResponse<\n readonly MessageLogRow[]\n >;\n },\n async send(options) {\n const { idempotencyKey, signal, ...body } = options;\n return client.execute<SendMessageResponse>({\n method: 'POST',\n operationId: OperationId.SendMessage,\n path: '/api/v1/messages/send',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n templates: {\n async list(options) {\n const { agencyRef, signal } = options;\n return client.execute<MessageTemplateListResponse>({\n method: 'GET',\n operationId: OperationId.ListMessageTemplates,\n path: '/api/v1/agencies/{ref}/templates',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<MessageTemplateResponse>({\n method: 'POST',\n operationId: OperationId.CreateMessageTemplate,\n path: '/api/v1/agencies/{ref}/templates',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { templateId, version, signal, ...body } = options;\n return client.execute<MessageTemplateResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchMessageTemplate,\n path: '/api/v1/templates/{id}',\n pathParams: { id: templateId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n providers: {\n async create(options) {\n const { idempotencyKey, signal, ...body } = options;\n return client.execute<CreateProviderCredentialResponse>({\n method: 'POST',\n operationId: OperationId.CreateCommsProviderCredential,\n path: '/api/v1/comms/providers',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async test(options) {\n const { providerId, idempotencyKey, signal, ...body } = options;\n return client.execute<TestProviderCredentialResponse>({\n method: 'POST',\n operationId: OperationId.TestCommsProviderCredential,\n path: '/api/v1/comms/providers/{id}/test',\n pathParams: { id: providerId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n async sendTestMessage(options) {\n const { idempotencyKey, signal, ...body } = options;\n return client.execute<TestMessageResponse>({\n method: 'POST',\n operationId: OperationId.SendCommsTestMessage,\n path: '/api/v1/comms/test-message',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `events` — the event feed. `architecture/08-sdk.md §4`: \"the delta feed for\n * missed-webhook recovery.\" `listEvents` is `apiKeyAuth`-only and\n * cursor-paginated (`cursor`+`limit` query params, `meta.page.hasNext`);\n * `list()` returns a `KaafilPaginator` and `listPage()` is the manual\n * single-page escape hatch (`../pagination/paginator.ts`).\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse } from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype EventEnvelopeResponse = components['schemas']['EventEnvelopeResponse'];\n\ntype ListEventsQuery = NonNullable<operations['listEvents']['parameters']['query']>;\n/** The filterable half of `listEvents`'s query params — `cursor` and\n * `limit` are the paginator's job, never the caller's to hold. */\nexport type EventFilters = Omit<ListEventsQuery, 'cursor' | 'limit'>;\n\nasync function fetchEventsPage(\n client: KaafilHttpClient,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: EventFilters;\n },\n) {\n const response = await client.execute<readonly EventEnvelopeResponse[]>({\n method: 'GET',\n operationId: OperationId.ListEvents,\n path: '/api/v1/events',\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListEventsOptions {\n readonly filters?: EventFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListEventsPageOptions extends EventFilters {\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface EventsResource {\n /** `GET /api/v1/events` as a `KaafilPaginator` — the SDK holds the cursor;\n * the consumer never sees or stores one. */\n list(options?: ListEventsOptions): KaafilPaginator<EventEnvelopeResponse, EventFilters>;\n /** The manual single-page escape hatch: fetches exactly one page and\n * returns it directly, for a caller who wants to drive paging itself\n * rather than use the paginator `list()` returns. */\n listPage(\n options?: ListEventsPageOptions,\n ): Promise<KaafilPagedResponse<readonly EventEnvelopeResponse[]>>;\n}\n\nexport function createEventsResource(client: KaafilHttpClient): EventsResource {\n return {\n list(options = {}) {\n return createPaginator({\n fetchPage: (request) => fetchEventsPage(client, request),\n filters: options.filters ?? {},\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n });\n },\n async listPage(options = {}) {\n const { cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly EventEnvelopeResponse[]>({\n method: 'GET',\n operationId: OperationId.ListEvents,\n path: '/api/v1/events',\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n };\n}\n","/**\n * `expenses` — on-trip agency spend, its receipt lane, and the claim\n * lifecycle for a manager's own `PERSONAL` spend. `architecture/08-\n * sdk.md §4`.\n *\n * `list`/`read` accept a manager session OR an API key, never an agency\n * admin. `log`, `linkReceipt` and `void` additionally accept an agency-admin\n * session (three alternatives: `managerAuth`, `apiKeyAuth`,\n * `agencyAdminAuth`) — an agency back-office can log/annotate/void a trip's\n * spend without a manager on the ground. `claims.submit`/`claims.withdraw`\n * accept `managerAuth` OR `apiKeyAuth`, never `agencyAdminAuth` — a claim is\n * the manager's own reimbursement request, not something an agency admin\n * files on their behalf. `claims.ingest` is the one method on this resource\n * an API key alone may call — see its own doc below. Checked against\n * `../generated/security.ts`'s `OPERATION_SECURITY`, the source of truth.\n *\n * `paymentMode ∈ ExpensePaymentMode` (`FLOAT_CASH|PERSONAL|OTHER`) is\n * IMMUTABLE after `log()` and never accepted on any later call — an agency\n * spend mode, disjoint from `collections`' customer payment `mode`.\n * `category ∈ ExpenseCategory`.\n *\n * ── FLOAT_CASH AUTO-COUPLES TO THE FLOAT LEDGER ──────────────────────────\n *\n * `log()` with `paymentMode: 'FLOAT_CASH'` creates, in ONE transaction, the\n * expense, a paired `FloatMovement.EXPENSE(OUT)`, and sets the expense's\n * `floatMovementId` — the negative-float guard (`float.ts`'s header)\n * applies unconditionally, so an expense that would overdraw the manager's\n * float is refused rather than logged. `PERSONAL`/`OTHER` touch no float\n * at all. `log({ submitClaim: true, ... })` (PERSONAL only) files the\n * claim in the SAME transaction — equivalent to a `log()` immediately\n * followed by `claims.submit()`, but atomic.\n *\n * ── THE CLAIM STATE MACHINE, AND WHO MAY MOVE IT ─────────────────────────\n *\n * `ExpenseResponse.claimStatus` is a five-member vocabulary —\n * `SUBMITTED|WITHDRAWN|APPROVED|PAID|REJECTED` — split down the middle by\n * WHO can set each value. `claims.submit()`/`claims.withdraw()` are the\n * only two a Kaafil caller ever drives, and neither takes a `status` field\n * at all: submitting always produces `SUBMITTED`, withdrawing always\n * produces `WITHDRAWN`, so there is no enum a manager writes here.\n * `APPROVED|PAID|REJECTED` arrive ONLY through `claims.ingest()` — the\n * CRM's own decision, mirrored, never decided by Kaafil. That three-member\n * subset is `ClaimStatusIngest` (`../generated/enums.ts`), deliberately not\n * named `ClaimStatus` — see `scripts/gen-meta.mjs`'s `REQUEST_ENUM_NAMES`\n * comment on that entry for why a bare domain name here would be the same\n * trap as `ItineraryItemStatusUpdate`'s.\n *\n * `claims.submit()` only succeeds on a row the caller themselves logged —\n * a different manager's row answers `404 RESOURCE_NOT_FOUND`, never `403`\n * — with `paymentMode: 'PERSONAL'` and `claimStatus` currently `null` or\n * `WITHDRAWN`. `claims.withdraw()` requires `If-Match` and only succeeds\n * while `claimStatus = SUBMITTED` AND no CRM decision has landed yet — a\n * decision arriving mid-flight wins the race cleanly, the withdraw loses.\n * `claims.ingest()` accepts ONLY the three CRM-only values; `SUBMITTED` or\n * `WITHDRAWN` on this route is `422 VALIDATION_ERROR` — the ingest route is\n * one-directional by contract, not just by convention.\n *\n * `void()` reverses the paired float movement (if any) and cascades an\n * open claim; `linkReceipt()` back-fills `receiptFileKey` for a client that\n * logged an expense offline before an upload could confirm — it takes an\n * `Idempotency-Key`, never an `If-Match`: it addresses no client-held\n * version, only a key the log call could not carry offline. Both refuse on\n * an already-voided row or one the CRM has already decided.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype ExpenseResponse = components['schemas']['ExpenseResponse'];\ntype ExpenseListResponse = components['schemas']['ExpenseListResponse'];\ntype ClaimStatusIngestResponse = components['schemas']['ClaimStatusIngestResponse'];\ntype LogExpenseRequest = components['schemas']['LogExpenseRequest'];\ntype LinkExpenseReceiptRequest = components['schemas']['LinkExpenseReceiptRequest'];\ntype VoidExpenseRequest = components['schemas']['VoidExpenseRequest'];\ntype ClaimStatusIngestRequest = components['schemas']['ClaimStatusIngestRequest'];\n\ntype ListExpensesQuery = NonNullable<operations['listExpenses']['parameters']['query']>;\n/** The filterable half of `list`'s query params — `since` is the delta\n * cursor and is passed as its own option, never bundled in here. */\nexport type ExpenseFilters = Omit<ListExpensesQuery, 'since'>;\n\n// --- date-time widening --------------------------------------------------\n//\n// `spentAt` (`LogExpenseRequest`) and `decisionAt` (`ClaimStatusIngestRequest`)\n// are `string` (`Format: date-time`) in the generated schema, because the\n// schema is a faithful mirror of the spec and the wire format really is a\n// string. The `*Options` types below widen exactly those fields to\n// `DateTimeInput` (see `../datetime`) by indexing off the generated type and\n// overriding — never restating a request body by hand. The factory\n// normalizes back down to `string` before the body reaches the wire.\n\n// --- expenses.list / expenses.read ----------------------------------------\n\nexport interface ListExpensesOptions extends ExpenseFilters {\n readonly tripRef: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit it for the full list. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the window is\n * INCLUSIVE and overlapped by five seconds, so a pull is at-least-once.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadExpenseOptions {\n readonly tripRef: string;\n readonly expenseId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- expenses.log ----------------------------------------------------------\n\nexport interface LogExpenseOptions extends Omit<LogExpenseRequest, 'spentAt'> {\n readonly tripRef: string;\n readonly spentAt?: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- expenses.linkReceipt / expenses.void ---------------------------------\n\nexport interface LinkExpenseReceiptOptions extends LinkExpenseReceiptRequest {\n readonly tripRef: string;\n readonly expenseId: string;\n /** Required — this route addresses no client-held version; see this\n * file's header for why `If-Match` never applies here. */\n readonly idempotencyKey: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface VoidExpenseOptions extends VoidExpenseRequest {\n readonly tripRef: string;\n readonly expenseId: string;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both\n * answer `409 CONFLICT_VERSION` — identically confusing either way — so\n * this method makes forgetting it impossible instead of merely\n * discouraged. Pass the `version` from an expense just read via `list()`\n * or `read()`. The SDK builds the `If-Match` header itself; never set it\n * in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\n// --- expenses.claims -------------------------------------------------------\n\nexport interface SubmitExpenseClaimOptions {\n readonly tripRef: string;\n readonly expenseId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface WithdrawExpenseClaimOptions {\n readonly tripRef: string;\n readonly expenseId: string;\n /** Required — see `VoidExpenseOptions.version` above for why this SDK\n * never makes `If-Match` optional on a versioned write. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface IngestClaimStatusOptions extends Omit<ClaimStatusIngestRequest, 'decisionAt'> {\n readonly tripRef: string;\n readonly expenseId: string;\n readonly decisionAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ExpenseClaimsResource {\n /** `POST /api/v1/trips/{ref}/expenses/{id}/claim` — files a claim on the\n * caller's own `PERSONAL` expense. No body: submitting always produces\n * `SUBMITTED`, never a status the caller names. */\n submit(options: SubmitExpenseClaimOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `DELETE /api/v1/trips/{ref}/expenses/{id}/claim/withdraw` — only while\n * still `SUBMITTED` with no CRM decision landed. `DELETE`, not the FRD\n * table's nominal `POST` — the same forced deviation `expenses.void()`\n * and `collections.void()` make, for the identical `If-Match`-on-`POST`\n * reason; nothing else about the contract changes. */\n withdraw(options: WithdrawExpenseClaimOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `POST /api/v1/trips/{ref}/expenses/{id}/claim-status` — partner API\n * key ONLY; a manager bearer answers `401 UNAUTHENTICATED`, never `403`.\n * The CRM's own decision, mirrored — Kaafil never approves, rejects or\n * pays. `status` accepts only `ClaimStatusIngest`'s three values;\n * `SUBMITTED`/`WITHDRAWN` here is `422 VALIDATION_ERROR`. The response's\n * `verdict` (`applied`/`ignored_stale`) tells the CRM whether this\n * decision actually landed or arrived after a newer one already had. */\n ingest(options: IngestClaimStatusOptions): Promise<KaafilResponse<ClaimStatusIngestResponse>>;\n}\n\n// --- expenses ----------------------------------------------------------------\n\nexport interface ExpensesResource {\n /** `GET /api/v1/trips/{ref}/expenses` — a trip's expenses, with category\n * totals and a spend summary over the filtered set (live rows only). See\n * this file's header for the delta-cursor semantics. */\n list(options: ListExpensesOptions): Promise<KaafilResponse<ExpenseListResponse>>;\n /** `GET /api/v1/trips/{ref}/expenses/{id}` — one expense, including its\n * claim view. `id` is a plain Kaafil id, never dual-resolved. */\n read(options: ReadExpenseOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `POST /api/v1/trips/{ref}/expenses` — logs an on-trip spend. See this\n * file's header for `FLOAT_CASH` auto-coupling and `submitClaim`. */\n log(options: LogExpenseOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `PATCH /api/v1/trips/{ref}/expenses/{id}/receipt` — back-fills\n * `receiptFileKey` against a confirmed (`ready`) upload from `files.*`. */\n linkReceipt(options: LinkExpenseReceiptOptions): Promise<KaafilResponse<ExpenseResponse>>;\n /** `DELETE /api/v1/trips/{ref}/expenses/{id}/void` — reverses the paired\n * float movement and cascades an open claim. See this file's header for\n * the `DELETE`-not-`POST` note. */\n void(options: VoidExpenseOptions): Promise<KaafilResponse<ExpenseResponse>>;\n readonly claims: ExpenseClaimsResource;\n}\n\nexport function createExpensesResource(client: KaafilHttpClient): ExpensesResource {\n return {\n async list(options) {\n const { tripRef, since, signal, ...filters } = options;\n return client.execute<ExpenseListResponse>({\n method: 'GET',\n operationId: OperationId.ListExpenses,\n path: '/api/v1/trips/{ref}/expenses',\n pathParams: { ref: tripRef },\n query: { ...filters, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async read(options) {\n const { tripRef, expenseId, signal } = options;\n return client.execute<ExpenseResponse>({\n method: 'GET',\n operationId: OperationId.ReadExpense,\n path: '/api/v1/trips/{ref}/expenses/{id}',\n pathParams: { ref: tripRef, id: expenseId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async log(options) {\n const { tripRef, idempotencyKey, signal, spentAt, ...rest } = options;\n const body: LogExpenseRequest = {\n ...rest,\n ...(spentAt !== undefined ? { spentAt: normalizeDateTimeInput(spentAt, 'spentAt') } : {}),\n };\n return client.execute<ExpenseResponse>({\n method: 'POST',\n operationId: OperationId.LogExpense,\n path: '/api/v1/trips/{ref}/expenses',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async linkReceipt(options) {\n const { tripRef, expenseId, idempotencyKey, signal, ...body } = options;\n return client.execute<ExpenseResponse>({\n method: 'PATCH',\n operationId: OperationId.LinkExpenseReceipt,\n path: '/api/v1/trips/{ref}/expenses/{id}/receipt',\n pathParams: { ref: tripRef, id: expenseId },\n body,\n idempotencyKey,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async void(options) {\n const { tripRef, expenseId, version, signal, ...body } = options;\n return client.execute<ExpenseResponse>({\n method: 'DELETE',\n operationId: OperationId.VoidExpense,\n path: '/api/v1/trips/{ref}/expenses/{id}/void',\n pathParams: { ref: tripRef, id: expenseId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n claims: {\n async submit(options) {\n const { tripRef, expenseId, idempotencyKey, signal } = options;\n return client.execute<ExpenseResponse>({\n method: 'POST',\n operationId: OperationId.SubmitExpenseClaim,\n path: '/api/v1/trips/{ref}/expenses/{id}/claim',\n pathParams: { ref: tripRef, id: expenseId },\n body: {},\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async withdraw(options) {\n const { tripRef, expenseId, version, signal } = options;\n return client.execute<ExpenseResponse>({\n method: 'DELETE',\n operationId: OperationId.WithdrawExpenseClaim,\n path: '/api/v1/trips/{ref}/expenses/{id}/claim/withdraw',\n pathParams: { ref: tripRef, id: expenseId },\n body: {},\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async ingest(options) {\n const { tripRef, expenseId, idempotencyKey, signal, decisionAt, ...rest } = options;\n const body: ClaimStatusIngestRequest = {\n ...rest,\n decisionAt: normalizeDateTimeInput(decisionAt, 'decisionAt'),\n };\n return client.execute<ClaimStatusIngestResponse>({\n method: 'POST',\n operationId: OperationId.ClaimStatusIngest,\n path: '/api/v1/trips/{ref}/expenses/{id}/claim-status',\n pathParams: { ref: tripRef, id: expenseId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `feedbackNps` — two read-only rollups over `forms` responses to whichever\n * form an agency has designated its feedback/NPS survey: one across an\n * agency's forms catalog, one scoped to a single trip.\n * `architecture/08-sdk.md §4`. Both accept an API key; `trip` additionally\n * accepts a manager session or an agency-admin session, `agency` an\n * agency-admin session — never a manager alone (an agency-wide rollup is\n * not a single trip's manager's business).\n *\n * This resource is READ-ONLY by design: there is no \"designate this form as\n * the feedback survey\" write anywhere in the vendored spec. That\n * designation is `forms.create`/`forms.patch`'s `templateKey`/`programKey`\n * (`forms.ts`) — `feedbackNps` only reads the rollup the engine computes\n * over whichever form already carries that designation; it mints nothing\n * of its own.\n *\n * ── BOTH RESPONSE SCHEMAS NEST A SECOND `data` INSIDE THE ENVELOPE'S OWN\n * `data` ──────────────────────────────────────────────────────────────────\n *\n * Every other `SuccessEnvelope`-wrapped response in this SDK has the\n * envelope's `data` land directly on the resource shape (`trip.data` reads\n * as \"the trip\", not \"the trip's own `.data` field\"). Both\n * `AgencyFeedbackSummaryResponse` and `TripFeedbackSummaryResponse` are\n * exceptions: EACH schema itself declares a `data` property one level in,\n * so the value this SDK hands back is `{ data: { definitions: [...] } }`\n * (agency) or `{ data: { configured: false, reason } | { configured: true,\n * ... } }` (trip) — a caller reads `response.data.definitions` /\n * `response.data.configured`, not `response.definitions` /\n * `response.configured`. This SDK does not unwrap the extra layer or\n * rename it — the generated schema is a faithful mirror of the spec, same\n * as everywhere else in this package — but it is worth stating plainly\n * once, here, rather than leaving a caller to discover the double nesting\n * by trial and error.\n *\n * `trip.read()`'s result is a discriminated union on `data.configured`:\n * `false` carries only `reason` (no form has ever been designated, or the\n * designated form was archived); `true` carries the window, the funnel\n * counts (`dispatched`/`started`/`submitted`), `completionRate` (`null`\n * until at least one dispatch), the same `nps` shape `agency.read()`'s\n * `definitions[]` rows carry, and `reopenClosesAt`. Narrow on\n * `data.configured` before reading any of the `true`-only fields —\n * TypeScript enforces this at the call site.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype AgencyFeedbackSummaryResponse = components['schemas']['AgencyFeedbackSummaryResponse'];\ntype TripFeedbackSummaryResponse = components['schemas']['TripFeedbackSummaryResponse'];\n\n// --- feedbackNps.agency ------------------------------------------------------\n\nexport interface ReadAgencyFeedbackSummaryOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- feedbackNps.trip ---------------------------------------------------------\n\nexport interface ReadTripFeedbackSummaryOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- feedbackNps ---------------------------------------------------------------\n\nexport interface FeedbackNpsResource {\n /** `GET /api/v1/agencies/{ref}/feedback/summary` — one row per designated\n * feedback form across the agency's whole forms catalog. See this file's\n * header for the double `data.data`-shaped nesting. */\n agency(\n options: ReadAgencyFeedbackSummaryOptions,\n ): Promise<KaafilResponse<AgencyFeedbackSummaryResponse>>;\n /** `GET /api/v1/trips/{ref}/feedback/summary` — one trip's rollup, or\n * `{ configured: false, reason }` if no feedback form is designated for\n * it. See this file's header for the discriminated union and the double\n * `data.data`-shaped nesting. */\n trip(\n options: ReadTripFeedbackSummaryOptions,\n ): Promise<KaafilResponse<TripFeedbackSummaryResponse>>;\n}\n\nexport function createFeedbackNpsResource(client: KaafilHttpClient): FeedbackNpsResource {\n return {\n async agency(options) {\n const { agencyRef, signal } = options;\n return client.execute<AgencyFeedbackSummaryResponse>({\n method: 'GET',\n operationId: OperationId.ReadAgencyFeedbackSummary,\n path: '/api/v1/agencies/{ref}/feedback/summary',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async trip(options) {\n const { tripRef, signal } = options;\n return client.execute<TripFeedbackSummaryResponse>({\n method: 'GET',\n operationId: OperationId.ReadTripFeedbackSummary,\n path: '/api/v1/trips/{ref}/feedback/summary',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `files` — the blob lane: request a presigned upload slot, confirm it,\n * read metadata, and mint a short-lived signed GET. `architecture/08-\n * sdk.md §4`. All four operations — `request`/`confirm`/`meta`/`url` —\n * accept the SAME three alternatives: a manager session, an agency-admin\n * session, OR an API key (`managerAuth`, `agencyAdminAuth`, `apiKeyAuth`;\n * never an AND). Checked against `../generated/security.ts`'s\n * `OPERATION_SECURITY`, the source of truth. An agency admin confirming a\n * `PENDING` upload attributes the confirmation to itself, not to whichever\n * manager (if any) requested the slot — see the actor-attribution fields on\n * the eight models and `ItineraryChangeLog` for the general shape of that\n * distinction; `FileResponse` itself still carries none (`uploadedByManagerId`\n * only, `null` for a non-manager caller).\n *\n * `purpose` is further gated per credential kind server-side, and the three\n * kinds no longer collapse into two:\n *\n * apiKey `booking_voucher` | `trip_document`\n * manager `expense_receipt` | `form_attachment`\n * agencyAdmin ALL FOUR\n *\n * This paragraph used to say a manager and an agency admin shared one set and\n * that `booking_voucher` was \"apiKey-only regardless of session kind\" — both\n * halves are now false. The desk may file a voucher the CRM never pushed, and\n * `trip_document` (new) is the desk's own purpose for the trip's paperwork.\n * A purpose outside the caller's set answers **404, with no capability hint**,\n * not a 422 — so a refused request looks like a missing trip, which is\n * deliberate and worth knowing when debugging one.\n *\n * `trip_document` carries two fields no other purpose accepts, and supplying\n * either elsewhere is a `422`, never a silent drop:\n *\n * `title` REQUIRED — nothing else names this file. The other three\n * are named by the expense, form field or booking they hang\n * off; a trip document hangs off nothing.\n * `travellerRef` optional — omit it and the document belongs to the whole\n * trip and reaches every share link on it; name a traveller\n * and it reaches only a share token whose SUBJECT is that\n * traveller. It also decides retention: scoped →\n * `TRAVELLER_PII` (24-month ceiling), unscoped →\n * `OPERATIONAL` (no clock).\n *\n * That gate is enforced by the engine, not this SDK.\n *\n * ── THE FOUR-STATUS LIFECYCLE ────────────────────────────────────────────\n *\n * `FileResponse.status` is `pending → ready → orphaned`/`purged`. Bytes\n * never pass through this SDK or the Kaafil API at all: `request()` hands\n * back a presigned `PUT` URL (`CreateFileResponse.uploadUrl`) that the\n * caller's own HTTP stack uses to write directly to object storage, with\n * NO Kaafil auth header — the signed URL itself is the authorization. This\n * package does not perform that `PUT`; it only mints the URL and later\n * confirms what landed.\n *\n * `confirm()` verifies the object actually arrived — existence, the\n * declared `sizeBytes`, and the leading bytes against `contentType`'s file\n * signature — because the presigned `PUT` pins `sizeBytes` into its\n * signature but NOT `contentType`, so a caller-declared type is otherwise\n * unverified. A mismatch answers `422 UPLOAD_MISMATCH` and the file stays\n * `pending`; re-`PUT` and re-confirm until the presigned URL's window\n * lapses. On success `retentionClass` is stamped SERVER-SIDE (never\n * client-declared) and the file flips to `ready`. It is a function of\n * `purpose` for two of the four; the other two SPLIT — `form_attachment` on\n * the answering field's kind (`SIGNATURE` → `CONSENT_EVIDENCE`, else\n * `TRAVELLER_PII`) and `trip_document` on whether it names a traveller.\n *\n * `url()` mints a fresh 5-minute signed GET on every call — never stored,\n * never reused — and only for a `ready` file. A `purged` file answers\n * `410 FILE_PURGED`: the metadata row survives forever, the bytes do not.\n * `meta()` itself never 404s for a purged file — it is the one read that\n * still answers `200` whatever `status` says, which is how a caller tells\n * \"gone\" (`410` from `url()`) apart from \"never existed\" (`404` from\n * `meta()`) without a second not-found class.\n *\n * `purpose ∈ FilePurpose` gates what `contentType ∈ FileContentType` may\n * accompany it server-side; both are `../generated/enums.ts` constants\n * that come from the same vendored spec.\n *\n * `list()` and `managerView()` are two additive reads alongside the original\n * four, both `managerAuth`/`apiKeyAuth`/`agencyAdminAuth` like every other\n * read here. `list()` is the one method on this resource that needs no\n * `fileId` at all — it is how a caller with no id yet discovers what exists\n * for a trip. `managerView()` composes `meta()` + `url()` server-side into\n * one manager-doc-viewer-shaped response; it never refuses on a non-`ready`\n * file the way `url()` does — `url`/`urlExpiresAt` simply come back `null`.\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype CreateFileResponse = components['schemas']['CreateFileResponse'];\ntype FileResponse = components['schemas']['FileResponse'];\ntype FileUrlResponse = components['schemas']['FileUrlResponse'];\ntype FileListResponse = components['schemas']['FileListResponse'];\ntype ManagerFileViewResponse = components['schemas']['ManagerFileViewResponse'];\ntype RequestFileUploadRequest = components['schemas']['RequestFileUploadRequest'];\n\ntype ListFilesQuery = NonNullable<operations['listFiles']['parameters']['query']>;\n\n// --- files.request -----------------------------------------------------\n\nexport interface RequestFileUploadOptions extends RequestFileUploadRequest {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- files.meta / files.confirm / files.url -----------------------------\n\nexport interface ReadFileOptions {\n readonly fileId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ConfirmFileUploadOptions {\n readonly fileId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFileUrlOptions {\n readonly fileId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- files.list ------------------------------------------------------------\n\nexport interface ListFilesOptions extends ListFilesQuery {\n readonly signal?: AbortSignal;\n}\n\n// --- files.managerView -----------------------------------------------------\n\nexport interface DeleteFileOptions {\n readonly fileId: string;\n /**\n * The `version` from the file as last read. Required, not optional: a\n * missing `If-Match` and a stale one both answer `409 CONFLICT_VERSION`,\n * identically confusing either way, so this makes forgetting it impossible\n * rather than merely discouraged. The SDK builds the header itself.\n */\n readonly version: number;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadManagerFileViewOptions {\n readonly fileId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- files ---------------------------------------------------------------\n\nexport interface FilesResource {\n /** `POST /api/v1/files` — mints a `pending` metadata row plus a presigned\n * `PUT`, 15-minute window, `contentType`/`sizeBytes` pinned as request\n * conditions. This method never uploads bytes itself — see this file's\n * header. */\n request(options: RequestFileUploadOptions): Promise<KaafilResponse<CreateFileResponse>>;\n /** `GET /api/v1/files/{id}` — the metadata skeleton, `200` for every\n * status including `purged`. Never carries `storageKey`, `tripRef` or\n * `agencyId`; `retentionClass` is `null` until the file is `ready`. */\n meta(options: ReadFileOptions): Promise<KaafilResponse<FileResponse>>;\n /** `POST /api/v1/files/{id}/confirm` — verifies the uploaded object and\n * flips `pending` → `ready`. See this file's header for the mismatch and\n * retention-stamping behaviour. */\n confirm(options: ConfirmFileUploadOptions): Promise<KaafilResponse<FileResponse>>;\n /** `GET /api/v1/files/{id}/url` — a fresh 5-minute signed GET for a\n * `ready` file. `410 FILE_PURGED` once the bytes are gone. */\n url(options: ReadFileUrlOptions): Promise<KaafilResponse<FileUrlResponse>>;\n /** `GET /api/v1/files?tripRef=` — every file for a trip, newest first,\n * optionally narrowed by `purpose`/`status`. The one method on this\n * resource that needs no `fileId` — see this file's header. */\n list(options: ListFilesOptions): Promise<KaafilResponse<FileListResponse>>;\n /** `GET /api/v1/files/{id}/manager-view` — `meta()` + `url()` composed\n * into one manager-doc-viewer-shaped response. See this file's header for\n * why it never refuses on a non-`ready` file the way `url()` does. */\n managerView(\n options: ReadManagerFileViewOptions,\n ): Promise<KaafilResponse<ManagerFileViewResponse>>;\n /**\n * `DELETE /api/v1/files/{id}` — withdraw a `trip_document` and DELETE THE\n * STORED OBJECT. The one call on this resource that destroys bytes.\n *\n * `trip_document` ONLY. The other three purposes are evidence owned by a\n * parent record that decides its own life — a receipt by its expense, an\n * attachment by its form field, a voucher by its booking (use\n * `bookings.vouchers.replace`) — so calling this on one is `422\n * BUSINESS_RULE_VIOLATION`, `details.rule:\n * \"file.deleteRestrictedToTripDocument\"`. A `retentionClass` of `financial`\n * or `consent_evidence` is refused the same way with\n * `\"file.deleteBlockedByRetention\"`: those carry an obligation to KEEP.\n *\n * Afterwards the id is GONE — `meta()` answers `404`, not the `200`\n * skeleton a retention-purged file still returns. So unlike a purge, a\n * withdrawn document cannot be told apart from one that never existed. That\n * is deliberate; a caller who needs a record of the withdrawal keeps it on\n * their own side before calling.\n *\n * Safe to repeat: a retry after a partial failure finishes the job rather\n * than erroring.\n */\n remove(options: DeleteFileOptions): Promise<KaafilResponse<false>>;\n}\n\nexport function createFilesResource(client: KaafilHttpClient): FilesResource {\n return {\n async request(options) {\n const { idempotencyKey, signal, ...body } = options;\n return client.execute<CreateFileResponse>({\n method: 'POST',\n operationId: OperationId.RequestFileUpload,\n path: '/api/v1/files',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async meta(options) {\n const { fileId, signal } = options;\n return client.execute<FileResponse>({\n method: 'GET',\n operationId: OperationId.ReadFile,\n path: '/api/v1/files/{id}',\n pathParams: { id: fileId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async confirm(options) {\n const { fileId, idempotencyKey, signal } = options;\n return client.execute<FileResponse>({\n method: 'POST',\n operationId: OperationId.ConfirmFileUpload,\n path: '/api/v1/files/{id}/confirm',\n pathParams: { id: fileId },\n body: {},\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async url(options) {\n const { fileId, signal } = options;\n return client.execute<FileUrlResponse>({\n method: 'GET',\n operationId: OperationId.ReadFileUrl,\n path: '/api/v1/files/{id}/url',\n pathParams: { id: fileId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { signal, ...query } = options;\n return client.execute<FileListResponse>({\n method: 'GET',\n operationId: OperationId.ListFiles,\n path: '/api/v1/files',\n query,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { fileId, version, idempotencyKey, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteFile,\n path: '/api/v1/files/{id}',\n pathParams: { id: fileId },\n headers: { 'If-Match': String(version) },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async managerView(options) {\n const { fileId, signal } = options;\n return client.execute<ManagerFileViewResponse>({\n method: 'GET',\n operationId: OperationId.ReadManagerFileView,\n path: '/api/v1/files/{id}/manager-view',\n pathParams: { id: fileId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `float` — cash advanced to a manager, its ledger, and the derived\n * per-manager balance. `architecture/08-sdk.md §4`.\n *\n * ALL FIVE methods accept a manager session, an API key, OR an agency-admin\n * session. `return` included: this file previously described it as\n * `managerAuth`-only, \"an admin is view-only on that row\", and that was\n * wrong — `float.routes.ts` declares\n * `auth: ['manager', 'apiKey', 'agencyAdmin']` on it and its own route\n * description says so outright: \"A manager session, an API key, or an\n * agency admin session may call this (full parity with `issue`/`adjust` —\n * owner decision)\". An office reconciling a returned cash box is exactly\n * the case that parity exists for.\n *\n * Every movement is one of four `type`s (`ISSUE|RETURN|ADJUSTMENT|EXPENSE`)\n * with a `direction ∈ FloatDirection` (`IN|OUT`) — `EXPENSE` movements are\n * created by `expenses.log` when `paymentMode: 'FLOAT_CASH'`, never by a\n * method on this resource directly.\n *\n * ── THE NEGATIVE-FLOAT GUARD ─────────────────────────────────────────────\n *\n * Every `OUT` movement — `return()` and `adjust()` with `direction: 'OUT'`\n * — is guarded: `amountMinor` must not exceed the manager's current\n * derived `balanceMinor`, checked and enforced under an advisory lock so\n * two concurrent `OUT`s can never both pass the same stale read. A refusal\n * is `422 BUSINESS_RULE_VIOLATION` with `details.currentBalanceMinor` — the\n * figure the guard actually compared against. `issue()` (`direction: 'IN'`,\n * always additive) and `adjust()` with `direction: 'IN'` are never guarded.\n *\n * `adjust()`'s `note` is REQUIRED (the audit trail of every manual\n * correction) — unlike `issue()`/`return()`, where it is optional.\n * `issue()` never accepts a `currency` field: every write takes the trip's\n * own currency, never a caller-named one.\n *\n * ── DERIVED, NOT DELTA-MERGEABLE (readSummary) vs A PLAIN DELTA (readLedger) ──\n *\n * `readSummary()`'s rows are entirely derived (`issuedMinor`,\n * `returnedMinor`, `spentMinor`, `adjustmentsMinor`, `balanceMinor`) —\n * nothing here is stored. `since` narrows WHICH managers are returned (only\n * those with a movement at or after the cursor) but every returned row\n * still carries its FULL current balance, never a partial delta — a\n * derived scalar cannot be delta-merged the way a versioned list row can.\n * `mergeDeltaRows`/`isTombstone` (`../delta/cursor.ts`) do not apply here:\n * there is no tombstone case and no per-row `version` to compare.\n *\n * `readLedger()`'s `since`, by contrast, IS a plain delta over a genuine\n * append-only list: it narrows the returned MOVEMENT rows to those at or\n * after the cursor. Each surviving row's `runningBalanceMinor` is still its\n * correct absolute balance — the server computes the running sum over the\n * manager's full history before the cursor narrows what ships, so a client\n * resuming from a cursor never sees a balance re-based to zero.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype FloatSummaryResponse = components['schemas']['FloatSummaryResponse'];\ntype FloatLedgerResponse = components['schemas']['FloatLedgerResponse'];\ntype AdjustFloatResponse = components['schemas']['AdjustFloatResponse'];\ntype IssueFloatResponse = components['schemas']['IssueFloatResponse'];\ntype ReturnFloatResponse = components['schemas']['ReturnFloatResponse'];\ntype AdjustFloatRequest = components['schemas']['AdjustFloatRequest'];\ntype IssueFloatRequest = components['schemas']['IssueFloatRequest'];\ntype ReturnFloatRequest = components['schemas']['ReturnFloatRequest'];\n\n// --- float.readSummary / float.readLedger --------------------------------\n\nexport interface ReadFloatSummaryOptions {\n readonly tripRef: string;\n /** Narrows which managers are returned to those with a movement at or\n * after this cursor. See this file's header — the rows themselves are\n * never partial, so this is not a `../delta/cursor.ts` cursor. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFloatLedgerOptions {\n readonly tripRef: string;\n readonly managerId: string;\n /** Narrows the returned movement rows to those at or after this cursor —\n * a plain delta pull, unlike `ReadFloatSummaryOptions.since`. See this\n * file's header. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- float.issue / float.return / float.adjust ---------------------------\n\nexport interface IssueFloatOptions extends IssueFloatRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReturnFloatOptions extends ReturnFloatRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AdjustFloatOptions extends AdjustFloatRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- float -----------------------------------------------------------------\n\nexport interface FloatResource {\n /** `GET /api/v1/trips/{ref}/float` — one row per manager who has ever had\n * a movement on this trip, entirely derived. See this file's header. */\n readSummary(options: ReadFloatSummaryOptions): Promise<KaafilResponse<FloatSummaryResponse>>;\n /** `GET /api/v1/trips/{ref}/float/{managerId}/ledger` — one manager's\n * movement history, ordered `(createdAt asc, id asc)`, each row carrying\n * `runningBalanceMinor`. `404` if `managerId` does not name a manager\n * currently assigned to this trip. `since` narrows the rows returned to\n * those at or after the cursor — see this file's header. */\n readLedger(options: ReadFloatLedgerOptions): Promise<KaafilResponse<FloatLedgerResponse>>;\n /** `POST /api/v1/trips/{ref}/float/issue` — `type=ISSUE`, `direction=IN`,\n * never negative-float guarded. An admin or the manager themselves may\n * call this; both paths produce the identical row. */\n issue(options: IssueFloatOptions): Promise<KaafilResponse<IssueFloatResponse>>;\n /** `POST /api/v1/trips/{ref}/float/return` — `type=RETURN`,\n * `direction=OUT`, negative-float guarded. A manager, an API key or an\n * agency admin may call it — full parity with `issue`/`adjust`, see this\n * file's header. */\n return(options: ReturnFloatOptions): Promise<KaafilResponse<ReturnFloatResponse>>;\n /** `POST /api/v1/trips/{ref}/float/adjust` — `type=ADJUSTMENT`, direction\n * named by the caller; `note` is required. `direction: 'OUT'` is\n * negative-float guarded identically to `return()`; `direction: 'IN'`\n * never is. */\n adjust(options: AdjustFloatOptions): Promise<KaafilResponse<AdjustFloatResponse>>;\n}\n\nexport function createFloatResource(client: KaafilHttpClient): FloatResource {\n return {\n async readSummary(options) {\n const { tripRef, since, signal } = options;\n return client.execute<FloatSummaryResponse>({\n method: 'GET',\n operationId: OperationId.ReadFloatSummary,\n path: '/api/v1/trips/{ref}/float',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async readLedger(options) {\n const { tripRef, managerId, since, signal } = options;\n return client.execute<FloatLedgerResponse>({\n method: 'GET',\n operationId: OperationId.ReadFloatLedger,\n path: '/api/v1/trips/{ref}/float/{managerId}/ledger',\n pathParams: { ref: tripRef, managerId },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async issue(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<IssueFloatResponse>({\n method: 'POST',\n operationId: OperationId.IssueFloat,\n path: '/api/v1/trips/{ref}/float/issue',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async return(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<ReturnFloatResponse>({\n method: 'POST',\n operationId: OperationId.ReturnFloat,\n path: '/api/v1/trips/{ref}/float/return',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async adjust(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<AdjustFloatResponse>({\n method: 'POST',\n operationId: OperationId.AdjustFloat,\n path: '/api/v1/trips/{ref}/float/adjust',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `forms` — the agency's form-authoring surface (definitions, sections,\n * fields, publish lifecycle, response export) plus the trip-scoped read/\n * write surface a manager uses on the ground. `architecture/08-sdk.md §4`.\n *\n * Every authoring write (`create`/`patch`/`delete`/`archive`/`unarchive`/\n * `publish`/`close`/`reopen`/`clone`/`reorder`, and every `sections.*`/\n * `fields.*` write) accepts an API key OR an agency-admin session — never a\n * manager alone; a manager reads a form's definition (`get`) but never\n * authors one. The trip-scoped surface (`trip.*`) now accepts ALL THREE —\n * `list`/`answers`/`completion`/`dispatch`/`responses.list`/\n * `responses.get`/`export`/`consentReceipt` were a manager session or an\n * API key until this pass, which left an agency admin able to CREATE a\n * response on a traveller's behalf (`responses.create` always took the\n * triple) and unable to read the trip's responses to know one was\n * missing. The engine closed that asymmetry; these methods are now\n * reachable from a desk console. `bindings.list` accepts\n * all three (API key, agency-admin, manager) — it is a read-only catalog of\n * what a field MAY bind to, useful to every caller building a form UI.\n *\n * ── VERSIONED WRITES: `If-Match` EVERYWHERE, `data: false` ON DELETE ─────\n *\n * Every PATCH/DELETE below (the form itself, a section, a field) is a\n * versioned write and takes a required `version` — this SDK builds the\n * `If-Match` header itself, the same contract as every other versioned\n * write in this package (`checklists.ts#PatchChecklistItemOptions.version`'s\n * own argument for why it is never optional). `delete`/`sections.delete`/\n * `fields.delete`/`reorder` all answer their success body as a literal\n * `data: false` — not a deleted-row echo the way `checklists.items.remove`\n * or `bookings.delete` return one — so this file types those four returns\n * as `KaafilResponse<false>` rather than inventing a response shape the\n * spec does not declare.\n *\n * ── `getFormConsentReceipt` LIVES OUTSIDE `{formId}` ──────────────────────\n *\n * Every other response-scoped read/write nests under `/forms/{formId}/...`.\n * `responses.consentReceipt` is the one exception —\n * `GET /api/v1/forms/responses/{responseId}/consent-receipt` — because a\n * response's `id` alone already disambiguates it; the spec's own path\n * shape, not a stylistic choice made here.\n *\n * ── TWO BYTE-BODIED READS ─────────────────────────────────────────────────\n *\n * `responses.export` and `responses.consentReceipt` answer RAW BYTES, not a\n * `{ ok, data, meta }` envelope: the engine sets `text/csv; charset=utf-8`\n * or `application/pdf` and writes the file straight onto the response\n * (`forms.controller.ts#exportResponses`/`#consentReceipt`). They therefore\n * go through `client.executeBinary` and return `KaafilBinaryResponse` —\n * `{ bytes, meta }` — exactly like `closeout.exportPdf`.\n *\n * The generated schema types both payloads as `FormsBinaryResponse`, a bare\n * `string`. That is the SPEC being lossy about a binary body, not a promise\n * of a JSON string, and honouring it literally through `client.execute` made\n * every SUCCESSFUL call throw `KaafilNetworkError('Received an\n * unrecognizable success body')`: the enveloped reader calls `text()` and\n * then demands an envelope the engine never sends. The generated alias is\n * deliberately unused here rather than re-exported as a lie.\n *\n * `Accept` follows the request — `text/csv` when `format === 'csv'`,\n * `application/pdf` otherwise — and `meta.contentType` carries the server's\n * own header verbatim, which is where a caller reads what it actually got.\n *\n * `aggregate` answers `AggregateResponse` — an open `Record<string,\n * unknown>`, the field-key keyed rollup `getFormAggregate`'s own `fieldKey`\n * query param narrows.\n *\n * ── `trip.answers` AND `trip.completion` ARE OPEN-SHAPED TOO ─────────────\n *\n * `CrossModuleAnswersResponse` is a `Record<string, { travellerId, value\n * }[]>` keyed by whatever binding key `?keys=` asked for — there is no\n * closed set of keys this SDK could name in advance (`bindings.list` is the\n * read of what keys exist, but the two are not cross-checked here).\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilBinaryResponse, KaafilResponse } from '../types/meta';\n\ntype FormDetailResponse = components['schemas']['FormDetailResponse'];\ntype FormDefinitionResponse = components['schemas']['FormDefinitionResponse'];\ntype FormListResponse = components['schemas']['FormListResponse'];\ntype FormSectionResponse = components['schemas']['FormSectionResponse'];\ntype FormFieldResponse = components['schemas']['FormFieldResponse'];\ntype ResponseDetailResponse = components['schemas']['ResponseDetailResponse'];\ntype ResponsesListResponse = components['schemas']['ResponsesListResponse'];\ntype TripFormsListResponse = components['schemas']['TripFormsListResponse'];\ntype CrossModuleAnswersResponse = components['schemas']['CrossModuleAnswersResponse'];\ntype CompletionMatrixResponse = components['schemas']['CompletionMatrixResponse'];\ntype DispatchResultResponse = components['schemas']['DispatchResultResponse'];\ntype BindingsListResponse = components['schemas']['BindingsListResponse'];\ntype AggregateResponse = components['schemas']['AggregateResponse'];\n\ntype CreateFormRequest = components['schemas']['CreateFormRequest'];\ntype PatchFormRequest = components['schemas']['PatchFormRequest'];\ntype CloneFormRequest = components['schemas']['CloneFormRequest'];\ntype ReorderFormRequest = components['schemas']['ReorderFormRequest'];\ntype CreateFormSectionRequest = components['schemas']['CreateFormSectionRequest'];\ntype PatchFormSectionRequest = components['schemas']['PatchFormSectionRequest'];\ntype CreateFormFieldRequest = components['schemas']['CreateFormFieldRequest'];\ntype PatchFormFieldRequest = components['schemas']['PatchFormFieldRequest'];\ntype ExportFormResponsesRequest = components['schemas']['ExportFormResponsesRequest'];\ntype DispatchFormRequest = components['schemas']['DispatchFormRequest'];\ntype ManagerCreateFormResponseRequest = components['schemas']['ManagerCreateFormResponseRequest'];\ntype FormResponseResponse = components['schemas']['FormResponseResponse'];\n\n// --- forms.{create,list,get,patch,delete} -----------------------------------\n\nexport interface CreateFormOptions extends CreateFormRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ListFormsOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchFormOptions extends PatchFormRequest {\n readonly formId: string;\n /** See this file's header — required, builds `If-Match` itself. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteFormOptions {\n readonly formId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\n// --- forms.{archive,unarchive,publish,close,reopen,clone,reorder} ----------\n\nexport interface ArchiveFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UnarchiveFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PublishFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CloseFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReopenFormOptions {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CloneFormOptions extends CloneFormRequest {\n readonly formId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReorderFormOptions extends ReorderFormRequest {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- forms.sections / forms.fields ------------------------------------------\n\nexport interface CreateFormSectionOptions extends CreateFormSectionRequest {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchFormSectionOptions extends PatchFormSectionRequest {\n readonly formId: string;\n readonly sectionId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteFormSectionOptions {\n readonly formId: string;\n readonly sectionId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface FormSectionsResource {\n /** `POST /api/v1/forms/{formId}/sections`. */\n create(options: CreateFormSectionOptions): Promise<KaafilResponse<FormSectionResponse>>;\n /** `PATCH /api/v1/forms/{formId}/sections/{sectionId}`. */\n patch(options: PatchFormSectionOptions): Promise<KaafilResponse<FormSectionResponse>>;\n /** `DELETE /api/v1/forms/{formId}/sections/{sectionId}` — cascades its\n * fields. See this file's header for the `data: false` response shape. */\n delete(options: DeleteFormSectionOptions): Promise<KaafilResponse<false>>;\n}\n\nexport interface CreateFormFieldOptions extends CreateFormFieldRequest {\n readonly formId: string;\n readonly sectionId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchFormFieldOptions extends PatchFormFieldRequest {\n readonly formId: string;\n readonly fieldId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteFormFieldOptions {\n readonly formId: string;\n readonly fieldId: string;\n /** See this file's header. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface FormFieldsResource {\n /** `POST /api/v1/forms/{formId}/sections/{sectionId}/fields`. */\n create(options: CreateFormFieldOptions): Promise<KaafilResponse<FormFieldResponse>>;\n /** `PATCH /api/v1/forms/{formId}/fields/{fieldId}`. */\n patch(options: PatchFormFieldOptions): Promise<KaafilResponse<FormFieldResponse>>;\n /** `DELETE /api/v1/forms/{formId}/fields/{fieldId}`. See this file's\n * header for the `data: false` response shape. */\n delete(options: DeleteFormFieldOptions): Promise<KaafilResponse<false>>;\n}\n\n// --- forms.aggregate ---------------------------------------------------------\n\ntype GetFormAggregateQuery = NonNullable<operations['getFormAggregate']['parameters']['query']>;\n\nexport interface ReadFormAggregateOptions extends GetFormAggregateQuery {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- forms.responses -----------------------------------------------------------\n\nexport interface ReadFormResponseOptions {\n readonly formId: string;\n readonly responseId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ExportFormResponsesOptions extends ExportFormResponsesRequest {\n readonly formId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFormConsentReceiptOptions {\n readonly responseId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface FormResponsesResource {\n /** `GET /api/v1/forms/{formId}/responses/{responseId}` — the full answer\n * set, plus staleness flags against the CURRENT form version\n * (`formVersionNow`/`definitionChangedSince`/`staleAnswers`). */\n get(options: ReadFormResponseOptions): Promise<KaafilResponse<ResponseDetailResponse>>;\n /** `POST /api/v1/forms/{formId}/responses/export` — the CSV or PDF file\n * itself, as bytes. See this file's header for why this is a\n * `KaafilBinaryResponse` and not an envelope. */\n export(options: ExportFormResponsesOptions): Promise<KaafilBinaryResponse>;\n /** `GET /api/v1/forms/responses/{responseId}/consent-receipt` — the receipt\n * PDF as bytes. See this file's header for why this one route carries no\n * `formId` in its path, and why it answers bytes. */\n consentReceipt(options: ReadFormConsentReceiptOptions): Promise<KaafilBinaryResponse>;\n}\n\n// --- forms.bindings ------------------------------------------------------------\n\nexport interface ListFormBindingsOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface FormBindingsResource {\n /** `GET /api/v1/forms/bindings` — the closed catalog of profile/CRM keys\n * a field's `binding` may target, with `optionSet` for the ones that\n * resolve to a fixed choice list. */\n list(options?: ListFormBindingsOptions): Promise<KaafilResponse<BindingsListResponse>>;\n}\n\n// --- forms.trip ------------------------------------------------------------------\n\nexport interface ListTripFormsOptions {\n readonly tripRef: string;\n readonly phase?: components['schemas']['FormDetailResponse']['phase'];\n /** The delta cursor: a previous response's own `meta.serverTime`. Omit\n * for the full live set. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFormsCrossModuleAnswersOptions {\n readonly tripRef: string;\n /** Comma-separated binding keys (`bindings.list()`'s own `key` column) to\n * resolve — the wire shape is one query string, not an array; this SDK\n * does not join one for you, since the spec itself types `keys` as a\n * single string. */\n readonly keys: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadFormsCompletionMatrixOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface DispatchFormOptions extends DispatchFormRequest {\n readonly tripRef: string;\n readonly formId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ManagerCreateFormResponseOptions extends ManagerCreateFormResponseRequest {\n readonly tripRef: string;\n readonly formId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\ntype ListTripFormResponsesQuery = NonNullable<\n operations['listTripFormResponses']['parameters']['query']\n>;\n\nexport interface ListTripFormResponsesOptions extends Omit<ListTripFormResponsesQuery, 'since'> {\n readonly tripRef: string;\n readonly formId: string;\n /** The delta cursor: a previous response's own `meta.serverTime`. Omit\n * for the full live set. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripFormResponsesResource {\n /** `POST /api/v1/trips/{ref}/forms/{formId}/responses` — on-behalf\n * capture. Accepts a manager session, an API key OR an agency-admin\n * session; this comment claimed `managerAuth`-only and was wrong even\n * before the trip-scoped reads were widened — the route has carried the\n * triple all along, which is exactly why the read gap beside it was\n * worth closing.\n * `startNew` forces a fresh response even under `responsePolicy:\n * 'SINGLE'`, where the form would otherwise resume the traveller's one\n * open response. */\n create(options: ManagerCreateFormResponseOptions): Promise<KaafilResponse<FormResponseResponse>>;\n /** `GET /api/v1/trips/{ref}/forms/{formId}/responses`. */\n list(options: ListTripFormResponsesOptions): Promise<KaafilResponse<ResponsesListResponse>>;\n}\n\nexport interface ListTravellerFormResponsesOptions {\n readonly tripRef: string;\n /** A `tripTravellerId` or the traveller's own `travellerId` — the engine\n * resolves either the same way `responses.create`'s `travellerRef` does. */\n readonly travellerRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripTravellerResponsesResource {\n /** `GET /api/v1/trips/{ref}/travellers/{travellerRef}/forms/responses` —\n * one traveller's `FormResponse` rows across every form on the trip, the\n * cross-form read `TripFormResponsesResource.list` cannot give you since\n * that one is scoped to a single `formId`. */\n list(options: ListTravellerFormResponsesOptions): Promise<KaafilResponse<ResponsesListResponse>>;\n}\n\nexport interface FormsTripResource {\n /** `GET /api/v1/trips/{ref}/forms` — this trip's applicable forms, each\n * with its resolved open/close `window` and `dispatched`/`submitted`\n * counts. */\n list(options: ListTripFormsOptions): Promise<KaafilResponse<TripFormsListResponse>>;\n /** `GET /api/v1/trips/{ref}/forms/answers` — see this file's header for\n * the open, `?keys=`-shaped response. */\n answers(\n options: ReadFormsCrossModuleAnswersOptions,\n ): Promise<KaafilResponse<CrossModuleAnswersResponse>>;\n /** `GET /api/v1/trips/{ref}/forms/completion` — per-form dispatched/\n * submitted/total counts across the trip's whole forms set. */\n completion(\n options: ReadFormsCompletionMatrixOptions,\n ): Promise<KaafilResponse<CompletionMatrixResponse>>;\n /** `POST /api/v1/trips/{ref}/forms/{formId}/dispatch` — an explicit send\n * outside the form's own `dispatchMode: 'JOURNEY'` trigger; `reason`\n * defaults to `'manual'`. */\n dispatch(options: DispatchFormOptions): Promise<KaafilResponse<DispatchResultResponse>>;\n readonly responses: TripFormResponsesResource;\n readonly travellerResponses: TripTravellerResponsesResource;\n}\n\n// --- forms -------------------------------------------------------------------\n\nexport interface FormsResource {\n /** `POST /api/v1/agencies/{ref}/forms` — authors a new definition\n * (`DRAFT`). */\n create(options: CreateFormOptions): Promise<KaafilResponse<FormDetailResponse>>;\n /** `GET /api/v1/agencies/{ref}/forms` — the agency's whole catalog. */\n list(options: ListFormsOptions): Promise<KaafilResponse<FormListResponse>>;\n /** `GET /api/v1/forms/{formId}` — definition detail: sections + fields +\n * resolved options. */\n get(options: ReadFormOptions): Promise<KaafilResponse<FormDetailResponse>>;\n /** `PATCH /api/v1/forms/{formId}`. See this file's header for the\n * required `version`. */\n patch(options: PatchFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `DELETE /api/v1/forms/{formId}`. See this file's header for the\n * required `version` and the `data: false` response shape. */\n delete(options: DeleteFormOptions): Promise<KaafilResponse<false>>;\n /** `POST /api/v1/forms/{formId}/archive`. */\n archive(options: ArchiveFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/unarchive`. */\n unarchive(options: UnarchiveFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/publish` — `DRAFT` → `ACTIVE`. */\n publish(options: PublishFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/close`. */\n close(options: CloseFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/reopen` — only within `reopenDays` of\n * closing. */\n reopen(options: ReopenFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/clone` — a new `DRAFT` copy under `key`. */\n clone(options: CloneFormOptions): Promise<KaafilResponse<FormDefinitionResponse>>;\n /** `POST /api/v1/forms/{formId}/reorder` — sets every section's and\n * field's `sortOrder` in one call. See this file's header for the\n * `data: false` response shape. */\n reorder(options: ReorderFormOptions): Promise<KaafilResponse<false>>;\n readonly sections: FormSectionsResource;\n readonly fields: FormFieldsResource;\n /** `GET /api/v1/forms/{formId}/aggregate` — see this file's header for\n * the open `AggregateResponse` payload. */\n aggregate(options: ReadFormAggregateOptions): Promise<KaafilResponse<AggregateResponse>>;\n readonly responses: FormResponsesResource;\n readonly bindings: FormBindingsResource;\n readonly trip: FormsTripResource;\n}\n\nexport function createFormsResource(client: KaafilHttpClient): FormsResource {\n return {\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<FormDetailResponse>({\n method: 'POST',\n operationId: OperationId.CreateForm,\n path: '/api/v1/agencies/{ref}/forms',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { agencyRef, signal } = options;\n return client.execute<FormListResponse>({\n method: 'GET',\n operationId: OperationId.ListForms,\n path: '/api/v1/agencies/{ref}/forms',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async get(options) {\n const { formId, signal } = options;\n return client.execute<FormDetailResponse>({\n method: 'GET',\n operationId: OperationId.GetForm,\n path: '/api/v1/forms/{formId}',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { formId, version, signal, ...body } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchForm,\n path: '/api/v1/forms/{formId}',\n pathParams: { formId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async delete(options) {\n const { formId, version, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteForm,\n path: '/api/v1/forms/{formId}',\n pathParams: { formId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async archive(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.ArchiveForm,\n path: '/api/v1/forms/{formId}/archive',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async unarchive(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.UnarchiveForm,\n path: '/api/v1/forms/{formId}/unarchive',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async publish(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.PublishForm,\n path: '/api/v1/forms/{formId}/publish',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async close(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.CloseForm,\n path: '/api/v1/forms/{formId}/close',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reopen(options) {\n const { formId, signal } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.ReopenForm,\n path: '/api/v1/forms/{formId}/reopen',\n pathParams: { formId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async clone(options) {\n const { formId, idempotencyKey, signal, ...body } = options;\n return client.execute<FormDefinitionResponse>({\n method: 'POST',\n operationId: OperationId.CloneForm,\n path: '/api/v1/forms/{formId}/clone',\n pathParams: { formId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reorder(options) {\n const { formId, signal, ...body } = options;\n return client.execute<false>({\n method: 'POST',\n operationId: OperationId.ReorderForm,\n path: '/api/v1/forms/{formId}/reorder',\n pathParams: { formId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n sections: {\n async create(options) {\n const { formId, signal, ...body } = options;\n return client.execute<FormSectionResponse>({\n method: 'POST',\n operationId: OperationId.CreateFormSection,\n path: '/api/v1/forms/{formId}/sections',\n pathParams: { formId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { formId, sectionId, version, signal, ...body } = options;\n return client.execute<FormSectionResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchFormSection,\n path: '/api/v1/forms/{formId}/sections/{sectionId}',\n pathParams: { formId, sectionId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async delete(options) {\n const { formId, sectionId, version, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteFormSection,\n path: '/api/v1/forms/{formId}/sections/{sectionId}',\n pathParams: { formId, sectionId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n fields: {\n async create(options) {\n const { formId, sectionId, signal, ...body } = options;\n return client.execute<FormFieldResponse>({\n method: 'POST',\n operationId: OperationId.CreateFormField,\n path: '/api/v1/forms/{formId}/sections/{sectionId}/fields',\n pathParams: { formId, sectionId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { formId, fieldId, version, signal, ...body } = options;\n return client.execute<FormFieldResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchFormField,\n path: '/api/v1/forms/{formId}/fields/{fieldId}',\n pathParams: { formId, fieldId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async delete(options) {\n const { formId, fieldId, version, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteFormField,\n path: '/api/v1/forms/{formId}/fields/{fieldId}',\n pathParams: { formId, fieldId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n async aggregate(options) {\n const { formId, signal, ...query } = options;\n return client.execute<AggregateResponse>({\n method: 'GET',\n operationId: OperationId.GetFormAggregate,\n path: '/api/v1/forms/{formId}/aggregate',\n pathParams: { formId },\n query,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n responses: {\n async get(options) {\n const { formId, responseId, signal } = options;\n return client.execute<ResponseDetailResponse>({\n method: 'GET',\n operationId: OperationId.GetFormResponse,\n path: '/api/v1/forms/{formId}/responses/{responseId}',\n pathParams: { formId, responseId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async export(options) {\n const { formId, signal, ...body } = options;\n return client.executeBinary({\n method: 'POST',\n operationId: OperationId.ExportFormResponses,\n path: '/api/v1/forms/{formId}/responses/export',\n pathParams: { formId },\n body,\n // Follows the requested format rather than being hardcoded: the\n // engine branches on `body.format` and sets the matching\n // `Content-Type` (`forms.controller.ts#exportResponses`).\n accept: body.format === 'csv' ? 'text/csv' : 'application/pdf',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async consentReceipt(options) {\n const { responseId, signal } = options;\n return client.executeBinary({\n method: 'GET',\n operationId: OperationId.GetFormConsentReceipt,\n path: '/api/v1/forms/responses/{responseId}/consent-receipt',\n pathParams: { responseId },\n accept: 'application/pdf',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n bindings: {\n async list(options = {}) {\n const { signal } = options;\n return client.execute<BindingsListResponse>({\n method: 'GET',\n operationId: OperationId.ListFormBindings,\n path: '/api/v1/forms/bindings',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n trip: {\n async list(options) {\n const { tripRef, phase, since, signal } = options;\n return client.execute<TripFormsListResponse>({\n method: 'GET',\n operationId: OperationId.ListTripForms,\n path: '/api/v1/trips/{ref}/forms',\n pathParams: { ref: tripRef },\n query: { phase, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async answers(options) {\n const { tripRef, keys, signal } = options;\n return client.execute<CrossModuleAnswersResponse>({\n method: 'GET',\n operationId: OperationId.GetFormsCrossModuleAnswers,\n path: '/api/v1/trips/{ref}/forms/answers',\n pathParams: { ref: tripRef },\n query: { keys },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async completion(options) {\n const { tripRef, signal } = options;\n return client.execute<CompletionMatrixResponse>({\n method: 'GET',\n operationId: OperationId.GetFormsCompletionMatrix,\n path: '/api/v1/trips/{ref}/forms/completion',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async dispatch(options) {\n const { tripRef, formId, idempotencyKey, signal, ...body } = options;\n return client.execute<DispatchResultResponse>({\n method: 'POST',\n operationId: OperationId.DispatchForm,\n path: '/api/v1/trips/{ref}/forms/{formId}/dispatch',\n pathParams: { ref: tripRef, formId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n responses: {\n async create(options) {\n const { tripRef, formId, idempotencyKey, signal, ...body } = options;\n return client.execute<FormResponseResponse>({\n method: 'POST',\n operationId: OperationId.ManagerCreateFormResponse,\n path: '/api/v1/trips/{ref}/forms/{formId}/responses',\n pathParams: { ref: tripRef, formId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { tripRef, formId, since, signal, ...filters } = options;\n return client.execute<ResponsesListResponse>({\n method: 'GET',\n operationId: OperationId.ListTripFormResponses,\n path: '/api/v1/trips/{ref}/forms/{formId}/responses',\n pathParams: { ref: tripRef, formId },\n query: { ...filters, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n travellerResponses: {\n async list(options) {\n const { tripRef, travellerRef, signal } = options;\n return client.execute<ResponsesListResponse>({\n method: 'GET',\n operationId: OperationId.ListTravellerFormResponses,\n path: '/api/v1/trips/{ref}/travellers/{travellerRef}/forms/responses',\n pathParams: { ref: tripRef, travellerRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n },\n };\n}\n","/**\n * `itinerary` — the day cards and their ordered items, plus the change log.\n * `architecture/08-sdk.md §4`.\n *\n * EVERY operation here — both reads AND all five writes — accepts an API key,\n * a manager session OR an agency-admin session, never an AND; the consumer\n * never chooses which, `../auth/credentials.ts`'s `CredentialResolver` picks\n * whichever scheme the configured credential satisfies.\n *\n * This block previously said \"Every WRITE here is `managerAuth`-only: the\n * itinerary is edited on the ground, and an API-key write answers `401`.\" That\n * is no longer true and is corrected rather than softened, because it is the\n * sentence a reader would act on. `itinerary.routes.ts` now declares\n * `auth: ['manager', 'apiKey', 'agencyAdmin']` on all five writes — the same\n * triple the reads already carried — and `../generated/security.ts` agrees\n * (`addItineraryItem`, `patchItineraryItem`, `deleteItineraryItem`,\n * `reorderItineraryItem` and `patchItineraryDay` each list all three schemes).\n * The engine's own router header carries the argument: the agency knob FRD §9\n * describes (`itinerary.adminEditing`) has no flag-catalog key to live in, so\n * the widening landed ahead of a gate that has nothing to switch off. A\n * COORDINATOR-role manager still reads 200 and is refused every write with\n * `422 READ_ONLY_ROLE`, which is a role check on the SESSION, not a scheme.\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so `items.patch` (a trip ref AND an item id) and\n * `days.patch` (a trip ref AND a day index) can't be called with their\n * arguments swapped.\n *\n * `read` is one operation with three modes, because OpenAPI keys an operation\n * by (path, method) and all three are `GET /trips/{ref}/itinerary`: the full\n * aggregate, `?dayIndex=` for one day, and `?since=` for a delta. The two\n * compose. For the delta mode, drive `since` through\n * `../delta/cursor.ts`'s `createDeltaCursor` rather than by hand — that file's\n * header is the argument for why any other cursor loses rows.\n */\n\nimport {\n type DateTimeInput,\n normalizeDateTimeInput,\n normalizeNullableDateTimeInput,\n} from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype ItineraryReadResponse = components['schemas']['ItineraryReadResponse'];\ntype ItineraryDayResponse = components['schemas']['ItineraryDayResponse'];\ntype ItineraryItemResponse = components['schemas']['ItineraryItemResponse'];\ntype ItineraryItemTombstoneResponse = components['schemas']['ItineraryItemTombstoneResponse'];\ntype ItineraryReorderResponse = components['schemas']['ItineraryReorderResponse'];\ntype ItineraryChangeLogEntryResponse = components['schemas']['ItineraryChangeLogEntryResponse'];\ntype AddItineraryItemRequest = components['schemas']['AddItineraryItemRequest'];\ntype PatchItineraryItemRequest = components['schemas']['PatchItineraryItemRequest'];\ntype ReorderItineraryItemRequest = components['schemas']['ReorderItineraryItemRequest'];\ntype PatchItineraryDayRequest = components['schemas']['PatchItineraryDayRequest'];\n\n/**\n * One row of `read`'s `items[]`: a live item, or the tombstone for one deleted\n * since the cursor. Aliased off the response type rather than restated, so the\n * union stays whatever the contract says it is.\n *\n * Named and exported because a consumer writing a render function over\n * `items` has to name its parameter, and the union is the whole point — see\n * `../delta/cursor.ts`'s `isTombstone`.\n */\nexport type ItineraryItemDeltaRow = ItineraryReadResponse['items'][number];\n\n// --- date-time widening --------------------------------------------------\n//\n// `isoDate`, `startTime` and `endTime` are `string` (`Format: date-time`) in\n// the generated schema, because the schema is a faithful mirror of the spec\n// and the wire format really is a string. The `*Options` types below widen\n// exactly those fields to `DateTimeInput` (see `../datetime`) by indexing off\n// the generated type and overriding — never restating a request body by hand —\n// so a spec change to any other field flows through untouched. The factory\n// normalizes back down to `string` before the body reaches the wire.\n//\n// `startTime`/`endTime` widen to `DateTimeInput | null`, not just\n// `DateTimeInput`: `null` is how a manager CLEARS a time that was set, and it\n// is distinct from omitting the field. `../datetime.ts`'s\n// `normalizeNullableDateTimeInput` carries that argument.\n\n// --- itinerary.read ----------------------------------------------------------\n\nexport interface ReadItineraryOptions {\n readonly tripRef: string;\n /** Narrows the same shape to one day. 0-based, as `days[].dayIndex` reports it. */\n readonly dayIndex?: number;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and nothing\n * else. Omit it for the full aggregate. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the boundary is the one\n * thing that silently loses rows, and that module owns it.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- itinerary.items ----------------------------------------------------------\n\nexport interface AddItineraryItemOptions\n extends Omit<AddItineraryItemRequest, 'isoDate' | 'startTime' | 'endTime'> {\n readonly tripRef: string;\n /**\n * Which day the item belongs to, as a date. The engine resolves it to a day\n * index in the TRIP's timezone and find-or-creates the day — a client never\n * computes a day index itself, and must not, because the answer depends on a\n * timezone the client may not be in.\n */\n readonly isoDate: DateTimeInput;\n readonly startTime?: DateTimeInput | null;\n readonly endTime?: DateTimeInput | null;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchItineraryItemOptions\n extends Omit<PatchItineraryItemRequest, 'startTime' | 'endTime'> {\n readonly tripRef: string;\n readonly itemId: string;\n readonly startTime?: DateTimeInput | null;\n readonly endTime?: DateTimeInput | null;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this method\n * makes forgetting it impossible instead of merely discouraged. Pass the\n * `version` from the item as last read. The SDK builds the `If-Match` header\n * itself; never set it in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteItineraryItemOptions {\n readonly tripRef: string;\n readonly itemId: string;\n /** See `PatchItineraryItemOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReorderItineraryItemOptions extends ReorderItineraryItemRequest {\n readonly tripRef: string;\n readonly itemId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ItineraryItemsResource {\n /**\n * `POST …/itinerary/items` — APPENDS at the tail of its day.\n *\n * This is the one write in the ingest path that is not an upsert, and the\n * asymmetry is worth stating because everything around it is. `trips.upsert`,\n * `travellers.pushManifest` and `managers.upsert` are all safe to replay —\n * push the same payload twice and the second is answered `ignored_stale`.\n * Call this twice with the same title and you get TWO items on that day.\n *\n * ── WHY A RETRY DOES NOT SAVE YOU ──────────────────────────────────────────\n *\n * `Idempotency-Key` protects the TRANSPORT: the SDK mints one per call\n * (`../http/client.ts`'s `execute()`), so a socket that dies after the server\n * committed cannot create the item twice on the automatic retry.\n *\n * It does NOT protect an APPLICATION retry. Re-running your seeding script,\n * or catching an error and calling `add` again, is a NEW call with a NEW\n * generated key, and the server appends again. The auto-minting is what makes\n * this easy to miss — the safety is real and it is guarding a different thing.\n *\n * ── WHAT TO DO INSTEAD ─────────────────────────────────────────────────────\n *\n * Either pass your own stable `idempotencyKey` derived from the content\n * (`newIdempotencyKey()` in `../idempotency.ts` explains the shape), or read\n * the day first with `itinerary.read()` and skip titles already on it. A\n * seeding script that runs more than once wants the second.\n */\n add(options: AddItineraryItemOptions): Promise<KaafilResponse<ItineraryItemResponse>>;\n patch(options: PatchItineraryItemOptions): Promise<KaafilResponse<ItineraryItemResponse>>;\n /**\n * Soft-deletes the item. Answers the TOMBSTONE — the same `_tombstone`\n * marker a later `?since=` pull would carry for it — rather than an empty\n * body, so the caller that issued the delete applies the identical drop to\n * its local store as one that learned about it from a delta.\n */\n remove(\n options: DeleteItineraryItemOptions,\n ): Promise<KaafilResponse<ItineraryItemTombstoneResponse>>;\n /**\n * Moves the item to `index` within its own day; the index is clamped\n * server-side, and the whole day is re-stamped densely so two devices\n * replaying the same reorder land on identical `sortOrder` values.\n *\n * No `version` and no `If-Match`, deliberately: a reorder is last-write-wins\n * by design, and a conflict is resolved by re-reading the day (the response\n * already carries the day's full item list, in its new order).\n */\n reorder(options: ReorderItineraryItemOptions): Promise<KaafilResponse<ItineraryReorderResponse>>;\n}\n\n// --- itinerary.days -----------------------------------------------------------\n\nexport interface PatchItineraryDayOptions extends PatchItineraryDayRequest {\n readonly tripRef: string;\n /** 0-based, as `days[].dayIndex` reports it — the day's position, not its id. */\n readonly dayIndex: number;\n /** See `PatchItineraryItemOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ItineraryDaysResource {\n /** `PATCH …/itinerary/days/{dayIndex}` — the card title and the summary line. */\n patch(options: PatchItineraryDayOptions): Promise<KaafilResponse<ItineraryDayResponse>>;\n}\n\n// --- itinerary.changeLog ------------------------------------------------------\n\nexport interface ListItineraryChangeLogOptions {\n readonly tripRef: string;\n /** See `ReadItineraryOptions.since`. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ItineraryChangeLogResource {\n /** `GET …/itinerary/change-log` — the most recent entries, newest first.\n * Not cursor-paginated (no `cursor`/`limit` query params in the spec).\n * `performedByKind ∈ MANAGER|AGENCY_ADMIN|API_KEY|SYSTEM` and\n * `performedById` (nullable for `SYSTEM`) name WHO made each change — the\n * same actor-attribution pair now normalized onto this and eight other\n * response models, replacing the old free-form `actorType`/`actorId`\n * shape. */\n list(\n options: ListItineraryChangeLogOptions,\n ): Promise<KaafilResponse<readonly ItineraryChangeLogEntryResponse[]>>;\n}\n\n// --- itinerary ----------------------------------------------------------------\n\nexport interface ItineraryResource {\n read(options: ReadItineraryOptions): Promise<KaafilResponse<ItineraryReadResponse>>;\n readonly items: ItineraryItemsResource;\n readonly days: ItineraryDaysResource;\n readonly changeLog: ItineraryChangeLogResource;\n}\n\nexport function createItineraryResource(client: KaafilHttpClient): ItineraryResource {\n return {\n async read(options) {\n const { tripRef, dayIndex, since, signal } = options;\n return client.execute<ItineraryReadResponse>({\n method: 'GET',\n operationId: OperationId.ReadItinerary,\n path: '/api/v1/trips/{ref}/itinerary',\n pathParams: { ref: tripRef },\n query: { dayIndex, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n items: {\n async add(options) {\n const { tripRef, idempotencyKey, signal, isoDate, startTime, endTime, ...rest } = options;\n const body: AddItineraryItemRequest = {\n ...rest,\n isoDate: normalizeDateTimeInput(isoDate, 'isoDate'),\n ...(startTime !== undefined\n ? { startTime: normalizeNullableDateTimeInput(startTime, 'startTime') }\n : {}),\n ...(endTime !== undefined\n ? { endTime: normalizeNullableDateTimeInput(endTime, 'endTime') }\n : {}),\n };\n return client.execute<ItineraryItemResponse>({\n method: 'POST',\n operationId: OperationId.AddItineraryItem,\n path: '/api/v1/trips/{ref}/itinerary/items',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, itemId, version, signal, startTime, endTime, ...rest } = options;\n const body: PatchItineraryItemRequest = {\n ...rest,\n ...(startTime !== undefined\n ? { startTime: normalizeNullableDateTimeInput(startTime, 'startTime') }\n : {}),\n ...(endTime !== undefined\n ? { endTime: normalizeNullableDateTimeInput(endTime, 'endTime') }\n : {}),\n };\n return client.execute<ItineraryItemResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchItineraryItem,\n path: '/api/v1/trips/{ref}/itinerary/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, itemId, version, signal } = options;\n return client.execute<ItineraryItemTombstoneResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteItineraryItem,\n path: '/api/v1/trips/{ref}/itinerary/items/{itemId}',\n pathParams: { ref: tripRef, itemId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reorder(options) {\n const { tripRef, itemId, idempotencyKey, signal, ...body } = options;\n return client.execute<ItineraryReorderResponse>({\n method: 'POST',\n operationId: OperationId.ReorderItineraryItem,\n path: '/api/v1/trips/{ref}/itinerary/items/{itemId}/reorder',\n pathParams: { ref: tripRef, itemId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n days: {\n async patch(options) {\n const { tripRef, dayIndex, version, signal, ...body } = options;\n return client.execute<ItineraryDayResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchItineraryDay,\n path: '/api/v1/trips/{ref}/itinerary/days/{dayIndex}',\n pathParams: { ref: tripRef, dayIndex },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n changeLog: {\n async list(options) {\n const { tripRef, since, signal } = options;\n return client.execute<readonly ItineraryChangeLogEntryResponse[]>({\n method: 'GET',\n operationId: OperationId.ReadItineraryChangeLog,\n path: '/api/v1/trips/{ref}/itinerary/change-log',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `journey` — get, capabilities, rebuild, runStep, and the agency-level\n * triggers (list, patch). `architecture/08-sdk.md §4`, amended `C-028`.\n *\n * `get`/`capabilities` accept an API key, a manager session, OR an\n * agency-admin session (`readJourney`/`readJourneyCapabilities` declare\n * `security: [{apiKeyAuth}, {managerAuth}, {agencyAdminAuth}]` — three\n * alternatives, `D-067`/`D-070`) — the consumer never chooses which;\n * `../auth/credentials.ts`'s `CredentialResolver` already picks whichever\n * scheme the configured credential satisfies. `triggers.list`/`triggers.patch`\n * accept the same set minus the API key\n * (`listJourneyTriggers`/`patchJourneyTrigger` declare `apiKeyAuth` OR\n * `agencyAdminAuth`).\n *\n * The trip-scoped methods (`get`, `capabilities`, `rebuild`, `runStep`) and\n * the agency-scoped ones (`triggers.list`, `triggers.patch`) use different\n * `{ref}` path parameters in the spec — a trip ref for the former, an agency\n * ref for the latter. Named `tripRef` / `agencyRef` respectively so the two\n * can never be confused for one another at a call site.\n *\n * `capabilities({ live: true })` (GAP-003) asks for a synchronous recompute\n * against live trip/entitlement state instead of the last persisted build —\n * never persisted itself. This is a query-param addition to\n * `readJourneyCapabilities`, not a new operation, so it carries the exact\n * same three-scheme accept list as a plain `capabilities()` call.\n * `rebuild` (`rebuildJourney`) was deliberately NOT widened to take `live` —\n * it stays `apiKeyAuth`-only, a full async rebuild, and remains a distinct\n * operation from this synchronous read.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { KaafilAbortError, KaafilNotFoundError, KaafilTimeoutError } from '../http/errors';\nimport { delayWithAbort } from '../http/retry';\nimport type { KaafilResponse } from '../types/meta';\n\ntype JourneyReadResponse = components['schemas']['JourneyReadResponse'];\ntype JourneyCapabilitiesResponse = components['schemas']['JourneyCapabilitiesResponse'];\ntype JourneyRebuildResponse = components['schemas']['JourneyRebuildResponse'];\ntype JourneyStepRunResponse = components['schemas']['JourneyStepRunResponse'];\ntype JourneyTriggerResponse = components['schemas']['JourneyTriggerResponse'];\ntype PatchJourneyTriggerRequest = components['schemas']['PatchJourneyTriggerRequest'];\n\n// --- journey.{get,capabilities,rebuild,runStep} -----------------------------\n\nexport interface ReadJourneyOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadJourneyCapabilitiesOptions {\n readonly tripRef: string;\n /**\n * `true` for a synchronous recompute against LIVE trip/entitlement state,\n * never persisted — GAP-003. Omit (or `false`) for the last persisted\n * build, the unchanged default. The spec declares `live` as the literal\n * string `\"true\"` (`operations['readJourneyCapabilities']['parameters']\n * ['query']`), never a JSON boolean — this method takes a real `boolean`\n * and does the `'true'` string conversion itself so a caller never has to\n * know that.\n */\n readonly live?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface RebuildJourneyOptions {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface RunJourneyStepOptions {\n readonly tripRef: string;\n readonly stepId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- journey.waitUntilReady ---------------------------------------------------\n\n/**\n * There is no ready endpoint — a journey build is enqueued by\n * `trips.upsert` plus a manager assignment, consumed asynchronously by a\n * background worker, and `journey.get` answers `404 RESOURCE_NOT_FOUND`\n * until it lands (`architecture/06-offline-first.md`). Every consumer was\n * hand-writing this same poll loop; this method owns it instead so a\n * caller cannot get it wrong by forgetting a deadline or by treating the\n * interim `404` as fatal.\n */\nexport interface WaitUntilJourneyReadyOptions {\n readonly tripRef: string;\n /** Total budget before giving up. Default ~60s — comfortably above a\n * healthy worker's build time, short enough not to hang a caller forever\n * behind a dead one. */\n readonly timeoutMs?: number;\n /** Delay between polls once a `404` says \"not yet\". Default ~1s. */\n readonly pollIntervalMs?: number;\n readonly signal?: AbortSignal;\n}\n\nconst DEFAULT_WAIT_UNTIL_READY_TIMEOUT_MS = 60_000;\nconst DEFAULT_WAIT_UNTIL_READY_POLL_INTERVAL_MS = 1_000;\n\n// --- journey.triggers ---------------------------------------------------------\n\nexport interface ListJourneyTriggersOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchJourneyTriggerOptions extends PatchJourneyTriggerRequest {\n readonly agencyRef: string;\n readonly key: string;\n /**\n * Disambiguates which row to patch when `key` exists under more than one\n * trip mode (`@@unique([agencyId, tripMode, key])` on the engine's own\n * `JourneyTrigger` — the seeded set does this for\n * `form.post-trip-feedback`). Omit when `key` is unique for this agency;\n * the engine falls back to a deterministic GROUP-first resolution in that\n * case, but a caller that already knows which `tripMode` row it read via\n * `triggers.list()` should always pass it back here rather than rely on\n * that fallback.\n */\n readonly tripMode?: 'GROUP' | 'PERSONALIZED';\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this\n * method makes forgetting it impossible instead of merely discouraged.\n * Pass the `version` from a trigger just read via `triggers.list()`. The\n * SDK builds the `If-Match` header itself; never set it in `headers`.\n */\n readonly version: number;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface JourneyTriggersResource {\n /** `GET /api/v1/agencies/{ref}/journey-triggers` — not cursor-paginated\n * (no `cursor`/`limit` query params in the spec); returns the full list. */\n list(\n options: ListJourneyTriggersOptions,\n ): Promise<KaafilResponse<readonly JourneyTriggerResponse[]>>;\n /** `PATCH /api/v1/agencies/{ref}/journey-triggers/{key}`. */\n patch(options: PatchJourneyTriggerOptions): Promise<KaafilResponse<JourneyTriggerResponse>>;\n}\n\n// --- journey -------------------------------------------------------------------\n\nexport interface JourneyResource {\n get(options: ReadJourneyOptions): Promise<KaafilResponse<JourneyReadResponse>>;\n capabilities(\n options: ReadJourneyCapabilitiesOptions,\n ): Promise<KaafilResponse<readonly JourneyCapabilitiesResponse[]>>;\n rebuild(options: RebuildJourneyOptions): Promise<KaafilResponse<JourneyRebuildResponse>>;\n runStep(options: RunJourneyStepOptions): Promise<KaafilResponse<JourneyStepRunResponse>>;\n /**\n * Polls `get` until the journey lands, resolving with the exact same\n * value `get` would — a drop-in replacement for \"get, but wait for it\".\n * A `404` is treated as \"not ready yet\"; every other typed error (a\n * `402`, `422`, `401`, …) propagates immediately, since retrying those\n * only burns the deadline on an outcome that will never change.\n */\n waitUntilReady(\n options: WaitUntilJourneyReadyOptions,\n ): Promise<KaafilResponse<JourneyReadResponse>>;\n readonly triggers: JourneyTriggersResource;\n}\n\nexport function createJourneyResource(client: KaafilHttpClient): JourneyResource {\n const resource: JourneyResource = {\n async get(options) {\n const { tripRef, signal } = options;\n return client.execute<JourneyReadResponse>({\n method: 'GET',\n operationId: OperationId.ReadJourney,\n path: '/api/v1/trips/{ref}/journey',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async capabilities(options) {\n const { tripRef, live, signal } = options;\n return client.execute<readonly JourneyCapabilitiesResponse[]>({\n method: 'GET',\n operationId: OperationId.ReadJourneyCapabilities,\n path: '/api/v1/trips/{ref}/journey/capabilities',\n pathParams: { ref: tripRef },\n ...(live === true ? { query: { live: 'true' as const } } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async rebuild(options) {\n const { tripRef, idempotencyKey, signal } = options;\n return client.execute<JourneyRebuildResponse>({\n method: 'POST',\n operationId: OperationId.RebuildJourney,\n path: '/api/v1/trips/{ref}/journey/rebuild',\n pathParams: { ref: tripRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async runStep(options) {\n const { tripRef, stepId, idempotencyKey, signal } = options;\n return client.execute<JourneyStepRunResponse>({\n method: 'POST',\n operationId: OperationId.RunJourneyStep,\n path: '/api/v1/trips/{ref}/journey/steps/{stepId}/run',\n pathParams: { ref: tripRef, stepId },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n async waitUntilReady(options) {\n const {\n tripRef,\n timeoutMs = DEFAULT_WAIT_UNTIL_READY_TIMEOUT_MS,\n pollIntervalMs = DEFAULT_WAIT_UNTIL_READY_POLL_INTERVAL_MS,\n signal,\n } = options;\n const deadlineAt = Date.now() + timeoutMs;\n\n for (;;) {\n try {\n return await resource.get({ tripRef, ...(signal !== undefined ? { signal } : {}) });\n } catch (error) {\n // Everything except \"not ready yet\" is terminal: a 402, 422 or\n // 401 will never become ready, so propagate it immediately\n // rather than spending the caller's deadline retrying it.\n if (!(error instanceof KaafilNotFoundError)) {\n throw error;\n }\n\n const remainingMs = deadlineAt - Date.now();\n if (remainingMs <= 0) {\n throw new KaafilTimeoutError(\n `journey.waitUntilReady timed out after ${String(timeoutMs)}ms waiting for trip ` +\n `\"${tripRef}\" to become ready. The most likely cause is that the background worker ` +\n 'that consumes the build queue is not running against this engine.',\n { cause: error },\n );\n }\n\n try {\n await delayWithAbort(Math.min(pollIntervalMs, remainingMs), signal);\n } catch (sleepError) {\n // `delayWithAbort` only ever rejects because `signal` fired —\n // normalize to the same `KaafilAbortError` a `get()` abort\n // would have thrown, so a caller branching on error type sees\n // one shape regardless of which tick the abort landed on.\n throw new KaafilAbortError('Request aborted', { cause: sleepError });\n }\n }\n }\n },\n\n triggers: {\n async list(options) {\n const { agencyRef, signal } = options;\n return client.execute<readonly JourneyTriggerResponse[]>({\n method: 'GET',\n operationId: OperationId.ListJourneyTriggers,\n path: '/api/v1/agencies/{ref}/journey-triggers',\n pathParams: { ref: agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { agencyRef, key, tripMode, version, idempotencyKey, signal, ...body } = options;\n return client.execute<JourneyTriggerResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchJourneyTrigger,\n path: '/api/v1/agencies/{ref}/journey-triggers/{key}',\n pathParams: { ref: agencyRef, key },\n ...(tripMode !== undefined ? { query: { tripMode } } : {}),\n body,\n headers: { 'If-Match': String(version) },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n\n return resource;\n}\n","/**\n * `managerToday` — `GET /trips/{ref}/manager/today`, the phase-and-day-aware\n * aggregate a manager operating a trip in the field needs, so they do not\n * have to call `itinerary`, `pickups`, `rooming`, `checklists` and `seating`\n * separately and merge them on the phone. `architecture/08-sdk.md §4`.\n *\n * One read, `readManagerToday` — declares the same three-alternative auth set\n * `itinerary.read` does (an API key, a manager session OR an agency-admin\n * session), because it is itself a read composing five other already-gated\n * reads, never a write.\n *\n * `data.kind` discriminates the response: `'idle'` (the trip is not\n * `ON_TRIP` right now — nothing before departure or after close to report),\n * `'trip'`, or `'trek'` (`'trek'` carries every field `'trip'` does, plus its\n * own `trekPhase`). Narrow on `kind` before reading any of the\n * `trip`/`trek`-only fields — the response type already forces this.\n *\n * `itinerary`/`checklist`/`pickups`/`rooming`/`transport` are each\n * independently `null` when that domain's OWN capability is dark for the\n * agency, never a thrown error for the whole read — branch on `null`, not on\n * a catch.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\nexport type ManagerTodayResponse = components['schemas']['ManagerTodayResponse'];\n\n/** The `kind: 'idle'` reading, narrowed off the union. */\nexport type ManagerTodayIdle = Extract<ManagerTodayResponse, { kind: 'idle' }>;\n/** The `kind: 'trip'` reading, narrowed off the union. */\nexport type ManagerTodayTrip = Extract<ManagerTodayResponse, { kind: 'trip' }>;\n/** The `kind: 'trek'` reading, narrowed off the union — `ManagerTodayTrip`'s fields plus `trekPhase`. */\nexport type ManagerTodayTrek = Extract<ManagerTodayResponse, { kind: 'trek' }>;\n\nexport interface ReadManagerTodayOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ManagerTodayResource {\n read(options: ReadManagerTodayOptions): Promise<KaafilResponse<ManagerTodayResponse>>;\n}\n\nexport function createManagerTodayResource(client: KaafilHttpClient): ManagerTodayResource {\n return {\n async read(options) {\n const { tripRef, signal } = options;\n return client.execute<ManagerTodayResponse>({\n method: 'GET',\n operationId: OperationId.ReadManagerToday,\n path: '/api/v1/trips/{ref}/manager/today',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `pickups` — the stop list, reorder, manifest-by-pickup, assign/board and\n * the close/reopen policy. `architecture/08-sdk.md §4`.\n *\n * `list` and `manifestByPickup` accept a manager session, an agency-admin\n * session OR an API key (three alternatives, never an AND) — same for the\n * authoring writes `create`/`patch`/`remove`/`reorder`/`assign`/\n * `correctBoardStatus` (stop-list management an agency admin or a CRM can do\n * off the ground). Only the three ON-GROUND actions — `board`, `close`,\n * `reopen` — are `managerAuth`-only, the same split `seating`, `rooming` and\n * `itinerary` have and for the same reason: boarding a traveller or\n * closing/reopening a stop is a call made standing at the stop, not from an\n * office. Checked against `../generated/security.ts`'s `OPERATION_SECURITY`,\n * the source of truth.\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so `assign` (a trip ref AND a stop id) can't be called\n * with its arguments swapped.\n *\n * ── ONE `close` METHOD, TWO POLICIES, ONE CODE ──────────────────────────────\n *\n * `close()` is a single operation whichever `Trip.eventType` the trip carries\n * — never two endpoints and never two codes. On a `TRIP`, every `PENDING`\n * traveller must appear in `resolutions[]` with a terminal status, and\n * `confirm` is ignored; on a `TREK`, `resolutions[]` is optional and a short\n * close (`boardedCount < expectedCount`) needs `confirm: true` PLUS\n * `confirmedHeadCount`. Both branches answer the SAME `422 STOP_HAS_PENDING`\n * when they refuse — a TREK short-close refusal additionally carries\n * `details.requiresConfirm: true`, which is what tells a caller to show the\n * confirm sheet rather than the per-traveller resolver, and NOT a second\n * code. `details` is untyped at the transport boundary (the envelope\n * schema's own `additionalProperties: {}`), so read it defensively:\n * `error.details?.requiresConfirm === true`.\n *\n * `confirmedHeadCount` disagreeing with the actual count is FLAGGED\n * (`CloseResponse.headCountMismatch`), never blocking — \"a manager on a\n * trailhead can't wait forever.\"\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype PickupStopResponse = components['schemas']['PickupStopResponse'];\ntype PickupStopDeltaResponse = components['schemas']['PickupStopDeltaResponse'];\ntype PickupStopDeleteResponse = components['schemas']['PickupStopDeleteResponse'];\ntype ManifestByPickupResponse = components['schemas']['ManifestByPickupResponse'];\ntype AssignResponse = components['schemas']['AssignResponse'];\ntype ReassignResponse = components['schemas']['ReassignResponse'];\ntype ReassignPickupStopTravellersRequest =\n components['schemas']['ReassignPickupStopTravellersRequest'];\ntype BoardResponse = components['schemas']['BoardResponse'];\ntype CorrectPickupBoardStatusRequest = components['schemas']['CorrectPickupBoardStatusRequest'];\ntype CloseResponse = components['schemas']['CloseResponse'];\ntype ReopenResponse = components['schemas']['ReopenResponse'];\ntype CreatePickupStopRequest = components['schemas']['CreatePickupStopRequest'];\ntype PatchPickupStopRequest = components['schemas']['PatchPickupStopRequest'];\ntype ReorderPickupStopsRequest = components['schemas']['ReorderPickupStopsRequest'];\ntype AssignPickupTravellerRequest = components['schemas']['AssignPickupTravellerRequest'];\ntype BoardPickupTravellerRequest = components['schemas']['BoardPickupTravellerRequest'];\ntype ClosePickupStopRequest = components['schemas']['ClosePickupStopRequest'];\n\n/**\n * One row of `list`'s result: a live stop, or the tombstone for one deleted\n * since the cursor. Aliased off the response type rather than restated, so\n * the union stays whatever the contract says it is. See `../delta/cursor.ts`'s\n * `isTombstone`.\n */\nexport type PickupStopDeltaRow = PickupStopDeltaResponse;\n\n// --- date-time widening --------------------------------------------------\n//\n// `scheduledTime` is `string` (`Format: date-time`) in the generated schema,\n// because the schema is a faithful mirror of the spec and the wire format\n// really is a string. The `*Options` types below widen exactly that field to\n// `DateTimeInput` (see `../datetime`) by indexing off the generated type and\n// overriding — never restating a request body by hand. The factory\n// normalizes back down to `string` before the body reaches the wire.\n\n// --- pickups.list / pickups.manifestByPickup ---------------------------------\n\nexport interface ListPickupStopsOptions {\n readonly tripRef: string;\n /** Narrows to one stop kind. Omitted lists both `PICKUP` and `DROP`. */\n readonly kind?: components['schemas']['PickupStopResponse']['kind'];\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit it for the full list. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the boundary is the\n * one thing that silently loses rows, and that module owns it.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadManifestByPickupOptions {\n readonly tripRef: string;\n /** See `ListPickupStopsOptions.kind`. */\n readonly kind?: components['schemas']['PickupStopResponse']['kind'];\n readonly signal?: AbortSignal;\n}\n\n// --- pickups CRUD --------------------------------------------------------\n\nexport interface CreatePickupStopOptions extends Omit<CreatePickupStopRequest, 'scheduledTime'> {\n readonly tripRef: string;\n readonly scheduledTime: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchPickupStopOptions extends Omit<PatchPickupStopRequest, 'scheduledTime'> {\n readonly tripRef: string;\n readonly pointId: string;\n readonly scheduledTime?: DateTimeInput;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this\n * method makes forgetting it impossible instead of merely discouraged.\n * Pass the `version` from the stop as last read. The SDK builds the\n * `If-Match` header itself; never set it in `headers`.\n *\n * Changing `kind` while the stop holds assignments is refused with\n * `422 BUSINESS_RULE_VIOLATION` and `details.assignedCount` — reassign or\n * clear the stop first.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeletePickupStopOptions {\n readonly tripRef: string;\n readonly pointId: string;\n /** See `PatchPickupStopOptions.version` — same contract. */\n readonly version: number;\n /** Releases every assignment on this stop back to unassigned before\n * deleting it. Without it, a stop with assignments is refused. */\n readonly force?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReorderPickupStopsOptions extends ReorderPickupStopsRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- pickups.assign / pickups.board -------------------------------------------\n\nexport interface AssignPickupTravellerOptions extends AssignPickupTravellerRequest {\n readonly tripRef: string;\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReassignPickupStopTravellersOptions extends ReassignPickupStopTravellersRequest {\n readonly tripRef: string;\n /** The stop to move every live, not-yet-boarded traveller OFF of. */\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface BoardPickupTravellerOptions extends BoardPickupTravellerRequest {\n readonly tripRef: string;\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CorrectPickupBoardStatusOptions extends CorrectPickupBoardStatusRequest {\n readonly tripRef: string;\n readonly pointId: string;\n readonly travellerId: string;\n readonly signal?: AbortSignal;\n}\n\n// --- pickups.close / pickups.reopen -------------------------------------------\n\nexport interface ClosePickupStopOptions extends ClosePickupStopRequest {\n readonly tripRef: string;\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReopenPickupStopOptions {\n readonly tripRef: string;\n readonly pointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- pickups -------------------------------------------------------------\n\nexport interface PickupsResource {\n /** `GET /api/v1/trips/{ref}/pickups`. With `?since=` the rows are\n * `PickupStopDeltaResponse` — a union with the tombstone, so the drop case\n * cannot be forgotten. Without one, no tombstone can appear. */\n list(options: ListPickupStopsOptions): Promise<KaafilResponse<readonly PickupStopDeltaRow[]>>;\n create(options: CreatePickupStopOptions): Promise<KaafilResponse<PickupStopResponse>>;\n patch(options: PatchPickupStopOptions): Promise<KaafilResponse<PickupStopResponse>>;\n remove(options: DeletePickupStopOptions): Promise<KaafilResponse<PickupStopDeleteResponse>>;\n reorder(\n options: ReorderPickupStopsOptions,\n ): Promise<KaafilResponse<readonly PickupStopResponse[]>>;\n /**\n * `POST …/pickups/{pointId}/assign` — puts one traveller on one stop. If\n * they were already on a different stop of the SAME `kind`, the move is one\n * atomic delete+create (R1: at most one `PICKUP` and one `DROP` per\n * traveller, enforced by a composite unique, not merely a service-layer\n * promise), and the response's `previousPickupPointId` names where they\n * moved from.\n */\n assign(options: AssignPickupTravellerOptions): Promise<KaafilResponse<AssignResponse>>;\n /**\n * `POST …/pickups/{pointId}/reassign` — the bulk, stop-level sibling of\n * `assign()`: moves every live, not-yet-boarded traveller off `pointId`\n * onto `toPickupPointId` in one call (FRD §8's \"delete a stop with\n * travellers on it\" flow — reassign the survivors first, then `remove()`\n * the now-empty stop). `toPickupPointId` must be a different, live stop of\n * the SAME `kind` — else `422 BUSINESS_RULE_VIOLATION`. A traveller already\n * `BOARDED` at the source stop is left there, not moved; the response's\n * `skippedBoardedCount` says how many, `movedCount` everyone else. Both\n * affected stops come back whole, same \"rebase without a follow-up read\"\n * convention as `assign()`.\n */\n reassign(options: ReassignPickupStopTravellersOptions): Promise<KaafilResponse<ReassignResponse>>;\n board(options: BoardPickupTravellerOptions): Promise<KaafilResponse<BoardResponse>>;\n /**\n * `PATCH …/pickups/{pointId}/board/{travellerId}` — amends or reverses a\n * board/no-show observation `board()` already recorded; it can never\n * ORIGINATE one. A still-`PENDING` row is refused with\n * `422 pickups.correctionRequiresObservation`. Accepts a manager session,\n * an agency-admin session, OR an API key — unlike `board()`, which is\n * `managerAuth`-only. Not `Idempotency-Key`- or `If-Match`-guarded: same\n * unversioned `setBoardStatus` write `board()` makes, and re-sending the\n * same corrected status is naturally idempotent.\n */\n correctBoardStatus(\n options: CorrectPickupBoardStatusOptions,\n ): Promise<KaafilResponse<BoardResponse>>;\n /** See this file's header for the close policy: one method, two branches\n * on `Trip.eventType`, one code (`STOP_HAS_PENDING`) either way. */\n close(options: ClosePickupStopOptions): Promise<KaafilResponse<CloseResponse>>;\n /** Flips `CLOSED → OPEN` and clears `closedAt`/`closedByManagerId` — there\n * is no `REOPENED` state. The next `close()` on this stop emits a fresh\n * CORRECTIVE `pickup.stop_closed` event, `reopened: true`. */\n reopen(options: ReopenPickupStopOptions): Promise<KaafilResponse<ReopenResponse>>;\n /** `GET …/manifest-by-pickup` — the roster grouped by stop, for a printed\n * or on-screen boarding sheet. Renders the same glyph/tone canon as\n * `rooming`'s and `seating`'s occupants — no second derivation. */\n manifestByPickup(\n options: ReadManifestByPickupOptions,\n ): Promise<KaafilResponse<ManifestByPickupResponse>>;\n}\n\nexport function createPickupsResource(client: KaafilHttpClient): PickupsResource {\n return {\n async list(options) {\n const { tripRef, kind, since, signal } = options;\n return client.execute<readonly PickupStopDeltaRow[]>({\n method: 'GET',\n operationId: OperationId.ListPickupStops,\n path: '/api/v1/trips/{ref}/pickups',\n pathParams: { ref: tripRef },\n query: { kind, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { tripRef, idempotencyKey, signal, scheduledTime, ...rest } = options;\n const body: CreatePickupStopRequest = {\n ...rest,\n scheduledTime: normalizeDateTimeInput(scheduledTime, 'scheduledTime'),\n };\n return client.execute<PickupStopResponse>({\n method: 'POST',\n operationId: OperationId.CreatePickupStop,\n path: '/api/v1/trips/{ref}/pickups',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, pointId, version, signal, scheduledTime, ...rest } = options;\n const body: PatchPickupStopRequest = {\n ...rest,\n ...(scheduledTime !== undefined\n ? { scheduledTime: normalizeDateTimeInput(scheduledTime, 'scheduledTime') }\n : {}),\n };\n return client.execute<PickupStopResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchPickupStop,\n path: '/api/v1/trips/{ref}/pickups/{pointId}',\n pathParams: { ref: tripRef, pointId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, pointId, version, force, signal } = options;\n return client.execute<PickupStopDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeletePickupStop,\n path: '/api/v1/trips/{ref}/pickups/{pointId}',\n pathParams: { ref: tripRef, pointId },\n query: { force },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reorder(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<readonly PickupStopResponse[]>({\n method: 'POST',\n operationId: OperationId.ReorderPickupStops,\n path: '/api/v1/trips/{ref}/pickups/reorder',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async assign(options) {\n const { tripRef, pointId, idempotencyKey, signal, ...body } = options;\n return client.execute<AssignResponse>({\n method: 'POST',\n operationId: OperationId.AssignPickupTraveller,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/assign',\n pathParams: { ref: tripRef, pointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reassign(options) {\n const { tripRef, pointId, idempotencyKey, signal, ...body } = options;\n return client.execute<ReassignResponse>({\n method: 'POST',\n operationId: OperationId.ReassignPickupStopTravellers,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/reassign',\n pathParams: { ref: tripRef, pointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async board(options) {\n const { tripRef, pointId, idempotencyKey, signal, ...body } = options;\n return client.execute<BoardResponse>({\n method: 'POST',\n operationId: OperationId.BoardPickupTraveller,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/board',\n pathParams: { ref: tripRef, pointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async correctBoardStatus(options) {\n const { tripRef, pointId, travellerId, signal, ...body } = options;\n return client.execute<BoardResponse>({\n method: 'PATCH',\n operationId: OperationId.CorrectPickupBoardStatus,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/board/{travellerId}',\n pathParams: { ref: tripRef, pointId, travellerId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async close(options) {\n const { tripRef, pointId, idempotencyKey, signal, ...body } = options;\n return client.execute<CloseResponse>({\n method: 'POST',\n operationId: OperationId.ClosePickupStop,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/close',\n pathParams: { ref: tripRef, pointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reopen(options) {\n const { tripRef, pointId, idempotencyKey, signal } = options;\n return client.execute<ReopenResponse>({\n method: 'POST',\n operationId: OperationId.ReopenPickupStop,\n path: '/api/v1/trips/{ref}/pickups/{pointId}/reopen',\n pathParams: { ref: tripRef, pointId },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async manifestByPickup(options) {\n const { tripRef, kind, signal } = options;\n return client.execute<ManifestByPickupResponse>({\n method: 'GET',\n operationId: OperationId.ReadManifestByPickup,\n path: '/api/v1/trips/{ref}/manifest-by-pickup',\n pathParams: { ref: tripRef },\n query: { kind },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `rooming` — the board, stay windows, rooms, manual bed assignment and\n * auto-assign. `architecture/08-sdk.md §4`.\n *\n * `board.read` and `stayWindows.list` accept a manager session, an\n * agency-admin session OR an API key (three alternatives, never an AND); every\n * WRITE is `managerAuth`-only, the same split `itinerary` has and for the same\n * reason — rooming is decided on the ground.\n *\n * Rooming is a gated capability (`GROUP` trips only, behind the `rooming` plan\n * flag), so its refusals are ordinary typed errors a caller should expect:\n * `402` for a flag that is off, `422 CAPABILITY_UNAVAILABLE` on a\n * `PERSONALIZED` trip, `422 READ_ONLY_ROLE` for a COORDINATOR. See\n * `../http/errors.ts`.\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so `rooms.patch` (a trip ref AND a room id) and\n * `stayWindows.patch` (a trip ref AND a window id) can't be called with their\n * arguments swapped. The two child ids are named `roomId` and `windowId` after\n * the thing they identify, never both `id`.\n *\n * `HEURISTIC_SEVERITY` and the glyph/tone vocabulary a client needs to RENDER\n * this module's output are not here — they are not on the wire. See\n * `../rooming/vocabulary.ts`.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype RoomingBoardResponse = components['schemas']['RoomingBoardResponse'];\ntype RoomingStayWindowResponse = components['schemas']['RoomingStayWindowResponse'];\ntype RoomingStayWindowDeltaResponse = components['schemas']['RoomingStayWindowDeltaResponse'];\ntype RoomingRoomResponse = components['schemas']['RoomingRoomResponse'];\ntype RoomingDeleteResponse = components['schemas']['RoomingDeleteResponse'];\ntype RoomingAssignResponse = components['schemas']['RoomingAssignResponse'];\ntype RoomingAutoAssignResponse = components['schemas']['RoomingAutoAssignResponse'];\ntype CreateRoomingStayWindowRequest = components['schemas']['CreateRoomingStayWindowRequest'];\ntype PatchRoomingStayWindowRequest = components['schemas']['PatchRoomingStayWindowRequest'];\ntype CreateRoomingRoomRequest = components['schemas']['CreateRoomingRoomRequest'];\ntype PatchRoomingRoomRequest = components['schemas']['PatchRoomingRoomRequest'];\ntype AssignRoomingBedRequest = components['schemas']['AssignRoomingBedRequest'];\ntype AutoAssignRoomingRequest = components['schemas']['AutoAssignRoomingRequest'];\n\n/**\n * One row of the board's `rooms[]`: a live room, or the tombstone for one\n * deleted since the cursor. Aliased off the response type, never restated.\n */\nexport type RoomingRoomDeltaRow = RoomingBoardResponse['rooms'][number];\n\n/** One traveller's chip, wherever it appears — in a bed, or in `unassigned[]`. */\nexport type RoomingOccupant = RoomingBoardResponse['unassigned'][number];\n\n/**\n * `autoAssign`'s rules block, named so a caller can build one and hold it in a\n * variable. Indexed off the request type, so the three knobs stay whatever the\n * contract says they are.\n */\nexport type RoomingAutoAssignRules = NonNullable<AutoAssignRoomingRequest['rules']>;\n\n// --- date-time widening --------------------------------------------------\n//\n// A stay window's `startDate`/`endDate` are `string` (`Format: date-time`) in\n// the generated schema — a faithful mirror of the spec, where the wire format\n// really is a string. The `*Options` types below widen exactly those two\n// fields to `DateTimeInput` (see `../datetime`) by indexing off the generated\n// type and overriding — never restating a request body by hand. The factory\n// normalizes back down to `string` before the body reaches the wire.\n//\n// Nothing else on this surface takes a date: rooms, beds and assignments are\n// all identified by id and label.\n\n// --- rooming.board -------------------------------------------------------------\n\nexport interface ReadRoomingBoardOptions {\n readonly tripRef: string;\n /** Narrows the board to one stay window. Omitted reads every window. */\n readonly stayWindowId?: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and nothing\n * else. Omit it for the full board. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the boundary is the one\n * thing that silently loses rows, and that module owns it.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- rooming.stayWindows -------------------------------------------------------\n\nexport interface ListRoomingStayWindowsOptions {\n readonly tripRef: string;\n /** See `ReadRoomingBoardOptions.since`. */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CreateRoomingStayWindowOptions\n extends Omit<CreateRoomingStayWindowRequest, 'startDate' | 'endDate'> {\n readonly tripRef: string;\n readonly startDate: DateTimeInput;\n /**\n * Half-open with `startDate`: a checkout date equal to the next window's\n * check-in is legal, because multi-hotel trips are contiguous by nature.\n * Overlap beyond that is refused with `422 BUSINESS_RULE_VIOLATION` and\n * `details.rule === 'stay_window_overlap'`.\n */\n readonly endDate: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchRoomingStayWindowOptions\n extends Omit<PatchRoomingStayWindowRequest, 'startDate' | 'endDate'> {\n readonly tripRef: string;\n readonly windowId: string;\n readonly startDate?: DateTimeInput;\n readonly endDate?: DateTimeInput;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this method\n * makes forgetting it impossible instead of merely discouraged. Pass the\n * `version` from the window as last read. The SDK builds the `If-Match`\n * header itself; never set it in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteRoomingStayWindowOptions {\n readonly tripRef: string;\n readonly windowId: string;\n /** See `PatchRoomingStayWindowOptions.version` — same contract. */\n readonly version: number;\n /**\n * Deleting a window that still has rooms with occupants is REFUSED\n * (`422 BUSINESS_RULE_VIOLATION`, `details.rule ===\n * 'stay_window_has_assignments'`) unless this is `true`, which also releases\n * the beds. A query param and never a body, because a DELETE body is not\n * reliably carried; an explicit opt-in and never the default, because the\n * refusal is the whole safety property — a manager who did not mean to empty\n * a hotel gets told, not obeyed.\n */\n readonly force?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface RoomingStayWindowsResource {\n /**\n * `GET …/rooming/stay-windows`. With `?since=` the rows are\n * `RoomingStayWindowDeltaResponse` — a union with the tombstone, so the drop\n * case cannot be forgotten (`../delta/cursor.ts`'s `isTombstone`). Without\n * one, no tombstone can appear: a cold read has nothing to drop.\n */\n list(\n options: ListRoomingStayWindowsOptions,\n ): Promise<KaafilResponse<readonly RoomingStayWindowDeltaResponse[]>>;\n create(\n options: CreateRoomingStayWindowOptions,\n ): Promise<KaafilResponse<RoomingStayWindowResponse>>;\n patch(options: PatchRoomingStayWindowOptions): Promise<KaafilResponse<RoomingStayWindowResponse>>;\n remove(options: DeleteRoomingStayWindowOptions): Promise<KaafilResponse<RoomingDeleteResponse>>;\n}\n\n// --- rooming.rooms -------------------------------------------------------------\n\nexport interface CreateRoomingRoomOptions extends CreateRoomingRoomRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchRoomingRoomOptions extends PatchRoomingRoomRequest {\n readonly tripRef: string;\n readonly roomId: string;\n /** See `PatchRoomingStayWindowOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteRoomingRoomOptions {\n readonly tripRef: string;\n readonly roomId: string;\n /** See `PatchRoomingStayWindowOptions.version` — same contract. */\n readonly version: number;\n /** See `DeleteRoomingStayWindowOptions.force` — same contract, one room's worth. */\n readonly force?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadRoomingRoomOptions {\n readonly tripRef: string;\n readonly roomId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface RoomingRoomsResource {\n /**\n * `GET …/rooming/rooms/{roomId}` — one room, whole: its synthesised beds,\n * their occupants and its notes. The same shape every write on this\n * resource already returns, narrowed to one room, for a room-detail screen\n * that does not need the whole board.\n */\n get(options: ReadRoomingRoomOptions): Promise<KaafilResponse<RoomingRoomResponse>>;\n create(options: CreateRoomingRoomOptions): Promise<KaafilResponse<RoomingRoomResponse>>;\n /**\n * Beds are synthesised from `capacity` (`A`..`H`, truncated), never stored,\n * so `beds[]` on the response is derived — dropping `capacity` below the\n * room's current occupancy is refused with `422 BUSINESS_RULE_VIOLATION` and\n * `details.rule === 'room_capacity_below_occupancy'` rather than silently\n * evicting whoever was in the last bed.\n */\n patch(options: PatchRoomingRoomOptions): Promise<KaafilResponse<RoomingRoomResponse>>;\n remove(options: DeleteRoomingRoomOptions): Promise<KaafilResponse<RoomingDeleteResponse>>;\n}\n\n// --- rooming.assign / rooming.autoAssign ---------------------------------------\n\nexport interface AssignRoomingBedOptions extends AssignRoomingBedRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AutoAssignRoomingOptions extends AutoAssignRoomingRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- rooming -------------------------------------------------------------------\n\nexport interface RoomingResource {\n /** `GET /api/v1/trips/{ref}/rooming` — windows, rooms with their beds, the\n * unassigned roster, and the summary counters. */\n read(options: ReadRoomingBoardOptions): Promise<KaafilResponse<RoomingBoardResponse>>;\n /**\n * `POST …/rooming/assign` — puts one traveller in one bed. `bedLabel: null`\n * un-assigns them. If the target bed is taken the occupant is displaced, and\n * the response names them in `displacedTravellerId` rather than leaving the\n * caller to diff two boards to notice a second person moved.\n */\n assign(options: AssignRoomingBedOptions): Promise<KaafilResponse<RoomingAssignResponse>>;\n /**\n * `POST …/rooming/auto-assign`. `dryRun: true` returns the plan without\n * writing it; `dryRun: false` returns the plan it actually applied. The two\n * are the SAME computation — the solver is pure and the only difference is\n * whether the result is also written — so a preview and its apply agree by\n * construction, and a client that stored the preview can diff it against the\n * applied plan to see whether the rooms moved underneath it.\n *\n * Every rule reports an outcome in `perRule`, including rules that had\n * nothing to do; a relaxation is never silent. How loudly to render each one\n * is `HEURISTIC_SEVERITY` in `../rooming/vocabulary.ts`. A traveller who got\n * no bed is in `unassigned[]` WITH a reason — absence from `plan` alone is\n * ambiguous, because a manually-pinned traveller is also absent and is fine.\n */\n autoAssign(options: AutoAssignRoomingOptions): Promise<KaafilResponse<RoomingAutoAssignResponse>>;\n readonly stayWindows: RoomingStayWindowsResource;\n readonly rooms: RoomingRoomsResource;\n}\n\nexport function createRoomingResource(client: KaafilHttpClient): RoomingResource {\n return {\n async read(options) {\n const { tripRef, stayWindowId, since, signal } = options;\n return client.execute<RoomingBoardResponse>({\n method: 'GET',\n operationId: OperationId.ReadRoomingBoard,\n path: '/api/v1/trips/{ref}/rooming',\n pathParams: { ref: tripRef },\n query: { stayWindowId, since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async assign(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<RoomingAssignResponse>({\n method: 'POST',\n operationId: OperationId.AssignRoomingBed,\n path: '/api/v1/trips/{ref}/rooming/assign',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async autoAssign(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<RoomingAutoAssignResponse>({\n method: 'POST',\n operationId: OperationId.AutoAssignRooming,\n path: '/api/v1/trips/{ref}/rooming/auto-assign',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n stayWindows: {\n async list(options) {\n const { tripRef, since, signal } = options;\n return client.execute<readonly RoomingStayWindowDeltaResponse[]>({\n method: 'GET',\n operationId: OperationId.ListRoomingStayWindows,\n path: '/api/v1/trips/{ref}/rooming/stay-windows',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { tripRef, idempotencyKey, signal, startDate, endDate, ...rest } = options;\n const body: CreateRoomingStayWindowRequest = {\n ...rest,\n startDate: normalizeDateTimeInput(startDate, 'startDate'),\n endDate: normalizeDateTimeInput(endDate, 'endDate'),\n };\n return client.execute<RoomingStayWindowResponse>({\n method: 'POST',\n operationId: OperationId.CreateRoomingStayWindow,\n path: '/api/v1/trips/{ref}/rooming/stay-windows',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, windowId, version, signal, startDate, endDate, ...rest } = options;\n const body: PatchRoomingStayWindowRequest = {\n ...rest,\n ...(startDate !== undefined\n ? { startDate: normalizeDateTimeInput(startDate, 'startDate') }\n : {}),\n ...(endDate !== undefined ? { endDate: normalizeDateTimeInput(endDate, 'endDate') } : {}),\n };\n return client.execute<RoomingStayWindowResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchRoomingStayWindow,\n path: '/api/v1/trips/{ref}/rooming/stay-windows/{windowId}',\n pathParams: { ref: tripRef, windowId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, windowId, version, force, signal } = options;\n return client.execute<RoomingDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteRoomingStayWindow,\n path: '/api/v1/trips/{ref}/rooming/stay-windows/{windowId}',\n pathParams: { ref: tripRef, windowId },\n query: { force },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n rooms: {\n async get(options) {\n const { tripRef, roomId, signal } = options;\n return client.execute<RoomingRoomResponse>({\n method: 'GET',\n operationId: OperationId.ReadRoomingRoom,\n path: '/api/v1/trips/{ref}/rooming/rooms/{roomId}',\n pathParams: { ref: tripRef, roomId },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<RoomingRoomResponse>({\n method: 'POST',\n operationId: OperationId.CreateRoomingRoom,\n path: '/api/v1/trips/{ref}/rooming/rooms',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, roomId, version, signal, ...body } = options;\n return client.execute<RoomingRoomResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchRoomingRoom,\n path: '/api/v1/trips/{ref}/rooming/rooms/{roomId}',\n pathParams: { ref: tripRef, roomId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, roomId, version, force, signal } = options;\n return client.execute<RoomingDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteRoomingRoom,\n path: '/api/v1/trips/{ref}/rooming/rooms/{roomId}',\n pathParams: { ref: tripRef, roomId },\n query: { force },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `seating` — the transport board, vehicles, manual seat assignment,\n * auto-assign and the vehicle-manager link. `architecture/08-sdk.md §4`.\n *\n * `read` accepts a manager session, an agency-admin session OR an API key\n * (three alternatives, never an AND); every WRITE is `managerAuth`-only, the\n * same split `rooming` and `itinerary` have and for the same reason — seating\n * is decided on the ground.\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so `vehicles.patch` (a trip ref AND a vehicle id) can't\n * be called with its arguments swapped.\n *\n * `deriveOccupantMark` and `synthesiseBedLabels` — the glyph/tone and\n * bed-label logic a client needs to RENDER this module's output — are not\n * here; they are rooming's, imported by the engine's seating module rather\n * than re-derived (`architecture` 10B notes), and are not on the wire either.\n * A client renders an occupant's `glyph`/`tone` fields straight off the\n * response, the same as `rooming`'s occupants.\n *\n * ── THE TYPE↔LAYOUT RULE, AND WHY `seatLabel` CANNOT BE STATICALLY TIED TO IT ──\n *\n * A vehicle's `layout` is non-null only for `type ∈ {FLIGHT, TRAIN}`\n * (`Vehicle_layout_requires_seatable_type`, enforced server-side by a CHECK).\n * `layout: null` means the vehicle carries no seat map at all — most road\n * vehicles, because \"the label grid was a fiction the manager maintained and\n * the driver ignored\" — and on such a vehicle every assignment's `seatLabel`\n * is `null`, enforced on write. The converse is deliberately NOT an invariant:\n * a seat-mapped vehicle may still hold `seatLabel: null` rows (a group\n * confirmed on a flight before the airline issues seat numbers), so `layout`\n * being non-null does not mean `seatLabel` is required either.\n *\n * `assign()` below is intentionally NOT generic over \"which vehicle\", so\n * `AssignSeatingOptions.seatLabel` cannot be narrowed to \"required when this\n * vehicle has a layout, forbidden when it doesn't\" at the type level: the\n * call site names a `vehicleId`, not the vehicle object it was read from, and\n * whether that id currently has a layout is server-side state this SDK does\n * not — and must not — cache and re-derive locally (the whole point of a\n * board read is that the server is the source of truth for it). Encoding the\n * rule here would mean either accepting a vehicle object just to read one\n * field, which no other write on this surface does, or building a second,\n * client-side copy of `seatMapped` that could drift from what the server\n * actually enforces. So `seatLabel` stays `string | null | undefined` on every\n * vehicle unconditionally, and the rule is enforced where the truth lives:\n * the server accepts a `seatLabel` for a seat-less vehicle and silently\n * ignores it into `null`; the honest type-level statement of this surface is\n * that `seatLabel` is ALWAYS optional and ALWAYS nullable, never that it\n * varies by vehicle. Read a vehicle's own `seatMapped` (`SeatingBoardResponse`\n * / `SeatingVehicleResponse`) before deciding whether to show a seat picker.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype SeatingBoardResponse = components['schemas']['SeatingBoardResponse'];\ntype SeatingVehicleResponse = components['schemas']['SeatingVehicleResponse'];\ntype SeatingDeleteVehicleResponse = components['schemas']['SeatingDeleteVehicleResponse'];\ntype SeatingAssignResponse = components['schemas']['SeatingAssignResponse'];\ntype SeatingAutoAssignResponse = components['schemas']['SeatingAutoAssignResponse'];\ntype SeatingManagerLinkResponse = components['schemas']['SeatingManagerLinkResponse'];\ntype CreateSeatingVehicleRequest = components['schemas']['CreateSeatingVehicleRequest'];\ntype PatchSeatingVehicleRequest = components['schemas']['PatchSeatingVehicleRequest'];\ntype AssignSeatingRequest = components['schemas']['AssignSeatingRequest'];\ntype AutoAssignSeatingRequest = components['schemas']['AutoAssignSeatingRequest'];\ntype LinkSeatingManagerRequest = components['schemas']['LinkSeatingManagerRequest'];\n\n/**\n * One row of the board's `vehicles[]`: a live vehicle, or the tombstone for\n * one deleted since the cursor. Aliased off the response type, never\n * restated.\n */\nexport type SeatingVehicleDeltaRow = SeatingBoardResponse['vehicles'][number];\n\n/** One traveller's chip in `unassignedPool[]`, or (per vehicle) in\n * `occupants[]`/`unseatedOnVehicle[]`/a seat's `occupant`. */\nexport type SeatingOccupant = SeatingBoardResponse['unassignedPool'][number];\n\n/**\n * `autoAssign`'s rules block, named so a caller can build one and hold it in\n * a variable. Indexed off the request type, so the three knobs stay whatever\n * the contract says they are.\n */\nexport type SeatingAutoAssignRules = NonNullable<AutoAssignSeatingRequest['rules']>;\n\n// --- date-time widening --------------------------------------------------\n//\n// Nothing on this surface takes a date: vehicles, seats and assignments are\n// all identified by id and label, and the board itself is read with `?since=`\n// (a cursor string, not a caller-built date). No `*Input` widening applies\n// here — unlike `rooming` and `itinerary`, this file has no\n// `normalizeDateTimeInput` call site for a request body.\n\n// --- seating.read ----------------------------------------------------------\n\nexport interface ReadSeatingBoardOptions {\n readonly tripRef: string;\n /**\n * The delta cursor: a previous response's own `meta.serverTime`, and\n * nothing else. Omit it for the full board. Prefer `createDeltaCursor`\n * (`../delta/cursor.ts`) over passing this by hand — the boundary is the\n * one thing that silently loses rows, and that module owns it.\n */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- seating.vehicles --------------------------------------------------------\n\nexport interface CreateSeatingVehicleOptions extends CreateSeatingVehicleRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchSeatingVehicleOptions extends PatchSeatingVehicleRequest {\n readonly tripRef: string;\n readonly vehicleId: string;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both answer\n * `409 CONFLICT_VERSION` — identically confusing either way — so this\n * method makes forgetting it impossible instead of merely discouraged.\n * Pass the `version` from the vehicle as last read. The SDK builds the\n * `If-Match` header itself; never set it in `headers`.\n *\n * A capacity-down or a `layout` change that would orphan a recorded seat\n * label is refused with `422 SEATING_CAPACITY_ORPHAN` rather than silently\n * dropping whoever held that label — see this file's header for the three\n * forms of the guard.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteSeatingVehicleOptions {\n readonly tripRef: string;\n readonly vehicleId: string;\n /** See `PatchSeatingVehicleOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface LinkSeatingManagerOptions extends LinkSeatingManagerRequest {\n readonly tripRef: string;\n readonly vehicleId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UnlinkSeatingManagerOptions {\n readonly tripRef: string;\n readonly vehicleId: string;\n /** See `PatchSeatingVehicleOptions.version` — same contract. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface SeatingVehicleManagerResource {\n /** `POST …/seating/vehicles/{vehicleId}/manager` — links a manager to this\n * vehicle. Demotes whichever vehicle that manager was previously linked to,\n * atomically: a manager only ever rides one vehicle. */\n link(options: LinkSeatingManagerOptions): Promise<KaafilResponse<SeatingManagerLinkResponse>>;\n unlink(options: UnlinkSeatingManagerOptions): Promise<KaafilResponse<SeatingManagerLinkResponse>>;\n}\n\nexport interface SeatingVehiclesResource {\n create(options: CreateSeatingVehicleOptions): Promise<KaafilResponse<SeatingVehicleResponse>>;\n patch(options: PatchSeatingVehicleOptions): Promise<KaafilResponse<SeatingVehicleResponse>>;\n /** Clears every occupant on this vehicle back to the unassigned pool and\n * unlinks its manager, then deletes it. */\n remove(\n options: DeleteSeatingVehicleOptions,\n ): Promise<KaafilResponse<SeatingDeleteVehicleResponse>>;\n readonly manager: SeatingVehicleManagerResource;\n}\n\n// --- seating.assign / seating.autoAssign -------------------------------------\n\nexport interface AssignSeatingOptions extends AssignSeatingRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AutoAssignSeatingOptions extends AutoAssignSeatingRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- seating -----------------------------------------------------------------\n\nexport interface SeatingResource {\n /** `GET /api/v1/trips/{ref}/seating` — vehicles with their seats and\n * occupants, the unassigned pool, and the summary counters. */\n read(options: ReadSeatingBoardOptions): Promise<KaafilResponse<SeatingBoardResponse>>;\n /**\n * `POST …/seating/assign` — puts one traveller in one vehicle (and, on a\n * seat-mapped vehicle, one seat). `vehicleId: null` moves them to the\n * unassigned pool. If the target seat is taken the occupant is displaced,\n * and the response names them in `displacedTravellerId` (plus\n * `displacedVehicleId`/`displacedSeatLabel`) rather than leaving the caller\n * to diff two boards to notice a second person moved.\n */\n assign(options: AssignSeatingOptions): Promise<KaafilResponse<SeatingAssignResponse>>;\n /**\n * `POST …/seating/auto-assign`. `dryRun: true` returns the plan without\n * writing it; `dryRun: false` returns the plan it actually applied. The two\n * are the SAME computation — the solver is pure and the only difference is\n * whether the result is also written — so a preview and its apply agree by\n * construction.\n *\n * Every rule reports an outcome in `perRule`: `applied`, `relaxed`, or\n * `noop` with `noopReason: 'no_seat_map'` — the third outcome seating has\n * that rooming does not, because `medicalFirst` and `gender` are\n * seat-adjacency heuristics with nothing to do on a seat-less vehicle. A\n * `noop` and a relaxed rule are different facts (a heuristic that could not\n * apply vs. one that applied a weaker version of itself), so both are\n * reported rather than one masquerading as the other.\n */\n autoAssign(options: AutoAssignSeatingOptions): Promise<KaafilResponse<SeatingAutoAssignResponse>>;\n readonly vehicles: SeatingVehiclesResource;\n}\n\nexport function createSeatingResource(client: KaafilHttpClient): SeatingResource {\n return {\n async read(options) {\n const { tripRef, since, signal } = options;\n return client.execute<SeatingBoardResponse>({\n method: 'GET',\n operationId: OperationId.ReadSeatingBoard,\n path: '/api/v1/trips/{ref}/seating',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async assign(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<SeatingAssignResponse>({\n method: 'POST',\n operationId: OperationId.AssignSeating,\n path: '/api/v1/trips/{ref}/seating/assign',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async autoAssign(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<SeatingAutoAssignResponse>({\n method: 'POST',\n operationId: OperationId.AutoAssignSeating,\n path: '/api/v1/trips/{ref}/seating/auto-assign',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n vehicles: {\n async create(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<SeatingVehicleResponse>({\n method: 'POST',\n operationId: OperationId.CreateSeatingVehicle,\n path: '/api/v1/trips/{ref}/seating/vehicles',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, vehicleId, version, signal, ...body } = options;\n return client.execute<SeatingVehicleResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchSeatingVehicle,\n path: '/api/v1/trips/{ref}/seating/vehicles/{vehicleId}',\n pathParams: { ref: tripRef, vehicleId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, vehicleId, version, signal } = options;\n return client.execute<SeatingDeleteVehicleResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteSeatingVehicle,\n path: '/api/v1/trips/{ref}/seating/vehicles/{vehicleId}',\n pathParams: { ref: tripRef, vehicleId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n manager: {\n async link(options) {\n const { tripRef, vehicleId, idempotencyKey, signal, ...body } = options;\n return client.execute<SeatingManagerLinkResponse>({\n method: 'POST',\n operationId: OperationId.LinkSeatingManager,\n path: '/api/v1/trips/{ref}/seating/vehicles/{vehicleId}/manager',\n pathParams: { ref: tripRef, vehicleId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async unlink(options) {\n const { tripRef, vehicleId, version, signal } = options;\n return client.execute<SeatingManagerLinkResponse>({\n method: 'DELETE',\n operationId: OperationId.UnlinkSeatingManager,\n path: '/api/v1/trips/{ref}/seating/vehicles/{vehicleId}/manager',\n pathParams: { ref: tripRef, vehicleId },\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n },\n };\n}\n","/**\n * `shareTokens` — create, read, revoke, patch, regenerate.\n * `architecture/08-sdk.md §3.3, §4`; every operation here is `apiKeyAuth`-only\n * in the spec (server-side mint, matching `03-auth-and-tokens.md §1`:\n * browsers only ever hold the *minted* token, never the key that mints it).\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype MintShareTokenRequest = components['schemas']['MintShareTokenRequest'];\ntype MintedShareTokenViewResponse = components['schemas']['MintedShareTokenViewResponse'];\ntype ShareTokenViewResponse = components['schemas']['ShareTokenViewResponse'];\ntype PatchShareTokenRequest = components['schemas']['PatchShareTokenRequest'];\ntype RegenerateShareTokenRequest = components['schemas']['RegenerateShareTokenRequest'];\ntype RevealedShareTokenViewResponse = components['schemas']['RevealedShareTokenViewResponse'];\n\nexport interface CreateShareTokenOptions extends Omit<MintShareTokenRequest, 'expiresAt'> {\n /** Optional on the wire (`ttlDays` is the other way to set expiry) — see\n * `../datetime` for the coercion contract; a full ISO string with an\n * offset still passes through unchanged. */\n readonly expiresAt?: DateTimeInput;\n /** Stable across retries — reused as-is, never re-minted per attempt. */\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadShareTokenOptions {\n readonly id: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ListShareTokensOptions {\n /** REQUIRED — a bare list would enumerate every live link in the agency. */\n readonly tripRef: string;\n /** Omit for the whole trip, INCLUDING the subject-less family link. */\n readonly travellerRef?: string;\n /** Adds revoked and expired links. Defaults to live only. */\n readonly includeRevoked?: boolean;\n readonly signal?: AbortSignal;\n}\n\nexport interface RevokeShareTokenOptions {\n readonly id: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchShareTokenOptions extends Omit<PatchShareTokenRequest, 'expiresAt'> {\n readonly id: string;\n /** Optional on the wire (`ttlDays` is the other way to set expiry) — see\n * `../datetime` for the coercion contract; a full ISO string with an\n * offset still passes through unchanged. */\n readonly expiresAt?: DateTimeInput;\n /**\n * Required, not optional. A missing `If-Match` and a stale one both\n * answer the same version-conflict error, so this method makes forgetting\n * it impossible instead of merely discouraged. Pass the `version` from\n * the token as last read. The SDK builds the `If-Match` header itself;\n * never set it in `headers`.\n */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface RegenerateShareTokenOptions extends RegenerateShareTokenRequest {\n readonly id: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ShareTokensResource {\n /**\n * `POST /api/v1/share-tokens` — mints a config-scoped, expiring share\n * token. Expiry is top-level (`ttlDays` OR `expiresAt` on this options\n * object — never inside `config`); the server clamps it as documented on\n * `MintShareTokenRequest`. The CRM builds its own link around the returned\n * `token`; this SDK never constructs one.\n */\n create(options: CreateShareTokenOptions): Promise<KaafilResponse<MintedShareTokenViewResponse>>;\n /** `GET /api/v1/share-tokens/{id}` — a share token's metadata, never its plaintext value. */\n read(options: ReadShareTokenOptions): Promise<KaafilResponse<ShareTokenViewResponse>>;\n /**\n * `GET /api/v1/share-tokens?tripRef=` — the links on one trip, metadata\n * only, newest first.\n *\n * The read that makes revoking possible for a caller that did not mint:\n * before it, an id could only be held by whoever called `create`, so a\n * surface that reloads had no way to revoke a link it had already handed\n * out. `tripRef` is required by design.\n */\n list(options: ListShareTokensOptions): Promise<KaafilResponse<readonly ShareTokenViewResponse[]>>;\n /** `DELETE /api/v1/share-tokens/{id}`. */\n revoke(options: RevokeShareTokenOptions): Promise<KaafilResponse<ShareTokenViewResponse>>;\n /** `PATCH /api/v1/share-tokens/{id}` — update a share token's section\n * config and/or expiry. `config.sections`, if sent, REPLACES the whole\n * map; a partial PATCH is not a partial write. */\n patch(options: PatchShareTokenOptions): Promise<KaafilResponse<ShareTokenViewResponse>>;\n /** `POST /api/v1/share-tokens/{id}/regenerate` — mints a fresh token for\n * the same subject, superseding the old one. By default the old token is\n * revoked in the same transaction; pass `keepOld: true` to retain it. */\n regenerate(\n options: RegenerateShareTokenOptions,\n ): Promise<KaafilResponse<MintedShareTokenViewResponse>>;\n /**\n * `GET /api/v1/share-tokens/{id}/reveal` — show an EXISTING link's address\n * again, so a desk can re-send it instead of calling `regenerate`, which\n * revokes the copy the family is already using.\n *\n * `token` is `null` with `reason: 'not_recoverable'` for a link minted\n * before Kaafil kept a recoverable copy: those rows hold only a digest, so\n * the address is gone for good and the caller should offer `regenerate`\n * rather than a retry. That is a 200, not an error.\n */\n reveal(options: ReadShareTokenOptions): Promise<KaafilResponse<RevealedShareTokenViewResponse>>;\n}\n\nexport function createShareTokensResource(client: KaafilHttpClient): ShareTokensResource {\n return {\n async list(options) {\n const { tripRef, travellerRef, includeRevoked, signal } = options;\n return client.execute<readonly ShareTokenViewResponse[]>({\n method: 'GET',\n operationId: OperationId.ListShareTokens,\n path: '/api/v1/share-tokens',\n query: { tripRef, travellerRef, includeRevoked },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { idempotencyKey, signal, expiresAt, ...rest } = options;\n const body: MintShareTokenRequest = {\n ...rest,\n ...(expiresAt !== undefined\n ? { expiresAt: normalizeDateTimeInput(expiresAt, 'expiresAt') }\n : {}),\n };\n return client.execute<MintedShareTokenViewResponse>({\n method: 'POST',\n operationId: OperationId.MintShareToken,\n path: '/api/v1/share-tokens',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async read(options) {\n const { id, signal } = options;\n return client.execute<ShareTokenViewResponse>({\n method: 'GET',\n operationId: OperationId.ReadShareToken,\n path: '/api/v1/share-tokens/{id}',\n pathParams: { id },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async reveal(options) {\n const { id, signal } = options;\n return client.execute<RevealedShareTokenViewResponse>({\n method: 'GET',\n operationId: OperationId.RevealShareToken,\n path: '/api/v1/share-tokens/{id}/reveal',\n pathParams: { id },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async revoke(options) {\n const { id, signal } = options;\n return client.execute<ShareTokenViewResponse>({\n method: 'DELETE',\n operationId: OperationId.RevokeShareToken,\n path: '/api/v1/share-tokens/{id}',\n pathParams: { id },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { id, version, signal, expiresAt, ...rest } = options;\n const body: PatchShareTokenRequest = {\n ...rest,\n ...(expiresAt !== undefined\n ? { expiresAt: normalizeDateTimeInput(expiresAt, 'expiresAt') }\n : {}),\n };\n return client.execute<ShareTokenViewResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchShareToken,\n path: '/api/v1/share-tokens/{id}',\n pathParams: { id },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async regenerate(options) {\n const { id, idempotencyKey, signal, ...rest } = options;\n const body: RegenerateShareTokenRequest = { ...rest };\n return client.execute<MintedShareTokenViewResponse>({\n method: 'POST',\n operationId: OperationId.RegenerateShareToken,\n path: '/api/v1/share-tokens/{id}/regenerate',\n pathParams: { id },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `sync` — the batched transport's three routes.\n * `architecture/06-offline-first.md §4.1`, `08-sdk.md §5`.\n *\n * This is a WIRE-SHAPE resource, not a semantic one. Every op inside a push\n * is defined, validated and versioned by its OWN endpoint; the batch changes\n * how many round trips it takes to deliver them and nothing else. That is why\n * this module has no per-module knowledge at all — an op is a method, a path,\n * an idempotency key and a body, exactly as `SyncPushRequest` declares them.\n *\n * ── `pushShare` AND A GAP IN THE VENDORED SPEC ─────────────────────────────\n *\n * `POST /api/v1/sync/push/share` is the traveller surface's drain route\n * (`06 §8`), and it must be authorized by the share token — the ops inside it\n * are that traveller's queued form writes. In the vendored spec as it stands,\n * that operation declares NO security scheme at all: `OPERATION_SECURITY\n * .syncPushShare` is `[]`, which `../auth/credentials.ts` correctly reads as\n * \"public operation, no header is due\" and sends with no credential.\n *\n * That is not something this package can paper over by attaching a header\n * behind the resolver's back — the resolver is the single place a credential\n * becomes a header, and a second path would be exactly the kind of drift this\n * SDK does not carry. So `pushShare` REFUSES, locally and by name, when the\n * spec declares no scheme for it: shipping an unauthenticated POST carrying a\n * traveller's submissions would be worse than not shipping the route. The\n * offline engine reads the same fact from the same table and simply keeps the\n * share lane on the single-op endpoints (`shareSaveForm`/`shareSubmitForm`,\n * both `['shareAuth']`), which work today. When the engine's spec declares\n * `shareAuth` here, re-vendoring turns the batch on with no code change.\n */\n\nimport type { components } from '../generated/schema';\nimport { OPERATION_SECURITY, OperationId, SecuritySchemeId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { KaafilInvalidRequestError } from '../http/errors';\nimport type { KaafilResponse } from '../types/meta';\n\ntype SyncPushRequest = components['schemas']['SyncPushRequest'];\ntype SyncPushShareRequest = components['schemas']['SyncPushShareRequest'];\ntype SyncPushResponse = components['schemas']['SyncPushResponse'];\ntype SyncPullResponse = components['schemas']['SyncPullResponse'];\ntype SyncDigestRow = components['schemas']['SyncDigestRow'];\n\n/** One op on the wire — the spec's own element type, never restated. */\nexport type SyncPushOp = SyncPushRequest['ops'][number];\n\n/** One verdict — likewise. */\nexport type SyncPushVerdict = SyncPushResponse['verdicts'][number];\n\nexport interface SyncPushOptions {\n readonly ops: readonly SyncPushOp[];\n readonly signal?: AbortSignal;\n}\n\nexport interface SyncPullTripOptions {\n readonly tripRef: string;\n /** The last successful pull's `meta.serverTime`. Omitted on a cold start,\n * which is a full snapshot with no tombstones (`06 §5`). */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface SyncDigestOptions {\n readonly agencyRef: string;\n readonly signal?: AbortSignal;\n}\n\n/** Thrown by `pushShare` when the vendored spec declares no security scheme\n * for `syncPushShare` — see this module's header. */\nexport class KaafilShareBatchUnauthenticatedError extends KaafilInvalidRequestError {\n constructor() {\n super(\n 'The vendored spec declares no security scheme for \"syncPushShare\", so a batched ' +\n \"share push would be sent with no credential at all, carrying a traveller's queued \" +\n 'writes. Refused locally. Drain share ops through their own endpoints ' +\n '(shareSaveForm / shareSubmitForm) until the engine declares shareAuth on ' +\n 'POST /api/v1/sync/push/share.',\n );\n this.name = 'KaafilShareBatchUnauthenticatedError';\n Object.setPrototypeOf(this, KaafilShareBatchUnauthenticatedError.prototype);\n }\n}\n\n/**\n * Whether the batched SHARE push is usable at all, read from the generated\n * security table rather than assumed. Exported so the offline engine can make\n * the same call without duplicating the reasoning, and so the fact is\n * inspectable from a gate.\n */\nexport function isShareBatchPushAvailable(): boolean {\n return (OPERATION_SECURITY[OperationId.SyncPushShare] as readonly SecuritySchemeId[]).includes(\n SecuritySchemeId.ShareAuth,\n );\n}\n\nexport interface SyncResource {\n /** `POST /api/v1/sync/push` — an ordered array of ops, one verdict each.\n * One op's `409` or `423` never fails the batch. */\n push(options: SyncPushOptions): Promise<KaafilResponse<SyncPushResponse>>;\n /** `GET /api/v1/trips/{ref}/sync` — every list a trip snapshot needs, in\n * one response. A section this tenant is not entitled to, or that this trip\n * leaves dark, is ABSENT from `sections` — never a `402` in the payload. */\n pullTrip(options: SyncPullTripOptions): Promise<KaafilResponse<SyncPullResponse>>;\n /** `POST /api/v1/sync/push/share` — the traveller surface's drain route.\n * See this module's header for why this can refuse locally today. */\n pushShare(options: SyncPushOptions): Promise<KaafilResponse<SyncPushResponse>>;\n /** `GET /api/v1/sync/digest` — one row per active trip, with a stable hash\n * for cheap drift detection. Compare each trip's `hash` against your own\n * and re-push only the trips that differ, instead of blind re-pushes of\n * the whole book. */\n digest(options: SyncDigestOptions): Promise<KaafilResponse<readonly SyncDigestRow[]>>;\n}\n\nexport function createSyncResource(client: KaafilHttpClient): SyncResource {\n return {\n async push(options) {\n const { ops, signal } = options;\n const body: SyncPushRequest = { ops: [...ops] };\n return client.execute<SyncPushResponse>({\n method: 'POST',\n operationId: OperationId.SyncPush,\n path: '/api/v1/sync/push',\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n async pullTrip(options) {\n const { tripRef, since, signal } = options;\n return client.execute<SyncPullResponse>({\n method: 'GET',\n operationId: OperationId.SyncPullTrip,\n path: '/api/v1/trips/{ref}/sync',\n pathParams: { ref: tripRef },\n // A `since` of `undefined` is omitted by `RequestDescriptor`'s own\n // rule, which is exactly the cold-start shape: no `?since=` at all.\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n async pushShare(options) {\n if (!isShareBatchPushAvailable()) {\n throw new KaafilShareBatchUnauthenticatedError();\n }\n const { ops, signal } = options;\n const body: SyncPushShareRequest = { ops: [...ops] };\n return client.execute<SyncPushResponse>({\n method: 'POST',\n operationId: OperationId.SyncPushShare,\n path: '/api/v1/sync/push/share',\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n async digest(options) {\n const { agencyRef, signal } = options;\n return client.execute<readonly SyncDigestRow[]>({\n method: 'GET',\n operationId: OperationId.SyncDigest,\n path: '/api/v1/sync/digest',\n query: { agencyRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `test` — the sandbox toolkit: the simulated clock, fixture rebuilds, and\n * the sandbox tenant's fixed quota. `architecture/12-testing-sandbox.md\n * §2/§4`.\n *\n * `kaafil-engine/src/modules/test/test.routes.ts`'s own header explains the\n * SERVER-side half of this: every one of the six `/api/v1/test/*` routes is\n * `auth: 'apiKey'` — reachable by either key prefix — and then a SECOND,\n * explicit `guardTestPlane` middleware 404s a LIVE-prefixed key against the\n * resolved tenant's own `Tenant.plane`, no existence hint given. That check\n * is the engine's, runs against the ACTUAL tenant a key resolves to, and\n * this module cannot see or duplicate it — a construction-time `apiKey`\n * prefix and a resolver-supplied one are exactly the case\n * `guardApiKeyEnvironment` (`../config.ts`) already handles honestly by\n * deferring to the resolved value, and this module has no narrower fact to\n * add.\n *\n * What THIS module adds is a courtesy this package already extends to every\n * multi-scheme resource `UnsatisfiableSchemeError` covers\n * (`../auth/credentials.ts`'s header, `../client-entry.ts`'s browser-entry\n * doc comment): a client's `environment` IS known at construction, so a\n * client built `{ environment: 'live' }` and pointed at these six operations\n * refuses LOCALLY, before any request exists, the same shape of mistake\n * `UnsatisfiableSchemeError` refuses for a credential that cannot satisfy an\n * operation's scheme — a `TestEnvironmentRequiredError` below, thrown by\n * every leaf method here before `client.execute()` is ever called. This is a\n * courtesy on top of the engine's own 404, not a replacement for it: a\n * resolver-supplied key that turns out to be LIVE despite `environment:\n * 'test'` still reaches the engine and still gets 404'd there, exactly like\n * `ApiKeyEnvironmentMismatchError` is a courtesy on top of, never a\n * substitute for, the engine's own tenant-plane checks.\n *\n * There used to be a would-be extra operation here, `webhooks.sendTest`\n * (`testWebhookEndpoint`) — removed because the vendored spec declares THAT\n * one `['consoleAuth']` alone, and no scheme this package's\n * `CredentialResolver` ever holds can satisfy it (see\n * `../auth/credentials.ts`'s `CREDENTIAL_KIND_SCHEME`: no kind maps to\n * `consoleAuth`, on purpose — \"the SDK does not serve the console\"). It has\n * NOT come back here, and should not. The engine now publishes an API-key\n * entry point onto the same controller — `POST\n * /api/v1/webhooks/endpoints/{id}/test`, `testWebhookEndpointApiKey`,\n * `['apiKeyAuth']` — and that one lives on `webhooks.testEvent()`\n * (`./webhooks.ts`), not in this module. Deliberately: it is a webhooks\n * operation that happens to send a canned event, it works on BOTH planes,\n * and it must therefore NOT be gated by `TestEnvironmentRequiredError` — a\n * LIVE client proving its own LIVE endpoint verifies signatures is the\n * normal case for it, not a mistake to refuse.\n *\n * The sixth operation this module actually gained is `readFixtures()`, the\n * read-only counterpart of `fixtures()`.\n */\n\nimport type { Environment } from '../config';\nimport { Environment as EnvironmentValues } from '../config';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { KaafilInvalidRequestError } from '../http/errors';\nimport type { KaafilResponse } from '../types/meta';\n\ntype TestClockResponse = components['schemas']['TestClockResponse'];\ntype AdvanceTimeResponse = components['schemas']['AdvanceTimeResponse'];\ntype FixtureRefMapResponse = components['schemas']['FixtureRefMapResponse'];\ntype SandboxQuotaResponse = components['schemas']['SandboxQuotaResponse'];\n\n/**\n * Thrown by every `test.*` method, before `client.execute()` is ever called,\n * when the client was constructed with `environment: 'live'`. Mirrors\n * `UnsatisfiableSchemeError`'s shape (`../auth/credentials.ts`) on purpose:\n * a non-retryable `KaafilInvalidRequestError`, so a consumer's `isRetryable`\n * check (or an outbox's own class lookup) never spends a retry ladder on a\n * mistake that is permanent by construction, and `catch (e) { e instanceof\n * TestEnvironmentRequiredError }` works the same way the documented\n * `UnsatisfiableSchemeError` pattern does — never a bare `Error` a consumer's\n * `KaafilError` hierarchy check would miss.\n *\n * Named for what it enforces, not for the plane it enforces against: the\n * engine's own vocabulary is TEST/LIVE \"planes\" (`architecture/\n * 12-testing-sandbox.md`), but this class's job is narrower and purely\n * client-side — refusing before a request exists for a client whose\n * `KaafilOptions.environment` is `'live'` — so it names the environment\n * field a caller actually passed, not the engine-side concept this module\n * cannot itself observe (see this file's header for why the engine's own\n * `guardTestPlane` 404 is the check that actually matters for a\n * resolver-supplied key).\n */\nexport class TestEnvironmentRequiredError extends KaafilInvalidRequestError {\n readonly operationId: OperationId;\n readonly environment: Environment;\n\n constructor(operationId: OperationId, environment: Environment) {\n super(\n `\"${operationId}\" is a TEST-plane sandbox operation and refuses to run against a ` +\n `client constructed with environment: \"${environment}\". Construct a client with ` +\n 'environment: \"test\" to use the sandbox toolkit.',\n );\n this.name = 'TestEnvironmentRequiredError';\n // Same reason every class in `../http/errors.ts` and\n // `../auth/credentials.ts`'s `UnsatisfiableSchemeError` does this: an ES5\n // target loses the prototype chain through `super()`, and without it\n // `instanceof` fails for the one class whose whole purpose is to be\n // caught by name.\n Object.setPrototypeOf(this, TestEnvironmentRequiredError.prototype);\n this.operationId = operationId;\n this.environment = environment;\n }\n}\n\nexport interface AdvanceTestTimeOptions {\n /** The exact instant to advance the sandbox clock to. Mutually exclusive\n * with `byHours` — exactly one is required (`AdvanceTestTimeRequest`).\n *\n * Bounded at BOTH ends. At or before the clock's current `simulatedNow` is\n * `422 TEST_CLOCK_BACKWARDS`; more than one year past `simulatedNow` is\n * `422 TEST_CLOCK_TOO_FAR`; more than one year past REAL time is refused\n * earlier still, as a `422 VALIDATION_ERROR` on this field — the same\n * one-year horizon, measured from the other anchor. */\n readonly to?: string;\n /** Hours to advance the sandbox clock by, from its current `simulatedNow`.\n * Mutually exclusive with `to`. Capped at `8760` (one year) by the schema\n * itself, so this field hits the horizon as a `422 VALIDATION_ERROR`\n * rather than as `TEST_CLOCK_TOO_FAR`. */\n readonly byHours?: number;\n /** Pins the `Idempotency-Key` this call sends. Omitting it does not mean\n * \"no key\": `advanceTestTime` is now idempotent-capable\n * (`OPERATION_ACCEPTS_IDEMPOTENCY_KEY`, `../generated/security.ts`), so\n * `../http/client.ts` mints one per call and reuses it across the retry\n * ladder either way. Pass your own when the KEY itself has to survive\n * something this client does not — a process restart, a re-run of the same\n * suite step — because a forward-only advance is exactly the write a lost\n * response cannot be safely repeated for: with no key in common, the\n * repeat advances the clock a SECOND time instead of replaying the first\n * advance. A replay whose body differs is `422 IDEMPOTENCY_KEY_REUSED`. */\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadTestClockOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface ResetTestClockOptions {\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface BuildTestFixturesOptions {\n /** Which fixture scenario to (re)build. v1 ships exactly one: `\"default\"`. */\n readonly scenario?: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadTestFixturesOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadTestQuotaOptions {\n readonly signal?: AbortSignal;\n}\n\nexport interface TestResource {\n /** `POST /api/v1/test/advance-time` — advances the sandbox clock and\n * replays every scheduled evaluation in between.\n *\n * Forward only AND bounded: `422 TEST_CLOCK_BACKWARDS` for a target at or\n * before `simulatedNow`, `422 TEST_CLOCK_TOO_FAR` for one more than a year\n * past it — that one's `details` carry `simulatedNow`, `requestedTo` and\n * `maxHorizonHours`. `byHours` is capped at `8760`, and a `to` beyond a\n * year from REAL time is refused as `422 VALIDATION_ERROR`. All of these\n * are non-retryable (`../generated/error-codes.ts`), so a suite clamps its\n * own horizon rather than backing off — read `maxHorizonHours` off the\n * refusal and re-aim.\n *\n * Idempotent-capable and rate-limited. The SDK always sends an\n * `Idempotency-Key` (see `AdvanceTestTimeOptions.idempotencyKey` for why\n * it matters more here than elsewhere), and the per-tenant sandbox\n * mutation limiter answers `429 RATE_LIMITED` with `Retry-After` when a\n * suite advances the clock in a tight loop — that one IS retryable, and\n * `../http/retry.ts` honours the header so the caller never sleeps by\n * hand. */\n advanceTime(options: AdvanceTestTimeOptions): Promise<KaafilResponse<AdvanceTimeResponse>>;\n /** `GET /api/v1/test/clock` — reads the sandbox's simulated clock. */\n clock(options?: ReadTestClockOptions): Promise<KaafilResponse<TestClockResponse>>;\n /** `POST /api/v1/test/clock/reset` — resets the sandbox clock to wall\n * time. Does not touch fixtures. */\n resetClock(options?: ResetTestClockOptions): Promise<KaafilResponse<TestClockResponse>>;\n /** `GET /api/v1/test/fixtures` — reads the current fixture's external\n * reference map and DOES NOT REBUILD IT. The read-only counterpart of\n * `fixtures()` below (identical `FixtureRefMapResponse`), assembled from\n * the rows that exist right now: nothing is written, no clock moves, no\n * row is created. That is the whole point — a suite can ask \"is my fixture\n * there?\" without the act of asking resetting it, which calling\n * `fixtures()` to find out would. `clock()`/`resetClock()` name the GET\n * plainly and the mutation with a verb; this pair reads the other way\n * round only because `fixtures()` already shipped as the POST.\n *\n * `404 RESOURCE_NOT_FOUND` (`KaafilNotFoundError`, `resource:\n * \"TestFixture\"`) when this tenant has never called `fixtures()`, or when\n * a previous rebuild was interrupted after the wipe. Deliberately a 404\n * rather than an empty `200`: the refs are deterministic constants, so a\n * `200` assembled from them would answer \"yes, it's there\"\n * unconditionally, and existence — not the strings — is the only thing\n * this route is actually asked. Read this 404 as \"build it first\" (call\n * `fixtures()`), not as the loss-of-access a generic 404 usually means.\n *\n * `travellerRefs`/`managerRefs` come from the live rows and are ordered by\n * external id, so an interrupted rebuild reports the manifest that\n * actually survived rather than the one that was intended. */\n readFixtures(options?: ReadTestFixturesOptions): Promise<KaafilResponse<FixtureRefMapResponse>>;\n /** `POST /api/v1/test/fixtures` — (re)builds a fixture scenario to\n * pristine, with the same external refs on every call. Reach for\n * `readFixtures()` instead when you only need to know whether it is\n * already there. */\n fixtures(options?: BuildTestFixturesOptions): Promise<KaafilResponse<FixtureRefMapResponse>>;\n /** `GET /api/v1/test/quota` — reads the sandbox tenant's fixed caps and\n * current usage. Independent of the partner's plan tier: TEST-plane trip\n * ingest is never metered against the plan.\n *\n * All three caps are ENFORCED, each on its own path and with its own\n * refusal, and each is `null` when UNCAPPED — render that as \"No limit\",\n * never as a fallback number:\n * - `tripSlots.limit` — the effective per-tenant ceiling, refused by trip\n * ingest as `422 TEST_TRIP_LIMIT`.\n * - `travellersPerTripLimit` — a PER-TRIP roster ceiling, refused on the\n * manifest ingest path as `422 TEST_TRAVELLER_LIMIT` with `details:\n * { limit, resulting }` (`resulting` is the roster size the push would\n * have produced, so a caller can split the batch instead of guessing).\n * `travellers` beside it is a tenant-wide COUNT, deliberately not\n * comparable with this limit.\n * - `storageBytesLimit` — refused at file-confirm time as\n * `402 PLAN_FEATURE_DISABLED` with `reason: 'storageQuota'`\n * (`KaafilEntitlementError.reason`, `../http/errors.ts`). On this plane\n * that refusal's `details.includedBytes` is `null`: the sandbox has no\n * soft rung to bill overage against, only the hard cap — do not render\n * a `null` `includedBytes` as zero. `storageBytes` counts `READY` files\n * only, the same rows the enforcing side counts, so THAT pair is\n * directly comparable.\n *\n * `filePurgeDays` is not a limit at all: it is the retention window a\n * sandbox upload survives before the purge sweep removes it. */\n quota(options?: ReadTestQuotaOptions): Promise<KaafilResponse<SandboxQuotaResponse>>;\n}\n\n/**\n * `environment` is threaded in alongside the transport — the one piece of\n * construction-time state this resource needs that `KaafilHttpClient` itself\n * carries no opinion about (it serves every environment identically; the\n * refusal below is this module's own, not the transport's).\n */\nexport function createTestResource(\n client: KaafilHttpClient,\n environment: Environment,\n): TestResource {\n function assertTestEnvironment(operationId: OperationId): void {\n if (environment !== EnvironmentValues.Test) {\n throw new TestEnvironmentRequiredError(operationId, environment);\n }\n }\n\n return {\n async advanceTime(options) {\n assertTestEnvironment(OperationId.AdvanceTestTime);\n const { to, byHours, idempotencyKey, signal } = options;\n return client.execute<AdvanceTimeResponse>({\n method: 'POST',\n operationId: OperationId.AdvanceTestTime,\n path: '/api/v1/test/advance-time',\n body: {\n ...(to !== undefined ? { to } : {}),\n ...(byHours !== undefined ? { byHours } : {}),\n },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async clock(options = {}) {\n assertTestEnvironment(OperationId.ReadTestClock);\n const { signal } = options;\n return client.execute<TestClockResponse>({\n method: 'GET',\n operationId: OperationId.ReadTestClock,\n path: '/api/v1/test/clock',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async resetClock(options = {}) {\n assertTestEnvironment(OperationId.ResetTestClock);\n const { idempotencyKey, signal } = options;\n return client.execute<TestClockResponse>({\n method: 'POST',\n operationId: OperationId.ResetTestClock,\n path: '/api/v1/test/clock/reset',\n body: {},\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async readFixtures(options = {}) {\n assertTestEnvironment(OperationId.ReadTestFixtures);\n const { signal } = options;\n return client.execute<FixtureRefMapResponse>({\n method: 'GET',\n operationId: OperationId.ReadTestFixtures,\n path: '/api/v1/test/fixtures',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async fixtures(options = {}) {\n assertTestEnvironment(OperationId.BuildTestFixtures);\n const { scenario, idempotencyKey, signal } = options;\n return client.execute<FixtureRefMapResponse>({\n method: 'POST',\n operationId: OperationId.BuildTestFixtures,\n path: '/api/v1/test/fixtures',\n body: { ...(scenario !== undefined ? { scenario } : {}) },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async quota(options = {}) {\n assertTestEnvironment(OperationId.ReadTestQuota);\n const { signal } = options;\n return client.execute<SandboxQuotaResponse>({\n method: 'GET',\n operationId: OperationId.ReadTestQuota,\n path: '/api/v1/test/quota',\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `travellers` — the traveller-identity endpoints that live outside any one\n * trip: DPDP erasure and DSAR export, plus the two cross-trip/cross-agency\n * traveller reads. `architecture/08-sdk.md §4`.\n *\n * `erase`/`export_` (`eraseTraveller`/`exportTraveller`, `../generated/security.ts`'s\n * `OPERATION_SECURITY`) declare `apiKeyAuth` as their ONLY accepted scheme —\n * no manager or agency-admin session can ever satisfy them.\n *\n * `listForTrip`/`listForAgency` (`getTripManifest`/`searchTravellerDirectory`)\n * accept `apiKeyAuth`, `managerAuth`, OR `agencyAdminAuth` — the same\n * multi-scheme shape `./vendors.ts`'s `listTripVendors` has — so, following\n * that file's precedent, this whole resource (erase/export_ included) is\n * exposed unchanged from both `../client.ts` and `../client-entry.ts`; a\n * manager- or agency-admin-opened `KaafilClient` calling `erase`/`export_`\n * simply fails at the point of use with `UnsatisfiableSchemeError`, the same\n * way a `shareToken`-opened client calling `vendors`/`journey` already does.\n *\n * `listForTrip` mirrors `listTripVendors`: no `cursor`/`limit` query\n * parameters on `getTripManifest`, so it returns the full manifest directly\n * rather than a `KaafilPaginator`. `listForAgency` wraps\n * `searchTravellerDirectory`, which is cursor-paginated — `q` is now\n * OPTIONAL engine-side (a deliberate reversal of the previous \"search-only,\n * never browsable\" posture; when supplied it must be non-empty). Omitting\n * `q` lists every traveller in the agency, so `TravellerDirectoryFilters`\n * carries no required field.\n *\n * `create` (`createTraveller`, `POST /api/v1/agencies/{ref}/travellers`,\n * GAP-008) accepts `apiKeyAuth` OR `agencyAdminAuth` — NEVER `managerAuth`: a\n * manager acts on one trip on the ground and reaches the roster through a\n * trip's manifest or a trek's walk-in, not the agency-wide directory this\n * route writes into directly. `externalTravellerId` is optional — omitted,\n * Kaafil mints the traveller with `externalId: null`, reconciled later by\n * phone, the same shape `treks.walkIns.create` already takes. A supplied id\n * that already resolves within the SAME agency returns the EXISTING\n * directory row rather than a conflict; a ref that resolves in a DIFFERENT\n * agency is the ordinary `404` isolation refusal. `fullName` is the only\n * required body field. Because it lacks `managerAuth`, it is agencyRef-BOUND\n * on `../client-entry.ts` alongside `listForAgency`/`listForAgencyPage` — see\n * that file's \"agencyRef-bound option types\" section.\n *\n * `getAgencyProfile` (`getTravellerAgencyProfile`,\n * `GET /api/v1/agencies/{ref}/travellers/{travellerRef}`, GAP-016) — the\n * traveller-wide profile a host needs after selecting a row from\n * `listForAgency`/`listForAgencyPage`, which carries no trip reference at\n * all. Accepts `apiKeyAuth` OR `agencyAdminAuth`, NEVER `managerAuth` — the\n * identical posture `create` above already takes, for the identical reason\n * (no trip in the URL for a manager bearer's own per-trip gate to check\n * against). Also agencyRef-BOUND on `../client-entry.ts` alongside `create`.\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype EraseResponse = components['schemas']['EraseResponse'];\ntype DsarBundleResponse = components['schemas']['DsarBundleResponse'];\ntype TripManifestItemResponse = components['schemas']['TripManifestItemResponse'];\ntype TravellerDirectoryItemResponse = components['schemas']['TravellerDirectoryItemResponse'];\ntype CreateTravellerRequest = components['schemas']['CreateTravellerRequest'];\ntype TravellerDetailResponse = components['schemas']['TravellerDetailResponse'];\ntype TravellerNoteResponse = components['schemas']['TravellerNoteResponse'];\ntype AddTravellerNoteRequest = components['schemas']['AddTravellerNoteRequest'];\nexport type TravellerAgencyProfileResponse =\n components['schemas']['TravellerAgencyProfileResponse'];\n\nexport interface EraseTravellerOptions {\n readonly ref: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ExportTravellerOptions {\n readonly ref: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ListForTripOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- travellers.getDetail / .addNote (manager-facing profile) ------------\n\nexport interface GetTravellerDetailOptions {\n readonly tripRef: string;\n readonly travellerRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AddTravellerNoteOptions extends AddTravellerNoteRequest {\n readonly tripRef: string;\n readonly travellerRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\ntype SearchTravellerDirectoryQuery = NonNullable<\n operations['searchTravellerDirectory']['parameters']['query']\n>;\n/** The filterable half of `searchTravellerDirectory`'s query params —\n * `cursor`/`limit` are the paginator's job; `q` is required, never a filter\n * the caller can omit. */\nexport type TravellerDirectoryFilters = Omit<SearchTravellerDirectoryQuery, 'cursor' | 'limit'>;\n\nasync function fetchAgencyDirectoryPage(\n client: KaafilHttpClient,\n agencyRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: TravellerDirectoryFilters;\n },\n) {\n const response = await client.execute<readonly TravellerDirectoryItemResponse[]>({\n method: 'GET',\n operationId: OperationId.SearchTravellerDirectory,\n path: '/api/v1/agencies/{ref}/travellers',\n pathParams: { ref: agencyRef },\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListForAgencyOptions {\n readonly agencyRef: string;\n readonly filters: TravellerDirectoryFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListForAgencyPageOptions extends TravellerDirectoryFilters {\n readonly agencyRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\n// --- travellers.create ---------------------------------------------------\n\nexport interface CreateTravellerOptions extends CreateTravellerRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- travellers.getAgencyProfile (GAP-016) --------------------------------\n\nexport interface GetTravellerAgencyProfileOptions {\n readonly agencyRef: string;\n readonly travellerRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TravellersResource {\n /** `POST /api/v1/travellers/{ref}/erase` — DPDP right to erasure,\n * anonymize in place. Idempotent on `Traveller.erasedAt`. */\n erase(options: EraseTravellerOptions): Promise<KaafilResponse<EraseResponse>>;\n /** `GET /api/v1/travellers/{ref}/export` — DSAR export, generated fresh\n * on every call. Named `export_` because `export` is a reserved word. */\n export_(options: ExportTravellerOptions): Promise<KaafilResponse<DsarBundleResponse>>;\n /** `GET /api/v1/trips/{ref}/travellers` — the trip's manifest. Not\n * cursor-paginated, same as `./vendors.ts`'s `listTripVendors`. */\n listForTrip(\n options: ListForTripOptions,\n ): Promise<KaafilResponse<readonly TripManifestItemResponse[]>>;\n /** `GET /api/v1/trips/{ref}/travellers/{travellerRef}` — a manager-facing\n * profile: identity, booking status, party, profile-sourced attributes\n * (email/DOB/meal preference/dietary/allergies/medical notes/emergency\n * contact), current room/seat assignment, this trip's balance (`null`\n * when the agency's plan doesn't carry `collections` — a server-side\n * gate), and the note thread. */\n getDetail(options: GetTravellerDetailOptions): Promise<KaafilResponse<TravellerDetailResponse>>;\n /** `POST /api/v1/trips/{ref}/travellers/{travellerRef}/notes` — adds a\n * free-text note to a traveller's profile, scoped to this trip. */\n addNote(options: AddTravellerNoteOptions): Promise<KaafilResponse<TravellerNoteResponse>>;\n /** `GET /api/v1/agencies/{ref}/travellers` as a `KaafilPaginator` — the\n * agency-wide traveller directory search/browse. `q` is optional; omit it\n * to page through every traveller in the agency. */\n listForAgency(\n options: ListForAgencyOptions,\n ): KaafilPaginator<TravellerDirectoryItemResponse, TravellerDirectoryFilters>;\n /** The manual single-page escape hatch for `listForAgency`. */\n listForAgencyPage(\n options: ListForAgencyPageOptions,\n ): Promise<KaafilPagedResponse<readonly TravellerDirectoryItemResponse[]>>;\n /** `POST /api/v1/agencies/{ref}/travellers` (GAP-008) — adds a traveller\n * to the agency's directory directly. See this file's header for the\n * `externalTravellerId`-optional and existing-row-return behaviour. */\n create(options: CreateTravellerOptions): Promise<KaafilResponse<TravellerDirectoryItemResponse>>;\n /** `GET /api/v1/agencies/{ref}/travellers/{travellerRef}` (GAP-016) — the\n * agency-wide profile: identity, cross-trip `profile.*` attributes, every\n * trip this traveller has been on (each with its own balance, `null` when\n * none exists yet), a computed lifetime-finance total across those trips,\n * and every trip-scoped note, read-only. See this file's header for the\n * full citation. */\n getAgencyProfile(\n options: GetTravellerAgencyProfileOptions,\n ): Promise<KaafilResponse<TravellerAgencyProfileResponse>>;\n}\n\nexport function createTravellersResource(client: KaafilHttpClient): TravellersResource {\n return {\n async erase(options) {\n const { ref, idempotencyKey, signal } = options;\n return client.execute<EraseResponse>({\n method: 'POST',\n operationId: OperationId.EraseTraveller,\n path: '/api/v1/travellers/{ref}/erase',\n pathParams: { ref },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async export_(options) {\n const { ref, signal } = options;\n return client.execute<DsarBundleResponse>({\n method: 'GET',\n operationId: OperationId.ExportTraveller,\n path: '/api/v1/travellers/{ref}/export',\n pathParams: { ref },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async listForTrip(options) {\n const { tripRef, signal } = options;\n return client.execute<readonly TripManifestItemResponse[]>({\n method: 'GET',\n operationId: OperationId.GetTripManifest,\n path: '/api/v1/trips/{ref}/travellers',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async getDetail(options) {\n const { tripRef, travellerRef, signal } = options;\n return client.execute<TravellerDetailResponse>({\n method: 'GET',\n operationId: OperationId.GetTravellerDetail,\n path: '/api/v1/trips/{ref}/travellers/{travellerRef}',\n pathParams: { ref: tripRef, travellerRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async addNote(options) {\n const { tripRef, travellerRef, idempotencyKey, signal, ...body } = options;\n return client.execute<TravellerNoteResponse>({\n method: 'POST',\n operationId: OperationId.AddTravellerNote,\n path: '/api/v1/trips/{ref}/travellers/{travellerRef}/notes',\n pathParams: { ref: tripRef, travellerRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n listForAgency(options) {\n const { agencyRef, filters, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchAgencyDirectoryPage(client, agencyRef, request),\n filters,\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listForAgencyPage(options) {\n const { agencyRef, cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly TravellerDirectoryItemResponse[]>({\n method: 'GET',\n operationId: OperationId.SearchTravellerDirectory,\n path: '/api/v1/agencies/{ref}/travellers',\n pathParams: { ref: agencyRef },\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<TravellerDirectoryItemResponse>({\n method: 'POST',\n operationId: OperationId.CreateTraveller,\n path: '/api/v1/agencies/{ref}/travellers',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async getAgencyProfile(options) {\n const { agencyRef, travellerRef, signal } = options;\n return client.execute<TravellerAgencyProfileResponse>({\n method: 'GET',\n operationId: OperationId.GetTravellerAgencyProfile,\n path: '/api/v1/agencies/{ref}/travellers/{travellerRef}',\n pathParams: { ref: agencyRef, travellerRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `treks` — the boarding-day board, walk-ins, and postpone. `architecture/08-\n * sdk.md §4`. Deliberately small: board/close/reopen belong to `pickups`, and\n * this module contributes only trek POLICY on top of them.\n *\n * All six operations — `board`, `walkIns.meta`, `walkIns.create`,\n * `walkIns.list` (GAP-006), `walkIns.reconcile`, and `postpone` — accept the\n * SAME three alternatives: a manager session, an agency-admin session, OR an\n * API key (`managerAuth`, `apiKeyAuth`, `agencyAdminAuth`; never an AND) —\n * see `../generated/security.ts`'s `OPERATION_SECURITY`, the source of truth\n * for all of this. The `ACTIVE_TREK_REF` sentinel (below) narrows this\n * further at the semantic layer for EVERY ONE of the six, `walkIns.list`/\n * `walkIns.reconcile` included: resolving `trekRef: 'active'` is\n * manager-only regardless of which of the above credentials the request\n * carries — an apiKey or agencyAdmin caller passing the sentinel gets\n * `422 ACTIVE_REQUIRES_MANAGER`, not the trek (`assertActiveSentinelResolvable`,\n * called by every one of these six engine-side).\n *\n * ── THE `active` SENTINEL ────────────────────────────────────────────────────\n *\n * `trekRef` in these paths is a dual-mode identity like every other `ref` in\n * this SDK — Kaafil id or the CRM's external id — PLUS one reserved word,\n * `ACTIVE_TREK_REF` (`'active'`), which resolves to the manager's CURRENT\n * trek rather than being looked up as an id at all. `RESERVED_TREK_REF` in the\n * engine already guards the ingest direction (an external trip id can never\n * literally be `\"active\"`); this path position is a second, distinct place\n * the same reservation applies, and the engine's own docblock says a new path\n * position \"must opt in explicitly\" rather than inheriting the ingest guard\n * for free. Exposed here as a named constant rather than left for a caller to\n * type the string, so `treks.board({ trekRef: ACTIVE_TREK_REF })` reads as\n * \"whichever trek this manager is on\" at the call site instead of a magic\n * string that happens to mean something special.\n *\n * The consequence for a real external trip id: one literally equal to\n * `\"active\"` can NEVER be addressed through any of these four routes — it\n * would always resolve as the sentinel instead. That is a property of the\n * contract, not a bug in this SDK; a CRM minting external ids should treat\n * `\"active\"` as unusable here the same way it would a reserved keyword in any\n * other system.\n *\n * When no trek is currently assigned, `board` still answers `200` with an\n * `emptyState` block (`{ reason: 'no_trek_assigned', message }`) rather than\n * `404` — the manager stays where they tapped instead of hitting an error\n * screen. Every OTHER trek endpoint (`walkIns.*`, `postpone`) answers `404`\n * for \"no such trek\" the normal way.\n *\n * A trek endpoint reached on an `eventType: 'TRIP'` trip is `422 NOT_A_TREK`\n * — wrong kind, not missing. Unknown or cross-scope stays `404`, the same\n * not-found used everywhere else in this SDK (`../http/errors.ts`'s standing\n * argument for why there is exactly one not-found class applies here too).\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype TrekBoardResponse = components['schemas']['TrekBoardResponse'];\ntype WalkInMetaResponse = components['schemas']['WalkInMetaResponse'];\ntype WalkInResponse = components['schemas']['WalkInResponse'];\ntype WalkInListItemResponse = components['schemas']['WalkInListItemResponse'];\ntype WalkInReconcileResponse = components['schemas']['WalkInReconcileResponse'];\ntype PostponeResponse = components['schemas']['PostponeResponse'];\ntype CreateTrekWalkInRequest = components['schemas']['CreateTrekWalkInRequest'];\ntype ReconcileTrekWalkInRequest = components['schemas']['ReconcileTrekWalkInRequest'];\ntype PostponeTrekRequest = components['schemas']['PostponeTrekRequest'];\n\n/**\n * The reserved `trekRef` value meaning \"the manager's current trek\" — see\n * this file's header. Never a real external trip id: the engine refuses to\n * ingest one equal to this string (`RESERVED_TREK_REF` in\n * `shared/ingest/external-ref.resolver.ts`), so no trip that reaches this SDK\n * can ever collide with it.\n */\nexport const ACTIVE_TREK_REF = 'active';\n\n// --- date-time widening --------------------------------------------------\n//\n// `newStartDate`/`newEndDate` are `string` (`Format: date-time`) in the\n// generated schema, because the schema is a faithful mirror of the spec and\n// the wire format really is a string. `PostponeTrekOptions` widens exactly\n// those two fields to `DateTimeInput` (see `../datetime`) by indexing off the\n// generated type and overriding — never restating a request body by hand.\n// The factory normalizes back down to `string` before the body reaches the\n// wire.\n\n// --- treks.board -----------------------------------------------------------\n\nexport interface ReadTrekBoardOptions {\n /** A trek's dual-mode ref, or `ACTIVE_TREK_REF` for the manager's current\n * one — see this file's header. */\n readonly trekRef: string;\n readonly signal?: AbortSignal;\n}\n\n// --- treks.walkIns -----------------------------------------------------------\n\nexport interface ReadTrekWalkInMetaOptions {\n readonly trekRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CreateTrekWalkInOptions extends CreateTrekWalkInRequest {\n readonly trekRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n/** `listTrekWalkIns` takes no filter query params beyond `cursor`/`limit` —\n * this is the paginator's `F` type parameter, kept as an explicit empty\n * shape (never `object`, which would also accept a stray non-empty value\n * unintentionally) so `setFilters({})` is the only value that ever\n * type-checks. */\ntype TrekWalkInFilters = Record<string, never>;\n\nasync function fetchTrekWalkInsPage(\n client: KaafilHttpClient,\n trekRef: string,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: TrekWalkInFilters;\n },\n) {\n const response = await client.execute<readonly WalkInListItemResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTrekWalkIns,\n path: '/api/v1/treks/{trekRef}/walk-ins',\n pathParams: { trekRef },\n query: { cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListTrekWalkInsOptions {\n /** A trek's dual-mode ref, or `ACTIVE_TREK_REF` for the manager's current\n * one — see this file's header. Same manager-only sentinel gate as\n * `board`/`walkIns.meta`/`walkIns.create`/`postpone`: an apiKey or\n * agencyAdmin caller passing `ACTIVE_TREK_REF` here gets\n * `422 ACTIVE_REQUIRES_MANAGER`, not the trek. */\n readonly trekRef: string;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListTrekWalkInsPageOptions {\n readonly trekRef: string;\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReconcileTrekWalkInOptions extends ReconcileTrekWalkInRequest {\n readonly trekRef: string;\n readonly walkInId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TrekWalkInsResource {\n /** `GET /api/v1/treks/{trekRef}/walk-ins/meta` — the open pickup points a\n * walk-in may be assigned to, plus field hints for the intake form. */\n meta(options: ReadTrekWalkInMetaOptions): Promise<KaafilResponse<WalkInMetaResponse>>;\n /**\n * `POST /api/v1/treks/{trekRef}/walk-ins` — mints a Kaafil-owned traveller\n * (no `externalId`) plus a `WalkIn` row, and upserts the manifest so\n * rooming, seating and this trek's own board see them immediately. Name and\n * phone live on the traveller, never on the walk-in row — one PII home.\n * Reconciliation against a later CRM upsert happens by normalised phone and\n * emits no event of its own; a walk-in on a `CLOSED` stop auto-reopens it\n * through `pickups.reopen` in-process, so the eventual re-close carries the\n * corrective event, not this call.\n */\n create(options: CreateTrekWalkInOptions): Promise<KaafilResponse<WalkInResponse>>;\n /** `GET /api/v1/treks/{trekRef}/walk-ins` (GAP-006) as a `KaafilPaginator`\n * — the sibling read of `create`, one row per recorded walk-in. */\n list(options: ListTrekWalkInsOptions): KaafilPaginator<WalkInListItemResponse, TrekWalkInFilters>;\n /** The manual single-page escape hatch for `list`. */\n listPage(\n options: ListTrekWalkInsPageOptions,\n ): Promise<KaafilPagedResponse<readonly WalkInListItemResponse[]>>;\n /**\n * `POST /api/v1/treks/{trekRef}/walk-ins/{walkInId}/reconcile` — the human\n * fallback `create`'s own `needsReconciliation` notice promises: a\n * name-only walk-in (no phone) has nothing for the automatic CRM-phone\n * match to compare against, so it stays flagged until claimed by hand.\n * `travellerRef` must resolve to a traveller your CRM already knows (one\n * carrying an external id) — linking to another still-unreconciled\n * Kaafil-minted traveller just trades one unclaimed row for two, so the\n * engine refuses it. Writes the same two columns the automatic path\n * writes; `WalkIn.travellerId` itself is unchanged.\n */\n reconcile(options: ReconcileTrekWalkInOptions): Promise<KaafilResponse<WalkInReconcileResponse>>;\n}\n\n// --- treks.postpone ----------------------------------------------------------\n\nexport interface PostponeTrekOptions\n extends Omit<PostponeTrekRequest, 'newStartDate' | 'newEndDate'> {\n readonly trekRef: string;\n /** Must be in the future AND after the trek's current `startDate` — a\n * postpone moves the trip forward, never back. `CANCELLED`/`COMPLETED`\n * trips answer `422 CANNOT_POSTPONE`; a write racing the close-out lock\n * answers `423 LOCKED`. */\n readonly newStartDate: DateTimeInput;\n readonly newEndDate: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- treks -----------------------------------------------------------------\n\nexport interface TreksResource {\n /** `GET /api/v1/treks/{trekRef}/board` — stops with expected-vs-boarded,\n * the running head-count, and the current phase. See this file's header\n * for the sentinel and the no-trek `emptyState`. */\n board(options: ReadTrekBoardOptions): Promise<KaafilResponse<TrekBoardResponse>>;\n readonly walkIns: TrekWalkInsResource;\n /**\n * `POST /api/v1/treks/{trekRef}/postpone`. Shifts every `ItineraryDay` and\n * `StayWindow` by the same delta in ONE transaction; `sortOrder` and bed/seat\n * assignments are untouched throughout. Pickup `scheduledTime` is\n * DELIBERATELY NOT shifted — stop times are re-confirmed by the manager on\n * the ground, because they usually change with the new departure — so\n * `ripple` on the response reports itinerary and stay-window counts only,\n * never a pickup count. `postponedFromDate` on the response always holds the\n * FIRST original start date, even across a second postpone.\n */\n postpone(options: PostponeTrekOptions): Promise<KaafilResponse<PostponeResponse>>;\n}\n\nexport function createTreksResource(client: KaafilHttpClient): TreksResource {\n return {\n async board(options) {\n const { trekRef, signal } = options;\n return client.execute<TrekBoardResponse>({\n method: 'GET',\n operationId: OperationId.ReadTrekBoard,\n path: '/api/v1/treks/{trekRef}/board',\n pathParams: { trekRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async postpone(options) {\n const { trekRef, idempotencyKey, signal, newStartDate, newEndDate, ...rest } = options;\n const body: PostponeTrekRequest = {\n ...rest,\n newStartDate: normalizeDateTimeInput(newStartDate, 'newStartDate'),\n newEndDate: normalizeDateTimeInput(newEndDate, 'newEndDate'),\n };\n return client.execute<PostponeResponse>({\n method: 'POST',\n operationId: OperationId.PostponeTrek,\n path: '/api/v1/treks/{trekRef}/postpone',\n pathParams: { trekRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n walkIns: {\n async meta(options) {\n const { trekRef, signal } = options;\n return client.execute<WalkInMetaResponse>({\n method: 'GET',\n operationId: OperationId.ReadTrekWalkInMeta,\n path: '/api/v1/treks/{trekRef}/walk-ins/meta',\n pathParams: { trekRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { trekRef, idempotencyKey, signal, ...body } = options;\n return client.execute<WalkInResponse>({\n method: 'POST',\n operationId: OperationId.CreateTrekWalkIn,\n path: '/api/v1/treks/{trekRef}/walk-ins',\n pathParams: { trekRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n list(options) {\n const { trekRef, limit } = options;\n return createPaginator({\n fetchPage: (request) => fetchTrekWalkInsPage(client, trekRef, request),\n filters: {},\n ...(limit !== undefined ? { limit } : {}),\n });\n },\n async listPage(options) {\n const { trekRef, cursor, limit, signal } = options;\n const response = await client.execute<readonly WalkInListItemResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTrekWalkIns,\n path: '/api/v1/treks/{trekRef}/walk-ins',\n pathParams: { trekRef },\n query: { cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n async reconcile(options) {\n const { trekRef, walkInId, idempotencyKey, signal, ...body } = options;\n return client.execute<WalkInReconcileResponse>({\n method: 'POST',\n operationId: OperationId.ReconcileTrekWalkIn,\n path: '/api/v1/treks/{trekRef}/walk-ins/{walkInId}/reconcile',\n pathParams: { trekRef, walkInId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `trips` — upsert, get, cancel, plus `travellers`, `managers`, `parties`,\n * `balance`, and the bulk push. `architecture/08-sdk.md §4`. MOST operations\n * here are `apiKeyAuth`-only in the spec (CRM-backend ingest,\n * `03-auth-and-tokens.md §1`) — `upsert`/`get`/`cancel`, `travellers.upsert`,\n * `bulk.push`, and `managers.upsert`/`assign`/`unassign`.\n *\n * `parties.*` (`listParties`/`createParty`/`patchParty`/`deleteParty`),\n * `managers.list`/`managers.patch` (`listTripManagers`/`patchTripManager`),\n * `travellers.pushManifest`/`travellers.remove`\n * (`pushManifest`/`removeFromManifest`), and `balance.push`\n * (`pushTripBalances`) are the exception: each accepts `managerAuth`,\n * `apiKeyAuth`, OR `agencyAdminAuth` in the spec (`../generated/security.ts`'s\n * `OPERATION_SECURITY`) — the same multi-scheme shape `./vendors.ts`'s\n * `listTripVendors` has. Following that file's precedent, this WHOLE\n * resource is exposed unchanged from both `../client.ts` and\n * `../client-entry.ts`; a manager- or agency-admin-opened `KaafilClient`\n * calling any of the `apiKeyAuth`-only members above simply fails at the\n * point of use with `UnsatisfiableSchemeError`, the same way a\n * `shareToken`-opened client calling `vendors`/`journey` already does. (Note:\n * `patchTripManager` also authenticates a manager bearer at the HTTP layer,\n * then REFUSES the act itself with `422 BUSINESS_RULE_VIOLATION` — see the\n * spec's own operation doc — which is a business rule this SDK does not\n * pre-empt client-side, the same posture every other role-gated write here\n * takes.)\n *\n * Every path parameter is a named field on its options object — never a\n * positional string — so a two-parameter route (`travellers.remove` takes a\n * trip ref AND a traveller ref; `managers.unassign`/`managers.patch` take a\n * trip ref AND a manager ref; `parties.patch`/`parties.remove` take a trip\n * ref AND a party id) can't be called with its arguments swapped.\n */\n\nimport { type DateTimeInput, normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype UpsertTripRequest = components['schemas']['UpsertTripRequest'];\ntype TripUpsertResponse = components['schemas']['TripUpsertResponse'];\ntype TripEchoResponse = components['schemas']['TripEchoResponse'];\ntype TripCancelResponse = components['schemas']['TripCancelResponse'];\ntype UpsertTravellerProfileRequest = components['schemas']['UpsertTravellerProfileRequest'];\ntype TravellerUpsertResponse = components['schemas']['TravellerUpsertResponse'];\ntype PushManifestRequest = components['schemas']['PushManifestRequest'];\ntype ManifestPushResponse = components['schemas']['ManifestPushResponse'];\ntype ManifestRemoveResponse = components['schemas']['ManifestRemoveResponse'];\ntype UpsertManagerRequest = components['schemas']['UpsertManagerRequest'];\ntype ManagerResponse = components['schemas']['ManagerResponse'];\ntype AssignManagerRequest = components['schemas']['AssignManagerRequest'];\ntype TripManagerResponse = components['schemas']['TripManagerResponse'];\ntype TripManagerRowResponse = components['schemas']['TripManagerRowResponse'];\ntype PatchTripManagerRequest = components['schemas']['PatchTripManagerRequest'];\ntype PartyDeltaResponse = components['schemas']['PartyDeltaResponse'];\ntype PartyResponse = components['schemas']['PartyResponse'];\ntype PartyDeleteResponse = components['schemas']['PartyDeleteResponse'];\ntype CreatePartyRequest = components['schemas']['CreatePartyRequest'];\ntype PatchPartyRequest = components['schemas']['PatchPartyRequest'];\n/** `PushTripBalancesRequest` is itself an array in the spec — there is no wrapper object. */\ntype PushTripBalancesRow = components['schemas']['PushTripBalancesRequest'][number];\ntype BalancePushResponse = components['schemas']['BalancePushResponse'];\n/** Likewise `PushBulkTripsRequest`. */\ntype PushBulkTripsItem = components['schemas']['PushBulkTripsRequest'][number];\ntype BulkTripsPushResponse = components['schemas']['BulkTripsPushResponse'];\n\n// --- date-time widening --------------------------------------------------\n//\n// Every field below is `string` (with `Format: date-time`) in the generated\n// schema, because the schema is a faithful mirror of the OpenAPI spec, and\n// the wire format really is a string. The `*Input` types here widen just\n// those fields to `DateTimeInput` (see `../datetime`) by indexing off the\n// generated type and overriding — never restating a whole request body by\n// hand — so a spec change to any *other* field on these shapes still flows\n// through untouched. The `create*Resource` functions below normalize back\n// down to the schema's `string` shape before the body reaches the wire.\n\ntype UpsertTripSegment = NonNullable<UpsertTripRequest['segments']>[number];\ntype UpsertTripSegmentInput = Omit<UpsertTripSegment, 'startDate' | 'endDate'> & {\n readonly startDate: DateTimeInput;\n readonly endDate: DateTimeInput;\n};\n\ntype PushManifestTraveller = PushManifestRequest['travellers'][number];\n/**\n * `sourceUpdatedAt` is OPTIONAL here, unlike every sibling below, because the\n * wire made it optional for this one entry shape: a desk adding a traveller to\n * a trip has no \"when my system last changed this\" instant to send, and the\n * server stamps the write when it is omitted. A CRM mirroring its own records\n * still sends its real instant and still wins or loses a race on it.\n */\ntype PushManifestTravellerInput = Omit<PushManifestTraveller, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt?: DateTimeInput;\n};\n\ntype PushBulkTripsTraveller = NonNullable<PushBulkTripsItem['travellers']>[number];\ntype PushBulkTripsTravellerInput = Omit<PushBulkTripsTraveller, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt: DateTimeInput;\n};\n\ntype PushBulkTripsBalanceRow = NonNullable<PushBulkTripsItem['balance']>[number];\ntype PushBulkTripsBalanceRowInput = Omit<PushBulkTripsBalanceRow, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt: DateTimeInput;\n};\n\ntype PushBulkTripsManager = NonNullable<PushBulkTripsItem['managers']>[number];\ntype PushBulkTripsManagerInput = Omit<PushBulkTripsManager, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt: DateTimeInput;\n};\n\ntype PushBulkTripsItemInput = Omit<\n PushBulkTripsItem,\n 'startDate' | 'endDate' | 'sourceUpdatedAt' | 'travellers' | 'balance' | 'managers'\n> & {\n readonly startDate: DateTimeInput;\n readonly endDate: DateTimeInput;\n readonly sourceUpdatedAt: DateTimeInput;\n readonly travellers?: readonly PushBulkTripsTravellerInput[];\n readonly balance?: readonly PushBulkTripsBalanceRowInput[];\n readonly managers?: readonly PushBulkTripsManagerInput[];\n};\n\n// --- trips.{upsert,get,cancel} ---------------------------------------------\n\nexport interface UpsertTripOptions\n extends Omit<UpsertTripRequest, 'startDate' | 'endDate' | 'sourceUpdatedAt' | 'segments'> {\n readonly startDate: DateTimeInput;\n readonly endDate: DateTimeInput;\n /** The CRM's own record-updated timestamp, used for last-write-wins\n * staleness detection (`06-offline-first.md §6`). Deliberately still\n * required, with no \"defaults to now\" — defaulting it would make every\n * write look like the newest write and silently defeat the staleness\n * check on out-of-order delivery. Accepting a `Date` here (via\n * `DateTimeInput`) is the correct amount of help: the caller still\n * supplies the CRM's real timestamp, just without hand-formatting it. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly segments?: readonly UpsertTripSegmentInput[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface GetTripOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface CancelTripOptions {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n// --- trips.travellers -------------------------------------------------------\n\nexport interface UpsertTravellerProfileOptions\n extends Omit<UpsertTravellerProfileRequest, 'sourceUpdatedAt'> {\n /** The traveller's own ref — dual-mode identity (Kaafil id or the CRM's\n * `externalTravellerId`); resolution is the engine's job. */\n readonly travellerRef: string;\n /** See the comment on `UpsertTripOptions.sourceUpdatedAt` — same contract,\n * required, never defaulted. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PushManifestOptions extends Omit<PushManifestRequest, 'travellers'> {\n readonly tripRef: string;\n readonly travellers: readonly PushManifestTravellerInput[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface RemoveFromManifestOptions {\n readonly tripRef: string;\n readonly travellerRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripTravellersResource {\n upsert(options: UpsertTravellerProfileOptions): Promise<KaafilResponse<TravellerUpsertResponse>>;\n pushManifest(options: PushManifestOptions): Promise<KaafilResponse<ManifestPushResponse>>;\n remove(options: RemoveFromManifestOptions): Promise<KaafilResponse<ManifestRemoveResponse>>;\n}\n\n// --- trips.managers ----------------------------------------------------------\n\nexport interface UpsertManagerOptions extends Omit<UpsertManagerRequest, 'sourceUpdatedAt'> {\n /** See the comment on `UpsertTripOptions.sourceUpdatedAt` — same contract,\n * required, never defaulted. */\n readonly sourceUpdatedAt: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface AssignManagerOptions extends Omit<AssignManagerRequest, 'sourceUpdatedAt'> {\n readonly tripRef: string;\n /** OPTIONAL, unlike every other `sourceUpdatedAt` in this file, and only\n * because this route now accepts an agency admin as well as an API key. A\n * CRM sends its own last-changed instant and should keep doing so — that\n * is what orders concurrent writes. A desk operator assigning a manager\n * by hand has no such instant, so omitting it lets the SERVER stamp the\n * write, which beats a client inventing one from its own clock.\n *\n * See the comment on `UpsertTripOptions.sourceUpdatedAt` — same contract,\n * required, never defaulted. */\n readonly sourceUpdatedAt?: DateTimeInput;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UnassignManagerOptions {\n readonly tripRef: string;\n readonly managerRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ListTripManagersOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchTripManagerOptions extends PatchTripManagerRequest {\n readonly tripRef: string;\n readonly managerRef: string;\n /** Required, not optional — see `../resources/itinerary.ts`'s\n * `PatchItineraryItemOptions.version` for why a missing `If-Match` and a\n * stale one are deliberately the same `409 CONFLICT_VERSION`. Pass the\n * `version` from `managers.list`'s (or `managers.assign`'s) row. */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripManagersResource {\n /** Not trip-scoped — `POST /api/v1/managers` upserts the manager entity\n * itself (dual-mode identity), independent of any one trip assignment. */\n upsert(options: UpsertManagerOptions): Promise<KaafilResponse<ManagerResponse>>;\n assign(options: AssignManagerOptions): Promise<KaafilResponse<TripManagerResponse>>;\n unassign(options: UnassignManagerOptions): Promise<KaafilResponse<TripManagerResponse>>;\n /** `GET /api/v1/trips/{ref}/managers` — every live manager assigned to\n * this trip, leads first. Not cursor-paginated, same posture as\n * `./vendors.ts`'s `listTripVendors`.\n *\n * Each row also carries the manager's vehicle on this trip (`vehicleReg`/\n * `vehicleType`, `null`/`null` when they own none), a few admin-panel\n * display fields (`contactLine`, `label`, `assignedOnLabel`), and two\n * per-request permission hints computed against the calling credential\n * (`canSetPrimary`, `canRemove` — the latter `false` only for a `manager`\n * bearer; unassign now accepts an agency admin too). */\n list(\n options: ListTripManagersOptions,\n ): Promise<KaafilResponse<readonly TripManagerRowResponse[]>>;\n /** `PATCH /api/v1/trips/{ref}/managers/{managerRef}` — changes `role` and/\n * or promotes/demotes the trip lead. See this file's header for the\n * `managerAuth`-authenticated-but-business-rule-refused case. */\n patch(options: PatchTripManagerOptions): Promise<KaafilResponse<TripManagerRowResponse>>;\n}\n\n// --- trips.parties -------------------------------------------------------------\n\nexport interface ListPartiesOptions {\n readonly tripRef: string;\n /** See `./itinerary.ts`'s `ReadItineraryOptions.since` — the identical\n * shared delta-sync cursor contract. Omit for every LIVE party; supply a\n * previous response's own cursor for a delta (live + newly-retired,\n * tombstones for the latter). */\n readonly since?: string;\n readonly signal?: AbortSignal;\n}\n\n/** One row of `parties.list`'s result: a live party, or the tombstone for\n * one retired since the cursor. Aliased off the response type rather than\n * restated, so the union stays whatever the contract says it is — see\n * `./itinerary.ts`'s `ItineraryItemDeltaRow` for the identical pattern. */\nexport type PartyDeltaRow = PartyDeltaResponse;\n\nexport interface AddPartyOptions extends CreatePartyRequest {\n readonly tripRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface PatchPartyOptions extends PatchPartyRequest {\n readonly tripRef: string;\n readonly partyId: string;\n /** Required, not optional — same contract as\n * `PatchTripManagerOptions.version`. Pass the `version` from `parties.list`\n * (or a prior `add`/`patch`). */\n readonly version: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface RemovePartyOptions {\n readonly tripRef: string;\n readonly partyId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripPartiesResource {\n /** `GET /api/v1/trips/{ref}/parties` — every live party and its current\n * members, or, with `?since=`, the delta since a prior cursor. */\n list(options: ListPartiesOptions): Promise<KaafilResponse<readonly PartyDeltaRow[]>>;\n /** `POST /api/v1/trips/{ref}/parties` — creates a PINNED party (the\n * manager override). */\n add(options: AddPartyOptions): Promise<KaafilResponse<PartyResponse>>;\n patch(options: PatchPartyOptions): Promise<KaafilResponse<PartyResponse>>;\n /** Retires the party. No `If-Match`/`version` — idempotent on an\n * already-retired party, the same `{ id, deleted: true }` ack, never a\n * `404`. */\n remove(options: RemovePartyOptions): Promise<KaafilResponse<PartyDeleteResponse>>;\n}\n\n// --- trips.balance / trips.bulk ----------------------------------------------\n\ntype PushTripBalancesRowInput = Omit<PushTripBalancesRow, 'sourceUpdatedAt'> & {\n readonly sourceUpdatedAt: DateTimeInput;\n};\n\nexport interface PushTripBalancesOptions {\n readonly tripRef: string;\n readonly balances: readonly PushTripBalancesRowInput[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripBalanceResource {\n push(options: PushTripBalancesOptions): Promise<KaafilResponse<BalancePushResponse>>;\n}\n\nexport interface PushBulkTripsOptions {\n readonly trips: readonly PushBulkTripsItemInput[];\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TripsBulkResource {\n /** `POST /api/v1/bulk/trips` — a batch of full trip bundles (trip +\n * manifest + balance + managers) in one call. */\n push(options: PushBulkTripsOptions): Promise<KaafilResponse<BulkTripsPushResponse>>;\n}\n\n// --- trips -------------------------------------------------------------------\n\nexport interface TripsResource {\n upsert(options: UpsertTripOptions): Promise<KaafilResponse<TripUpsertResponse>>;\n get(options: GetTripOptions): Promise<KaafilResponse<TripEchoResponse>>;\n cancel(options: CancelTripOptions): Promise<KaafilResponse<TripCancelResponse>>;\n readonly travellers: TripTravellersResource;\n readonly managers: TripManagersResource;\n readonly parties: TripPartiesResource;\n readonly balance: TripBalanceResource;\n readonly bulk: TripsBulkResource;\n}\n\n/**\n * `trips.bulk.push` carries the same four date-time fields as `upsert`,\n * `pushManifest`, `balance.push` and `managers.assign` combined — trip,\n * travellers, balance and managers rows all riding in one bundle — which is\n * exactly why hand-writing ISO strings there is the most painful and most\n * error-prone spot on the whole ingest surface. Pulled out to its own\n * function rather than inlined in `bulk.push` because there are four\n * separately-optional nested collections to walk.\n */\nfunction normalizeBulkTripsItem(\n item: PushBulkTripsItemInput,\n tripIndex: number,\n): PushBulkTripsItem {\n const { startDate, endDate, sourceUpdatedAt, travellers, balance, managers, ...rest } = item;\n return {\n ...rest,\n startDate: normalizeDateTimeInput(startDate, `trips[${tripIndex}].startDate`),\n endDate: normalizeDateTimeInput(endDate, `trips[${tripIndex}].endDate`),\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, `trips[${tripIndex}].sourceUpdatedAt`),\n ...(travellers !== undefined\n ? {\n travellers: travellers.map((traveller, index) => ({\n ...traveller,\n sourceUpdatedAt: normalizeDateTimeInput(\n traveller.sourceUpdatedAt,\n `trips[${tripIndex}].travellers[${index}].sourceUpdatedAt`,\n ),\n })),\n }\n : {}),\n ...(balance !== undefined\n ? {\n balance: balance.map((row, index) => ({\n ...row,\n sourceUpdatedAt: normalizeDateTimeInput(\n row.sourceUpdatedAt,\n `trips[${tripIndex}].balance[${index}].sourceUpdatedAt`,\n ),\n })),\n }\n : {}),\n ...(managers !== undefined\n ? {\n managers: managers.map((manager, index) => ({\n ...manager,\n sourceUpdatedAt: normalizeDateTimeInput(\n manager.sourceUpdatedAt,\n `trips[${tripIndex}].managers[${index}].sourceUpdatedAt`,\n ),\n })),\n }\n : {}),\n };\n}\n\nexport function createTripsResource(client: KaafilHttpClient): TripsResource {\n return {\n async upsert(options) {\n const { idempotencyKey, signal, startDate, endDate, sourceUpdatedAt, segments, ...rest } =\n options;\n const body: UpsertTripRequest = {\n ...rest,\n startDate: normalizeDateTimeInput(startDate, 'startDate'),\n endDate: normalizeDateTimeInput(endDate, 'endDate'),\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n ...(segments !== undefined\n ? {\n segments: segments.map((segment, index) => ({\n ...segment,\n startDate: normalizeDateTimeInput(\n segment.startDate,\n `segments[${index}].startDate`,\n ),\n endDate: normalizeDateTimeInput(segment.endDate, `segments[${index}].endDate`),\n })),\n }\n : {}),\n };\n return client.execute<TripUpsertResponse>({\n method: 'POST',\n operationId: OperationId.UpsertTrip,\n path: '/api/v1/trips',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async get(options) {\n const { tripRef, signal } = options;\n return client.execute<TripEchoResponse>({\n method: 'GET',\n operationId: OperationId.GetTrip,\n path: '/api/v1/trips/{ref}',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async cancel(options) {\n const { tripRef, idempotencyKey, signal } = options;\n return client.execute<TripCancelResponse>({\n method: 'DELETE',\n operationId: OperationId.CancelTrip,\n path: '/api/v1/trips/{ref}',\n pathParams: { ref: tripRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n\n travellers: {\n async upsert(options) {\n const { travellerRef, idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n const body: UpsertTravellerProfileRequest = {\n ...rest,\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n };\n return client.execute<TravellerUpsertResponse>({\n method: 'POST',\n operationId: OperationId.UpsertTravellerProfile,\n path: '/api/v1/travellers/{ref}',\n pathParams: { ref: travellerRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async pushManifest(options) {\n const { tripRef, idempotencyKey, signal, travellers, ...rest } = options;\n const body: PushManifestRequest = {\n ...rest,\n // `sourceUpdatedAt` is optional on this entry shape. Omitted, the\n // key is left OFF the body entirely rather than sent as `undefined`\n // — the server stamps the write itself, and an explicit `undefined`\n // would serialise as a missing key anyway but read, in this file, as\n // though a value had been intended.\n travellers: travellers.map((traveller, index) => {\n const { sourceUpdatedAt, ...entry } = traveller;\n return sourceUpdatedAt === undefined\n ? entry\n : {\n ...entry,\n sourceUpdatedAt: normalizeDateTimeInput(\n sourceUpdatedAt,\n `travellers[${index}].sourceUpdatedAt`,\n ),\n };\n }),\n };\n return client.execute<ManifestPushResponse>({\n method: 'POST',\n operationId: OperationId.PushManifest,\n path: '/api/v1/trips/{ref}/travellers',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, travellerRef, idempotencyKey, signal } = options;\n return client.execute<ManifestRemoveResponse>({\n method: 'DELETE',\n operationId: OperationId.RemoveFromManifest,\n path: '/api/v1/trips/{ref}/travellers/{travellerRef}',\n pathParams: { ref: tripRef, travellerRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n managers: {\n async upsert(options) {\n const { idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n const body: UpsertManagerRequest = {\n ...rest,\n sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt'),\n };\n return client.execute<ManagerResponse>({\n method: 'POST',\n operationId: OperationId.UpsertManager,\n path: '/api/v1/managers',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async assign(options) {\n const { tripRef, idempotencyKey, signal, sourceUpdatedAt, ...rest } = options;\n // Omitted entirely rather than sent as `null`/`undefined`: the\n // server's own default only applies to an ABSENT key, and a desk\n // caller has no stamp to send. A CRM still passes one.\n const body: AssignManagerRequest = {\n ...rest,\n ...(sourceUpdatedAt === undefined\n ? {}\n : { sourceUpdatedAt: normalizeDateTimeInput(sourceUpdatedAt, 'sourceUpdatedAt') }),\n };\n return client.execute<TripManagerResponse>({\n method: 'POST',\n operationId: OperationId.AssignManager,\n path: '/api/v1/trips/{ref}/managers',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async unassign(options) {\n const { tripRef, managerRef, idempotencyKey, signal } = options;\n return client.execute<TripManagerResponse>({\n method: 'DELETE',\n operationId: OperationId.UnassignManager,\n path: '/api/v1/trips/{ref}/managers/{managerRef}',\n pathParams: { ref: tripRef, managerRef },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async list(options) {\n const { tripRef, signal } = options;\n return client.execute<readonly TripManagerRowResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTripManagers,\n path: '/api/v1/trips/{ref}/managers',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, managerRef, version, signal, ...body } = options;\n return client.execute<TripManagerRowResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchTripManager,\n path: '/api/v1/trips/{ref}/managers/{managerRef}',\n pathParams: { ref: tripRef, managerRef },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n parties: {\n async list(options) {\n const { tripRef, since, signal } = options;\n return client.execute<readonly PartyDeltaRow[]>({\n method: 'GET',\n operationId: OperationId.ListParties,\n path: '/api/v1/trips/{ref}/parties',\n pathParams: { ref: tripRef },\n query: { since },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async add(options) {\n const { tripRef, idempotencyKey, signal, ...body } = options;\n return client.execute<PartyResponse>({\n method: 'POST',\n operationId: OperationId.CreateParty,\n path: '/api/v1/trips/{ref}/parties',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async patch(options) {\n const { tripRef, partyId, version, signal, ...body } = options;\n return client.execute<PartyResponse>({\n method: 'PATCH',\n operationId: OperationId.PatchParty,\n path: '/api/v1/trips/{ref}/parties/{partyId}',\n pathParams: { ref: tripRef, partyId },\n body,\n headers: { 'If-Match': String(version) },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { tripRef, partyId, idempotencyKey, signal } = options;\n return client.execute<PartyDeleteResponse>({\n method: 'DELETE',\n operationId: OperationId.DeleteParty,\n path: '/api/v1/trips/{ref}/parties/{partyId}',\n pathParams: { ref: tripRef, partyId },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n balance: {\n async push(options) {\n const { tripRef, balances, idempotencyKey, signal } = options;\n const body: readonly PushTripBalancesRow[] = balances.map((row, index) => ({\n ...row,\n sourceUpdatedAt: normalizeDateTimeInput(\n row.sourceUpdatedAt,\n `balances[${index}].sourceUpdatedAt`,\n ),\n }));\n return client.execute<BalancePushResponse>({\n method: 'POST',\n operationId: OperationId.PushTripBalances,\n path: '/api/v1/trips/{ref}/balance',\n pathParams: { ref: tripRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n\n bulk: {\n async push(options) {\n const { trips, idempotencyKey, signal } = options;\n const body: readonly PushBulkTripsItem[] = trips.map((item, index) =>\n normalizeBulkTripsItem(item, index),\n );\n return client.execute<BulkTripsPushResponse>({\n method: 'POST',\n operationId: OperationId.PushBulkTrips,\n path: '/api/v1/bulk/trips',\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n };\n}\n","/**\n * `vendors` — the trip vendor list, plus the agency's own vendor directory\n * CRUD (GAP-005). `architecture/08-sdk.md §4` (\"`managers` / `vendors` …\n * `list` (vendors optional)\").\n *\n * `list` (`listTripVendors`) accepts `apiKeyAuth`, `managerAuth`, OR\n * `agencyAdminAuth` in the spec (`../generated/security.ts`'s\n * `OPERATION_SECURITY`) — an API key, a manager session, or an agency-admin\n * session all read the same agency vendor directory. Not cursor-paginated:\n * `listTripVendors` declares no `cursor`/`limit` query parameters, so this\n * returns the full list directly rather than a `KaafilPaginator`.\n *\n * `upsert`/`remove` (`upsertVendor`/`deleteVendor`,\n * `PUT`/`DELETE /api/v1/agencies/{ref}/vendors/{externalVendorId}`) accept\n * `apiKeyAuth` OR `agencyAdminAuth` — NEVER `managerAuth`: the vendor\n * directory is an agency-wide CRM-fed record, not something worked from a\n * trip on the ground, the same posture `./travellers.ts`'s `create` takes.\n * `Vendor.externalId` is REQUIRED and, on those two calls, never\n * Kaafil-minted — so `externalVendorId` is a path parameter on both, not an\n * optional body field. `create` (`createVendor`, `POST /api/v1/agencies/\n * {ref}/vendors`) is the one form that DOES let Kaafil mint one, prefixed\n * `kf-`, for a vendor an agency admin adds by hand and therefore has no CRM\n * id for; the minted value is an ordinary `externalId` afterwards, so\n * `upsert`/`remove` address such a vendor exactly like a CRM-fed one using\n * the `externalId` the trip vendor list now returns.\n * `upsert` is LWW on `sourceUpdatedAt`, the same \"stamp not newer than\n * stored → `200 ignored_stale`\" contract every other CRM-ingest upsert in\n * this SDK uses — though that field is now OPTIONAL: omit it and the server\n * stamps its own clock, which is what an admin editing by hand needs, since\n * they have no CRM stamp and a stale one would silently drop the edit; `created: true` only on the vendor's first sighting.\n * `remove` requires `If-Match` and soft-deletes (`deletedAt`); it REFUSES\n * with `422 BUSINESS_RULE_VIOLATION` (`details.rule:\n * \"vendor.deleteBlockedByReferences\"`) rather than nulling either reference\n * when a live `Vehicle.vendorId` or `Expense.vendorId` still points at the\n * vendor. Its success body is a literal `data: false` — not a deleted-row\n * echo — so this file types it as `KaafilResponse<false>`, the same\n * convention `./forms.ts`'s header documents for its own delete calls.\n * Because neither `upsert` nor `remove` accepts `managerAuth`, both are\n * agencyRef-BOUND on `../client-entry.ts` — see that file's \"agencyRef-bound\n * option types\" section.\n */\n\nimport type { components } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport type { KaafilResponse } from '../types/meta';\n\ntype VendorSummaryResponse = components['schemas']['VendorSummaryResponse'];\ntype UpsertVendorRequest = components['schemas']['UpsertVendorRequest'];\ntype CreateVendorRequest = components['schemas']['CreateVendorRequest'];\ntype VendorUpsertResponse = components['schemas']['VendorUpsertResponse'];\n\nexport interface ListTripVendorsOptions {\n readonly tripRef: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface UpsertVendorOptions extends UpsertVendorRequest {\n readonly agencyRef: string;\n readonly externalVendorId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\n/**\n * `POST /api/v1/agencies/{ref}/vendors` — no `externalVendorId` and no\n * `sourceUpdatedAt`, deliberately: the server mints the first (prefixed\n * `kf-`) and stamps the second. This is the create path for a vendor the\n * AGENCY authored rather than one a CRM pushed; see this file's header.\n */\nexport interface CreateVendorOptions extends CreateVendorRequest {\n readonly agencyRef: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface DeleteVendorOptions {\n readonly agencyRef: string;\n readonly externalVendorId: string;\n /** Required — see this file's header, \"the agency's own vendor directory\"\n * section. */\n readonly version: number;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface VendorsResource {\n /** `GET /api/v1/trips/{ref}/vendors`. */\n list(options: ListTripVendorsOptions): Promise<KaafilResponse<readonly VendorSummaryResponse[]>>;\n /** `POST /api/v1/agencies/{ref}/vendors` — Kaafil mints the external id. */\n create(options: CreateVendorOptions): Promise<KaafilResponse<VendorUpsertResponse>>;\n /** `PUT /api/v1/agencies/{ref}/vendors/{externalVendorId}` (GAP-005). */\n upsert(options: UpsertVendorOptions): Promise<KaafilResponse<VendorUpsertResponse>>;\n /** `DELETE /api/v1/agencies/{ref}/vendors/{externalVendorId}` (GAP-005).\n * Success body is a literal `data: false` — see this file's header. */\n remove(options: DeleteVendorOptions): Promise<KaafilResponse<false>>;\n}\n\nexport function createVendorsResource(client: KaafilHttpClient): VendorsResource {\n return {\n async list(options) {\n const { tripRef, signal } = options;\n return client.execute<readonly VendorSummaryResponse[]>({\n method: 'GET',\n operationId: OperationId.ListTripVendors,\n path: '/api/v1/trips/{ref}/vendors',\n pathParams: { ref: tripRef },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async create(options) {\n const { agencyRef, idempotencyKey, signal, ...body } = options;\n return client.execute<VendorUpsertResponse>({\n method: 'POST',\n operationId: OperationId.CreateVendor,\n path: '/api/v1/agencies/{ref}/vendors',\n pathParams: { ref: agencyRef },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async upsert(options) {\n const { agencyRef, externalVendorId, idempotencyKey, signal, ...body } = options;\n return client.execute<VendorUpsertResponse>({\n method: 'PUT',\n operationId: OperationId.UpsertVendor,\n path: '/api/v1/agencies/{ref}/vendors/{externalVendorId}',\n pathParams: { ref: agencyRef, externalVendorId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async remove(options) {\n const { agencyRef, externalVendorId, version, idempotencyKey, signal } = options;\n return client.execute<false>({\n method: 'DELETE',\n operationId: OperationId.DeleteVendor,\n path: '/api/v1/agencies/{ref}/vendors/{externalVendorId}',\n pathParams: { ref: agencyRef, externalVendorId },\n headers: { 'If-Match': String(version) },\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `webhooks` — the API-key-reachable operations only: list deliveries, read\n * a delivery, redeliver, replay, and send one test event.\n * `architecture/08-sdk.md §4`, amended `C-028`: \"the delivery-facing\n * operations … and `replayEndpoint` are API-key\" —\n * `configure`/`rotateSecret` (console-session, endpoint CRUD) are a\n * different auth model entirely and are out of this lane's scope by the\n * brief's own instruction.\n *\n * `testEvent` joined the group when the engine published an API-key entry\n * point onto the operation that used to be console-only. There are now TWO\n * routes onto the same controller and this SDK can only ever call one of\n * them: `POST /api/v1/webhooks/endpoints/{id}/test`\n * (`testWebhookEndpointApiKey`, `['apiKeyAuth']`) is the one below, and\n * `POST /api/v1/webhooks/endpoints/{id}/test-event` (`testWebhookEndpoint`)\n * is `['consoleAuth']` alone — unreachable by any credential a\n * `CredentialResolver` holds (`../auth/credentials.ts`), so it is\n * deliberately absent here. Do not repoint `testEvent` at `/test-event`\n * \"because it looks the same\": it would fail with\n * `UnsatisfiableSchemeError` before a request was built.\n *\n * `listWebhookDeliveries` is cursor-paginated (`cursor`+`limit` query params,\n * `meta.page.hasNext`); `deliveries.list()` returns a `KaafilPaginator` and\n * `deliveries.listPage()` is the manual single-page escape hatch for a\n * caller who wants to drive paging itself (`../pagination/paginator.ts`).\n */\n\nimport type { components, operations } from '../generated/schema';\nimport { OperationId } from '../generated/security';\nimport type { KaafilHttpClient } from '../http/client';\nimport { createPaginator, type KaafilPaginator } from '../pagination/paginator';\nimport type { KaafilPagedResponse, KaafilResponse } from '../types/meta';\nimport { narrowPaged, toPaginatorPage } from './internal';\n\ntype DeliveryResponse = components['schemas']['DeliveryResponse'];\ntype DeliveryDetailResponse = components['schemas']['DeliveryDetailResponse'];\ntype RedeliverResponse = components['schemas']['RedeliverResponse'];\ntype ReplayResponse = components['schemas']['ReplayResponse'];\ntype ReplayWebhookEndpointRequest = components['schemas']['ReplayWebhookEndpointRequest'];\ntype TestEventResponse = components['schemas']['TestEventResponse'];\ntype TestWebhookEndpointApiKeyRequest = components['schemas']['TestWebhookEndpointApiKeyRequest'];\n\ntype ListWebhookDeliveriesQuery = NonNullable<\n operations['listWebhookDeliveries']['parameters']['query']\n>;\n/** The filterable half of `listWebhookDeliveries`'s query params — `cursor`\n * and `limit` are the paginator's job, never the caller's to hold. */\nexport type WebhookDeliveryFilters = Omit<ListWebhookDeliveriesQuery, 'cursor' | 'limit'>;\n\nasync function fetchDeliveriesPage(\n client: KaafilHttpClient,\n request: {\n readonly cursor: string | undefined;\n readonly limit: number | undefined;\n readonly filters: WebhookDeliveryFilters;\n },\n) {\n const response = await client.execute<readonly DeliveryResponse[]>({\n method: 'GET',\n operationId: OperationId.ListWebhookDeliveries,\n path: '/api/v1/webhooks/deliveries',\n query: { ...request.filters, cursor: request.cursor, limit: request.limit },\n });\n return toPaginatorPage(response);\n}\n\nexport interface ListWebhookDeliveriesOptions {\n readonly filters?: WebhookDeliveryFilters;\n /** Page size sent as the `limit` query param on every page this paginator fetches. */\n readonly limit?: number;\n}\n\nexport interface ListWebhookDeliveriesPageOptions extends WebhookDeliveryFilters {\n readonly cursor?: string;\n readonly limit?: number;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReadWebhookDeliveryOptions {\n readonly id: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface RedeliverWebhookDeliveryOptions {\n readonly id: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface ReplayWebhookEndpointOptions extends ReplayWebhookEndpointRequest {\n /** The endpoint to replay against — `replayWebhookEndpoint`'s path\n * parameter is the webhook endpoint id, not a delivery id. */\n readonly endpointId: string;\n readonly idempotencyKey?: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface TestWebhookEndpointOptions extends TestWebhookEndpointApiKeyRequest {\n /** The endpoint to send the test event to — `testWebhookEndpointApiKey`'s\n * path parameter is the webhook endpoint id, same as `replay`'s. */\n readonly endpointId: string;\n readonly signal?: AbortSignal;\n}\n\nexport interface WebhookDeliveriesResource {\n /** `GET /api/v1/webhooks/deliveries` as a `KaafilPaginator` — the SDK holds\n * the cursor; the consumer never sees or stores one. */\n list(\n options?: ListWebhookDeliveriesOptions,\n ): KaafilPaginator<DeliveryResponse, WebhookDeliveryFilters>;\n /** The manual single-page escape hatch: fetches exactly one page and\n * returns it directly, for a caller who wants to drive paging itself\n * rather than use the paginator `list()` returns. */\n listPage(\n options?: ListWebhookDeliveriesPageOptions,\n ): Promise<KaafilPagedResponse<readonly DeliveryResponse[]>>;\n read(options: ReadWebhookDeliveryOptions): Promise<KaafilResponse<DeliveryDetailResponse>>;\n redeliver(options: RedeliverWebhookDeliveryOptions): Promise<KaafilResponse<RedeliverResponse>>;\n}\n\nexport interface WebhooksResource {\n readonly deliveries: WebhookDeliveriesResource;\n /** `POST /api/v1/webhooks/endpoints/{id}/replay` — re-delivers every event\n * since `from` to one endpoint. */\n replay(options: ReplayWebhookEndpointOptions): Promise<KaafilResponse<ReplayResponse>>;\n /** `POST /api/v1/webhooks/endpoints/{id}/test` — sends ONE fabricated,\n * signed sample event of `eventType` (one concrete type, never the `\"*\"`\n * wildcard) to that endpoint, through the real delivery worker.\n *\n * Called directly rather than queued, so the response is the ONE attempt's\n * real result — `statusCode` (`null` on a timeout, network error or\n * blocked destination), `latencyMs`, the `signatureHeaderSample` headers\n * signed with the CURRENT secret (verify against those to prove your\n * receiver end-to-end), and `deliveryId` — not a fire-and-forget `202`.\n *\n * Never touches tenant state. The minted id is always `evt_test_`-prefixed\n * — never a real event id — and the payload carries fabricated `TEST-*`\n * `externalRefs` rather than any of your rows, so nothing here can be\n * mistaken for, or corrupt, production data. The attempt is also excluded\n * from every delivery health metric (`health`/`stats` on the endpoint\n * reads), so probing your own endpoint cannot tank its own success rate.\n *\n * Works on BOTH planes: it targets the named endpoint directly instead of\n * going through the plane-matched fan-out, so a LIVE-keyed client testing\n * a LIVE endpoint is the normal case — this is not a TEST-plane sandbox\n * tool and nothing gates it on `environment` (contrast `./test.ts`, whose\n * `TestEnvironmentRequiredError` covers only the six `/api/v1/test/*`\n * operations).\n *\n * Not idempotent-capable — every call sends a fresh event by design, so\n * there is no `idempotencyKey` to pass\n * (`OPERATION_ACCEPTS_IDEMPOTENCY_KEY.testWebhookEndpointApiKey` is\n * `false`). */\n testEvent(options: TestWebhookEndpointOptions): Promise<KaafilResponse<TestEventResponse>>;\n}\n\nexport function createWebhooksResource(client: KaafilHttpClient): WebhooksResource {\n return {\n deliveries: {\n list(options = {}) {\n return createPaginator({\n fetchPage: (request) => fetchDeliveriesPage(client, request),\n filters: options.filters ?? {},\n ...(options.limit !== undefined ? { limit: options.limit } : {}),\n });\n },\n async listPage(options = {}) {\n const { cursor, limit, signal, ...filters } = options;\n const response = await client.execute<readonly DeliveryResponse[]>({\n method: 'GET',\n operationId: OperationId.ListWebhookDeliveries,\n path: '/api/v1/webhooks/deliveries',\n query: { ...filters, cursor, limit },\n ...(signal !== undefined ? { signal } : {}),\n });\n return narrowPaged(response);\n },\n async read(options) {\n const { id, signal } = options;\n return client.execute<DeliveryDetailResponse>({\n method: 'GET',\n operationId: OperationId.ReadWebhookDelivery,\n path: '/api/v1/webhooks/deliveries/{id}',\n pathParams: { id },\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async redeliver(options) {\n const { id, idempotencyKey, signal } = options;\n return client.execute<RedeliverResponse>({\n method: 'POST',\n operationId: OperationId.RedeliverWebhookDelivery,\n path: '/api/v1/webhooks/deliveries/{id}/redeliver',\n pathParams: { id },\n body: {},\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n },\n async replay(options) {\n const { endpointId, idempotencyKey, signal, ...body } = options;\n return client.execute<ReplayResponse>({\n method: 'POST',\n operationId: OperationId.ReplayWebhookEndpoint,\n path: '/api/v1/webhooks/endpoints/{id}/replay',\n pathParams: { id: endpointId },\n body,\n ...(idempotencyKey !== undefined ? { idempotencyKey } : {}),\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n async testEvent(options) {\n const { endpointId, signal, ...body } = options;\n return client.execute<TestEventResponse>({\n method: 'POST',\n operationId: OperationId.TestWebhookEndpointApiKey,\n path: '/api/v1/webhooks/endpoints/{id}/test',\n pathParams: { id: endpointId },\n body,\n ...(signal !== undefined ? { signal } : {}),\n });\n },\n };\n}\n","/**\n * `Kaafil` — the server client, exported from `src/index.ts`\n * (`kaafil-js`). Constructed with the partner API key; carries every\n * resource group an API key can reach. `architecture/08-sdk.md §2, §3.1`.\n *\n * This module is the ONLY place an API-key credential is ever assembled and\n * checked — `guardApiKeyEnvironment`/`assertApiKeyMatchesEnvironment`\n * (`./config.ts`) and the `{ kind: 'apiKey', apiKey }` config object below.\n * `./client-entry.ts` (the browser entry) does not import this file, does\n * not import those two guards, and builds no credential of this shape —\n * see that file's header comment for the structural argument, not just a\n * convention, for why a bundler following only the browser entry's import\n * graph has no path to this one.\n */\n\nimport type { Resolvable } from './auth/credentials';\nimport { CredentialResolver } from './auth/credentials';\nimport {\n assertValidMaxAttempts,\n assertValidTimeout,\n type Environment,\n guardApiKeyEnvironment,\n resolveBaseUrl,\n} from './config';\nimport type { KaafilHttpClient } from './http/client';\nimport { createHttpClient } from './http/client';\nimport { newIdempotencyKey } from './idempotency';\nimport type { AgenciesResource } from './resources/agencies';\nimport { createAgenciesResource } from './resources/agencies';\nimport type { AgencyAdminsResource } from './resources/agency-admins';\nimport { createAgencyAdminsResource } from './resources/agency-admins';\nimport type { AuthResource } from './resources/auth';\nimport { createAuthResource } from './resources/auth';\nimport type { BookingsResource } from './resources/bookings';\nimport { createBookingsResource } from './resources/bookings';\nimport type { ChecklistsResource } from './resources/checklists';\nimport { createChecklistsResource } from './resources/checklists';\nimport type { CloseoutResource } from './resources/closeout';\nimport { createCloseoutResource } from './resources/closeout';\nimport type { CollectionsResource } from './resources/collections';\nimport { createCollectionsResource } from './resources/collections';\nimport type { CommsResource } from './resources/comms';\nimport { createCommsResource } from './resources/comms';\nimport type { EventsResource } from './resources/events';\nimport { createEventsResource } from './resources/events';\nimport type { ExpensesResource } from './resources/expenses';\nimport { createExpensesResource } from './resources/expenses';\nimport type { FeedbackNpsResource } from './resources/feedback-nps';\nimport { createFeedbackNpsResource } from './resources/feedback-nps';\nimport type { FilesResource } from './resources/files';\nimport { createFilesResource } from './resources/files';\nimport type { FloatResource } from './resources/float';\nimport { createFloatResource } from './resources/float';\nimport type { FormsResource } from './resources/forms';\nimport { createFormsResource } from './resources/forms';\nimport type { ItineraryResource } from './resources/itinerary';\nimport { createItineraryResource } from './resources/itinerary';\nimport type { JourneyResource } from './resources/journey';\nimport { createJourneyResource } from './resources/journey';\nimport type { ManagerTodayResource } from './resources/manager-today';\nimport { createManagerTodayResource } from './resources/manager-today';\nimport type { PickupsResource } from './resources/pickups';\nimport { createPickupsResource } from './resources/pickups';\nimport type { RoomingResource } from './resources/rooming';\nimport { createRoomingResource } from './resources/rooming';\nimport type { SeatingResource } from './resources/seating';\nimport { createSeatingResource } from './resources/seating';\nimport type { ShareTokensResource } from './resources/share-tokens';\nimport { createShareTokensResource } from './resources/share-tokens';\nimport type { SyncResource } from './resources/sync';\nimport { createSyncResource } from './resources/sync';\nimport type { TestResource } from './resources/test';\nimport { createTestResource } from './resources/test';\nimport type { TravellersResource } from './resources/travellers';\nimport { createTravellersResource } from './resources/travellers';\nimport type { TreksResource } from './resources/treks';\nimport { createTreksResource } from './resources/treks';\nimport type { TripsResource } from './resources/trips';\nimport { createTripsResource } from './resources/trips';\nimport type { VendorsResource } from './resources/vendors';\nimport { createVendorsResource } from './resources/vendors';\nimport type { WebhooksResource } from './resources/webhooks';\nimport { createWebhooksResource } from './resources/webhooks';\n\nexport interface KaafilOptions {\n /** `kf_live_…` / `kf_test_…`, checked against `environment` at\n * construction for a literal key, or on every resolution for a resolver\n * (`./config.ts`'s `guardApiKeyEnvironment`). */\n readonly apiKey: Resolvable<string>;\n readonly environment: Environment;\n /** Overrides the environment's default base URL outright — see\n * `./config.ts`'s `resolveBaseUrl` for why the two are never merged. */\n readonly baseUrl?: string;\n readonly timeoutMs?: number;\n readonly maxAttempts?: number;\n readonly userAgent?: string;\n readonly random?: () => number;\n}\n\n/**\n * Thrown by any resource method called after `close()`. Every resource\n * getter reads through `#requireState()`, so a stale reference to\n * `kaafil.trips` obtained before `close()` still throws this on its next\n * call — there is no way to keep using a closed client's credential.\n */\nexport class KaafilClosedError extends Error {\n constructor() {\n super('This Kaafil client has been closed; construct a new one to keep making requests.');\n this.name = 'KaafilClosedError';\n Object.setPrototypeOf(this, KaafilClosedError.prototype);\n }\n}\n\n/**\n * Every piece of this client's live state, in one object. `close()` is the\n * single `this.#state = null` below — structurally impossible to forget a\n * field, because there is no second field anywhere else to forget.\n */\ninterface KaafilState {\n readonly http: KaafilHttpClient;\n readonly auth: AuthResource;\n readonly agencies: AgenciesResource;\n readonly agencyAdmins: AgencyAdminsResource;\n readonly shareTokens: ShareTokensResource;\n readonly trips: TripsResource;\n readonly itinerary: ItineraryResource;\n readonly managerToday: ManagerTodayResource;\n readonly rooming: RoomingResource;\n readonly seating: SeatingResource;\n readonly pickups: PickupsResource;\n readonly treks: TreksResource;\n readonly checklists: ChecklistsResource;\n readonly vendors: VendorsResource;\n readonly travellers: TravellersResource;\n readonly journey: JourneyResource;\n readonly webhooks: WebhooksResource;\n readonly events: EventsResource;\n readonly files: FilesResource;\n readonly collections: CollectionsResource;\n readonly expenses: ExpensesResource;\n readonly float: FloatResource;\n readonly forms: FormsResource;\n readonly bookings: BookingsResource;\n readonly feedbackNps: FeedbackNpsResource;\n readonly comms: CommsResource;\n readonly closeout: CloseoutResource;\n /** The batched transport's routes (`./resources/sync.ts`) — `digest()` is\n * the apiKey-scoped route on this shared resource; `push()`/`pullTrip()`\n * are manager-session-scoped and remain wired only on `./client-entry.ts`. */\n readonly sync: SyncResource;\n /** The sandbox toolkit (`./resources/test.ts`) — refuses locally, before\n * any request exists, for a client constructed with `environment: 'live'`.\n * See that module's header for why `environment` is threaded into its\n * factory alone among every other resource here. */\n readonly test: TestResource;\n}\n\nexport class Kaafil {\n #state: KaafilState | null;\n\n constructor(options: KaafilOptions) {\n assertValidTimeout(options.timeoutMs);\n assertValidMaxAttempts(options.maxAttempts);\n const baseUrl = resolveBaseUrl(options.environment, options.baseUrl);\n const apiKey = guardApiKeyEnvironment(options.apiKey, options.environment);\n\n const credentials = new CredentialResolver({ kind: 'apiKey', apiKey });\n const http = createHttpClient({\n baseUrl,\n credentials,\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n ...(options.maxAttempts !== undefined ? { maxAttempts: options.maxAttempts } : {}),\n ...(options.userAgent !== undefined ? { userAgent: options.userAgent } : {}),\n ...(options.random !== undefined ? { random: options.random } : {}),\n });\n\n this.#state = {\n http,\n auth: createAuthResource(http),\n agencies: createAgenciesResource(http),\n agencyAdmins: createAgencyAdminsResource(http),\n shareTokens: createShareTokensResource(http),\n trips: createTripsResource(http),\n itinerary: createItineraryResource(http),\n managerToday: createManagerTodayResource(http),\n rooming: createRoomingResource(http),\n seating: createSeatingResource(http),\n pickups: createPickupsResource(http),\n treks: createTreksResource(http),\n checklists: createChecklistsResource(http),\n vendors: createVendorsResource(http),\n travellers: createTravellersResource(http),\n journey: createJourneyResource(http),\n webhooks: createWebhooksResource(http),\n events: createEventsResource(http),\n files: createFilesResource(http),\n collections: createCollectionsResource(http),\n expenses: createExpensesResource(http),\n float: createFloatResource(http),\n forms: createFormsResource(http),\n bookings: createBookingsResource(http),\n feedbackNps: createFeedbackNpsResource(http),\n comms: createCommsResource(http),\n closeout: createCloseoutResource(http),\n sync: createSyncResource(http),\n test: createTestResource(http, options.environment),\n };\n }\n\n get auth(): AuthResource {\n return this.#requireState().auth;\n }\n\n get agencies(): AgenciesResource {\n return this.#requireState().agencies;\n }\n\n get agencyAdmins(): AgencyAdminsResource {\n return this.#requireState().agencyAdmins;\n }\n\n get shareTokens(): ShareTokensResource {\n return this.#requireState().shareTokens;\n }\n\n get trips(): TripsResource {\n return this.#requireState().trips;\n }\n\n get itinerary(): ItineraryResource {\n return this.#requireState().itinerary;\n }\n\n get managerToday(): ManagerTodayResource {\n return this.#requireState().managerToday;\n }\n\n get rooming(): RoomingResource {\n return this.#requireState().rooming;\n }\n\n get seating(): SeatingResource {\n return this.#requireState().seating;\n }\n\n get pickups(): PickupsResource {\n return this.#requireState().pickups;\n }\n\n get treks(): TreksResource {\n return this.#requireState().treks;\n }\n\n get checklists(): ChecklistsResource {\n return this.#requireState().checklists;\n }\n\n get vendors(): VendorsResource {\n return this.#requireState().vendors;\n }\n\n get travellers(): TravellersResource {\n return this.#requireState().travellers;\n }\n\n get journey(): JourneyResource {\n return this.#requireState().journey;\n }\n\n get webhooks(): WebhooksResource {\n return this.#requireState().webhooks;\n }\n\n get events(): EventsResource {\n return this.#requireState().events;\n }\n\n get files(): FilesResource {\n return this.#requireState().files;\n }\n\n get collections(): CollectionsResource {\n return this.#requireState().collections;\n }\n\n get expenses(): ExpensesResource {\n return this.#requireState().expenses;\n }\n\n get float(): FloatResource {\n return this.#requireState().float;\n }\n\n get forms(): FormsResource {\n return this.#requireState().forms;\n }\n\n get bookings(): BookingsResource {\n return this.#requireState().bookings;\n }\n\n get feedbackNps(): FeedbackNpsResource {\n return this.#requireState().feedbackNps;\n }\n\n get comms(): CommsResource {\n return this.#requireState().comms;\n }\n\n get closeout(): CloseoutResource {\n return this.#requireState().closeout;\n }\n\n get sync(): SyncResource {\n return this.#requireState().sync;\n }\n\n get test(): TestResource {\n return this.#requireState().test;\n }\n\n /**\n * Total teardown. One assignment, no field to forget — see `KaafilState`\n * above. Every subsequent call through any resource getter throws\n * `KaafilClosedError` instead of quietly continuing to work off a\n * credential this client no longer considers live.\n */\n close(): void {\n this.#state = null;\n }\n\n /**\n * Mints an idempotency key outside the normal per-call flow. Every\n * mutating method already mints and reuses one automatically\n * (`http/client.ts`) — this exists for the rare case of pinning a key\n * ahead of time, to replay the exact same logical operation across a\n * process restart.\n */\n static newIdempotencyKey(): string {\n return newIdempotencyKey();\n }\n\n #requireState(): KaafilState {\n if (this.#state === null) {\n throw new KaafilClosedError();\n }\n return this.#state;\n }\n}\n","/**\n * The `?since=` delta cursor. `architecture/06-offline-first.md §1, §5`.\n *\n * ── WHY THE CURSOR IS THE SERVER'S OWN CLOCK, AND NOTHING ELSE ──────────────\n *\n * Every delta read on this API answers with `meta.serverTime`. That value —\n * the timestamp of the response you are holding, taken by the machine that ran\n * the query — is the ONLY correct cursor to send back as the next `?since=`.\n * The two tempting alternatives both lose rows, silently, and only under load:\n *\n * - **A local clock** (`new Date()` when the response arrived) is skewed\n * against the server's by an unknown amount and drifts. Skew in the wrong\n * direction advances the cursor past rows the server had not committed yet\n * when it answered, and those rows are then never in any window again.\n * - **A row's own `updatedAt`** (the newest row in the page) is worse: it is a\n * bound on the rows you RECEIVED, not on the interval the server READ. Any\n * row committed between the query's snapshot and the response being stamped\n * sits after your cursor and before the server's, and is lost permanently.\n * An empty page also leaves you with no cursor at all.\n *\n * This module exists so that reasoning happens once, here, instead of at every\n * integrator's call site. `pull()` takes the cursor from the response's own\n * `meta.serverTime` and nothing else, and it advances it only after a\n * successful read — a failed pull leaves the cursor exactly where it was, so\n * the next attempt re-reads the same interval rather than skipping it.\n *\n * ── WHY DUPLICATES ARE EXPECTED, AND WHY THEY ARE FREE ──────────────────────\n *\n * The server window is deliberately AT-LEAST-ONCE: it matches\n * `updatedAt >= since - 5s`, and a cursor in the future clamps to now rather\n * than erroring. So a pull normally re-delivers rows you already have. That is\n * the design, not a defect, and the asymmetry is the reason:\n *\n * - A DUPLICATED row costs nothing. Every row — live or tombstone — carries\n * `id` and `version`, so re-applying one is a no-op rebase onto the state\n * you already hold. `mergeDeltaRows` below does exactly that, by version.\n * - A SKIPPED row is DATA LOSS. It is a hotel booking, a cancelled activity or\n * a deleted bed that the offline client never learns about and never asks\n * for again, because the cursor has already moved past it. Nothing detects\n * it; the client is simply, quietly wrong.\n *\n * A strict `> since` boundary would be exactly that trade in reverse — no\n * duplicates, and permanent loss from three separate mechanisms (the interval\n * between reading rows and stamping the response, clock skew between replicas,\n * and millisecond truncation). The engine chose the overlap; a consumer must\n * not undo it by narrowing the window on the client side.\n *\n * ── WHY A DELTA ROW IS A UNION ──────────────────────────────────────────────\n *\n * A delta read returns `Row | DeltaTombstone` in ONE array, never a second\n * `deleted[]` array, so a consumer cannot forget the drop case: the union does\n * not typecheck until the tombstone branch is handled. Ordering is\n * `(updatedAt asc, id asc)`, so each id appears at most once per page and at\n * its final state — \"deleted before or after updated\" is already answered\n * server-side.\n */\n\nimport { normalizeDateTimeInput } from '../datetime';\nimport type { components } from '../generated/schema';\nimport type { KaafilResponse, ResponseMeta } from '../types/meta';\n\n/**\n * The drop marker on a delta read.\n *\n * Aliased off the generated schema rather than hand-restated. The spec uses\n * one tombstone shape for every delta read (itinerary items, rooming rooms,\n * rooming stay windows) and `ItineraryItemTombstoneResponse` is the single\n * place it appears as a NAMED component — the others inline it inside their\n * own `anyOf`, so there is no more general name to alias. If the engine ever\n * gives the shape its own component, this alias moves; the four fields are\n * still never typed by hand here.\n */\nexport type DeltaTombstone = components['schemas']['ItineraryItemTombstoneResponse'];\n\n/** One row from a delta read: the live row, or the marker saying it is gone. */\nexport type DeltaRow<TRow> = TRow | DeltaTombstone;\n\n/**\n * Narrows a delta row to the drop case.\n *\n * Structural, and provably safe rather than conventional: every response\n * schema in this contract is `additionalProperties: false`, so a live row can\n * never carry a `_tombstone` key and the two branches of the union are\n * disjoint.\n */\nexport function isTombstone<TRow extends object>(row: DeltaRow<TRow>): row is DeltaTombstone {\n return (row as { _tombstone?: unknown })._tombstone === true;\n}\n\n/**\n * What `mergeDeltaRows` requires of a live row, and what makes a duplicate\n * free: an identity and a version. Both delta variants carry them.\n */\nexport interface DeltaIdentity {\n readonly id: string;\n readonly version: number;\n}\n\n/** What one `mergeDeltaRows` call actually changed. */\nexport interface DeltaMergeStats {\n /** Rows written that the store had not seen before. */\n readonly added: number;\n /** Rows written over an older version of a row already held. */\n readonly updated: number;\n /** Rows dropped because a tombstone arrived for them. */\n readonly removed: number;\n /**\n * Rows the store already held at this version or newer. This is the\n * at-least-once overlap doing its job — a non-zero count is normal on every\n * pull after the first and is not worth reporting to a user.\n */\n readonly unchanged: number;\n}\n\n/**\n * Rebases one delta page onto a local store, keyed by `id`.\n *\n * Version-guarded in both directions, which is what makes re-applying a\n * duplicated row a genuine no-op instead of merely a harmless-looking one: a\n * row whose `version` is not NEWER than the held one is left alone, and a\n * tombstone whose `version` is older than the held row is ignored rather than\n * deleting a row that has since been recreated or updated. The store is\n * mutated in place — a caller's `Map` is its own cache, and returning a fresh\n * copy per page would make a long offline catch-up quadratic.\n */\nexport function mergeDeltaRows<TRow extends DeltaIdentity>(\n store: Map<string, TRow>,\n rows: readonly DeltaRow<TRow>[],\n): DeltaMergeStats {\n let added = 0;\n let updated = 0;\n let removed = 0;\n let unchanged = 0;\n\n for (const row of rows) {\n const held = store.get(row.id);\n if (isTombstone(row)) {\n if (held === undefined || held.version > row.version) {\n unchanged += 1;\n continue;\n }\n store.delete(row.id);\n removed += 1;\n continue;\n }\n if (held === undefined) {\n store.set(row.id, row);\n added += 1;\n continue;\n }\n if (held.version >= row.version) {\n unchanged += 1;\n continue;\n }\n store.set(row.id, row);\n updated += 1;\n }\n\n return { added, updated, removed, unchanged };\n}\n\n/**\n * Runs one delta read for a given cursor. A caller supplies this as a thin\n * closure over a resource method — this module knows nothing about operation\n * ids, paths or query-param names, only that a read takes a `since` and\n * answers with an envelope carrying `meta.serverTime`.\n *\n * `since` is `undefined` on a cold start, which is a full read: the server\n * emits no tombstones without a cursor, because a client that has never\n * synced has nothing to drop.\n */\nexport type FetchDelta<T> = (request: {\n readonly since: string | undefined;\n readonly signal: AbortSignal | undefined;\n}) => Promise<KaafilResponse<T>>;\n\n/** One completed pull, with the cursor bookkeeping made visible. */\nexport interface DeltaPull<T> {\n readonly data: T;\n readonly meta: ResponseMeta;\n /** The cursor now stored: THIS response's `meta.serverTime`. */\n readonly cursor: string;\n /** What was sent as `?since=` — `undefined` on the cold start. */\n readonly previousCursor: string | undefined;\n}\n\n/** `pull()` was re-entered while a previous pull on the same cursor was in flight. */\nexport class KaafilDeltaCursorInFlightError extends Error {\n constructor() {\n super(\n 'pull() was called while a previous pull on this delta cursor was still in flight. ' +\n 'Two concurrent pulls would settle in an unknown order and leave the cursor at ' +\n \"whichever response landed last, not the newest — await the first one's result.\",\n );\n this.name = 'KaafilDeltaCursorInFlightError';\n Object.setPrototypeOf(this, KaafilDeltaCursorInFlightError.prototype);\n }\n}\n\nexport interface KaafilDeltaCursor<T> {\n /**\n * The cursor that will be sent as `?since=` on the next `pull()`, or\n * `undefined` before the first successful one. Read this to PERSIST it; a\n * durable consumer stores it beside its rows and hands it back to\n * `restore()` after a restart, so a process death costs one overlapping\n * window rather than a full resync.\n */\n readonly cursor: string | undefined;\n readonly isLoading: boolean;\n /** Whether any pull has succeeded yet — i.e. whether the next one is a cold start. */\n readonly hasSynced: boolean;\n /**\n * Reads everything that changed since the stored cursor, then advances the\n * cursor to this response's own `meta.serverTime`. On failure the cursor is\n * left untouched, so a retry re-reads the same interval instead of stepping\n * over it.\n */\n pull(options?: { readonly signal?: AbortSignal }): Promise<DeltaPull<T>>;\n /**\n * Adopts a cursor persisted from an earlier session. Takes a `string`\n * only — deliberately not a `Date` or an epoch number, the two things that\n * would let a local clock become a cursor, which is the failure this whole\n * module exists to prevent. Must be a value some response's\n * `meta.serverTime` actually carried.\n */\n restore(cursor: string): void;\n /**\n * Discards the cursor, so the next `pull()` is a cold start: a full read,\n * with no tombstones. The honest recovery when a local store is corrupt or\n * of unknown provenance — cheaper to re-read the trip than to reconcile a\n * cache you cannot vouch for.\n */\n reset(): void;\n}\n\nexport interface CreateDeltaCursorConfig<T> {\n readonly fetchDelta: FetchDelta<T>;\n /** A cursor persisted from an earlier session, as `restore()` would take it. */\n readonly cursor?: string;\n}\n\nexport function createDeltaCursor<T>(config: CreateDeltaCursorConfig<T>): KaafilDeltaCursor<T> {\n const { fetchDelta } = config;\n const state: { cursor: string | undefined; isLoading: boolean } = {\n cursor: undefined,\n isLoading: false,\n };\n\n function restore(cursor: string): void {\n // Routed through the same validator every date-time field on the ingest\n // surface uses, so a malformed cursor (an empty string read back from an\n // empty cache row, a date-only string) fails locally and by name instead\n // of becoming a `?since=` the server has to reject — or worse, clamp.\n state.cursor = normalizeDateTimeInput(cursor, 'cursor');\n }\n\n if (config.cursor !== undefined) {\n restore(config.cursor);\n }\n\n async function pull(options: { readonly signal?: AbortSignal } = {}): Promise<DeltaPull<T>> {\n if (state.isLoading) {\n throw new KaafilDeltaCursorInFlightError();\n }\n const previousCursor = state.cursor;\n state.isLoading = true;\n try {\n const response = await fetchDelta({ since: previousCursor, signal: options.signal });\n // The one assignment that matters in this file. `meta.serverTime`, from\n // this very response — never `Date.now()`, never a row's `updatedAt`.\n state.cursor = response.meta.serverTime;\n return {\n data: response,\n meta: response.meta,\n cursor: response.meta.serverTime,\n previousCursor,\n };\n } finally {\n state.isLoading = false;\n }\n }\n\n return {\n get cursor() {\n return state.cursor;\n },\n get isLoading() {\n return state.isLoading;\n },\n get hasSynced() {\n return state.cursor !== undefined;\n },\n pull,\n restore,\n reset() {\n state.cursor = undefined;\n },\n };\n}\n","/**\n * This file was auto-generated by `scripts/gen-meta.mjs` from\n * `openapi/openapi.json`. Do not make direct changes to the file — re-run\n * `pnpm gen:types` instead.\n *\n * @generated src/generated/enums.ts\n */\n\n// Every distinct request-body enum value set in the vendored spec, as a\n// runtime `as const` object plus its matching type — the same pattern\n// `Environment` uses in `src/config.ts`. `openapi-typescript` already\n// types these fields as string-literal unions; this gives a caller something\n// to import, autocomplete from, and check an incoming string against, so\n// `tripMode: TripMode.Personalized` replaces `tripMode: 'PERSONALIZED'`\n// without changing what a caller may still write literally — a bare string\n// literal keeps working, unchanged, because the field's type is still the\n// union, not this object.\n//\n// Named per value set, not per property path: the same set\n// (`GROUP|PERSONALIZED`) appears under several different fields across\n// several request schemas, and this file exports it once. See\n// `REQUEST_ENUM_NAMES` in `scripts/gen-meta.mjs` for the explicit mapping.\n\nexport const BoardStatus = {\n Boarded: 'BOARDED',\n NoShow: 'NO_SHOW',\n} as const;\nexport type BoardStatus = (typeof BoardStatus)[keyof typeof BoardStatus];\n\nexport const BookingStatus = {\n Confirmed: 'CONFIRMED',\n Tentative: 'TENTATIVE',\n Cancelled: 'CANCELLED',\n} as const;\nexport type BookingStatus = (typeof BookingStatus)[keyof typeof BookingStatus];\n\nexport const ChecklistAudience = {\n Internal: 'INTERNAL',\n External: 'EXTERNAL',\n} as const;\nexport type ChecklistAudience = (typeof ChecklistAudience)[keyof typeof ChecklistAudience];\n\nexport const ChecklistGate = {\n None: 'NONE',\n PreToActive: 'PRE_TO_ACTIVE',\n ActiveToClosedOut: 'ACTIVE_TO_CLOSED_OUT',\n} as const;\nexport type ChecklistGate = (typeof ChecklistGate)[keyof typeof ChecklistGate];\n\nexport const ChecklistItemStatus = {\n Open: 'OPEN',\n Complete: 'COMPLETE',\n} as const;\nexport type ChecklistItemStatus = (typeof ChecklistItemStatus)[keyof typeof ChecklistItemStatus];\n\nexport const ChecklistPhase = {\n PreDeparture: 'PRE_DEPARTURE',\n InTrip: 'IN_TRIP',\n PostTrip: 'POST_TRIP',\n} as const;\nexport type ChecklistPhase = (typeof ChecklistPhase)[keyof typeof ChecklistPhase];\n\nexport const ChecklistPullTemplateMode = {\n Append: 'append',\n Replace: 'replace',\n} as const;\nexport type ChecklistPullTemplateMode = (typeof ChecklistPullTemplateMode)[keyof typeof ChecklistPullTemplateMode];\n\nexport const ClaimStatusIngest = {\n Approved: 'APPROVED',\n Paid: 'PAID',\n Rejected: 'REJECTED',\n} as const;\nexport type ClaimStatusIngest = (typeof ClaimStatusIngest)[keyof typeof ClaimStatusIngest];\n\nexport const CloseoutPackSection = {\n Summary: 'summary',\n Blockers: 'blockers',\n Handover: 'handover',\n Collections: 'collections',\n Expenses: 'expenses',\n Float: 'float',\n Checklists: 'checklists',\n Forms: 'forms',\n Rooming: 'rooming',\n Seating: 'seating',\n Pickups: 'pickups',\n Vendors: 'vendors',\n Itinerary: 'itinerary',\n} as const;\nexport type CloseoutPackSection = (typeof CloseoutPackSection)[keyof typeof CloseoutPackSection];\n\nexport const CollectionMode = {\n Cash: 'CASH',\n Upi: 'UPI',\n Card: 'CARD',\n Bank: 'BANK',\n} as const;\nexport type CollectionMode = (typeof CollectionMode)[keyof typeof CollectionMode];\n\nexport const CommsEmailProvider = {\n Sendgrid: 'SENDGRID',\n Brevo: 'BREVO',\n Resend: 'RESEND',\n} as const;\nexport type CommsEmailProvider = (typeof CommsEmailProvider)[keyof typeof CommsEmailProvider];\n\nexport const CommsMode = {\n KaafilSend: 'KAAFIL_SEND',\n CrmSend: 'CRM_SEND',\n} as const;\nexport type CommsMode = (typeof CommsMode)[keyof typeof CommsMode];\n\nexport const Currency = {\n Inr: 'INR',\n} as const;\nexport type Currency = (typeof Currency)[keyof typeof Currency];\n\nexport const EventType = {\n Trip: 'TRIP',\n Trek: 'TREK',\n} as const;\nexport type EventType = (typeof EventType)[keyof typeof EventType];\n\nexport const ExpenseCategory = {\n Accom: 'ACCOM',\n Food: 'FOOD',\n Transport: 'TRANSPORT',\n Activity: 'ACTIVITY',\n Misc: 'MISC',\n} as const;\nexport type ExpenseCategory = (typeof ExpenseCategory)[keyof typeof ExpenseCategory];\n\nexport const ExpensePaymentMode = {\n FloatCash: 'FLOAT_CASH',\n Personal: 'PERSONAL',\n Other: 'OTHER',\n} as const;\nexport type ExpensePaymentMode = (typeof ExpensePaymentMode)[keyof typeof ExpensePaymentMode];\n\nexport const FileContentType = {\n ImageJpeg: 'image/jpeg',\n ImagePng: 'image/png',\n ImageWebp: 'image/webp',\n ImageHeic: 'image/heic',\n ApplicationPdf: 'application/pdf',\n} as const;\nexport type FileContentType = (typeof FileContentType)[keyof typeof FileContentType];\n\nexport const FilePurpose = {\n ExpenseReceipt: 'expense_receipt',\n FormAttachment: 'form_attachment',\n BookingVoucher: 'booking_voucher',\n TripDocument: 'trip_document',\n} as const;\nexport type FilePurpose = (typeof FilePurpose)[keyof typeof FilePurpose];\n\nexport const FloatDirection = {\n In: 'IN',\n Out: 'OUT',\n} as const;\nexport type FloatDirection = (typeof FloatDirection)[keyof typeof FloatDirection];\n\nexport const FormAnchor = {\n TripStart: 'TRIP_START',\n TripEnd: 'TRIP_END',\n ManifestJoin: 'MANIFEST_JOIN',\n Dispatch: 'DISPATCH',\n ItineraryDay: 'ITINERARY_DAY',\n Absolute: 'ABSOLUTE',\n} as const;\nexport type FormAnchor = (typeof FormAnchor)[keyof typeof FormAnchor];\n\nexport const FormAnonymity = {\n Identified: 'IDENTIFIED',\n Optional: 'OPTIONAL',\n Anonymous: 'ANONYMOUS',\n} as const;\nexport type FormAnonymity = (typeof FormAnonymity)[keyof typeof FormAnonymity];\n\nexport const FormDispatchMode = {\n Journey: 'JOURNEY',\n Manual: 'MANUAL',\n None: 'NONE',\n} as const;\nexport type FormDispatchMode = (typeof FormDispatchMode)[keyof typeof FormDispatchMode];\n\nexport const FormDispatchReason = {\n Journey: 'journey',\n Manual: 'manual',\n} as const;\nexport type FormDispatchReason = (typeof FormDispatchReason)[keyof typeof FormDispatchReason];\n\nexport const FormFieldKind = {\n Heading: 'HEADING',\n InfoBlock: 'INFO_BLOCK',\n ShortText: 'SHORT_TEXT',\n LongText: 'LONG_TEXT',\n Email: 'EMAIL',\n Phone: 'PHONE',\n Url: 'URL',\n Number: 'NUMBER',\n Currency: 'CURRENCY',\n Rating: 'RATING',\n Nps: 'NPS',\n Date: 'DATE',\n Datetime: 'DATETIME',\n Time: 'TIME',\n Select: 'SELECT',\n Multiselect: 'MULTISELECT',\n Checkbox: 'CHECKBOX',\n Consent: 'CONSENT',\n Signature: 'SIGNATURE',\n FileUpload: 'FILE_UPLOAD',\n Address: 'ADDRESS',\n} as const;\nexport type FormFieldKind = (typeof FormFieldKind)[keyof typeof FormFieldKind];\n\nexport const FormFieldSensitivity = {\n Normal: 'NORMAL',\n SelfOnly: 'SELF_ONLY',\n} as const;\nexport type FormFieldSensitivity = (typeof FormFieldSensitivity)[keyof typeof FormFieldSensitivity];\n\nexport const FormPhase = {\n PreDeparture: 'PRE_DEPARTURE',\n OnTrip: 'ON_TRIP',\n PostTrip: 'POST_TRIP',\n} as const;\nexport type FormPhase = (typeof FormPhase)[keyof typeof FormPhase];\n\nexport const FormResponseExportFormat = {\n Csv: 'csv',\n Pdf: 'pdf',\n} as const;\nexport type FormResponseExportFormat = (typeof FormResponseExportFormat)[keyof typeof FormResponseExportFormat];\n\nexport const FormResponsePolicy = {\n Single: 'SINGLE',\n Multiple: 'MULTIPLE',\n} as const;\nexport type FormResponsePolicy = (typeof FormResponsePolicy)[keyof typeof FormResponsePolicy];\n\nexport const FormVisibilityOperator = {\n Answered: 'answered',\n Empty: 'empty',\n Eq: 'eq',\n Ne: 'ne',\n Gt: 'gt',\n Gte: 'gte',\n Lt: 'lt',\n Lte: 'lte',\n In: 'in',\n Nin: 'nin',\n Contains: 'contains',\n} as const;\nexport type FormVisibilityOperator = (typeof FormVisibilityOperator)[keyof typeof FormVisibilityOperator];\n\nexport const Gender = {\n Male: 'MALE',\n Female: 'FEMALE',\n Other: 'OTHER',\n Unknown: 'UNKNOWN',\n} as const;\nexport type Gender = (typeof Gender)[keyof typeof Gender];\n\nexport const ItineraryItemStatusUpdate = {\n Planned: 'PLANNED',\n Completed: 'COMPLETED',\n Skipped: 'SKIPPED',\n} as const;\nexport type ItineraryItemStatusUpdate = (typeof ItineraryItemStatusUpdate)[keyof typeof ItineraryItemStatusUpdate];\n\nexport const ItineraryItemType = {\n Accommodation: 'ACCOMMODATION',\n Transport: 'TRANSPORT',\n Activity: 'ACTIVITY',\n Meal: 'MEAL',\n Other: 'OTHER',\n} as const;\nexport type ItineraryItemType = (typeof ItineraryItemType)[keyof typeof ItineraryItemType];\n\nexport const ManagerRole = {\n Manager: 'MANAGER',\n Coordinator: 'COORDINATOR',\n} as const;\nexport type ManagerRole = (typeof ManagerRole)[keyof typeof ManagerRole];\n\nexport const ManifestMode = {\n Merge: 'merge',\n Replace: 'replace',\n} as const;\nexport type ManifestMode = (typeof ManifestMode)[keyof typeof ManifestMode];\n\nexport const MessageChannel = {\n Email: 'EMAIL',\n Sms: 'SMS',\n Whatsapp: 'WHATSAPP',\n} as const;\nexport type MessageChannel = (typeof MessageChannel)[keyof typeof MessageChannel];\n\nexport const MessageTemplateStatus = {\n Draft: 'DRAFT',\n Active: 'ACTIVE',\n Archived: 'ARCHIVED',\n} as const;\nexport type MessageTemplateStatus = (typeof MessageTemplateStatus)[keyof typeof MessageTemplateStatus];\n\nexport const PartyKind = {\n Family: 'FAMILY',\n Couple: 'COUPLE',\n Friends: 'FRIENDS',\n Corporate: 'CORPORATE',\n Other: 'OTHER',\n} as const;\nexport type PartyKind = (typeof PartyKind)[keyof typeof PartyKind];\n\nexport const PersonKind = {\n Traveller: 'TRAVELLER',\n Manager: 'MANAGER',\n} as const;\nexport type PersonKind = (typeof PersonKind)[keyof typeof PersonKind];\n\nexport const PickupKind = {\n Pickup: 'PICKUP',\n Drop: 'DROP',\n} as const;\nexport type PickupKind = (typeof PickupKind)[keyof typeof PickupKind];\n\nexport const RoomingFillOrder = {\n LargestRoomFirst: 'LARGEST_ROOM_FIRST',\n Sequential: 'SEQUENTIAL',\n Balanced: 'BALANCED',\n} as const;\nexport type RoomingFillOrder = (typeof RoomingFillOrder)[keyof typeof RoomingFillOrder];\n\nexport const RoomingGenderPolicy = {\n StrictSeparate: 'STRICT_SEPARATE',\n GroupMixedOk: 'GROUP_MIXED_OK',\n Off: 'OFF',\n} as const;\nexport type RoomingGenderPolicy = (typeof RoomingGenderPolicy)[keyof typeof RoomingGenderPolicy];\n\nexport const RoomingHeuristicKey = {\n MedicalFirst: 'medicalFirst',\n Couples: 'couples',\n Parties: 'parties',\n Gender: 'gender',\n Diet: 'diet',\n SpreadSolos: 'spreadSolos',\n PartyGenderPolicy: 'partyGenderPolicy',\n SameBus: 'sameBus',\n} as const;\nexport type RoomingHeuristicKey = (typeof RoomingHeuristicKey)[keyof typeof RoomingHeuristicKey];\n\nexport const RoomType = {\n Single: 'SINGLE',\n Twin: 'TWIN',\n Shared: 'SHARED',\n Dorm: 'DORM',\n} as const;\nexport type RoomType = (typeof RoomType)[keyof typeof RoomType];\n\nexport const SeatingFillOrder = {\n Balanced: 'BALANCED',\n FillFirst: 'FILL_FIRST',\n ByStop: 'BY_STOP',\n} as const;\nexport type SeatingFillOrder = (typeof SeatingFillOrder)[keyof typeof SeatingFillOrder];\n\nexport const SeatingGenderAdjacency = {\n Off: 'OFF',\n AvoidUnrelated: 'AVOID_UNRELATED',\n StrictRows: 'STRICT_ROWS',\n} as const;\nexport type SeatingGenderAdjacency = (typeof SeatingGenderAdjacency)[keyof typeof SeatingGenderAdjacency];\n\nexport const SeatingHeuristicKey = {\n MedicalFirst: 'medicalFirst',\n Parties: 'parties',\n SameStop: 'sameStop',\n Gender: 'gender',\n BalanceVehicles: 'balanceVehicles',\n} as const;\nexport type SeatingHeuristicKey = (typeof SeatingHeuristicKey)[keyof typeof SeatingHeuristicKey];\n\nexport const SettingsExpenseWindow = {\n Anytime: 'ANYTIME',\n TripPlusDays: 'TRIP_PLUS_DAYS',\n} as const;\nexport type SettingsExpenseWindow = (typeof SettingsExpenseWindow)[keyof typeof SettingsExpenseWindow];\n\nexport const SettingsPickupTreatment = {\n Advisory: 'ADVISORY',\n Strict: 'STRICT',\n} as const;\nexport type SettingsPickupTreatment = (typeof SettingsPickupTreatment)[keyof typeof SettingsPickupTreatment];\n\nexport const SyncOpMethod = {\n Post: 'POST',\n Patch: 'PATCH',\n Put: 'PUT',\n Delete: 'DELETE',\n} as const;\nexport type SyncOpMethod = (typeof SyncOpMethod)[keyof typeof SyncOpMethod];\n\nexport const TriggerAnchor = {\n Start: 'START',\n End: 'END',\n} as const;\nexport type TriggerAnchor = (typeof TriggerAnchor)[keyof typeof TriggerAnchor];\n\nexport const TripMode = {\n Group: 'GROUP',\n Personalized: 'PERSONALIZED',\n} as const;\nexport type TripMode = (typeof TripMode)[keyof typeof TripMode];\n\nexport const TripStatus = {\n Confirmed: 'CONFIRMED',\n InProgress: 'IN_PROGRESS',\n Completed: 'COMPLETED',\n Postponed: 'POSTPONED',\n Cancelled: 'CANCELLED',\n} as const;\nexport type TripStatus = (typeof TripStatus)[keyof typeof TripStatus];\n\nexport const VehicleLayout = {\n TwoTwo: 'TWO_TWO',\n TwoOne: 'TWO_ONE',\n Flat: 'FLAT',\n} as const;\nexport type VehicleLayout = (typeof VehicleLayout)[keyof typeof VehicleLayout];\n\nexport const VehicleType = {\n Bus: 'BUS',\n TempoTraveller: 'TEMPO_TRAVELLER',\n Car: 'CAR',\n Flight: 'FLIGHT',\n Train: 'TRAIN',\n Other: 'OTHER',\n} as const;\nexport type VehicleType = (typeof VehicleType)[keyof typeof VehicleType];\n\nexport const VendorCategory = {\n Hotel: 'HOTEL',\n Transport: 'TRANSPORT',\n Activity: 'ACTIVITY',\n Guide: 'GUIDE',\n Food: 'FOOD',\n Misc: 'MISC',\n} as const;\nexport type VendorCategory = (typeof VendorCategory)[keyof typeof VendorCategory];\n","/**\n * The rooming vocabulary a client needs to RENDER what\n * `rooming.autoAssign` and `rooming.read` answer — and which is deliberately\n * not on the wire.\n *\n * Two things live here, for the same reason: each is a property of the RULE or\n * of the CANON, not of a particular run, so shipping either inside every\n * response would put a second copy of one judgement in every payload and let\n * the two disagree after a contract change. The engine states this in\n * `src/modules/rooming/index.ts`, which re-exports both explicitly \"for the\n * SDK\". This file is that re-export's other end, so a client renders\n * relaxations and traveller chips without inventing its own severity map or\n * its own colour maths.\n *\n * ── HOW THIS STAYS HONEST ────────────────────────────────────────────────────\n *\n * These values are not in `openapi.json`, so `gen:check` cannot police them.\n * What does: both maps are typed as TOTAL `Record`s over GENERATED key types\n * (`RoomingHeuristicKey` and `Gender`, from `../generated/enums.ts`, which\n * `scripts/gen-meta.mjs` builds out of the vendored spec's own request enums).\n * Add a heuristic or a gender to the contract and re-vendor, and this file\n * stops compiling until someone decides what the new member's severity or hue\n * family is. A `Record<string, …>` here would have accepted the drift\n * silently, which is exactly the failure a hand-maintained mirror invites.\n */\n\nimport { Gender, type RoomingHeuristicKey } from '../generated/enums';\n\n/**\n * How loudly to render a rule's relaxation.\n *\n * - `warn` — the manager should look: a preference they set was given up.\n * - `split` — a group was broken up. Louder than `warn`; it is the complaint\n * the trip will actually generate.\n * - `info` — a soft preference, worth showing but not worth interrupting for.\n * - `never` — this rule is never relaxed at all. It exists so the map is TOTAL:\n * a missing entry would be indistinguishable from a rule nobody had\n * classified yet.\n */\nexport type RoomingHeuristicSeverity = 'warn' | 'split' | 'info' | 'never';\n\n/**\n * The frozen severity map, mirroring the engine's `HEURISTIC_SEVERITY`.\n *\n * `gender` is `'never'` because a gender rule is never relaxed — the traveller\n * stays unassigned instead, and turns up in `autoAssign`'s `unassigned[]` with\n * a reason. So a `perRule` entry for `gender` with `outcome: 'relaxed'` is not\n * something to render loudly; it is a contract violation, and a client is\n * entitled to treat it as a bug rather than as a user-facing warning.\n */\nexport const HEURISTIC_SEVERITY: Readonly<Record<RoomingHeuristicKey, RoomingHeuristicSeverity>> =\n Object.freeze({\n medicalFirst: 'warn',\n couples: 'warn',\n parties: 'split',\n gender: 'never',\n diet: 'info',\n spreadSolos: 'info',\n partyGenderPolicy: 'info',\n sameBus: 'info',\n });\n\n/**\n * Whether a string is one of the heuristic keys this SDK knows about.\n *\n * Exists because `autoAssign`'s `perRule[].rule` is an open `string` on the\n * wire, not the closed enum `strategyOrder` is on the request side — so a\n * response may name a rule a given SDK build has never heard of, and a client\n * must be able to ask.\n */\nexport function isRoomingHeuristicKey(rule: string): rule is RoomingHeuristicKey {\n return Object.hasOwn(HEURISTIC_SEVERITY, rule);\n}\n\n/**\n * How loudly to render one `perRule` entry's relaxation.\n *\n * ── WHY THIS FUNCTION EXISTS AND THE MAP IS NOT ENOUGH ──────────────────────\n *\n * `HEURISTIC_SEVERITY[entry.rule]` does not compile, and that is correct\n * rather than an oversight to paper over: `entry.rule` is `string` in the\n * contract, and a total `Record` over a closed key set legitimately refuses a\n * `string` index. The two possible fixes are not equivalent. Loosening the map\n * to `Record<string, …>` would also throw away the compile-time drift gate\n * described in this file's header, which is the only thing keeping this\n * hand-maintained mirror honest against a re-vendored spec. So the map stays\n * total and this accessor takes the wire's `string`.\n *\n * Returns `undefined` for a rule this build does not know. A caller should\n * render that entry rather than drop it — an unrecognised rule that was\n * RELAXED is still a relaxation the manager needs to see, and hiding it\n * because the severity lookup missed is the silent-relaxation failure the\n * `perRule` array exists to prevent. `'info'` is a reasonable default to draw\n * it at; `undefined` is deliberately not pre-defaulted here, so that choice is\n * visible at the call site instead of buried in this function.\n */\nexport function roomingHeuristicSeverity(rule: string): RoomingHeuristicSeverity | undefined {\n return isRoomingHeuristicKey(rule) ? HEURISTIC_SEVERITY[rule] : undefined;\n}\n\n// ── The identity-mark canon ──────────────────────────────────────────────────\n\n/**\n * The hue FAMILIES a `tone` token is built from, keyed by the occupant's\n * `gender`.\n *\n * `null` gender and `UNKNOWN` map to the SAME family: the field is nullable\n * AND the enum has an `UNKNOWN` member, so unknown-ness arrives two ways and\n * means one thing. Rendering them in two palettes would show the same fact\n * twice over as two different facts.\n */\nexport const TONE_FAMILIES: Readonly<Record<Gender, string>> = Object.freeze({\n [Gender.Male]: 'male',\n [Gender.Female]: 'female',\n [Gender.Other]: 'other',\n [Gender.Unknown]: 'unknown',\n});\n\n/** The family for a `null` gender. Identical to `UNKNOWN`'s, by the reasoning above. */\nexport const UNKNOWN_TONE_FAMILY: string = TONE_FAMILIES[Gender.Unknown];\n\n/**\n * How many shades each family has, so a client's palette knows how many to\n * define: `shade` in a `tone` token is always `0 .. SHADES_PER_FAMILY - 1`.\n *\n * It equals the maximum room capacity, and that is the whole argument. The\n * promise is that two same-gender travellers IN ONE ROOM still look different —\n * a room being the only place two chips sit side by side and have to be told\n * apart. A room holds at most 8 people, so with 8 shades per family a\n * collision is never FORCED inside that scope. It is frozen rather than\n * configurable because the mark is a property of the TRAVELLER, not of the\n * viewer: two agencies with different values would render the same person in\n * two different shades, and `transport-seating` — which draws the same chip\n * from the same canon — would have to know whose grid it was on to agree with\n * the rooming board.\n */\nexport const SHADES_PER_FAMILY = 8;\n\n/**\n * The glyph the engine sends for a traveller whose `fullName` has no\n * renderable characters at all. Reachable, because the name is CRM-supplied,\n * and an unnameable traveller must still get a chip rather than vanish off the\n * board.\n */\nexport const FALLBACK_GLYPH = '?';\n\n/** A parsed `tone` token. */\nexport interface RoomingTone {\n /** One of `TONE_FAMILIES`' values. */\n readonly family: string;\n /** `0 .. SHADES_PER_FAMILY - 1`. */\n readonly shade: number;\n}\n\n/**\n * Splits an occupant's `tone` into its family and shade.\n *\n * ── `tone` IS A TOKEN, NEVER A COLOUR ───────────────────────────────────────\n *\n * The engine sends `\"male.3\"`, not `\"#3B82F6\"`, and that is deliberate: the\n * engine must not own brand colour values. If it did, an agency re-theme would\n * be an engine deploy, and the same traveller would render in two different\n * palettes depending on which module's copy of the hex table was newer. What\n * the engine owns is the CONSISTENCY claim — `rooming` and `transport-seating`\n * handing you the same string for the same person IS the consistency —\n * and what you paint it is entirely yours. So the shape a consumer wants is\n * `palette[family][shade]`, with `palette` living in your own design system,\n * and this function is how you get the two indices out without string-slicing\n * by hand.\n *\n * Returns `undefined` rather than throwing for anything that is not a\n * recognisable token, because this runs while drawing a board: a chip with an\n * unreadable tone should fall back to a neutral swatch, not take the screen\n * down. The family is NOT checked against `TONE_FAMILIES` — a family added to\n * the contract before your palette knows about it should still parse, so you\n * can fall back on the family you do not recognise instead of on every chip.\n */\nexport function parseRoomingTone(tone: string): RoomingTone | undefined {\n const separator = tone.lastIndexOf('.');\n if (separator <= 0 || separator === tone.length - 1) {\n return undefined;\n }\n const family = tone.slice(0, separator);\n const rawShade = tone.slice(separator + 1);\n // `Number` and not `parseInt`: `parseInt('3x')` is 3, which would silently\n // accept a malformed token as a valid one.\n const shade = Number(rawShade);\n if (!Number.isInteger(shade) || shade < 0) {\n return undefined;\n }\n return { family, shade };\n}\n"]}