@gravity-rail/sdk 0.15.0 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/agui.cjs +13 -1
  2. package/dist/agui.cjs.map +1 -1
  3. package/dist/agui.d.cts +5 -1
  4. package/dist/agui.d.ts +5 -1
  5. package/dist/agui.js +12 -1
  6. package/dist/agui.js.map +1 -1
  7. package/dist/{chunk-QTJQTTIR.js → chunk-CEFOCGYO.js} +521 -69
  8. package/dist/chunk-CEFOCGYO.js.map +1 -0
  9. package/dist/{chunk-GP6ICMWF.js → chunk-PJFEGUHM.js} +8 -1
  10. package/dist/chunk-PJFEGUHM.js.map +1 -0
  11. package/dist/{client-BLuz00Qr.d.cts → client-8xakCsVs.d.cts} +2245 -232
  12. package/dist/{client-CefA5Mxe.d.ts → client-ASnNEN1U.d.ts} +2245 -232
  13. package/dist/helpers.cjs +7 -0
  14. package/dist/helpers.cjs.map +1 -1
  15. package/dist/helpers.d.cts +2 -2
  16. package/dist/helpers.d.ts +2 -2
  17. package/dist/helpers.js +1 -1
  18. package/dist/index.cjs +898 -87
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +182 -9
  21. package/dist/index.d.ts +182 -9
  22. package/dist/index.js +397 -23
  23. package/dist/index.js.map +1 -1
  24. package/dist/internal.cjs +607 -68
  25. package/dist/internal.cjs.map +1 -1
  26. package/dist/internal.d.cts +328 -7
  27. package/dist/internal.d.ts +328 -7
  28. package/dist/internal.js +86 -4
  29. package/dist/internal.js.map +1 -1
  30. package/dist/{revision-state-axZ62kJk.d.cts → revision-state-BDsQo_xD.d.cts} +4 -2
  31. package/dist/{revision-state-DL1ViZ57.d.ts → revision-state-Cz3mcUHc.d.ts} +4 -2
  32. package/dist/schemas.cjs +179 -217
  33. package/dist/schemas.cjs.map +1 -1
  34. package/dist/schemas.d.cts +2 -2
  35. package/dist/schemas.d.ts +2 -2
  36. package/dist/schemas.js +179 -210
  37. package/dist/schemas.js.map +1 -1
  38. package/dist/{tasks-Boi6AxGp.d.cts → tasks-Z4GcIqgO.d.cts} +200 -81
  39. package/dist/{tasks-Boi6AxGp.d.ts → tasks-Z4GcIqgO.d.ts} +200 -81
  40. package/package.json +3 -3
  41. package/dist/chunk-GP6ICMWF.js.map +0 -1
  42. package/dist/chunk-QTJQTTIR.js.map +0 -1
