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.
- package/LICENSE +21 -0
- package/README.md +37 -0
- package/dist/client-entry.cjs +1782 -0
- package/dist/client-entry.cjs.map +1 -0
- package/dist/client-entry.d.cts +187 -0
- package/dist/client-entry.d.ts +187 -0
- package/dist/client-entry.js +1739 -0
- package/dist/client-entry.js.map +1 -0
- package/dist/index.cjs +3541 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2311 -0
- package/dist/index.d.ts +2311 -0
- package/dist/index.js +3458 -0
- package/dist/index.js.map +1 -0
- package/dist/paginator-CE9JhsLi.d.cts +24009 -0
- package/dist/paginator-CE9JhsLi.d.ts +24009 -0
- package/package.json +75 -0
|
@@ -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/journey.ts","../src/resources/vendors.ts","../src/generated/enums.ts","../src/pagination/paginator.ts","../src/client-entry.ts"],"names":[],"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,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i.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 * `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 * `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 * 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 * 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 * `KaafilClient` — the browser entry (`kaafil-js/client`).\n * `architecture/08-sdk.md §2, §3.2, §3.3`.\n *\n * Kept as a separate module graph from `./client.ts`/`./index.ts` so it\n * structurally CANNOT reach the API-key credential path — not by\n * convention, by the shape of the import graph:\n *\n * - This file never imports `./client.ts` (the only place a\n * `{ kind: 'apiKey', apiKey }` config is ever assembled) or `./index.ts`.\n * - It never imports `./config.ts`'s API-key-specific exports —\n * `assertApiKeyMatchesEnvironment`, `guardApiKeyEnvironment`,\n * `ApiKeyEnvironmentMismatchError` — only `resolveBaseUrl`/\n * `assertValidTimeout`/`assertValidMaxAttempts`, which every client needs,\n * API key or not.\n * - It builds `ManagerSessionCredentialConfig`/`ShareTokenCredentialConfig`/\n * `AgencyAdminCredentialConfig` objects using the literal string kinds\n * (`'managerSession'`/`'shareToken'`/`'agencyAdmin'`) rather than\n * importing the shared `CredentialKind` value export from\n * `./auth/credentials.ts` — that constant's own object literal carries the\n * `'apiKey'` kind alongside the other three (one generated-adjacent table,\n * not four separable ones), so importing it at all would pull that value\n * into this bundle for no reason this file has.\n *\n * A bundler following only this file's import graph has no path to the code\n * that turns an API-key string into a working credential. (`./auth/credentials.ts`'s\n * `SECURITY_SCHEME_CARRIERS` table — shared infrastructure `CredentialResolver`\n * needs to resolve a `managerAuth`/`shareAuth`/`agencyAdminAuth` *bearer*\n * header just as much as an `apiKeyAuth` one — still carries the literal\n * header name `X-API-Key` as inert data for the scheme this file never\n * selects; that table is generated, single, and un-split, so its presence in\n * this bundle is not evidence of a reachable API-key path. What this file\n * cannot do, from its own code or anything it imports, is construct or\n * validate an API-key credential, or reach the `Kaafil` class.)\n */\n\nimport type {\n AgencyAdminCredentialConfig,\n AgencyAdminRefreshResult,\n ManagerRefreshResult,\n ManagerSessionCredentialConfig,\n Resolvable,\n ShareTokenCredentialConfig,\n} from './auth/credentials';\nimport { CredentialResolver } from './auth/credentials';\nimport type { Environment } from './config';\nimport {\n assertValidMaxAttempts,\n assertValidTimeout,\n KaafilConfigError,\n resolveBaseUrl,\n} from './config';\nimport type { KaafilHttpClient } from './http/client';\nimport {\n createAgencyAdminSessionRefreshExchange,\n createHttpClient,\n createManagerSessionRefreshExchange,\n} from './http/client';\nimport { newIdempotencyKey } from './idempotency';\nimport type { JourneyResource } from './resources/journey';\nimport { createJourneyResource } from './resources/journey';\nimport type { VendorsResource } from './resources/vendors';\nimport { createVendorsResource } from './resources/vendors';\n\nexport interface KaafilClientOptions {\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 * `session.open(...)`'s options — just the tokens a manager-token mint (or a\n * prior refresh) already handed the host; never a URL, never a header.\n * Rotation from here on is automatic (`./auth/credentials.ts`'s\n * `CredentialResolver`, exchanging directly with the engine).\n */\nexport interface OpenManagerSessionOptions {\n readonly accessToken: Resolvable<string>;\n readonly refreshToken: Resolvable<string>;\n readonly expiresAt?: Resolvable<string>;\n /** Persists the rotated pair after a successful refresh — the SDK keeps\n * no state across a reload, so this is the host's one hook to survive one. */\n readonly onRefresh?: (result: ManagerRefreshResult) => void | Promise<void>;\n /** Overrides the direct engine exchange with an integrator-supplied one —\n * see `./auth/credentials.ts`'s `ManagerSessionCredentialConfig.refresh`. */\n readonly refresh?: (refreshToken: string) => Promise<ManagerRefreshResult>;\n}\n\n/**\n * `admin.open(...)`'s options — the agency-admin analogue of\n * `OpenManagerSessionOptions` above: the access/refresh pair a server-side\n * `kaafil.auth.mintAgencyAdminToken(...)` call (or a prior refresh) already\n * handed the host. Rotation from here on is automatic, the same way a\n * manager session's is (`./auth/credentials.ts`'s `CredentialResolver`,\n * exchanging directly with the engine).\n */\nexport interface OpenAgencyAdminSessionOptions {\n readonly accessToken: Resolvable<string>;\n readonly refreshToken: Resolvable<string>;\n readonly expiresAt?: Resolvable<string>;\n readonly onRefresh?: (result: AgencyAdminRefreshResult) => void | Promise<void>;\n /** Overrides the direct engine exchange with an integrator-supplied one —\n * see `./auth/credentials.ts`'s `AgencyAdminCredentialConfig.refresh`. */\n readonly refresh?: (refreshToken: string) => Promise<AgencyAdminRefreshResult>;\n}\n\n/** `open()`'s per-kind field name and value — `accessToken` for either\n * rotating kind, `token` for a share token. An exhaustive switch, not a\n * ternary: a third openable kind added to `OpenInput` without a case here\n * fails to compile instead of silently falling into the wrong branch (this\n * is exactly the mistake the ternary this replaced was one kind away from\n * making). */\nfunction openTokenField(input: OpenInput): readonly [field: string, value: Resolvable<string>] {\n switch (input.kind) {\n case 'managerSession':\n case 'agencyAdmin':\n return ['accessToken', input.accessToken];\n case 'shareToken':\n return ['token', input.token];\n }\n}\n\n/** The human-readable name of what `open()` is opening, for\n * `assertOpenTokenPresent`'s error message. Kept as its own exhaustive\n * switch rather than folded into `openTokenField` above — the two vary\n * independently (a rotating kind's field name is uniform; its display name\n * is not), so a shared ternary over both would have to re-derive one from\n * the other anyway. */\nfunction openKindLabel(kind: OpenInput['kind']): string {\n switch (kind) {\n case 'managerSession':\n return 'manager session';\n case 'agencyAdmin':\n return 'agency-admin session';\n case 'shareToken':\n return 'share';\n }\n}\n\n/**\n * A token supplied to `open()` must actually be there.\n *\n * `Resolvable<string>` allows a function, so this checks only what it can check\n * synchronously: a present, non-empty string, or a function to be called later.\n * `undefined`, `null` and `''` are refused, naming the field — the case that\n * matters is a host passing a differently-named key (or a stale one from an\n * older sample), which otherwise reaches the wire as `Bearer undefined`.\n */\nfunction assertOpenTokenPresent(input: OpenInput): void {\n const [field, value] = openTokenField(input);\n\n if (typeof value === 'function') {\n return;\n }\n if (typeof value !== 'string' || value.length === 0) {\n throw new KaafilConfigError(\n `\"${field}\" is required to open a ${openKindLabel(input.kind)} ` +\n 'and was missing or empty. Pass the value returned by the mint call.',\n );\n }\n}\n\n/** `share.open(...)`'s options. */\nexport interface OpenShareTokenOptions {\n readonly token: Resolvable<string>;\n}\n\n/**\n * Thrown by `.vendors`/`.journey` before `session.open()`/`share.open()` has\n * run, or after `close()`. There is no resource surface without a credential\n * to resolve headers with, so this fails at the point of use rather than\n * letting a call fall through to an unauthenticated request.\n */\nexport class KaafilClientNotOpenError extends Error {\n constructor() {\n super(\n 'This KaafilClient has no open session — call \"session.open(...)\", ' +\n '\"admin.open(...)\", or \"share.open(...)\" before using a resource, or after \"close()\".',\n );\n this.name = 'KaafilClientNotOpenError';\n Object.setPrototypeOf(this, KaafilClientNotOpenError.prototype);\n }\n}\n\n/**\n * Thrown by `session.open()`/`share.open()` while a session is already open.\n * `close()` first — silently replacing a live session out from under\n * whatever the caller thought was still open is exactly the kind of\n * ambiguity this SDK does not leave implicit.\n */\nexport class KaafilClientAlreadyOpenError extends Error {\n constructor() {\n super('This KaafilClient already has an open session; call \"close()\" before opening another.');\n this.name = 'KaafilClientAlreadyOpenError';\n Object.setPrototypeOf(this, KaafilClientAlreadyOpenError.prototype);\n }\n}\n\n/**\n * Every piece of an opened session's live state, in one object. `close()` is\n * the single `this.#state = null` below — the credential resolver holding\n * the access/refresh token pair is reachable only through this one\n * reference, so dropping it is the whole teardown, not a field-by-field\n * list a future edit can leave incomplete.\n */\ninterface KaafilClientState {\n readonly http: KaafilHttpClient;\n readonly vendors: VendorsResource;\n readonly journey: JourneyResource;\n}\n\ninterface KaafilClientConfig {\n readonly baseUrl: string;\n readonly timeoutMs: number | undefined;\n readonly maxAttempts: number | undefined;\n readonly userAgent: string | undefined;\n readonly random: (() => number) | undefined;\n}\n\ntype OpenInput =\n | ({ readonly kind: 'agencyAdmin' } & OpenAgencyAdminSessionOptions)\n | ({ readonly kind: 'managerSession' } & OpenManagerSessionOptions)\n | ({ readonly kind: 'shareToken' } & OpenShareTokenOptions);\n\n/**\n * The browser client. Constructed with only an `environment` — no\n * credential yet, because none exists until a manager session, an\n * agency-admin session, or a share token is minted server-side and handed\n * to `session.open`/`admin.open`/`share.open`.\n *\n * Only `vendors` and `journey` are reachable from here: every other\n * resource group built in this wave (`trips`, `auth`, `shareTokens`,\n * `webhooks`, `events`) declares `apiKeyAuth` as its only accepted scheme in\n * the vendored spec (`../generated/security.ts`'s `OPERATION_SECURITY`) —\n * a scheme none of a manager session, an agency-admin session, or a share\n * token can ever satisfy — so exposing them here would just be a way to\n * reach `UnsatisfiableSchemeError` a resource-group at a time. `vendors`\n * (`listTripVendors`) and `journey` (`readJourney`/`readJourneyCapabilities`/\n * `listJourneyTriggers`/`patchJourneyTrigger`) both accept `apiKeyAuth` OR\n * `managerAuth` OR `agencyAdminAuth` — genuinely reachable from either\n * rotating session this file can open. Both are exposed uniformly for a\n * `shareToken`-opened client too, rather than hand-branching per credential\n * kind here: no operation in the current spec accepts `shareAuth` at all\n * (verified — `grep shareAuth src/generated/security.ts` matches only the\n * scheme's own declaration, never an operation's accepted-schemes list), so\n * a share-opened client calling either today gets `UnsatisfiableSchemeError`\n * from `CredentialResolver` itself; the moment a future spec revision adds a\n * `shareAuth`-accepting operation to either group, it becomes reachable here\n * with no change to this file, which is the entire point of leaving that\n * decision to the resolver rather than duplicating the spec's scheme table\n * as a second, hand-maintained gate here.\n */\nexport class KaafilClient {\n readonly #config: KaafilClientConfig;\n #state: KaafilClientState | null = null;\n\n constructor(options: KaafilClientOptions) {\n assertValidTimeout(options.timeoutMs);\n assertValidMaxAttempts(options.maxAttempts);\n this.#config = {\n baseUrl: resolveBaseUrl(options.environment, options.baseUrl),\n timeoutMs: options.timeoutMs,\n maxAttempts: options.maxAttempts,\n userAgent: options.userAgent,\n random: options.random,\n };\n }\n\n readonly session = {\n /**\n * Opens a manager session with the access/refresh pair a server-side\n * `kaafil.auth.mintManagerToken(...)` call already minted. Rotation\n * after this point — pre-emptive, and on a `401` — is entirely\n * automatic: `CredentialResolver` exchanges directly with the engine\n * (`../auth/credentials.ts`, `../http/client.ts`'s\n * `createManagerSessionRefreshExchange`). Nothing else is required —\n * `refresh`/`onRefresh` above are optional hooks, not obligations.\n */\n open: (options: OpenManagerSessionOptions): void => {\n this.#open({ kind: 'managerSession', ...options });\n },\n };\n\n readonly admin = {\n /**\n * Opens an agency-admin session with the access/refresh pair a\n * server-side `kaafil.auth.mintAgencyAdminToken(...)` call already\n * minted. Rotation after this point — pre-emptive, and on a `401` — is\n * entirely automatic, the same way `session.open`'s is:\n * `CredentialResolver` exchanges directly with the engine\n * (`../auth/credentials.ts`, `../http/client.ts`'s\n * `createAgencyAdminSessionRefreshExchange`). Nothing else is required\n * — `refresh`/`onRefresh` above are optional hooks, not obligations.\n */\n open: (options: OpenAgencyAdminSessionOptions): void => {\n this.#open({ kind: 'agencyAdmin', ...options });\n },\n };\n\n readonly share = {\n /** Opens a read-only session with a share token minted server-side by\n * `kaafil.shareTokens.create(...)`. */\n open: (options: OpenShareTokenOptions): void => {\n this.#open({ kind: 'shareToken', ...options });\n },\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 /**\n * Total teardown. One assignment, no field to forget — see\n * `KaafilClientState` above. Safe to call whether or not a session is\n * open; calling any resource method afterward throws\n * `KaafilClientNotOpenError`, and `session.open`/`share.open` can be\n * called again immediately after.\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 #open(input: OpenInput): void {\n if (this.#state !== null) {\n throw new KaafilClientAlreadyOpenError();\n }\n\n // Rejected HERE, at the call the host makes, rather than left to become a\n // `Bearer undefined` on the first request. A missing or misnamed token is a\n // mistake this method can see, and letting it through produced a\n // `401 UNAUTHENTICATED` on an unrelated read — a caller then debugs the\n // engine's credentials instead of their own `open()` call. TypeScript\n // catches it for a typed consumer; this catches it for everyone else, and\n // the error names the field.\n assertOpenTokenPresent(input);\n\n // An exhaustive switch, not a ternary: a third openable kind added to\n // `OpenInput` without a case here fails to compile instead of falling\n // into whichever branch happened to be the `else` — the exact failure\n // mode this method used to have before the ternary it replaced.\n let credentialConfig:\n | AgencyAdminCredentialConfig\n | ManagerSessionCredentialConfig\n | ShareTokenCredentialConfig;\n // Only a rotating credential (`managerSession`/`agencyAdmin`) ever\n // refreshes, so only those two kinds need an exchange function —\n // `CredentialResolver` simply never reads it for `shareToken`.\n let rotatingSessionExchange: ReturnType<typeof createManagerSessionRefreshExchange> | undefined;\n switch (input.kind) {\n case 'managerSession':\n credentialConfig = {\n kind: 'managerSession',\n accessToken: input.accessToken,\n refreshToken: input.refreshToken,\n ...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),\n ...(input.refresh !== undefined ? { refresh: input.refresh } : {}),\n ...(input.onRefresh !== undefined ? { onRefresh: input.onRefresh } : {}),\n };\n rotatingSessionExchange = createManagerSessionRefreshExchange(this.#config.baseUrl);\n break;\n case 'agencyAdmin':\n credentialConfig = {\n kind: 'agencyAdmin',\n accessToken: input.accessToken,\n refreshToken: input.refreshToken,\n ...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),\n ...(input.refresh !== undefined ? { refresh: input.refresh } : {}),\n ...(input.onRefresh !== undefined ? { onRefresh: input.onRefresh } : {}),\n };\n rotatingSessionExchange = createAgencyAdminSessionRefreshExchange(this.#config.baseUrl);\n break;\n case 'shareToken':\n credentialConfig = { kind: 'shareToken', token: input.token };\n break;\n }\n\n const credentials = new CredentialResolver(credentialConfig, rotatingSessionExchange);\n const http = createHttpClient({\n baseUrl: this.#config.baseUrl,\n credentials,\n ...(this.#config.timeoutMs !== undefined ? { timeoutMs: this.#config.timeoutMs } : {}),\n ...(this.#config.maxAttempts !== undefined ? { maxAttempts: this.#config.maxAttempts } : {}),\n ...(this.#config.userAgent !== undefined ? { userAgent: this.#config.userAgent } : {}),\n ...(this.#config.random !== undefined ? { random: this.#config.random } : {}),\n });\n\n this.#state = {\n http,\n vendors: createVendorsResource(http),\n journey: createJourneyResource(http),\n };\n }\n\n #requireState(): KaafilClientState {\n if (this.#state === null) {\n throw new KaafilClientNotOpenError();\n }\n return this.#state;\n }\n}\n\n// --- Re-exports a browser consumer needs to catch and branch on errors and\n// read paginated results, without a deep import into this package. Named\n// exports only, deliberately never `export *` — see `./index.ts`'s header\n// comment for why. None of these touch the API-key credential path: the\n// error hierarchy and paginator are credential-agnostic, and\n// `UnsatisfiableSchemeError` is thrown by `CredentialResolver` for every\n// credential kind, not just an API key.\n\n// Every type this entry NAMES in a public signature, so a consumer can write\n// those signatures down themselves. `onRefresh` takes a `ManagerRefreshResult`\n// or an `AgencyAdminRefreshResult`, and `KaafilClientOptions.environment` is\n// an `Environment`; without these a browser consumer can call the API but\n// cannot type a handler or a config object against it, which is the same\n// unreachable-surface defect as building an error table and forgetting to\n// export it. All are already type-only imports above, so re-exporting them\n// emits nothing and reaches no API-key code — `export type` is erased\n// entirely.\nexport type {\n AgencyAdminRefreshResult,\n ManagerRefreshResult,\n Resolvable,\n} from './auth/credentials';\nexport { UnsatisfiableSchemeError } from './auth/credentials';\nexport type { Environment } from './config';\n// One runtime constant + type per distinct request-body enum value set —\n// see `src/generated/enums.ts`'s header for why a caller gets these instead\n// of a bare string literal. Plain string constants, credential-agnostic,\n// same as the error-code table above; none of these touch the API-key path.\nexport {\n BookingStatus,\n ClaimStatusIngest,\n EventType,\n Gender,\n ManagerRole,\n ManifestMode,\n PartyKind,\n TriggerAnchor,\n TripMode,\n TripStatus,\n} from './generated/enums';\nexport type { ErrorCodeTableEntry } from './generated/error-codes';\n// The catalog table itself, not just the classes over it. A consumer building\n// its own retry or queueing policy needs a code's status, retryability and\n// outbox class; a reference SDK built exactly this table and then failed to\n// export it, leaving it unreachable.\nexport {\n ERROR_CODE_TABLE,\n KaafilErrorCode,\n OutboxClass,\n Retryability,\n} from './generated/error-codes';\nexport type { KaafilErrorKind, PlanRefusalReason } from './http/errors';\nexport {\n isKaafilError,\n isRetryable,\n KaafilAbortError,\n KaafilApiError,\n KaafilCapabilityUnavailableError,\n KaafilEntitlementError,\n KaafilError,\n KaafilInvalidRequestError,\n KaafilLockedError,\n KaafilNetworkError,\n KaafilNotFoundError,\n KaafilNotImplementedError,\n KaafilRateLimitedError,\n KaafilReadOnlyRoleError,\n KaafilShareTokenExpiredError,\n KaafilShareTokenRevokedError,\n KaafilTimeoutError,\n KaafilTransportError,\n KaafilUnauthenticatedError,\n KaafilValidationError,\n KaafilVersionConflictError,\n} from './http/errors';\nexport type { FetchPage, KaafilPaginator, PaginatorPage } from './pagination/paginator';\nexport {\n KaafilPaginationError,\n KaafilPaginationExhaustedError,\n KaafilPaginationInFlightError,\n} from './pagination/paginator';\nexport type { JourneyResource, WaitUntilJourneyReadyOptions } from './resources/journey';\nexport type { VendorsResource } from './resources/vendors';\nexport type {\n CursorPageMeta,\n KaafilPagedResponse,\n KaafilResponse,\n PagedResponseMeta,\n ResponseMeta,\n} from './types/meta';\n"]}
|