kaafil-js 0.1.0-beta.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.
@@ -0,0 +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/resources/auth.ts","../src/resources/checklists.ts","../src/datetime.ts","../src/resources/collections.ts","../src/pagination/paginator.ts","../src/resources/internal.ts","../src/resources/events.ts","../src/resources/expenses.ts","../src/resources/files.ts","../src/resources/float.ts","../src/resources/itinerary.ts","../src/resources/journey.ts","../src/resources/pickups.ts","../src/resources/rooming.ts","../src/resources/seating.ts","../src/resources/share-tokens.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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AA,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.cjs","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 AdjustFloat: 'adjustFloat',\n AssignManager: 'assignManager',\n AssignPickupTraveller: 'assignPickupTraveller',\n AssignRoomingBed: 'assignRoomingBed',\n AssignSeating: 'assignSeating',\n AutoAssignRooming: 'autoAssignRooming',\n AutoAssignSeating: 'autoAssignSeating',\n BoardPickupTraveller: 'boardPickupTraveller',\n CancelTrip: 'cancelTrip',\n ChangeOwnPlatformPassword: 'changeOwnPlatformPassword',\n ClaimStatusIngest: 'claimStatusIngest',\n ClosePickupStop: 'closePickupStop',\n ConfirmFileUpload: 'confirmFileUpload',\n ConsoleLogin: 'consoleLogin',\n ConsoleLogout: 'consoleLogout',\n ConsoleSwitchPlane: 'consoleSwitchPlane',\n CreateApiKey: 'createApiKey',\n CreateConsoleUser: 'createConsoleUser',\n CreatePickupStop: 'createPickupStop',\n CreatePlatformAdmin: 'createPlatformAdmin',\n CreatePlatformPartner: 'createPlatformPartner',\n CreatePlatformPartnerConsoleUser: 'createPlatformPartnerConsoleUser',\n CreateRoomingRoom: 'createRoomingRoom',\n CreateRoomingStayWindow: 'createRoomingStayWindow',\n CreateSeatingVehicle: 'createSeatingVehicle',\n CreateTrekWalkIn: 'createTrekWalkIn',\n DeleteChecklistItem: 'deleteChecklistItem',\n DeleteItineraryItem: 'deleteItineraryItem',\n DeletePickupStop: 'deletePickupStop',\n DeletePlatformPartnerPlan: 'deletePlatformPartnerPlan',\n DeleteRoomingRoom: 'deleteRoomingRoom',\n DeleteRoomingStayWindow: 'deleteRoomingStayWindow',\n DeleteSeatingVehicle: 'deleteSeatingVehicle',\n EditWebhookEndpoint: 'editWebhookEndpoint',\n GetTrip: 'getTrip',\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 ListApiKeys: 'listApiKeys',\n ListChecklistTemplates: 'listChecklistTemplates',\n ListCollections: 'listCollections',\n ListConsoleTrips: 'listConsoleTrips',\n ListConsoleUsers: 'listConsoleUsers',\n ListEligibleCollections: 'listEligibleCollections',\n ListEvents: 'listEvents',\n ListExpenses: 'listExpenses',\n ListJourneyTriggers: 'listJourneyTriggers',\n ListPickupStops: 'listPickupStops',\n ListPlatformAdmins: 'listPlatformAdmins',\n ListPlatformPartnerApiKeys: 'listPlatformPartnerApiKeys',\n ListPlatformPartnerConsoleUsers: 'listPlatformPartnerConsoleUsers',\n ListPlatformPartners: 'listPlatformPartners',\n ListRoomingStayWindows: 'listRoomingStayWindows',\n ListTripVendors: 'listTripVendors',\n ListWebhookDeliveries: 'listWebhookDeliveries',\n ListWebhookEndpoints: 'listWebhookEndpoints',\n LogExpense: 'logExpense',\n MintAgencyAdminTokens: 'mintAgencyAdminTokens',\n MintManagerTokens: 'mintManagerTokens',\n MintShareToken: 'mintShareToken',\n PatchAgencyEntitlement: 'patchAgencyEntitlement',\n PatchChecklistItem: 'patchChecklistItem',\n PatchConsoleUser: 'patchConsoleUser',\n PatchItineraryDay: 'patchItineraryDay',\n PatchItineraryItem: 'patchItineraryItem',\n PatchJourneyTrigger: 'patchJourneyTrigger',\n PatchPickupStop: 'patchPickupStop',\n PatchPlatformAdmin: 'patchPlatformAdmin',\n PatchPlatformPartnerConsoleUser: 'patchPlatformPartnerConsoleUser',\n PatchRoomingRoom: 'patchRoomingRoom',\n PatchRoomingStayWindow: 'patchRoomingStayWindow',\n PatchSeatingVehicle: 'patchSeatingVehicle',\n PlatformLogin: 'platformLogin',\n PlatformLogout: 'platformLogout',\n PlatformMe: 'platformMe',\n PlatformRefreshTokens: 'platformRefreshTokens',\n PostponeTrek: 'postponeTrek',\n PullChecklistTemplate: 'pullChecklistTemplate',\n PushBulkTrips: 'pushBulkTrips',\n PushManifest: 'pushManifest',\n PushTripBalances: 'pushTripBalances',\n PutPlatformPartnerPlan: 'putPlatformPartnerPlan',\n ReadAgencyEntitlement: 'readAgencyEntitlement',\n ReadApiKey: 'readApiKey',\n ReadChecklistAggregate: 'readChecklistAggregate',\n ReadConsoleAudit: 'readConsoleAudit',\n ReadConsoleChecklist: 'readConsoleChecklist',\n ReadConsoleItinerary: 'readConsoleItinerary',\n ReadConsolePickups: 'readConsolePickups',\n ReadConsoleRooming: 'readConsoleRooming',\n ReadConsoleSeating: 'readConsoleSeating',\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 ReadItinerary: 'readItinerary',\n ReadItineraryChangeLog: 'readItineraryChangeLog',\n ReadJourney: 'readJourney',\n ReadJourneyCapabilities: 'readJourneyCapabilities',\n ReadManifestByPickup: 'readManifestByPickup',\n ReadPlan: 'readPlan',\n ReadPlatformPartner: 'readPlatformPartner',\n ReadRoomingBoard: 'readRoomingBoard',\n ReadSeatingBoard: 'readSeatingBoard',\n ReadShareToken: 'readShareToken',\n ReadTrekBoard: 'readTrekBoard',\n ReadTrekWalkInMeta: 'readTrekWalkInMeta',\n ReadUsage: 'readUsage',\n ReadWebhookDelivery: 'readWebhookDelivery',\n ReadWebhookEndpoint: 'readWebhookEndpoint',\n RebuildJourney: 'rebuildJourney',\n RecordCollection: 'recordCollection',\n RedeliverEndpointDelivery: 'redeliverEndpointDelivery',\n RedeliverWebhookDelivery: 'redeliverWebhookDelivery',\n RefreshAgencyAdminTokens: 'refreshAgencyAdminTokens',\n RefreshManagerTokens: 'refreshManagerTokens',\n RegisterWebhookEndpoint: 'registerWebhookEndpoint',\n ReissueConsoleUserInvite: 'reissueConsoleUserInvite',\n ReissuePlatformAdminInvite: 'reissuePlatformAdminInvite',\n ReissuePlatformPartnerConsoleUserInvite: 'reissuePlatformPartnerConsoleUserInvite',\n RemoveFromManifest: 'removeFromManifest',\n RenamePlatformPartner: 'renamePlatformPartner',\n ReopenPickupStop: 'reopenPickupStop',\n ReorderItineraryItem: 'reorderItineraryItem',\n ReorderPickupStops: 'reorderPickupStops',\n ReplayWebhookEndpoint: 'replayWebhookEndpoint',\n RequestFileUpload: 'requestFileUpload',\n ResetPlatformPartnerConsoleUser: 'resetPlatformPartnerConsoleUser',\n ReturnFloat: 'returnFloat',\n RevokeApiKey: 'revokeApiKey',\n RevokePlatformPartnerApiKey: 'revokePlatformPartnerApiKey',\n RevokeShareToken: 'revokeShareToken',\n RotateApiKey: 'rotateApiKey',\n RotateWebhookEndpointSecret: 'rotateWebhookEndpointSecret',\n RunJourneyStep: 'runJourneyStep',\n SetPlatformPartnerStatus: 'setPlatformPartnerStatus',\n SubmitExpenseClaim: 'submitExpenseClaim',\n ToggleChecklistItem: 'toggleChecklistItem',\n UnassignManager: 'unassignManager',\n UnlinkSeatingManager: 'unlinkSeatingManager',\n UpsertAgencyAdmin: 'upsertAgencyAdmin',\n UpsertManager: 'upsertManager',\n UpsertTravellerProfile: 'upsertTravellerProfile',\n UpsertTrip: 'upsertTrip',\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'],\n addItineraryItem: ['managerAuth'],\n adjustFloat: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n assignManager: ['apiKeyAuth'],\n assignPickupTraveller: ['managerAuth'],\n assignRoomingBed: ['managerAuth'],\n assignSeating: ['managerAuth'],\n autoAssignRooming: ['managerAuth'],\n autoAssignSeating: ['managerAuth'],\n boardPickupTraveller: ['managerAuth'],\n cancelTrip: ['apiKeyAuth'],\n changeOwnPlatformPassword: ['platformAdminAuth'],\n claimStatusIngest: ['apiKeyAuth'],\n closePickupStop: ['managerAuth'],\n confirmFileUpload: ['managerAuth'],\n consoleLogin: [],\n consoleLogout: ['consoleAuth'],\n consoleSwitchPlane: ['consoleAuth'],\n createApiKey: ['consoleAuth'],\n createConsoleUser: ['consoleAuth'],\n createPickupStop: ['managerAuth'],\n createPlatformAdmin: ['platformAdminAuth'],\n createPlatformPartner: ['platformAdminAuth'],\n createPlatformPartnerConsoleUser: ['platformAdminAuth'],\n createRoomingRoom: ['managerAuth'],\n createRoomingStayWindow: ['managerAuth'],\n createSeatingVehicle: ['managerAuth'],\n createTrekWalkIn: ['managerAuth'],\n deleteChecklistItem: ['managerAuth'],\n deleteItineraryItem: ['managerAuth'],\n deletePickupStop: ['managerAuth'],\n deletePlatformPartnerPlan: ['platformAdminAuth'],\n deleteRoomingRoom: ['managerAuth'],\n deleteRoomingStayWindow: ['managerAuth'],\n deleteSeatingVehicle: ['managerAuth'],\n editWebhookEndpoint: ['consoleAuth'],\n getTrip: ['apiKeyAuth'],\n health: [],\n healthV1: [],\n inspectConsoleInvite: [],\n inspectPlatformAdminInvite: [],\n issueFloat: ['managerAuth', 'apiKeyAuth', 'agencyAdminAuth'],\n linkExpenseReceipt: ['managerAuth'],\n linkSeatingManager: ['managerAuth'],\n listAgencies: ['consoleAuth'],\n listApiKeys: ['consoleAuth'],\n listChecklistTemplates: ['managerAuth', 'apiKeyAuth'],\n listCollections: ['managerAuth', 'apiKeyAuth'],\n listConsoleTrips: ['consoleAuth'],\n listConsoleUsers: ['consoleAuth'],\n listEligibleCollections: ['managerAuth', 'apiKeyAuth'],\n listEvents: ['apiKeyAuth'],\n listExpenses: ['managerAuth', 'apiKeyAuth'],\n listJourneyTriggers: ['apiKeyAuth', 'agencyAdminAuth'],\n listPickupStops: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n listPlatformAdmins: ['platformAdminAuth'],\n listPlatformPartnerApiKeys: ['platformAdminAuth'],\n listPlatformPartnerConsoleUsers: ['platformAdminAuth'],\n listPlatformPartners: ['platformAdminAuth'],\n listRoomingStayWindows: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n listTripVendors: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n listWebhookDeliveries: ['apiKeyAuth'],\n listWebhookEndpoints: ['consoleAuth'],\n logExpense: ['managerAuth'],\n mintAgencyAdminTokens: ['apiKeyAuth'],\n mintManagerTokens: ['apiKeyAuth'],\n mintShareToken: ['apiKeyAuth'],\n patchAgencyEntitlement: ['consoleAuth'],\n patchChecklistItem: ['managerAuth'],\n patchConsoleUser: ['consoleAuth'],\n patchItineraryDay: ['managerAuth'],\n patchItineraryItem: ['managerAuth'],\n patchJourneyTrigger: ['apiKeyAuth', 'agencyAdminAuth'],\n patchPickupStop: ['managerAuth'],\n patchPlatformAdmin: ['platformAdminAuth'],\n patchPlatformPartnerConsoleUser: ['platformAdminAuth'],\n patchRoomingRoom: ['managerAuth'],\n patchRoomingStayWindow: ['managerAuth'],\n patchSeatingVehicle: ['managerAuth'],\n platformLogin: [],\n platformLogout: ['platformAdminAuth'],\n platformMe: ['platformAdminAuth'],\n platformRefreshTokens: ['platformAdminAuth'],\n postponeTrek: ['managerAuth'],\n pullChecklistTemplate: ['managerAuth'],\n pushBulkTrips: ['apiKeyAuth'],\n pushManifest: ['apiKeyAuth'],\n pushTripBalances: ['apiKeyAuth'],\n putPlatformPartnerPlan: ['platformAdminAuth'],\n readAgencyEntitlement: ['consoleAuth'],\n readApiKey: ['consoleAuth'],\n readChecklistAggregate: ['managerAuth', 'apiKeyAuth'],\n readConsoleAudit: ['consoleAuth'],\n readConsoleChecklist: ['consoleAuth'],\n readConsoleItinerary: ['consoleAuth'],\n readConsolePickups: ['consoleAuth'],\n readConsoleRooming: ['consoleAuth'],\n readConsoleSeating: ['consoleAuth'],\n readConsoleUserInvite: ['consoleAuth'],\n readEndpointDeliveries: ['consoleAuth'],\n readEndpointDelivery: ['consoleAuth'],\n readEntitlementCatalog: ['consoleAuth'],\n readExpense: ['managerAuth', 'apiKeyAuth'],\n readFile: ['managerAuth', 'apiKeyAuth'],\n readFileUrl: ['managerAuth', 'apiKeyAuth'],\n readFloatLedger: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readFloatSummary: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readIngestLog: ['consoleAuth'],\n readItinerary: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readItineraryChangeLog: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readJourney: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readJourneyCapabilities: ['apiKeyAuth', 'managerAuth', 'agencyAdminAuth'],\n readManifestByPickup: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readPlan: ['consoleAuth'],\n readPlatformPartner: ['platformAdminAuth'],\n readRoomingBoard: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readSeatingBoard: ['managerAuth', 'agencyAdminAuth', 'apiKeyAuth'],\n readShareToken: ['apiKeyAuth'],\n readTrekBoard: ['managerAuth', 'apiKeyAuth'],\n readTrekWalkInMeta: ['managerAuth', 'apiKeyAuth'],\n readUsage: ['consoleAuth'],\n readWebhookDelivery: ['apiKeyAuth'],\n readWebhookEndpoint: ['consoleAuth'],\n rebuildJourney: ['apiKeyAuth'],\n recordCollection: ['managerAuth'],\n redeliverEndpointDelivery: ['consoleAuth'],\n redeliverWebhookDelivery: ['apiKeyAuth'],\n refreshAgencyAdminTokens: ['agencyAdminAuth'],\n refreshManagerTokens: ['managerAuth'],\n registerWebhookEndpoint: ['consoleAuth'],\n reissueConsoleUserInvite: ['consoleAuth'],\n reissuePlatformAdminInvite: ['platformAdminAuth'],\n reissuePlatformPartnerConsoleUserInvite: ['platformAdminAuth'],\n removeFromManifest: ['apiKeyAuth'],\n renamePlatformPartner: ['platformAdminAuth'],\n reopenPickupStop: ['managerAuth'],\n reorderItineraryItem: ['managerAuth'],\n reorderPickupStops: ['managerAuth'],\n replayWebhookEndpoint: ['apiKeyAuth'],\n requestFileUpload: ['managerAuth'],\n resetPlatformPartnerConsoleUser: ['platformAdminAuth'],\n returnFloat: ['managerAuth'],\n revokeApiKey: ['consoleAuth'],\n revokePlatformPartnerApiKey: ['platformAdminAuth'],\n revokeShareToken: ['apiKeyAuth'],\n rotateApiKey: ['consoleAuth'],\n rotateWebhookEndpointSecret: ['consoleAuth'],\n runJourneyStep: ['apiKeyAuth'],\n setPlatformPartnerStatus: ['platformAdminAuth'],\n submitExpenseClaim: ['managerAuth'],\n toggleChecklistItem: ['managerAuth'],\n unassignManager: ['apiKeyAuth'],\n unlinkSeatingManager: ['managerAuth'],\n upsertAgencyAdmin: ['apiKeyAuth'],\n upsertManager: ['apiKeyAuth'],\n upsertTravellerProfile: ['apiKeyAuth'],\n upsertTrip: ['apiKeyAuth'],\n voidCollection: ['managerAuth'],\n voidExpense: ['managerAuth'],\n withdrawExpenseClaim: ['managerAuth'],\n};\n\n// 63 of 162 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 adjustFloat: true,\n assignManager: true,\n assignPickupTraveller: true,\n assignRoomingBed: true,\n assignSeating: true,\n autoAssignRooming: true,\n autoAssignSeating: true,\n boardPickupTraveller: true,\n cancelTrip: true,\n changeOwnPlatformPassword: false,\n claimStatusIngest: true,\n closePickupStop: true,\n confirmFileUpload: true,\n consoleLogin: false,\n consoleLogout: false,\n consoleSwitchPlane: false,\n createApiKey: true,\n createConsoleUser: true,\n createPickupStop: true,\n createPlatformAdmin: false,\n createPlatformPartner: false,\n createPlatformPartnerConsoleUser: false,\n createRoomingRoom: true,\n createRoomingStayWindow: true,\n createSeatingVehicle: true,\n createTrekWalkIn: true,\n deleteChecklistItem: false,\n deleteItineraryItem: false,\n deletePickupStop: false,\n deletePlatformPartnerPlan: false,\n deleteRoomingRoom: false,\n deleteRoomingStayWindow: false,\n deleteSeatingVehicle: false,\n editWebhookEndpoint: true,\n getTrip: 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 listApiKeys: false,\n listChecklistTemplates: false,\n listCollections: false,\n listConsoleTrips: false,\n listConsoleUsers: false,\n listEligibleCollections: false,\n listEvents: false,\n listExpenses: false,\n listJourneyTriggers: false,\n listPickupStops: false,\n listPlatformAdmins: false,\n listPlatformPartnerApiKeys: false,\n listPlatformPartnerConsoleUsers: false,\n listPlatformPartners: false,\n listRoomingStayWindows: false,\n listTripVendors: false,\n listWebhookDeliveries: false,\n listWebhookEndpoints: false,\n logExpense: true,\n mintAgencyAdminTokens: false,\n mintManagerTokens: false,\n mintShareToken: true,\n patchAgencyEntitlement: true,\n patchChecklistItem: false,\n patchConsoleUser: true,\n patchItineraryDay: false,\n patchItineraryItem: false,\n patchJourneyTrigger: true,\n patchPickupStop: false,\n patchPlatformAdmin: false,\n patchPlatformPartnerConsoleUser: false,\n patchRoomingRoom: false,\n patchRoomingStayWindow: false,\n patchSeatingVehicle: false,\n platformLogin: true,\n platformLogout: false,\n platformMe: false,\n platformRefreshTokens: true,\n postponeTrek: true,\n pullChecklistTemplate: true,\n pushBulkTrips: true,\n pushManifest: true,\n pushTripBalances: true,\n putPlatformPartnerPlan: false,\n readAgencyEntitlement: false,\n readApiKey: false,\n readChecklistAggregate: false,\n readConsoleAudit: false,\n readConsoleChecklist: false,\n readConsoleItinerary: false,\n readConsolePickups: false,\n readConsoleRooming: false,\n readConsoleSeating: 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 readItinerary: false,\n readItineraryChangeLog: false,\n readJourney: false,\n readJourneyCapabilities: false,\n readManifestByPickup: false,\n readPlan: false,\n readPlatformPartner: false,\n readRoomingBoard: false,\n readSeatingBoard: false,\n readShareToken: false,\n readTrekBoard: false,\n readTrekWalkInMeta: false,\n readUsage: false,\n readWebhookDelivery: false,\n readWebhookEndpoint: false,\n rebuildJourney: true,\n recordCollection: true,\n redeliverEndpointDelivery: true,\n redeliverWebhookDelivery: true,\n refreshAgencyAdminTokens: false,\n refreshManagerTokens: false,\n registerWebhookEndpoint: true,\n reissueConsoleUserInvite: true,\n reissuePlatformAdminInvite: false,\n reissuePlatformPartnerConsoleUserInvite: false,\n removeFromManifest: true,\n renamePlatformPartner: false,\n reopenPickupStop: true,\n reorderItineraryItem: true,\n reorderPickupStops: true,\n replayWebhookEndpoint: true,\n requestFileUpload: true,\n resetPlatformPartnerConsoleUser: false,\n returnFloat: true,\n revokeApiKey: true,\n revokePlatformPartnerApiKey: false,\n revokeShareToken: false,\n rotateApiKey: true,\n rotateWebhookEndpointSecret: true,\n runJourneyStep: true,\n setPlatformPartnerStatus: false,\n submitExpenseClaim: true,\n toggleChecklistItem: true,\n unassignManager: true,\n unlinkSeatingManager: false,\n upsertAgencyAdmin: true,\n upsertManager: true,\n upsertTravellerProfile: true,\n upsertTrip: 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 BusinessRuleViolation: 'BUSINESS_RULE_VIOLATION',\n CannotPostpone: 'CANNOT_POSTPONE',\n CapabilityUnavailable: 'CAPABILITY_UNAVAILABLE',\n ConflictVersion: 'CONFLICT_VERSION',\n FileOrphaned: 'FILE_ORPHANED',\n FilePurged: 'FILE_PURGED',\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 SeatingCapacityOrphan: 'SEATING_CAPACITY_ORPHAN',\n SecretNotReplayable: 'SECRET_NOT_REPLAYABLE',\n ShareTokenExpired: 'SHARE_TOKEN_EXPIRED',\n ShareTokenRevoked: 'SHARE_TOKEN_REVOKED',\n StayWindowHasAssignments: 'STAY_WINDOW_HAS_ASSIGNMENTS',\n StayWindowOverlap: 'STAY_WINDOW_OVERLAP',\n StopHasPending: 'STOP_HAS_PENDING',\n SubjectRequired: 'SUBJECT_REQUIRED',\n TenantScopeMissing: 'TENANT_SCOPE_MISSING',\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 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 FILE_ORPHANED: { status: 409, retryability: 'no', outboxClass: 'FATAL' },\n FILE_PURGED: { status: 410, 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 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 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 TENANT_SCOPE_MISSING: { status: 500, retryability: 'yes', outboxClass: 'TRANSIENT' },\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`. Three different people act on the three values: the CRM\n * flips its own switch (`agencyFlag`), Kaafil sells an upgrade\n * (`partnerTier`), or nobody does anything until the billing period rolls\n * (`tripQuota`) — a bare `402` cannot tell a caller which.\n */\nexport type PlanRefusalReason = 'agencyFlag' | 'partnerTier' | 'tripQuota';\n\n/** `402 PLAN_FEATURE_DISABLED` — an entitlement gap. Never retried. */\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 of three different people can fix 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 fourth reason before this SDK knows\n * about it) surfaces as `undefined` rather than a wrong branch.\n */\n get reason(): PlanRefusalReason | undefined {\n const value = this.details?.reason;\n return value === 'agencyFlag' || value === 'partnerTier' || value === 'tripQuota'\n ? value\n : 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. `kaafil-engine`'s own OpenAPI document\n * declares no real host (`servers: [{ url: \"/\" }]` — a relative root, true\n * of every environment the spec is checked against) and no production\n * domain appears anywhere in the vendored architecture docs, so these are\n * this SDK's own placeholder convention, not a fact lifted from the engine.\n * A deployment against a real or self-hosted domain — or the current\n * sandbox host, whatever it is — MUST pass `baseUrl` explicitly; see\n * `resolveBaseUrl` below.\n */\nconst ENVIRONMENT_BASE_URLS: Readonly<Record<Environment, string>> = {\n live: 'https://api.kaafil.com',\n test: 'https://api.test.kaafil.com',\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\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 */\nexport function resolveBaseUrl(environment: Environment, baseUrl?: string): string {\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 { KaafilResponse, ResponseMeta } from '../types/meta';\nimport {\n fromEnvelope,\n isKaafilError,\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\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\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 };\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', '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 } {\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 */\nfunction attachMeta<T>(data: unknown, meta: ResponseMeta): KaafilResponse<T> {\n return Object.assign(data as object, { meta }) 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 * Sends exactly one HTTP attempt and returns the unwrapped payload, or\n * throws the right typed `KaafilError`. Knows nothing about retries,\n * ladders, or refresh — `execute()` owns all of that and calls this once\n * per attempt.\n */\nasync function sendOnce<T>(\n ctx: ClientContext,\n request: RequestDescriptor,\n idempotencyKey: string | undefined,\n): Promise<{ readonly data: T; readonly meta: ResponseMeta }> {\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 // 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` — it becomes an \"unrecognizable body\"\n // that both branches below turn into a coherent typed error.\n const text = await response.text();\n const body = text.length > 0 ? tryParseJson(text) : undefined;\n\n if (response.ok) {\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 { data: body.data as T, meta: buildResponseMeta(status, requestId, body.meta) };\n }\n\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 } 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 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 execute<T>(\n ctx: ClientContext,\n request: RequestDescriptor,\n): Promise<KaafilResponse<T>> {\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<KaafilResponse<T>>> => {\n try {\n const { data, meta } = await sendOnce<T>(ctx, request, idempotencyKey);\n return { ok: true, value: attachMeta<T>(data, meta) };\n } catch (error) {\n const typed = toKaafilError(error);\n lastError = typed;\n return toFailureOutcome(typed);\n }\n };\n\n const attempt = async (_attemptNumber: number): Promise<AttemptOutcome<KaafilResponse<T>>> => {\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 * 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 * `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 * `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 *\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'];\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 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 * `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 ----------------------------------------------------------------\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}\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 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}\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 * `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: only travellers with `outstandingMinor > 0` appear in\n * it — a traveller with nothing outstanding, or with no `Balance` row at\n * all, is simply absent, though still recordable through `record()` as an\n * 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\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 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\nexport interface ListEligibleCollectionsOptions {\n readonly tripRef: string;\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 with a\n * derived `outstandingMinor > 0`; \"who has a balance to chase\", not \"who\n * may be collected from\". */\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, 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 ...(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 * 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\nexport interface KaafilPaginator<T, F> {\n /** Every row fetched so far, across every page pulled on the current filters. */\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 * `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; `log`,\n * `linkReceipt`, `void` and every `claims.*` method except\n * `claims.ingest` are `managerAuth`-only. `claims.ingest` is the one\n * method on this resource an API key alone may call — see its own doc\n * below.\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 * `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`. `request`/`meta`/`url` accept a manager session OR an API\n * key; `confirm` is `managerAuth`-only — a manager confirms the upload\n * they themselves just made.\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 from\n * `purpose` (never client-declared) and the file flips to `ready`.\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\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 CreateFileResponse = components['schemas']['CreateFileResponse'];\ntype FileResponse = components['schemas']['FileResponse'];\ntype FileUrlResponse = components['schemas']['FileUrlResponse'];\ntype RequestFileUploadRequest = components['schemas']['RequestFileUploadRequest'];\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 ---------------------------------------------------------------\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}\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 };\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 * `readSummary`/`readLedger`/`issue`/`adjust` accept a manager session, an\n * API key, OR an agency-admin session; `return` is `managerAuth`-only —\n * only the manager holding the cash may hand it back (an admin is\n * view-only on that row).\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 ─────────────────────────────────────────\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 * `readLedger()` carries no `since` at all — it always returns one\n * manager's complete movement history, each row stamped with\n * `runningBalanceMinor` immediately after that row.\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 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 * full movement history, ordered `(createdAt asc, id asc)`, each row\n * carrying `runningBalanceMinor`. `404` if `managerId` does not name a\n * manager currently assigned to this trip. */\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`, `managerAuth`-only and negative-float guarded. See\n * this 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, 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 ...(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 * `itinerary` — the day cards and their ordered items, plus the change log.\n * `architecture/08-sdk.md §4`.\n *\n * `read` and `changeLog.list` accept an API key, a manager session OR an\n * agency-admin session (`readItinerary`/`readItineraryChangeLog` declare all\n * three as alternatives, never an AND) — the consumer never chooses which;\n * `../auth/credentials.ts`'s `CredentialResolver` picks whichever scheme the\n * configured credential satisfies. Every WRITE here is `managerAuth`-only: the\n * itinerary is edited on the ground, and an API-key write answers `401`.\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 /** `POST …/itinerary/items` — appends at the tail of its day. */\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 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\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 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 * 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, 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 ...(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, 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 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 * `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); every WRITE is\n * `managerAuth`-only, the same split `seating`, `rooming` and `itinerary`\n * have and for the same reason — pickups are worked on the ground.\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 BoardResponse = components['schemas']['BoardResponse'];\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 BoardPickupTravellerOptions extends BoardPickupTravellerRequest {\n readonly tripRef: string;\n readonly pointId: string;\n readonly idempotencyKey?: 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 board(options: BoardPickupTravellerOptions): 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 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 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 RoomingRoomsResource {\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 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. `architecture/08-sdk.md §3.3, §4`;\n * all three operations are `apiKeyAuth`-only in the spec (server-side mint,\n * matching `03-auth-and-tokens.md §1`: browsers only ever hold the *minted*\n * 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'];\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 RevokeShareTokenOptions {\n readonly id: 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 /** `DELETE /api/v1/share-tokens/{id}`. */\n revoke(options: RevokeShareTokenOptions): Promise<KaafilResponse<ShareTokenViewResponse>>;\n}\n\nexport function createShareTokensResource(client: KaafilHttpClient): ShareTokensResource {\n return {\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 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 };\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 * `board` and `walkIns.meta` accept a manager session OR an API key; `postpone`\n * and `walkIns.create` are `managerAuth`-only — a trek is worked and postponed\n * on the ground.\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 type { KaafilResponse } from '../types/meta';\n\ntype TrekBoardResponse = components['schemas']['TrekBoardResponse'];\ntype WalkInMetaResponse = components['schemas']['WalkInMetaResponse'];\ntype WalkInResponse = components['schemas']['WalkInResponse'];\ntype PostponeResponse = components['schemas']['PostponeResponse'];\ntype CreateTrekWalkInRequest = components['schemas']['CreateTrekWalkInRequest'];\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\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}\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 },\n };\n}\n","/**\n * `trips` — upsert, get, cancel, plus `travellers`, `managers`, `balance`,\n * and the bulk push. `architecture/08-sdk.md §4`. All operations here are\n * `apiKeyAuth`-only in the spec (CRM-backend ingest, `03-auth-and-tokens.md\n * §1`).\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` takes a trip ref AND a\n * manager ref) 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'];\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];\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 /** 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 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}\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 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 travellers: travellers.map((traveller, index) => ({\n ...traveller,\n sourceUpdatedAt: normalizeDateTimeInput(\n traveller.sourceUpdatedAt,\n `travellers[${index}].sourceUpdatedAt`,\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 const body: AssignManagerRequest = {\n ...rest,\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 },\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. `architecture/08-sdk.md §4`\n * (\"`managers` / `vendors` … `list` (vendors optional)\"). One operation,\n * `listTripVendors`, accepting `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\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'];\n\nexport interface ListTripVendorsOptions {\n readonly tripRef: 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}\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 };\n}\n","/**\n * `webhooks` — the delivery operations only: list deliveries, read a\n * delivery, redeliver, replay. `architecture/08-sdk.md §4`, amended `C-028`:\n * \"the delivery-facing 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 * `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'];\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 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}\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 };\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 { AuthResource } from './resources/auth';\nimport { createAuthResource } from './resources/auth';\nimport type { ChecklistsResource } from './resources/checklists';\nimport { createChecklistsResource } from './resources/checklists';\nimport type { CollectionsResource } from './resources/collections';\nimport { createCollectionsResource } from './resources/collections';\nimport type { EventsResource } from './resources/events';\nimport { createEventsResource } from './resources/events';\nimport type { ExpensesResource } from './resources/expenses';\nimport { createExpensesResource } from './resources/expenses';\nimport type { FilesResource } from './resources/files';\nimport { createFilesResource } from './resources/files';\nimport type { FloatResource } from './resources/float';\nimport { createFloatResource } from './resources/float';\nimport type { ItineraryResource } from './resources/itinerary';\nimport { createItineraryResource } from './resources/itinerary';\nimport type { JourneyResource } from './resources/journey';\nimport { createJourneyResource } from './resources/journey';\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 { 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 shareTokens: ShareTokensResource;\n readonly trips: TripsResource;\n readonly itinerary: ItineraryResource;\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 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}\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 shareTokens: createShareTokensResource(http),\n trips: createTripsResource(http),\n itinerary: createItineraryResource(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 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 };\n }\n\n get auth(): AuthResource {\n return this.#requireState().auth;\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 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 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 /**\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 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 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} 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 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 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 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 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","/**\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"]}