package/dist/helpers.cjs CHANGED
@@ -124,6 +124,13 @@ var ApiError = class extends Error {
124
124
  * Populated when the backend returns a WorkflowValidationErrorResponse.
125
125
  */
126
126
  validationErrors;
127
+ /**
128
+ * The raw structured `detail` object when the backend returned one (a body
129
+ * with `error: true` or a `code`). Declared here rather than bolted on with
130
+ * `as any` at the throw site so consumers can narrow it with a type guard —
131
+ * see `isMemberContactConflict` in `types/member-types`.
132
+ */
133
+ errorData;
127
134
  constructor(message, statusCode, errors, validationErrors) {
128
135
  super(message);
129
136
  this.statusCode = statusCode;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/helpers/index.ts","../src/helpers/outbound.ts","../src/api/base.ts","../src/helpers/enrollment.ts","../src/helpers/webhooks.ts"],"sourcesContent":["export {\n findMemberByPhone,\n listOutboundPhoneNumbers,\n normalizePhoneLast10,\n resolveOutboundPhoneNumberId,\n resolveOutboundWorkflowId,\n type OutboundPhoneNumberConfigDefaults,\n type OutboundPhoneNumberOption,\n type WorkspacePhoneNumbersPayload,\n} from './outbound';\n\nexport {\n resolveMemberId,\n findOrCreateMemberLabels,\n upsertDataRecordForMember,\n enrollMemberInJourney,\n type MemberRef,\n type EnrollMemberInJourneyOptions,\n type EnrollMemberInJourneyResult,\n} from './enrollment';\n\nexport {\n WEBHOOK_SIGNATURE_HEADER,\n signWebhookPayload,\n verifyWebhookSignature,\n type VerifyWebhookOptions,\n type VerifyWebhookResult,\n} from './webhooks';\n","import type { GravityRailClient } from '../client/client';\nimport type { Member } from '../types/member-types';\n\nexport interface OutboundPhoneNumberOption {\n id: number;\n number: string;\n name: string | null;\n}\n\nexport interface WorkspacePhoneNumbersPayload {\n phones: OutboundPhoneNumberOption[];\n defaultPhoneNumberId: number | null;\n}\n\n/** App/env fallbacks when resolving outbound phone numbers. */\nexport interface OutboundPhoneNumberConfigDefaults {\n /** e.g. GRAVITY_RAIL_PHONE_NUMBER_ID */\n phoneNumberId?: number;\n /** Explicit selection overriding workspace default */\n requestedPhoneNumberId?: number;\n}\n\n/** Strip to digits and return the last 10 (US-friendly match). */\nexport function normalizePhoneLast10(phone: string): string {\n const digits = phone.replace(/\\D/g, '');\n return digits.length >= 10 ? digits.slice(-10) : digits;\n}\n\nfunction phonesMatchLast10(a: string, b: string): boolean {\n const da = normalizePhoneLast10(a);\n const db = normalizePhoneLast10(b);\n if (!da || !db) return false;\n if (da.length >= 10 && db.length >= 10) {\n return da === db;\n }\n return da === db;\n}\n\nexport async function listOutboundPhoneNumbers(\n client: GravityRailClient,\n workspaceUuid: string\n): Promise<WorkspacePhoneNumbersPayload> {\n const [phones, defaults] = await Promise.all([\n client.getPhoneNumbers(workspaceUuid, { isArchived: false }),\n client.getWorkspaceDefaults(workspaceUuid),\n ]);\n\n const voicePhones = phones\n .filter((phone) => phone.enableVoice && !phone.isArchived)\n .map((phone) => ({\n id: phone.id,\n number: phone.number,\n name: phone.name,\n }));\n\n let defaultPhoneNumberId = defaults.defaultPhoneNumberId ?? null;\n if (\n defaultPhoneNumberId !== null &&\n !voicePhones.some((phone) => phone.id === defaultPhoneNumberId)\n ) {\n defaultPhoneNumberId = voicePhones[0]?.id ?? null;\n }\n if (defaultPhoneNumberId === null) {\n defaultPhoneNumberId = voicePhones[0]?.id ?? null;\n }\n\n return { phones: voicePhones, defaultPhoneNumberId };\n}\n\nexport async function resolveOutboundPhoneNumberId(\n client: GravityRailClient,\n workspaceUuid: string,\n configDefaults: OutboundPhoneNumberConfigDefaults\n): Promise<number> {\n const { phones, defaultPhoneNumberId } = await listOutboundPhoneNumbers(client, workspaceUuid);\n\n if (phones.length === 0) {\n throw new Error(\n 'No voice-enabled phone numbers in this workspace. Add a line in Gravity Rail first.'\n );\n }\n\n const requestedId = configDefaults.requestedPhoneNumberId;\n const candidate =\n requestedId ?? defaultPhoneNumberId ?? configDefaults.phoneNumberId ?? phones[0]?.id;\n\n if (candidate === undefined || !phones.some((phone) => phone.id === candidate)) {\n throw new Error('Selected outbound phone number is not available.');\n }\n\n return candidate;\n}\n\nexport async function resolveOutboundWorkflowId(\n client: GravityRailClient,\n workspaceUuid: string,\n defaultWorkflowId: number,\n override?: number\n): Promise<number> {\n const workflowsPage = await client.getWorkflows(workspaceUuid, { archived: false });\n const options = workflowsPage.items\n .filter((item) => !item.workflow.archived)\n .map((item) => ({\n id: item.workflow.id,\n name: item.workflow.name,\n }))\n .sort((a, b) => a.name.localeCompare(b.name));\n\n if (options.length === 0) {\n throw new Error('No workflows in this workspace. Create a workflow in Gravity Rail first.');\n }\n\n let resolvedDefault = defaultWorkflowId;\n if (!options.some((workflow) => workflow.id === resolvedDefault)) {\n resolvedDefault = options[0]?.id ?? defaultWorkflowId;\n }\n\n const candidate = override ?? resolvedDefault;\n\n if (!options.some((workflow) => workflow.id === candidate)) {\n throw new Error('Selected workflow is not available.');\n }\n\n return candidate;\n}\n\nexport async function findMemberByPhone(\n client: GravityRailClient,\n workspaceUuid: string,\n phone: string\n): Promise<Member | null> {\n const searchDigits = phone.replace(/\\D/g, '');\n\n for (let page = 1; page <= 5; page += 1) {\n const response = await client.getWorkspaceMembers(workspaceUuid, page, 50, searchDigits);\n const match = response.items.find(\n (member) => member.phone && phonesMatchLast10(member.phone, phone)\n );\n if (match) return match;\n\n if (page >= response.totalPages) break;\n }\n\n return null;\n}\n","// Utility function to read a specific cookie value\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const trimmedCookie = cookie.trim();\n const eqIndex = trimmedCookie.indexOf('=');\n if (eqIndex === -1) continue;\n\n const cookieName = trimmedCookie.substring(0, eqIndex);\n const cookieValue = trimmedCookie.substring(eqIndex + 1);\n\n if (cookieName === name) {\n return cookieValue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Structured validation error returned by the backend's workflow-expression\n * validator (CEL / Jinja schema checks). See WorkflowValidationErrorResponse\n * in workflowValidationTypes.ts for the public-facing shape.\n */\nexport interface ApiValidationError {\n field: string;\n kind: 'cel_syntax' | 'cel_schema' | 'jinja_syntax' | 'jinja_schema';\n message: string;\n offendingPath: string | null;\n location: {\n start: number;\n end: number;\n line: number;\n column: number;\n length: number;\n } | null;\n suggestion: string | null;\n}\n\nfunction isApiValidationError(value: unknown): value is ApiValidationError {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.field === 'string' && typeof v.kind === 'string' && typeof v.message === 'string'\n );\n}\n\nexport class ApiError extends Error {\n statusCode: number;\n /** Legacy string-array errors — kept for non-validation callers. */\n errors?: string[];\n /**\n * Structured workflow-expression validation errors (CEL/Jinja).\n * Populated when the backend returns a WorkflowValidationErrorResponse.\n */\n validationErrors?: ApiValidationError[];\n\n constructor(\n message: string,\n statusCode: number,\n errors?: string[],\n validationErrors?: ApiValidationError[]\n ) {\n super(message);\n this.statusCode = statusCode;\n this.errors = errors;\n this.validationErrors = validationErrors;\n }\n}\n\n/**\n * Handler for enhanced authentication requirement (RFC 9470 Step-Up Authentication).\n * Called when a 401 response includes WWW-Authenticate header with\n * error=\"insufficient_user_authentication\".\n * Should return a promise that resolves with the new auth token after re-auth.\n */\nexport type EnhancedAuthHandler = () => Promise<string>;\n\n/**\n * Info parsed from WWW-Authenticate header for org auth requirement.\n */\nexport interface OrgAuthInfo {\n orgUuid: string;\n cookieName: string;\n authUrl: string;\n}\n\n/**\n * Handler for organization authentication requirement.\n * Called when a 401 response includes WWW-Authenticate header with realm=\"org\".\n * The handler should redirect the user to the auth URL for consent/SSO.\n * Returns a promise that resolves when the user should retry (after page reload with cookie).\n */\nexport type OrgAuthHandler = (info: OrgAuthInfo) => Promise<void>;\n\n/**\n * Check if a WWW-Authenticate header indicates step-up authentication is required.\n * Per RFC 9470, this is indicated by error=\"insufficient_user_authentication\".\n */\nfunction requiresStepUpAuth(wwwAuthenticate: string | null): boolean {\n if (!wwwAuthenticate) return false;\n return wwwAuthenticate.includes('error=\"insufficient_user_authentication\"');\n}\n\n/**\n * Parse org auth info from WWW-Authenticate header.\n * Returns null if this is not an org auth challenge.\n * Expected format: Bearer realm=\"org\", org_uuid=\"...\", cookie_name=\"...\", auth_url=\"...\"\n *\n * Exported so non-SDK fetch paths (e.g. the app's same-origin file-content\n * proxy fetches) can detect the same challenge and trigger the shared org\n * step-up flow.\n */\nexport function parseOrgAuthChallenge(wwwAuthenticate: string | null): OrgAuthInfo | null {\n if (!wwwAuthenticate) return null;\n if (!wwwAuthenticate.includes('realm=\"org\"')) return null;\n\n // Parse the key-value pairs from the header\n const orgUuidMatch = wwwAuthenticate.match(/org_uuid=\"([^\"]+)\"/);\n const cookieNameMatch = wwwAuthenticate.match(/cookie_name=\"([^\"]+)\"/);\n const authUrlMatch = wwwAuthenticate.match(/auth_url=\"([^\"]+)\"/);\n\n if (!orgUuidMatch?.[1] || !cookieNameMatch?.[1] || !authUrlMatch?.[1]) {\n // Don't log the raw header value — it embeds org_uuid + auth_url.\n console.warn('Invalid org auth challenge header: missing required fields');\n return null;\n }\n\n return {\n orgUuid: orgUuidMatch[1],\n cookieName: cookieNameMatch[1],\n authUrl: authUrlMatch[1],\n };\n}\n\nfunction getRequestOrgCookieName(cookieName: string): string | null {\n if (cookieName.startsWith('orgToken')) {\n return cookieName.replace(/^orgToken/, 'requestOrgToken');\n }\n if (cookieName.startsWith('orgSession')) {\n return cookieName.replace(/^orgSession/, 'requestOrgSession');\n }\n return null;\n}\n\nfunction orgAuthHeaderName(token: string): 'X-Org-Token' | 'X-Org-Session' {\n return token.startsWith('gr_sess_') ? 'X-Org-Session' : 'X-Org-Token';\n}\n\nfunction setOrgAuthHeader(headers: Headers, token: string | undefined): void {\n if (!token) return;\n headers.set(orgAuthHeaderName(token), token);\n}\n\nexport class BaseApiClient {\n protected baseUrl: string;\n protected apiKey: string | undefined;\n protected isCrossDomain: boolean;\n protected fetchFunction: typeof fetch;\n private enhancedAuthHandler?: EnhancedAuthHandler;\n private enhancedAuthInProgress: Promise<string> | null = null;\n private orgAuthHandler?: OrgAuthHandler;\n private orgAuthInProgress: Promise<void> | null = null;\n private actingMemberUuid?: string;\n private orgSession?: string;\n /**\n * The org_uuid that issued the current org auth credential. Tracked so we can detect\n * a 401 challenge from a *different* org and re-fire the handler — the\n * credential is opaque to the client, so without this the original guard\n * `!this.orgSession` would prevent re-auth across orgs and surface as a silent\n * 401 in multi-org CLI workflows.\n */\n private orgSessionOrgUuid?: string;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n // console.log('[BaseApiClient] constructor - baseUrl:', baseUrl);\n // Bind fetch to its proper context (window in browser, global in Node)\n this.fetchFunction =\n customFetch || (typeof window !== 'undefined' ? fetch.bind(window) : fetch);\n\n // Determine if we're making cross-domain requests by comparing current origin to API origin\n const apiUrlParsed = new URL(baseUrl);\n const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';\n this.isCrossDomain = currentOrigin !== '' && currentOrigin !== apiUrlParsed.origin;\n // console.log('[BaseApiClient] isCrossDomain:', this.isCrossDomain, 'currentOrigin:', currentOrigin, 'apiOrigin:', apiUrlParsed.origin);\n }\n\n /**\n * Set the handler for enhanced authentication requirements (RFC 9470 Step-Up Auth).\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with error=\"insufficient_user_authentication\".\n */\n setEnhancedAuthHandler(handler: EnhancedAuthHandler | undefined) {\n this.enhancedAuthHandler = handler;\n }\n\n /**\n * Set the handler for organization authentication requirements.\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with realm=\"org\". The handler should redirect the user to complete org auth.\n */\n setOrgAuthHandler(handler: OrgAuthHandler | undefined) {\n this.orgAuthHandler = handler;\n }\n\n /**\n * Update the API key (used after successful re-authentication).\n */\n updateApiKey(newApiKey: string) {\n this.apiKey = newApiKey;\n }\n\n /**\n * Set the acting member UUID for member identity switching.\n * When set, all API requests will include the X-Acting-Member header.\n * The backend will validate that the authenticated account owns this member\n * and use it as the effective identity for the request.\n */\n setActingMember(memberUuid: string | undefined) {\n this.actingMemberUuid = memberUuid;\n }\n\n /**\n * Get the current acting member UUID.\n */\n getActingMember(): string | undefined {\n return this.actingMemberUuid;\n }\n\n /**\n * Set the opaque org session credential for cross-domain requests.\n * Opaque gr_sess_ values use X-Org-Session. Legacy orgToken JWE values still\n * use X-Org-Token through setOrgToken() during the migration window.\n *\n * `orgUuid` is the org that issued the credential; passing it lets the 401\n * handler detect a stale session when a subsequent request targets a\n * different org and re-fire the org-auth handler instead of silently\n * 401-ing. Callers without that context (legacy / unknown) may omit it.\n */\n setOrgSession(session: string | undefined, orgUuid?: string) {\n this.orgSession = session;\n this.orgSessionOrgUuid = session ? orgUuid : undefined;\n }\n\n /**\n * @deprecated Legacy compatibility for stateless orgToken JWE credentials.\n * Prefer setOrgSession() for opaque org browser sessions.\n */\n setOrgToken(token: string | undefined, orgUuid?: string) {\n this.setOrgSession(token, orgUuid);\n }\n\n protected async fetch<T>(endpoint: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n // Don't set Content-Type for FormData — the browser must set it\n // with the multipart boundary automatically.\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n // For cross-domain requests, try to use the requestToken cookie\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n // console.warn(\"Calling with apiKey:\", this.apiKey)\n const fullUrl = `${this.baseUrl}/api/v2/${endpoint}`;\n // console.log('[BaseApiClient] fetch - URL:', fullUrl, 'baseUrl:', this.baseUrl, 'endpoint:', endpoint);\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n // If the challenge targets a different org than our current\n // token, the token is stale (e.g. switching from Org A to Org\n // B mid-session). Clear it so the handler re-fires below.\n if (\n orgAuthInfo &&\n this.orgSession &&\n this.orgSessionOrgUuid &&\n this.orgSessionOrgUuid !== orgAuthInfo.orgUuid\n ) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n }\n if (orgAuthInfo && !this.orgSession) {\n const requestCookieName = getRequestOrgCookieName(orgAuthInfo.cookieName);\n const cachedOrgSession = requestCookieName\n ? getCookieValue(requestCookieName)\n : undefined;\n if (cachedOrgSession) {\n this.orgSession = cachedOrgSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (this.orgAuthHandler) {\n if (!this.orgAuthInProgress) {\n const handler = this.orgAuthHandler;\n this.orgAuthInProgress = (async () => {\n try {\n await handler(orgAuthInfo);\n } finally {\n this.orgAuthInProgress = null;\n }\n })();\n }\n await this.orgAuthInProgress;\n // Prefer cookie (browser). Fall back to this.orgSession which\n // non-browser handlers (e.g. CLI) set directly via setOrgSession().\n const postHandlerSession =\n (requestCookieName ? getCookieValue(requestCookieName) : undefined) ??\n this.orgSession;\n if (!postHandlerSession) {\n throw new ApiError(\n 'Organization authentication did not issue a session',\n 401\n );\n }\n this.orgSession = postHandlerSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n }\n }\n\n const errorData = await response.json().catch(() => ({}));\n\n // Handle unauthorized errors for account endpoint\n if (response.status === 401 && endpoint === 'account') {\n throw new Error('unauthorized');\n }\n\n // Handle structured validation errors (Pydantic array format)\n if (Array.isArray(errorData.detail)) {\n const formattedErrors = errorData.detail\n .map((error: any) => {\n const location = error.loc.join(' > ');\n return `${location}: ${error.msg}`;\n })\n .join('\\n');\n throw new ApiError(`Validation Error:\\n${formattedErrors}`, response.status);\n }\n\n // Handle validation errors with errors array (new format)\n if (errorData.errors && Array.isArray(errorData.errors)) {\n // Structured workflow-expression validation errors — objects with\n // { field, kind, message, offendingPath, location }. Build a\n // readable message and preserve the structured payload.\n if (errorData.errors.length > 0 && isApiValidationError(errorData.errors[0])) {\n const validationErrors: ApiValidationError[] =\n errorData.errors.filter(isApiValidationError);\n const [first] = validationErrors;\n if (first) {\n const extra =\n validationErrors.length > 1\n ? ` (+${validationErrors.length - 1} more)`\n : '';\n const readable = `${first.field}: ${first.message}${extra}`;\n throw new ApiError(\n readable,\n response.status,\n validationErrors.map((e) => `${e.field}: ${e.message}`),\n validationErrors\n );\n }\n }\n\n // Legacy string-array errors.\n const stringErrors: string[] = errorData.errors.filter(\n (e: unknown): e is string => typeof e === 'string'\n );\n const details = stringErrors.join('; ');\n const message = errorData.detail\n ? `${errorData.detail}: ${details}`\n : `Validation failed: ${details}`;\n throw new ApiError(message, response.status, stringErrors);\n }\n\n // Handle structured errors (with error: true or with code property)\n const structuredError = errorData.detail || errorData;\n if (\n structuredError &&\n typeof structuredError === 'object' &&\n (structuredError.error === true || structuredError.code)\n ) {\n const message = structuredError.message || structuredError.code || 'Unknown error';\n const error = new ApiError(message, response.status);\n // Attach the full error data for frontend handling\n (error as any).errorData = structuredError;\n throw error;\n }\n\n // Handle simple error messages\n const errorMessage =\n typeof errorData.detail === 'string'\n ? errorData.detail\n : errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n // Handle 204 No Content - no JSON body to parse\n if (response.status === 204) {\n return undefined as any;\n }\n\n return response.json();\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n\n protected async fetchRaw(\n endpoint: string,\n options?: RequestInit,\n allowedErrorStatuses: number[] = []\n ): Promise<Response> {\n try {\n const headers = new Headers({\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n // For cross-domain requests, try to use the requestToken cookie\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const response = await this.fetchFunction(`${this.baseUrl}/api/v2/${endpoint}`, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n // Mirror of the org-auth branch in fetch() above; see comments there.\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (\n orgAuthInfo &&\n this.orgSession &&\n this.orgSessionOrgUuid &&\n this.orgSessionOrgUuid !== orgAuthInfo.orgUuid\n ) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n }\n if (orgAuthInfo && !this.orgSession) {\n const requestCookieName = getRequestOrgCookieName(orgAuthInfo.cookieName);\n const cachedOrgSession = requestCookieName\n ? getCookieValue(requestCookieName)\n : undefined;\n if (cachedOrgSession) {\n this.orgSession = cachedOrgSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (this.orgAuthHandler) {\n if (!this.orgAuthInProgress) {\n const handler = this.orgAuthHandler;\n this.orgAuthInProgress = (async () => {\n try {\n await handler(orgAuthInfo);\n } finally {\n this.orgAuthInProgress = null;\n }\n })();\n }\n await this.orgAuthInProgress;\n // Prefer cookie (browser). Fall back to this.orgSession which\n // non-browser handlers (e.g. CLI) set directly via setOrgSession().\n const postHandlerSession =\n (requestCookieName ? getCookieValue(requestCookieName) : undefined) ??\n this.orgSession;\n if (!postHandlerSession) {\n throw new ApiError(\n 'Organization authentication did not issue a session',\n 401\n );\n }\n this.orgSession = postHandlerSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n }\n }\n\n if (allowedErrorStatuses.includes(response.status)) {\n return response;\n }\n\n const errorText = await response.text().catch(() => '');\n throw new ApiError(errorText || response.statusText, response.status);\n }\n\n return response;\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n\n /**\n * Fetch from root path (not prefixed with /api/v2/)\n * Used for OAuth and other non-API endpoints\n */\n protected async fetchRoot<T>(path: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const fullUrl = `${this.baseUrl}/${path}`;\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null as T;\n }\n const errorData = await response.json().catch(() => ({}));\n const errorMessage = errorData.detail || errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n return response.json();\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n}\n","/**\n * Enrollment-flow helpers: the small compound operations every integration\n * re-implements when wiring \"register member → populate a form → enroll into a\n * journey\". They build on the plain client methods and are safe to call from a\n * server-side BFF.\n */\nimport { ApiError } from '../api/base';\nimport type { GravityRailClient } from '../client/client';\nimport type { DataRecord } from '../types/data-types';\nimport { findMemberByPhone } from './outbound';\n\n/** Identify a member by any one of these; `memberId` wins when present. */\nexport interface MemberRef {\n memberId?: number;\n phone?: string;\n externalId?: string;\n}\n\n/** Resolve a `MemberRef` to a concrete member id (throws if none matches). */\nexport async function resolveMemberId(\n client: GravityRailClient,\n workspaceUuid: string,\n ref: MemberRef\n): Promise<number> {\n if (typeof ref.memberId === 'number') {\n return ref.memberId;\n }\n if (ref.phone) {\n const member = await findMemberByPhone(client, workspaceUuid, ref.phone);\n if (member?.id) return member.id;\n // Do not put the phone (PHI) in the message — it propagates to callers.\n throw new Error('No member found for the provided phone number');\n }\n if (ref.externalId) {\n const page = await client.getWorkspaceMembers(workspaceUuid, 1, 25, ref.externalId);\n const match = page.items.find((m) => m.externalId === ref.externalId);\n if (match?.id) return match.id;\n // Do not put the externalId (PHI) in the message — it propagates to callers.\n throw new Error('No member found for the provided externalId');\n }\n throw new Error('Provide memberId, phone, or externalId');\n}\n\n/**\n * Find member labels by name, creating any that don't exist, and return their\n * ids. Case-insensitive match on name. (The API derives the slug from the name.)\n */\nexport async function findOrCreateMemberLabels(\n client: GravityRailClient,\n workspaceUuid: string,\n names: string[],\n options: { color?: string } = {}\n): Promise<number[]> {\n const clean = names.map((n) => n.trim()).filter(Boolean);\n if (clean.length === 0) return [];\n\n const existing = await client.getMemberLabels(workspaceUuid);\n const byName = new Map(existing.map((l) => [l.name.toLowerCase(), l]));\n const ids: number[] = [];\n for (const name of clean) {\n const found = byName.get(name.toLowerCase());\n if (found) {\n ids.push(found.id);\n continue;\n }\n const created = await client.createMemberLabel(workspaceUuid, {\n name,\n color: options.color ?? '#6366f1',\n });\n byName.set(name.toLowerCase(), created);\n ids.push(created.id);\n }\n return ids;\n}\n\n/**\n * Idempotently write a member-scoped data record: update the member's existing\n * record for the DataType if one exists, otherwise create it.\n */\nexport async function upsertDataRecordForMember(\n client: GravityRailClient,\n workspaceUuid: string,\n dataTypeId: number,\n memberId: number,\n fieldValues: Record<string, unknown>\n): Promise<DataRecord> {\n const existing = await client.getDataRecords(workspaceUuid, dataTypeId, {\n memberId,\n pageSize: 1,\n });\n const record = existing.items?.[0];\n const body = { dataTypeId, memberId, fieldValues };\n if (record?.id) {\n return client.updateDataRecord(workspaceUuid, dataTypeId, record.id, body);\n }\n return client.createDataRecord(workspaceUuid, dataTypeId, body);\n}\n\nexport interface EnrollMemberInJourneyOptions extends MemberRef {\n /** Journey to enroll into. Defaults to the workspace's first journey. */\n journeyId?: number;\n /** Labels to apply to the member before enrolling (journey/cohort tags). */\n labels?: string[];\n labelColor?: string;\n}\n\nexport interface EnrollMemberInJourneyResult {\n journeyId: number;\n journeyName?: string;\n memberId: number;\n appliedLabels: string[];\n}\n\n/**\n * Resolve a member, optionally tag them, and enroll them into a journey. Treats\n * an \"already enrolled\" (409) response as success.\n */\nexport async function enrollMemberInJourney(\n client: GravityRailClient,\n workspaceUuid: string,\n options: EnrollMemberInJourneyOptions\n): Promise<EnrollMemberInJourneyResult> {\n const memberId = await resolveMemberId(client, workspaceUuid, options);\n\n const page = await client.getJourneys(workspaceUuid);\n const journeys = page.items ?? [];\n let journey: { id: number; name?: string } | undefined;\n if (options.journeyId != null) {\n journey = journeys.find((j) => j.id === options.journeyId) ?? { id: options.journeyId };\n } else {\n journey = journeys[0];\n }\n if (!journey) {\n throw new Error('No journey to enroll into: pass journeyId or create a journey');\n }\n\n const labelNames = (options.labels ?? []).map((l) => l.trim()).filter(Boolean);\n if (labelNames.length > 0) {\n const labelIds = await findOrCreateMemberLabels(client, workspaceUuid, labelNames, {\n color: options.labelColor,\n });\n // updateMember replaces the label set, so merge with the member's existing\n // labels rather than wiping them.\n const member = await client.getWorkspaceMember(workspaceUuid, memberId);\n const existingIds = (member.labels ?? [])\n .map((l) => l.id)\n .filter((id): id is number => typeof id === 'number');\n const mergedIds = Array.from(new Set([...existingIds, ...labelIds]));\n await client.updateMember(workspaceUuid, memberId, { labelIds: mergedIds });\n }\n\n try {\n await client.enrollMembers(workspaceUuid, journey.id, { memberId });\n } catch (error) {\n if (!(error instanceof ApiError && error.statusCode === 409)) {\n throw error;\n }\n }\n\n return { journeyId: journey.id, journeyName: journey.name, memberId, appliedLabels: labelNames };\n}\n","/**\n * Webhook signature helpers.\n *\n * Gravity Rail signs every outbound webhook with HMAC-SHA256 and sends the\n * result in the `X-Webhook-Signature` header as `t={unixSeconds},v1={hexDigest}`.\n * The signed message is the timestamp, a literal dot, then the raw request body:\n *\n * HMAC_SHA256(secret, `${t}.` + rawBody)\n *\n * The timestamp defeats replay — reject signatures older than the tolerance\n * window. Verify the signature against the RAW request body bytes, before any\n * JSON parsing/re-serialization.\n *\n * These use the Web Crypto API (`crypto.subtle`), so they run unchanged in Node\n * 18+ and the browser/edge runtimes.\n */\n\nexport const WEBHOOK_SIGNATURE_HEADER = 'X-Webhook-Signature';\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256Hex(secret: string, message: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n );\n const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(message));\n return Array.from(new Uint8Array(signature))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/** Constant-time comparison of two equal-length hex strings. */\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let mismatch = 0;\n for (let i = 0; i < a.length; i += 1) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\n/**\n * Produce the `X-Webhook-Signature` header value for a payload. Primarily useful\n * for tests and for re-signing when relaying webhooks.\n */\nexport async function signWebhookPayload(\n rawBody: string,\n secret: string,\n timestampSeconds: number\n): Promise<string> {\n const digest = await hmacSha256Hex(secret, `${timestampSeconds}.${rawBody}`);\n return `t=${timestampSeconds},v1=${digest}`;\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature in seconds (default 300). */\n toleranceSeconds?: number;\n /** Override \"now\" (unix seconds) — for deterministic tests. */\n nowSeconds?: number;\n}\n\nexport type VerifyWebhookResult = { ok: true } | { ok: false; reason: string };\n\n/**\n * Verify a webhook signature against the raw body. Returns a discriminated\n * result so callers can log the reason; it never throws on a bad signature.\n */\nexport async function verifyWebhookSignature(\n rawBody: string,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {}\n): Promise<VerifyWebhookResult> {\n if (!signatureHeader) {\n return { ok: false, reason: 'missing signature header' };\n }\n\n const parts: Record<string, string> = {};\n for (const segment of signatureHeader.split(',')) {\n const idx = segment.indexOf('=');\n if (idx > 0) {\n parts[segment.slice(0, idx).trim()] = segment.slice(idx + 1).trim();\n }\n }\n\n const timestamp = Number(parts.t);\n const provided = parts.v1;\n if (!Number.isFinite(timestamp) || !provided) {\n return { ok: false, reason: 'malformed signature header' };\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n const now = options.nowSeconds ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > tolerance) {\n return { ok: false, reason: 'signature timestamp outside tolerance' };\n }\n\n const expected = await hmacSha256Hex(secret, `${timestamp}.${rawBody}`);\n if (!timingSafeEqualHex(expected, provided)) {\n return { ok: false, reason: 'signature mismatch' };\n }\n\n return { ok: true };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuBO,SAAS,qBAAqB,OAAuB;AACzD,QAAM,SAAS,MAAM,QAAQ,OAAO,EAA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AA,EACpD;AAEA,SAAO,EAAE,IAAI,KAAK;AACrB;","names":[]}
1
+ {"version":3,"sources":["../src/helpers/index.ts","../src/helpers/outbound.ts","../src/api/base.ts","../src/helpers/enrollment.ts","../src/helpers/webhooks.ts"],"sourcesContent":["export {\n findMemberByPhone,\n listOutboundPhoneNumbers,\n normalizePhoneLast10,\n resolveOutboundPhoneNumberId,\n resolveOutboundWorkflowId,\n type OutboundPhoneNumberConfigDefaults,\n type OutboundPhoneNumberOption,\n type WorkspacePhoneNumbersPayload,\n} from './outbound';\n\nexport {\n resolveMemberId,\n findOrCreateMemberLabels,\n upsertDataRecordForMember,\n enrollMemberInJourney,\n type MemberRef,\n type EnrollMemberInJourneyOptions,\n type EnrollMemberInJourneyResult,\n} from './enrollment';\n\nexport {\n WEBHOOK_SIGNATURE_HEADER,\n signWebhookPayload,\n verifyWebhookSignature,\n type VerifyWebhookOptions,\n type VerifyWebhookResult,\n} from './webhooks';\n","import type { GravityRailClient } from '../client/client';\nimport type { Member } from '../types/member-types';\n\nexport interface OutboundPhoneNumberOption {\n id: number;\n number: string;\n name: string | null;\n}\n\nexport interface WorkspacePhoneNumbersPayload {\n phones: OutboundPhoneNumberOption[];\n defaultPhoneNumberId: number | null;\n}\n\n/** App/env fallbacks when resolving outbound phone numbers. */\nexport interface OutboundPhoneNumberConfigDefaults {\n /** e.g. GRAVITY_RAIL_PHONE_NUMBER_ID */\n phoneNumberId?: number;\n /** Explicit selection overriding workspace default */\n requestedPhoneNumberId?: number;\n}\n\n/** Strip to digits and return the last 10 (US-friendly match). */\nexport function normalizePhoneLast10(phone: string): string {\n const digits = phone.replace(/\\D/g, '');\n return digits.length >= 10 ? digits.slice(-10) : digits;\n}\n\nfunction phonesMatchLast10(a: string, b: string): boolean {\n const da = normalizePhoneLast10(a);\n const db = normalizePhoneLast10(b);\n if (!da || !db) return false;\n if (da.length >= 10 && db.length >= 10) {\n return da === db;\n }\n return da === db;\n}\n\nexport async function listOutboundPhoneNumbers(\n client: GravityRailClient,\n workspaceUuid: string\n): Promise<WorkspacePhoneNumbersPayload> {\n const [phones, defaults] = await Promise.all([\n client.getPhoneNumbers(workspaceUuid, { isArchived: false }),\n client.getWorkspaceDefaults(workspaceUuid),\n ]);\n\n const voicePhones = phones\n .filter((phone) => phone.enableVoice && !phone.isArchived)\n .map((phone) => ({\n id: phone.id,\n number: phone.number,\n name: phone.name,\n }));\n\n let defaultPhoneNumberId = defaults.defaultPhoneNumberId ?? null;\n if (\n defaultPhoneNumberId !== null &&\n !voicePhones.some((phone) => phone.id === defaultPhoneNumberId)\n ) {\n defaultPhoneNumberId = voicePhones[0]?.id ?? null;\n }\n if (defaultPhoneNumberId === null) {\n defaultPhoneNumberId = voicePhones[0]?.id ?? null;\n }\n\n return { phones: voicePhones, defaultPhoneNumberId };\n}\n\nexport async function resolveOutboundPhoneNumberId(\n client: GravityRailClient,\n workspaceUuid: string,\n configDefaults: OutboundPhoneNumberConfigDefaults\n): Promise<number> {\n const { phones, defaultPhoneNumberId } = await listOutboundPhoneNumbers(client, workspaceUuid);\n\n if (phones.length === 0) {\n throw new Error(\n 'No voice-enabled phone numbers in this workspace. Add a line in Gravity Rail first.'\n );\n }\n\n const requestedId = configDefaults.requestedPhoneNumberId;\n const candidate =\n requestedId ?? defaultPhoneNumberId ?? configDefaults.phoneNumberId ?? phones[0]?.id;\n\n if (candidate === undefined || !phones.some((phone) => phone.id === candidate)) {\n throw new Error('Selected outbound phone number is not available.');\n }\n\n return candidate;\n}\n\nexport async function resolveOutboundWorkflowId(\n client: GravityRailClient,\n workspaceUuid: string,\n defaultWorkflowId: number,\n override?: number\n): Promise<number> {\n const workflowsPage = await client.getWorkflows(workspaceUuid, { archived: false });\n const options = workflowsPage.items\n .filter((item) => !item.workflow.archived)\n .map((item) => ({\n id: item.workflow.id,\n name: item.workflow.name,\n }))\n .sort((a, b) => a.name.localeCompare(b.name));\n\n if (options.length === 0) {\n throw new Error('No workflows in this workspace. Create a workflow in Gravity Rail first.');\n }\n\n let resolvedDefault = defaultWorkflowId;\n if (!options.some((workflow) => workflow.id === resolvedDefault)) {\n resolvedDefault = options[0]?.id ?? defaultWorkflowId;\n }\n\n const candidate = override ?? resolvedDefault;\n\n if (!options.some((workflow) => workflow.id === candidate)) {\n throw new Error('Selected workflow is not available.');\n }\n\n return candidate;\n}\n\nexport async function findMemberByPhone(\n client: GravityRailClient,\n workspaceUuid: string,\n phone: string\n): Promise<Member | null> {\n const searchDigits = phone.replace(/\\D/g, '');\n\n for (let page = 1; page <= 5; page += 1) {\n const response = await client.getWorkspaceMembers(workspaceUuid, page, 50, searchDigits);\n const match = response.items.find(\n (member) => member.phone && phonesMatchLast10(member.phone, phone)\n );\n if (match) return match;\n\n if (page >= response.totalPages) break;\n }\n\n return null;\n}\n","// Utility function to read a specific cookie value\nexport function getCookieValue(name: string): string | undefined {\n if (typeof document === 'undefined') return undefined;\n\n const cookies = document.cookie.split(';');\n for (const cookie of cookies) {\n const trimmedCookie = cookie.trim();\n const eqIndex = trimmedCookie.indexOf('=');\n if (eqIndex === -1) continue;\n\n const cookieName = trimmedCookie.substring(0, eqIndex);\n const cookieValue = trimmedCookie.substring(eqIndex + 1);\n\n if (cookieName === name) {\n return cookieValue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Structured validation error returned by the backend's workflow-expression\n * validator (CEL / Jinja schema checks). See WorkflowValidationErrorResponse\n * in workflowValidationTypes.ts for the public-facing shape.\n */\nexport interface ApiValidationError {\n field: string;\n kind: 'cel_syntax' | 'cel_schema' | 'jinja_syntax' | 'jinja_schema';\n message: string;\n offendingPath: string | null;\n location: {\n start: number;\n end: number;\n line: number;\n column: number;\n length: number;\n } | null;\n suggestion: string | null;\n}\n\nfunction isApiValidationError(value: unknown): value is ApiValidationError {\n if (!value || typeof value !== 'object') return false;\n const v = value as Record<string, unknown>;\n return (\n typeof v.field === 'string' && typeof v.kind === 'string' && typeof v.message === 'string'\n );\n}\n\nexport class ApiError extends Error {\n statusCode: number;\n /** Legacy string-array errors — kept for non-validation callers. */\n errors?: string[];\n /**\n * Structured workflow-expression validation errors (CEL/Jinja).\n * Populated when the backend returns a WorkflowValidationErrorResponse.\n */\n validationErrors?: ApiValidationError[];\n /**\n * The raw structured `detail` object when the backend returned one (a body\n * with `error: true` or a `code`). Declared here rather than bolted on with\n * `as any` at the throw site so consumers can narrow it with a type guard —\n * see `isMemberContactConflict` in `types/member-types`.\n */\n errorData?: unknown;\n\n constructor(\n message: string,\n statusCode: number,\n errors?: string[],\n validationErrors?: ApiValidationError[]\n ) {\n super(message);\n this.statusCode = statusCode;\n this.errors = errors;\n this.validationErrors = validationErrors;\n }\n}\n\n/**\n * Handler for enhanced authentication requirement (RFC 9470 Step-Up Authentication).\n * Called when a 401 response includes WWW-Authenticate header with\n * error=\"insufficient_user_authentication\".\n * Should return a promise that resolves with the new auth token after re-auth.\n */\nexport type EnhancedAuthHandler = () => Promise<string>;\n\n/**\n * Info parsed from WWW-Authenticate header for org auth requirement.\n */\nexport interface OrgAuthInfo {\n orgUuid: string;\n cookieName: string;\n authUrl: string;\n}\n\n/**\n * Handler for organization authentication requirement.\n * Called when a 401 response includes WWW-Authenticate header with realm=\"org\".\n * The handler should redirect the user to the auth URL for consent/SSO.\n * Returns a promise that resolves when the user should retry (after page reload with cookie).\n */\nexport type OrgAuthHandler = (info: OrgAuthInfo) => Promise<void>;\n\n/**\n * Check if a WWW-Authenticate header indicates step-up authentication is required.\n * Per RFC 9470, this is indicated by error=\"insufficient_user_authentication\".\n */\nfunction requiresStepUpAuth(wwwAuthenticate: string | null): boolean {\n if (!wwwAuthenticate) return false;\n return wwwAuthenticate.includes('error=\"insufficient_user_authentication\"');\n}\n\n/**\n * Parse org auth info from WWW-Authenticate header.\n * Returns null if this is not an org auth challenge.\n * Expected format: Bearer realm=\"org\", org_uuid=\"...\", cookie_name=\"...\", auth_url=\"...\"\n *\n * Exported so non-SDK fetch paths (e.g. the app's same-origin file-content\n * proxy fetches) can detect the same challenge and trigger the shared org\n * step-up flow.\n */\nexport function parseOrgAuthChallenge(wwwAuthenticate: string | null): OrgAuthInfo | null {\n if (!wwwAuthenticate) return null;\n if (!wwwAuthenticate.includes('realm=\"org\"')) return null;\n\n // Parse the key-value pairs from the header\n const orgUuidMatch = wwwAuthenticate.match(/org_uuid=\"([^\"]+)\"/);\n const cookieNameMatch = wwwAuthenticate.match(/cookie_name=\"([^\"]+)\"/);\n const authUrlMatch = wwwAuthenticate.match(/auth_url=\"([^\"]+)\"/);\n\n if (!orgUuidMatch?.[1] || !cookieNameMatch?.[1] || !authUrlMatch?.[1]) {\n // Don't log the raw header value — it embeds org_uuid + auth_url.\n console.warn('Invalid org auth challenge header: missing required fields');\n return null;\n }\n\n return {\n orgUuid: orgUuidMatch[1],\n cookieName: cookieNameMatch[1],\n authUrl: authUrlMatch[1],\n };\n}\n\nfunction getRequestOrgCookieName(cookieName: string): string | null {\n if (cookieName.startsWith('orgToken')) {\n return cookieName.replace(/^orgToken/, 'requestOrgToken');\n }\n if (cookieName.startsWith('orgSession')) {\n return cookieName.replace(/^orgSession/, 'requestOrgSession');\n }\n return null;\n}\n\nfunction orgAuthHeaderName(token: string): 'X-Org-Token' | 'X-Org-Session' {\n return token.startsWith('gr_sess_') ? 'X-Org-Session' : 'X-Org-Token';\n}\n\nfunction setOrgAuthHeader(headers: Headers, token: string | undefined): void {\n if (!token) return;\n headers.set(orgAuthHeaderName(token), token);\n}\n\nexport class BaseApiClient {\n protected baseUrl: string;\n protected apiKey: string | undefined;\n protected isCrossDomain: boolean;\n protected fetchFunction: typeof fetch;\n private enhancedAuthHandler?: EnhancedAuthHandler;\n private enhancedAuthInProgress: Promise<string> | null = null;\n private orgAuthHandler?: OrgAuthHandler;\n private orgAuthInProgress: Promise<void> | null = null;\n private actingMemberUuid?: string;\n private orgSession?: string;\n /**\n * The org_uuid that issued the current org auth credential. Tracked so we can detect\n * a 401 challenge from a *different* org and re-fire the handler — the\n * credential is opaque to the client, so without this the original guard\n * `!this.orgSession` would prevent re-auth across orgs and surface as a silent\n * 401 in multi-org CLI workflows.\n */\n private orgSessionOrgUuid?: string;\n\n constructor(apiKey: string | undefined, baseUrl: string, customFetch?: typeof fetch) {\n this.baseUrl = baseUrl;\n this.apiKey = apiKey;\n // console.log('[BaseApiClient] constructor - baseUrl:', baseUrl);\n // Bind fetch to its proper context (window in browser, global in Node)\n this.fetchFunction =\n customFetch || (typeof window !== 'undefined' ? fetch.bind(window) : fetch);\n\n // Determine if we're making cross-domain requests by comparing current origin to API origin\n const apiUrlParsed = new URL(baseUrl);\n const currentOrigin = typeof window !== 'undefined' ? window.location.origin : '';\n this.isCrossDomain = currentOrigin !== '' && currentOrigin !== apiUrlParsed.origin;\n // console.log('[BaseApiClient] isCrossDomain:', this.isCrossDomain, 'currentOrigin:', currentOrigin, 'apiOrigin:', apiUrlParsed.origin);\n }\n\n /**\n * Set the handler for enhanced authentication requirements (RFC 9470 Step-Up Auth).\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with error=\"insufficient_user_authentication\".\n */\n setEnhancedAuthHandler(handler: EnhancedAuthHandler | undefined) {\n this.enhancedAuthHandler = handler;\n }\n\n /**\n * Set the handler for organization authentication requirements.\n * This handler is called when a 401 response includes WWW-Authenticate header\n * with realm=\"org\". The handler should redirect the user to complete org auth.\n */\n setOrgAuthHandler(handler: OrgAuthHandler | undefined) {\n this.orgAuthHandler = handler;\n }\n\n /**\n * Update the API key (used after successful re-authentication).\n */\n updateApiKey(newApiKey: string) {\n this.apiKey = newApiKey;\n }\n\n /**\n * Set the acting member UUID for member identity switching.\n * When set, all API requests will include the X-Acting-Member header.\n * The backend will validate that the authenticated account owns this member\n * and use it as the effective identity for the request.\n */\n setActingMember(memberUuid: string | undefined) {\n this.actingMemberUuid = memberUuid;\n }\n\n /**\n * Get the current acting member UUID.\n */\n getActingMember(): string | undefined {\n return this.actingMemberUuid;\n }\n\n /**\n * Set the opaque org session credential for cross-domain requests.\n * Opaque gr_sess_ values use X-Org-Session. Legacy orgToken JWE values still\n * use X-Org-Token through setOrgToken() during the migration window.\n *\n * `orgUuid` is the org that issued the credential; passing it lets the 401\n * handler detect a stale session when a subsequent request targets a\n * different org and re-fire the org-auth handler instead of silently\n * 401-ing. Callers without that context (legacy / unknown) may omit it.\n */\n setOrgSession(session: string | undefined, orgUuid?: string) {\n this.orgSession = session;\n this.orgSessionOrgUuid = session ? orgUuid : undefined;\n }\n\n /**\n * @deprecated Legacy compatibility for stateless orgToken JWE credentials.\n * Prefer setOrgSession() for opaque org browser sessions.\n */\n setOrgToken(token: string | undefined, orgUuid?: string) {\n this.setOrgSession(token, orgUuid);\n }\n\n protected async fetch<T>(endpoint: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n // Don't set Content-Type for FormData — the browser must set it\n // with the multipart boundary automatically.\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n // For cross-domain requests, try to use the requestToken cookie\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n // console.warn(\"Calling with apiKey:\", this.apiKey)\n const fullUrl = `${this.baseUrl}/api/v2/${endpoint}`;\n // console.log('[BaseApiClient] fetch - URL:', fullUrl, 'baseUrl:', this.baseUrl, 'endpoint:', endpoint);\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n // If the challenge targets a different org than our current\n // token, the token is stale (e.g. switching from Org A to Org\n // B mid-session). Clear it so the handler re-fires below.\n if (\n orgAuthInfo &&\n this.orgSession &&\n this.orgSessionOrgUuid &&\n this.orgSessionOrgUuid !== orgAuthInfo.orgUuid\n ) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n }\n if (orgAuthInfo && !this.orgSession) {\n const requestCookieName = getRequestOrgCookieName(orgAuthInfo.cookieName);\n const cachedOrgSession = requestCookieName\n ? getCookieValue(requestCookieName)\n : undefined;\n if (cachedOrgSession) {\n this.orgSession = cachedOrgSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (this.orgAuthHandler) {\n if (!this.orgAuthInProgress) {\n const handler = this.orgAuthHandler;\n this.orgAuthInProgress = (async () => {\n try {\n await handler(orgAuthInfo);\n } finally {\n this.orgAuthInProgress = null;\n }\n })();\n }\n await this.orgAuthInProgress;\n // Prefer cookie (browser). Fall back to this.orgSession which\n // non-browser handlers (e.g. CLI) set directly via setOrgSession().\n const postHandlerSession =\n (requestCookieName ? getCookieValue(requestCookieName) : undefined) ??\n this.orgSession;\n if (!postHandlerSession) {\n throw new ApiError(\n 'Organization authentication did not issue a session',\n 401\n );\n }\n this.orgSession = postHandlerSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetch<T>(endpoint, options);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n }\n }\n\n const errorData = await response.json().catch(() => ({}));\n\n // Handle unauthorized errors for account endpoint\n if (response.status === 401 && endpoint === 'account') {\n throw new Error('unauthorized');\n }\n\n // Handle structured validation errors (Pydantic array format)\n if (Array.isArray(errorData.detail)) {\n const formattedErrors = errorData.detail\n .map((error: any) => {\n const location = error.loc.join(' > ');\n return `${location}: ${error.msg}`;\n })\n .join('\\n');\n throw new ApiError(`Validation Error:\\n${formattedErrors}`, response.status);\n }\n\n // Handle validation errors with errors array (new format)\n if (errorData.errors && Array.isArray(errorData.errors)) {\n // Structured workflow-expression validation errors — objects with\n // { field, kind, message, offendingPath, location }. Build a\n // readable message and preserve the structured payload.\n if (errorData.errors.length > 0 && isApiValidationError(errorData.errors[0])) {\n const validationErrors: ApiValidationError[] =\n errorData.errors.filter(isApiValidationError);\n const [first] = validationErrors;\n if (first) {\n const extra =\n validationErrors.length > 1\n ? ` (+${validationErrors.length - 1} more)`\n : '';\n const readable = `${first.field}: ${first.message}${extra}`;\n throw new ApiError(\n readable,\n response.status,\n validationErrors.map((e) => `${e.field}: ${e.message}`),\n validationErrors\n );\n }\n }\n\n // Legacy string-array errors.\n const stringErrors: string[] = errorData.errors.filter(\n (e: unknown): e is string => typeof e === 'string'\n );\n const details = stringErrors.join('; ');\n const message = errorData.detail\n ? `${errorData.detail}: ${details}`\n : `Validation failed: ${details}`;\n throw new ApiError(message, response.status, stringErrors);\n }\n\n // Handle structured errors (with error: true or with code property)\n const structuredError = errorData.detail || errorData;\n if (\n structuredError &&\n typeof structuredError === 'object' &&\n (structuredError.error === true || structuredError.code)\n ) {\n const message = structuredError.message || structuredError.code || 'Unknown error';\n const error = new ApiError(message, response.status);\n // Attach the full error data for frontend handling\n error.errorData = structuredError;\n throw error;\n }\n\n // Handle simple error messages\n const errorMessage =\n typeof errorData.detail === 'string'\n ? errorData.detail\n : errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n // Handle 204 No Content - no JSON body to parse\n if (response.status === 204) {\n return undefined as any;\n }\n\n return response.json();\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n\n protected async fetchRaw(\n endpoint: string,\n options?: RequestInit,\n allowedErrorStatuses: number[] = []\n ): Promise<Response> {\n try {\n const headers = new Headers({\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n // For cross-domain requests, try to use the requestToken cookie\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const response = await this.fetchFunction(`${this.baseUrl}/api/v2/${endpoint}`, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n // Check for step-up auth requirement per RFC 9470 (superuser 2FA re-auth needed)\n if (\n response.status === 401 &&\n requiresStepUpAuth(response.headers.get('WWW-Authenticate')) &&\n this.enhancedAuthHandler\n ) {\n // If re-auth is already in progress, wait for it\n if (this.enhancedAuthInProgress) {\n await this.enhancedAuthInProgress;\n } else {\n // Trigger re-auth and wait for completion\n this.enhancedAuthInProgress = this.enhancedAuthHandler();\n try {\n const newToken = await this.enhancedAuthInProgress;\n this.apiKey = newToken;\n } finally {\n this.enhancedAuthInProgress = null;\n }\n }\n // Retry the request with the new token\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n // Mirror of the org-auth branch in fetch() above; see comments there.\n if (response.status === 401) {\n const orgAuthInfo = parseOrgAuthChallenge(response.headers.get('WWW-Authenticate'));\n if (\n orgAuthInfo &&\n this.orgSession &&\n this.orgSessionOrgUuid &&\n this.orgSessionOrgUuid !== orgAuthInfo.orgUuid\n ) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n }\n if (orgAuthInfo && !this.orgSession) {\n const requestCookieName = getRequestOrgCookieName(orgAuthInfo.cookieName);\n const cachedOrgSession = requestCookieName\n ? getCookieValue(requestCookieName)\n : undefined;\n if (cachedOrgSession) {\n this.orgSession = cachedOrgSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n\n if (this.orgAuthHandler) {\n if (!this.orgAuthInProgress) {\n const handler = this.orgAuthHandler;\n this.orgAuthInProgress = (async () => {\n try {\n await handler(orgAuthInfo);\n } finally {\n this.orgAuthInProgress = null;\n }\n })();\n }\n await this.orgAuthInProgress;\n // Prefer cookie (browser). Fall back to this.orgSession which\n // non-browser handlers (e.g. CLI) set directly via setOrgSession().\n const postHandlerSession =\n (requestCookieName ? getCookieValue(requestCookieName) : undefined) ??\n this.orgSession;\n if (!postHandlerSession) {\n throw new ApiError(\n 'Organization authentication did not issue a session',\n 401\n );\n }\n this.orgSession = postHandlerSession;\n this.orgSessionOrgUuid = orgAuthInfo.orgUuid;\n try {\n return await this.fetchRaw(endpoint, options, allowedErrorStatuses);\n } catch (retryError) {\n this.orgSession = undefined;\n this.orgSessionOrgUuid = undefined;\n throw retryError;\n }\n }\n }\n }\n\n if (allowedErrorStatuses.includes(response.status)) {\n return response;\n }\n\n const errorText = await response.text().catch(() => '');\n throw new ApiError(errorText || response.statusText, response.status);\n }\n\n return response;\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n\n /**\n * Fetch from root path (not prefixed with /api/v2/)\n * Used for OAuth and other non-API endpoints\n */\n protected async fetchRoot<T>(path: string, options?: RequestInit): Promise<T> {\n try {\n const headers = new Headers({\n ...(options?.body instanceof FormData ? {} : { 'Content-Type': 'application/json' }),\n ...((options?.headers as Record<string, string>) || {}),\n });\n\n if (this.apiKey) {\n headers.set('Authorization', `Bearer ${this.apiKey}`);\n } else if (this.isCrossDomain) {\n const requestToken = getCookieValue('requestToken');\n if (requestToken) {\n headers.set('Authorization', `Bearer ${requestToken}`);\n }\n }\n\n // Include X-Acting-Member header for member identity switching\n if (this.actingMemberUuid) {\n headers.set('X-Acting-Member', this.actingMemberUuid);\n }\n\n setOrgAuthHeader(headers, this.orgSession);\n\n const fullUrl = `${this.baseUrl}/${path}`;\n\n const response = await this.fetchFunction(fullUrl, {\n ...options,\n ...(this.apiKey ? {} : { credentials: 'include' }),\n ...(this.isCrossDomain ? { mode: 'cors' } : {}),\n headers,\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n return null as T;\n }\n const errorData = await response.json().catch(() => ({}));\n const errorMessage = errorData.detail || errorData.message || response.statusText;\n throw new ApiError(errorMessage, response.status);\n }\n\n if (response.status === 204) {\n return undefined as T;\n }\n\n return response.json();\n } catch (error) {\n console.warn(error);\n throw error;\n }\n }\n}\n","/**\n * Enrollment-flow helpers: the small compound operations every integration\n * re-implements when wiring \"register member → populate a form → enroll into a\n * journey\". They build on the plain client methods and are safe to call from a\n * server-side BFF.\n */\nimport { ApiError } from '../api/base';\nimport type { GravityRailClient } from '../client/client';\nimport type { DataRecord } from '../types/data-types';\nimport { findMemberByPhone } from './outbound';\n\n/** Identify a member by any one of these; `memberId` wins when present. */\nexport interface MemberRef {\n memberId?: number;\n phone?: string;\n externalId?: string;\n}\n\n/** Resolve a `MemberRef` to a concrete member id (throws if none matches). */\nexport async function resolveMemberId(\n client: GravityRailClient,\n workspaceUuid: string,\n ref: MemberRef\n): Promise<number> {\n if (typeof ref.memberId === 'number') {\n return ref.memberId;\n }\n if (ref.phone) {\n const member = await findMemberByPhone(client, workspaceUuid, ref.phone);\n if (member?.id) return member.id;\n // Do not put the phone (PHI) in the message — it propagates to callers.\n throw new Error('No member found for the provided phone number');\n }\n if (ref.externalId) {\n const page = await client.getWorkspaceMembers(workspaceUuid, 1, 25, ref.externalId);\n const match = page.items.find((m) => m.externalId === ref.externalId);\n if (match?.id) return match.id;\n // Do not put the externalId (PHI) in the message — it propagates to callers.\n throw new Error('No member found for the provided externalId');\n }\n throw new Error('Provide memberId, phone, or externalId');\n}\n\n/**\n * Find member labels by name, creating any that don't exist, and return their\n * ids. Case-insensitive match on name. (The API derives the slug from the name.)\n */\nexport async function findOrCreateMemberLabels(\n client: GravityRailClient,\n workspaceUuid: string,\n names: string[],\n options: { color?: string } = {}\n): Promise<number[]> {\n const clean = names.map((n) => n.trim()).filter(Boolean);\n if (clean.length === 0) return [];\n\n const existing = await client.getMemberLabels(workspaceUuid);\n const byName = new Map(existing.map((l) => [l.name.toLowerCase(), l]));\n const ids: number[] = [];\n for (const name of clean) {\n const found = byName.get(name.toLowerCase());\n if (found) {\n ids.push(found.id);\n continue;\n }\n const created = await client.createMemberLabel(workspaceUuid, {\n name,\n color: options.color ?? '#6366f1',\n });\n byName.set(name.toLowerCase(), created);\n ids.push(created.id);\n }\n return ids;\n}\n\n/**\n * Idempotently write a member-scoped data record: update the member's existing\n * record for the DataType if one exists, otherwise create it.\n */\nexport async function upsertDataRecordForMember(\n client: GravityRailClient,\n workspaceUuid: string,\n dataTypeId: number,\n memberId: number,\n fieldValues: Record<string, unknown>\n): Promise<DataRecord> {\n const existing = await client.getDataRecords(workspaceUuid, dataTypeId, {\n memberId,\n pageSize: 1,\n });\n const record = existing.items?.[0];\n const body = { dataTypeId, memberId, fieldValues };\n if (record?.id) {\n return client.updateDataRecord(workspaceUuid, dataTypeId, record.id, body);\n }\n return client.createDataRecord(workspaceUuid, dataTypeId, body);\n}\n\nexport interface EnrollMemberInJourneyOptions extends MemberRef {\n /** Journey to enroll into. Defaults to the workspace's first journey. */\n journeyId?: number;\n /** Labels to apply to the member before enrolling (journey/cohort tags). */\n labels?: string[];\n labelColor?: string;\n}\n\nexport interface EnrollMemberInJourneyResult {\n journeyId: number;\n journeyName?: string;\n memberId: number;\n appliedLabels: string[];\n}\n\n/**\n * Resolve a member, optionally tag them, and enroll them into a journey. Treats\n * an \"already enrolled\" (409) response as success.\n */\nexport async function enrollMemberInJourney(\n client: GravityRailClient,\n workspaceUuid: string,\n options: EnrollMemberInJourneyOptions\n): Promise<EnrollMemberInJourneyResult> {\n const memberId = await resolveMemberId(client, workspaceUuid, options);\n\n const page = await client.getJourneys(workspaceUuid);\n const journeys = page.items ?? [];\n let journey: { id: number; name?: string } | undefined;\n if (options.journeyId != null) {\n journey = journeys.find((j) => j.id === options.journeyId) ?? { id: options.journeyId };\n } else {\n journey = journeys[0];\n }\n if (!journey) {\n throw new Error('No journey to enroll into: pass journeyId or create a journey');\n }\n\n const labelNames = (options.labels ?? []).map((l) => l.trim()).filter(Boolean);\n if (labelNames.length > 0) {\n const labelIds = await findOrCreateMemberLabels(client, workspaceUuid, labelNames, {\n color: options.labelColor,\n });\n // updateMember replaces the label set, so merge with the member's existing\n // labels rather than wiping them.\n const member = await client.getWorkspaceMember(workspaceUuid, memberId);\n const existingIds = (member.labels ?? [])\n .map((l) => l.id)\n .filter((id): id is number => typeof id === 'number');\n const mergedIds = Array.from(new Set([...existingIds, ...labelIds]));\n await client.updateMember(workspaceUuid, memberId, { labelIds: mergedIds });\n }\n\n try {\n await client.enrollMembers(workspaceUuid, journey.id, { memberId });\n } catch (error) {\n if (!(error instanceof ApiError && error.statusCode === 409)) {\n throw error;\n }\n }\n\n return { journeyId: journey.id, journeyName: journey.name, memberId, appliedLabels: labelNames };\n}\n","/**\n * Webhook signature helpers.\n *\n * Gravity Rail signs every outbound webhook with HMAC-SHA256 and sends the\n * result in the `X-Webhook-Signature` header as `t={unixSeconds},v1={hexDigest}`.\n * The signed message is the timestamp, a literal dot, then the raw request body:\n *\n * HMAC_SHA256(secret, `${t}.` + rawBody)\n *\n * The timestamp defeats replay — reject signatures older than the tolerance\n * window. Verify the signature against the RAW request body bytes, before any\n * JSON parsing/re-serialization.\n *\n * These use the Web Crypto API (`crypto.subtle`), so they run unchanged in Node\n * 18+ and the browser/edge runtimes.\n */\n\nexport const WEBHOOK_SIGNATURE_HEADER = 'X-Webhook-Signature';\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256Hex(secret: string, message: string): Promise<string> {\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign']\n );\n const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(message));\n return Array.from(new Uint8Array(signature))\n .map((b) => b.toString(16).padStart(2, '0'))\n .join('');\n}\n\n/** Constant-time comparison of two equal-length hex strings. */\nfunction timingSafeEqualHex(a: string, b: string): boolean {\n if (a.length !== b.length) return false;\n let mismatch = 0;\n for (let i = 0; i < a.length; i += 1) {\n mismatch |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return mismatch === 0;\n}\n\n/**\n * Produce the `X-Webhook-Signature` header value for a payload. Primarily useful\n * for tests and for re-signing when relaying webhooks.\n */\nexport async function signWebhookPayload(\n rawBody: string,\n secret: string,\n timestampSeconds: number\n): Promise<string> {\n const digest = await hmacSha256Hex(secret, `${timestampSeconds}.${rawBody}`);\n return `t=${timestampSeconds},v1=${digest}`;\n}\n\nexport interface VerifyWebhookOptions {\n /** Max age of the signature in seconds (default 300). */\n toleranceSeconds?: number;\n /** Override \"now\" (unix seconds) — for deterministic tests. */\n nowSeconds?: number;\n}\n\nexport type VerifyWebhookResult = { ok: true } | { ok: false; reason: string };\n\n/**\n * Verify a webhook signature against the raw body. Returns a discriminated\n * result so callers can log the reason; it never throws on a bad signature.\n */\nexport async function verifyWebhookSignature(\n rawBody: string,\n signatureHeader: string | null | undefined,\n secret: string,\n options: VerifyWebhookOptions = {}\n): Promise<VerifyWebhookResult> {\n if (!signatureHeader) {\n return { ok: false, reason: 'missing signature header' };\n }\n\n const parts: Record<string, string> = {};\n for (const segment of signatureHeader.split(',')) {\n const idx = segment.indexOf('=');\n if (idx > 0) {\n parts[segment.slice(0, idx).trim()] = segment.slice(idx + 1).trim();\n }\n }\n\n const timestamp = Number(parts.t);\n const provided = parts.v1;\n if (!Number.isFinite(timestamp) || !provided) {\n return { ok: false, reason: 'malformed signature header' };\n }\n\n const tolerance = options.toleranceSeconds ?? 300;\n const now = options.nowSeconds ?? Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > tolerance) {\n return { ok: false, reason: 'signature timestamp outside tolerance' };\n }\n\n const expected = await hmacSha256Hex(secret, `${timestamp}.${rawBody}`);\n if (!timingSafeEqualHex(expected, provided)) {\n return { ok: false, reason: 'signature mismatch' };\n }\n\n return { ok: true };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACuBO,SAAS,qBAAqB,OAAuB;AACzD,QAAM,SAAS,MAAM,QAAQ,OAAO,EAAE;AACtC,SAAO,OAAO,UAAU,KAAK,OAAO,MAAM,GAAG,IAAI;AACpD;AAEA,SAAS,kBAAkB,GAAW,GAAoB;AACvD,QAAM,KAAK,qBAAqB,CAAC;AACjC,QAAM,KAAK,qBAAqB,CAAC;AACjC,MAAI,CAAC,MAAM,CAAC,GAAI,QAAO;AACvB,MAAI,GAAG,UAAU,MAAM,GAAG,UAAU,IAAI;AACrC,WAAO,OAAO;AAAA,EACjB;AACA,SAAO,OAAO;AACjB;AAEA,eAAsB,yBACnB,QACA,eACsC;AACtC,QAAM,CAAC,QAAQ,QAAQ,IAAI,MAAM,QAAQ,IAAI;AAAA,IAC1C,OAAO,g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AAiB;AACnB,WAAO,EAAE,IAAI,OAAO,QAAQ,2BAA2B;AAAA,EAC1D;AAEA,QAAM,QAAgC,CAAC;AACvC,aAAW,WAAW,gBAAgB,MAAM,GAAG,GAAG;AAC/C,UAAM,MAAM,QAAQ,QAAQ,GAAG;AAC/B,QAAI,MAAM,GAAG;AACV,YAAM,QAAQ,MAAM,GAAG,GAAG,EAAE,KAAK,CAAC,IAAI,QAAQ,MAAM,MAAM,CAAC,EAAE,KAAK;AAAA,IACrE;AAAA,EACH;AAEA,QAAM,YAAY,OAAO,MAAM,CAAC;AAChC,QAAM,WAAW,MAAM;AACvB,MAAI,CAAC,OAAO,SAAS,SAAS,KAAK,CAAC,UAAU;AAC3C,WAAO,EAAE,IAAI,OAAO,QAAQ,6BAA6B;AAAA,EAC5D;AAEA,QAAM,YAAY,QAAQ,oBAAoB;AAC9C,QAAM,MAAM,QAAQ,cAAc,KAAK,MAAM,KAAK,IAAI,IAAI,GAAI;AAC9D,MAAI,KAAK,IAAI,MAAM,SAAS,IAAI,WAAW;AACxC,WAAO,EAAE,IAAI,OAAO,QAAQ,wCAAwC;AAAA,EACvE;AAEA,QAAM,WAAW,MAAM,cAAc,QAAQ,GAAG,SAAS,IAAI,OAAO,EAAE;AACtE,MAAI,CAAC,mBAAmB,UAAU,QAAQ,GAAG;AAC1C,WAAO,EAAE,IAAI,OAAO,QAAQ,qBAAqB;AAAA,EACpD;AAEA,SAAO,EAAE,IAAI,KAAK;AACrB;","names":[]}
@@ -1,5 +1,5 @@
1
- import { e8 as GravityRailClient } from './client-BLuz00Qr.cjs';
2
- import { bU as WorkspaceMemberResponse, aK as DataRecordResponse } from './tasks-Boi6AxGp.cjs';
1
+ import { eb as GravityRailClient } from './client-8xakCsVs.cjs';
2
+ import { bW as WorkspaceMemberResponse, aM as DataRecordResponse } from './tasks-Z4GcIqgO.cjs';
3
3
  import 'zod';
4
4
 
5
5
  interface OutboundPhoneNumberOption {
package/dist/helpers.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { e8 as GravityRailClient } from './client-CefA5Mxe.js';
2
- import { bU as WorkspaceMemberResponse, aK as DataRecordResponse } from './tasks-Boi6AxGp.js';
1
+ import { eb as GravityRailClient } from './client-ASnNEN1U.js';
2
+ import { bW as WorkspaceMemberResponse, aM as DataRecordResponse } from './tasks-Z4GcIqgO.js';
3
3
  import 'zod';
4
4
 
5
5
  interface OutboundPhoneNumberOption {
package/dist/helpers.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  ApiError
3
- } from "./chunk-GP6ICMWF.js";
3
+ } from "./chunk-PJFEGUHM.js";
4
4
 
5
5
  // src/helpers/outbound.ts
6
6
  function normalizePhoneLast10(phone) {