import { PUBLIC_API_DEFAULT_LIMIT, PUBLIC_API_MAX_LIMIT, PUBLIC_API_RESOURCE_NAMES, publicApiResources } from "./resources.js"; const requestIdHeader = { description: "Request correlation identifier echoed from the request or generated by the API.", schema: { type: "string" }, } as const; const apiErrorResponse = (description: string, codes: string[]) => ({ description, headers: { "x-request-id": requestIdHeader }, content: { "application/json": { schema: { type: "object", properties: { error: { type: "object", properties: { code: { type: "string", enum: codes }, message: { type: "string" }, params: { type: "object", additionalProperties: true }, requestId: { type: "string" }, }, required: ["code", "message", "requestId"], }, }, required: ["error"], }, }, }, }); type PublicApiOpenApiPathItem = { get?: Record; post?: Record; }; const publicApiReadOpenApiPaths = Object.fromEntries( PUBLIC_API_RESOURCE_NAMES.map((resourceName) => { const resource = publicApiResources[resourceName]; return [ `/v1/${resource.name}`, { get: { operationId: `listPublicApi${capitalize(resource.name)}`, description: `${resource.description} Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.`, security: [{ apiKeyHeader: [] }], parameters: [ { name: "x-api-key", in: "header", required: true, description: "Tenant-bound API key. The key determines tenant scope; callers must not pass tenant ids in the URL.", schema: { type: "string", minLength: 1 }, }, { name: "limit", in: "query", required: false, description: `Page size. Defaults to ${PUBLIC_API_DEFAULT_LIMIT}; maximum ${PUBLIC_API_MAX_LIMIT}.`, schema: { type: "integer", minimum: 1, maximum: PUBLIC_API_MAX_LIMIT, default: PUBLIC_API_DEFAULT_LIMIT }, }, { name: "cursor", in: "query", required: false, description: "Opaque cursor returned as pageInfo.nextCursor.", schema: { type: "string" }, }, { name: "sort", in: "query", required: false, description: "Stable cursor sort.", schema: { type: "string", enum: ["createdAt.desc", "createdAt.asc", "updatedAt.desc", "updatedAt.asc"], default: "createdAt.desc" }, }, { name: "fields", in: "query", required: false, description: `Sparse fieldset. Supported fields: ${resource.fields.join(", ")}. The id field is always included.`, schema: { type: "string" }, }, { name: "embed", in: "query", required: false, description: resource.embeds.length ? `Comma-separated depth-1 embeds. Supported embeds: ${resource.embeds.join(", ")}.` : "No embeds are currently supported for this resource.", schema: { type: "string" }, }, { name: "q", in: "query", required: false, description: "Case-insensitive text filter over the resource's primary display/search fields.", schema: { type: "string" }, }, { name: "status", in: "query", required: false, description: resource.statusValues ? `Status filter. Supported values: ${resource.statusValues.join(", ")}.` : "Ignored for resources without status.", schema: resource.statusValues ? { type: "string", enum: resource.statusValues } : { type: "string" }, }, { name: "ownerUserId", in: "query", required: false, description: "Owner/assignee filter where the resource has an owner-like field.", schema: { type: "string" }, }, { name: "createdSince", in: "query", required: false, description: "Inclusive ISO date-time lower bound for createdAt.", schema: { type: "string", format: "date-time" }, }, { name: "updatedSince", in: "query", required: false, description: "Inclusive ISO date-time lower bound for updatedAt.", schema: { type: "string", format: "date-time" }, }, ], responses: { "200": { description: `Cursor-paginated ${resource.name} page.`, headers: { "x-request-id": requestIdHeader }, content: { "application/json": { schema: { type: "object", properties: { data: { type: "array", items: { type: "object", additionalProperties: true, properties: Object.fromEntries(resource.fields.map((field) => [field, { oneOf: [{ type: "string" }, { type: "number" }, { type: "boolean" }, { type: "null" }] }])), }, }, pageInfo: { type: "object", properties: { limit: { type: "integer", minimum: 1, maximum: PUBLIC_API_MAX_LIMIT }, nextCursor: { type: ["string", "null"] }, sort: { type: "string" }, }, required: ["limit", "nextCursor", "sort"], }, meta: { type: "object", properties: { resource: { type: "string", enum: [resource.name] }, readOnly: { type: "boolean", const: true }, requestId: { type: "string" }, }, required: ["resource", "readOnly", "requestId"], }, }, required: ["data", "pageInfo", "meta"], }, }, }, }, "400": apiErrorResponse("Invalid list query.", ["invalid_limit", "invalid_cursor", "invalid_sort", "invalid_fields", "invalid_embed", "invalid_status", "invalid_created_since", "invalid_updated_since"]), "401": apiErrorResponse("Missing or invalid API key.", ["unauthorized"]), "402": apiErrorResponse("API usage is disabled or exhausted for the tenant plan.", ["payment_required"]), "403": apiErrorResponse("Tenant is inactive or the API key scope does not allow this operation.", ["tenant_inactive", "insufficient_scope"]), "429": apiErrorResponse("Hourly key or tenant rate limit exceeded.", ["rate_limit_exceeded"]), "500": apiErrorResponse("Read request failed with a redacted request-ID-correlated envelope.", ["public_api_read_failed"]), }, }, }, ]; }), ) as unknown as Record<`/v1/${(typeof PUBLIC_API_RESOURCE_NAMES)[number]}`, PublicApiOpenApiPathItem>; export const publicApiOpenApiPaths = { ...publicApiReadOpenApiPaths, "/v1/webhooks/incoming/{tenant}/{slug}": { post: { operationId: "receivePublicApiIncomingWebhook", description: "Tenant-scoped incoming lead webhook. Credentials are verified before payload, billing, or ingestion work. HMAC timestamps have a five-minute freshness window and exact signed replays are deduplicated through the persistent idempotency store. Successful requests create an InboxLead and queue webhook.received automation executions.", security: [{ apiKeyHeader: [] }, { webhookTokenHeader: [] }, { webhookHmac: [] }], parameters: [ { name: "tenant", in: "path", required: true, description: "Tenant id or slug addressed by the incoming webhook endpoint.", schema: { type: "string", minLength: 1 }, }, { name: "slug", in: "path", required: true, description: "Tenant-local incoming webhook endpoint slug.", schema: { type: "string", minLength: 1 }, }, { name: "x-api-key", in: "header", required: false, description: "Required when the endpoint auth mode is api_key. The key must include public_api:webhooks:incoming, public_api:read legacy scope does not grant writes.", schema: { type: "string" }, }, { name: "X-HiveGrid-Webhook-Token", in: "header", required: false, description: "Required for hmac and url_token endpoint modes. For hmac, this presented token is also the HMAC key and is validated against the stored hash.", schema: { type: "string" }, }, { name: "X-HiveGrid-Timestamp", in: "header", required: false, description: "Unix timestamp used in the HMAC signing input '.'. Required for hmac mode and accepted only within five minutes of server time.", schema: { type: "string" }, }, { name: "X-HiveGrid-Signature", in: "header", required: false, description: "HMAC-SHA256 signature in the form sha256=. Required for hmac endpoint mode.", schema: { type: "string" }, }, { name: "token", in: "query", required: false, description: "Alternative token transport for url_token endpoints.", schema: { type: "string" }, }, ], requestBody: { required: true, content: { "application/json": { schema: { type: "object", additionalProperties: true, description: "Lead payload. Payload mapping on the endpoint selects fields such as email, phone, firstName, lastName and message.", }, }, }, }, responses: { "201": { description: "Lead webhook accepted and persisted.", headers: { "x-request-id": requestIdHeader, "X-RateLimit-Limit": { schema: { type: "string" } }, "X-RateLimit-Remaining": { schema: { type: "string" } }, "X-RateLimit-Reset": { schema: { type: "string" } }, }, content: { "application/json": { schema: { type: "object", properties: { data: { type: "object", properties: { leadId: { type: "string" }, matchedKontaktId: { type: ["string", "null"] }, automationExecutionIds: { type: "array", items: { type: "string" } }, }, required: ["leadId", "matchedKontaktId", "automationExecutionIds"], }, meta: { type: "object", properties: { requestId: { type: "string" }, endpoint: { type: "string" }, }, required: ["requestId", "endpoint"], }, }, required: ["data", "meta"], }, }, }, }, "400": apiErrorResponse("Invalid JSON webhook payload.", ["invalid_json"]), "401": apiErrorResponse("Missing or invalid webhook credentials.", ["unauthorized"]), "402": apiErrorResponse("Tenant plan or billing state blocks webhook writes.", ["payment_required"]), "403": apiErrorResponse("API key scope does not allow incoming webhooks.", ["insufficient_scope"]), "404": apiErrorResponse("Tenant or incoming webhook endpoint was not found.", ["not_found"]), "409": apiErrorResponse("An identical HMAC webhook is already being processed or conflicts with its replay fingerprint.", ["webhook_in_progress", "webhook_replay_conflict"]), "429": apiErrorResponse("Hourly key or tenant rate limit exceeded.", ["rate_limit_exceeded"]), "500": apiErrorResponse("Webhook ingestion failed with a redacted request-ID-correlated envelope.", ["webhook_ingestion_failed"]), "503": apiErrorResponse("Persistent webhook replay protection is unavailable; ingestion fails closed.", ["webhook_replay_guard_unavailable"]), }, }, }, } satisfies Record; function capitalize(value: string) { return value.charAt(0).toUpperCase() + value.slice(1); }