🚀. Socket Launch Week Day 2:Introducing Manifest Alerts.Learn more
Sign In

@primitivedotdev/sdk

Package Overview
Dependencies
Maintainers
2
Versions
64
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@primitivedotdev/sdk - npm Package Compare versions

Comparing version
0.31.8
to
0.32.0
+245
dist/errors-7E9sW9eX.d.ts
import { M as WebhookAttachment, c as EmailAnalysis, l as EmailAuth, u as EmailReceivedEvent } from "./types-yNU-Oiea.js";
import { ErrorObject } from "ajv";
//#region src/webhook/received-email.d.ts
interface ReceivedEmailAddress {
address: string;
name: string | null;
}
interface ReceivedEmailThread {
messageId: string | null;
inReplyTo: string[];
references: string[];
}
interface ReceivedEmail {
id: string;
eventId: string;
receivedAt: string;
sender: ReceivedEmailAddress;
replyTarget: ReceivedEmailAddress;
receivedBy: string;
receivedByAll: string[];
subject: string | null;
replySubject: string;
forwardSubject: string;
text: string | null;
thread: ReceivedEmailThread;
attachments: WebhookAttachment[];
auth: EmailAuth;
analysis: EmailAnalysis;
raw: EmailReceivedEvent;
}
declare function normalizeReceivedEmail(event: EmailReceivedEvent): ReceivedEmail;
declare function buildReplySubject(subject: string | null | undefined): string;
declare function buildForwardSubject(subject: string | null | undefined): string;
declare function formatAddress(address: ReceivedEmailAddress): string;
declare function parseHeaderAddress(value: string | null | undefined): ReceivedEmailAddress | null;
//#endregion
//#region src/webhook/errors.d.ts
/**
* Verification error definitions.
* Use these for documentation, dashboards, and i18n.
*/
declare const VERIFICATION_ERRORS: {
readonly INVALID_SIGNATURE_HEADER: {
readonly message: "Missing or malformed Primitive-Signature header";
readonly suggestion: "Check that you're reading the correct header (Primitive-Signature) and it's being passed correctly from your web framework.";
};
readonly TIMESTAMP_OUT_OF_RANGE: {
readonly message: "Timestamp is too old (possible replay attack)";
readonly suggestion: "This could indicate a replay attack, network delay, or server clock drift. Check your server's time is synced.";
};
readonly SIGNATURE_MISMATCH: {
readonly message: "Signature doesn't match expected value";
readonly suggestion: "Verify the webhook secret matches and you're using the raw request body (not re-serialized JSON).";
};
readonly MISSING_SECRET: {
readonly message: "No webhook secret was provided";
readonly suggestion: "Pass your webhook secret from the Primitive dashboard. Check that the environment variable is set.";
};
};
/**
* Payload parsing error definitions.
* Use these for documentation, dashboards, and i18n.
*/
declare const PAYLOAD_ERRORS: {
readonly PAYLOAD_NULL: {
readonly message: "Webhook payload is null";
readonly suggestion: "Ensure you're passing the parsed JSON body, not null. Check your framework's body parsing middleware.";
};
readonly PAYLOAD_UNDEFINED: {
readonly message: "Webhook payload is undefined";
readonly suggestion: "The payload was not provided. Make sure you're passing the request body to the handler.";
};
readonly PAYLOAD_WRONG_TYPE: {
readonly message: "Webhook payload must be an object";
readonly suggestion: "The payload should be a parsed JSON object. Check that you're not passing a string or other primitive.";
};
readonly PAYLOAD_IS_ARRAY: {
readonly message: "Webhook payload is an array, expected object";
readonly suggestion: "Primitive webhooks are single event objects, not arrays. Check the payload structure.";
};
readonly PAYLOAD_MISSING_EVENT: {
readonly message: "Webhook payload missing 'event' field";
readonly suggestion: "All webhook payloads must have an 'event' field. This may not be a valid Primitive webhook.";
};
readonly PAYLOAD_UNKNOWN_EVENT: {
readonly message: "Unknown webhook event type";
readonly suggestion: "This event type is not recognized. You may need to update your SDK or handle unknown events gracefully.";
};
readonly PAYLOAD_EMPTY_BODY: {
readonly message: "Request body is empty";
readonly suggestion: "The request body was empty. Ensure the webhook is sending data and your framework is parsing it correctly.";
};
readonly JSON_PARSE_FAILED: {
readonly message: "Failed to parse JSON body";
readonly suggestion: "The request body is not valid JSON. Check the raw body content and Content-Type header.";
};
readonly INVALID_ENCODING: {
readonly message: "Invalid body encoding";
readonly suggestion: "The request body encoding is not supported. Primitive webhooks use UTF-8 encoded JSON.";
};
};
/**
* Raw email decode error definitions.
* Use these for documentation, dashboards, and i18n.
*/
declare const RAW_EMAIL_ERRORS: {
readonly NOT_INCLUDED: {
readonly message: "Raw email content not included inline";
readonly suggestion: "Use the download URL at event.email.content.download.url to fetch the raw email.";
};
readonly INVALID_BASE64: {
readonly message: "Raw email content is not valid base64";
readonly suggestion: "The raw email data is malformed. Fetch the raw email from the download URL or regenerate the webhook payload.";
};
readonly HASH_MISMATCH: {
readonly message: "SHA-256 hash verification failed";
readonly suggestion: "The raw email data may be corrupted. Try downloading from the URL instead.";
};
};
/**
* All error codes that can be thrown by the SDK.
*/
type WebhookErrorCode = WebhookVerificationErrorCode | WebhookPayloadErrorCode | WebhookValidationErrorCode | RawEmailDecodeErrorCode;
type RawEmailDecodeErrorCode = keyof typeof RAW_EMAIL_ERRORS;
/**
* Base class for all Primitive webhook errors.
*
* Catch this to handle any error from the SDK in a single catch block.
*
* @example
* ```typescript
* import { handleWebhook, PrimitiveWebhookError } from '@primitivedotdev/sdk';
*
* try {
* const event = handleWebhook({ body, headers, secret });
* } catch (err) {
* if (err instanceof PrimitiveWebhookError) {
* console.error(`[${err.code}] ${err.message}`);
* return res.status(400).json({ error: err.code });
* }
* throw err;
* }
* ```
*/
declare abstract class PrimitiveWebhookError extends Error {
/** Programmatic error code for monitoring and handling */
abstract readonly code: WebhookErrorCode;
/** Actionable guidance for fixing the issue */
abstract readonly suggestion: string;
/**
* Formats the error for logging/display.
*/
toString(): string;
/**
* Serializes cleanly for structured logging (Datadog, CloudWatch, etc.)
*/
toJSON(): {
name: string;
code: WebhookErrorCode;
message: string;
suggestion: string;
};
}
/**
* Error codes for webhook verification failures.
* Derived from VERIFICATION_ERRORS keys.
*/
type WebhookVerificationErrorCode = keyof typeof VERIFICATION_ERRORS;
/**
* Error thrown when webhook signature verification fails.
*
* Use the `code` property to programmatically handle specific error cases.
*/
declare class WebhookVerificationError extends PrimitiveWebhookError {
readonly code: WebhookVerificationErrorCode;
readonly suggestion: string;
constructor(code: WebhookVerificationErrorCode, message?: string, suggestion?: string);
}
/**
* Error codes for webhook payload parsing failures.
* Derived from PAYLOAD_ERRORS keys.
*/
type WebhookPayloadErrorCode = keyof typeof PAYLOAD_ERRORS;
/**
* Error thrown when webhook payload parsing fails (lightweight parser).
*
* Use the `code` property for programmatic handling and monitoring.
* The `suggestion` property contains actionable guidance for fixing the issue.
*/
declare class WebhookPayloadError extends PrimitiveWebhookError {
readonly code: WebhookPayloadErrorCode;
readonly suggestion: string;
/** Original error if this wraps another error (e.g., JSON.parse failure) */
readonly cause?: Error;
constructor(code: WebhookPayloadErrorCode, message?: string, suggestion?: string, cause?: Error);
}
/**
* Error code for schema validation failures.
*/
type WebhookValidationErrorCode = "SCHEMA_VALIDATION_FAILED";
/**
* Error thrown when schema validation fails.
*/
declare class WebhookValidationError extends PrimitiveWebhookError {
readonly code: WebhookValidationErrorCode;
readonly suggestion: string;
/** The specific field path that failed (e.g., "email.headers.from") */
readonly field: string;
/** Original schema validation errors for advanced debugging */
readonly validationErrors: readonly ErrorObject[];
/** Number of additional validation errors beyond the first */
readonly additionalErrorCount: number;
constructor(field: string, message: string, suggestion: string, validationErrors: readonly ErrorObject[]);
/**
* Formats the error for logging/display.
* Includes error count and suggestion.
*/
toString(): string;
/**
* Serializes cleanly for structured logging (Datadog, CloudWatch, etc.)
*/
toJSON(): {
name: string;
code: "SCHEMA_VALIDATION_FAILED";
field: string;
message: string;
suggestion: string;
additionalErrorCount: number;
};
}
/**
* Error thrown when raw email decoding or verification fails.
*
* Use the `code` property to determine the failure reason:
* - `NOT_INCLUDED`: Raw email not inline, must download from URL
* - `HASH_MISMATCH`: SHA-256 verification failed, content may be corrupted
*/
declare class RawEmailDecodeError extends PrimitiveWebhookError {
readonly code: RawEmailDecodeErrorCode;
readonly suggestion: string;
constructor(code: RawEmailDecodeErrorCode, message?: string);
}
//#endregion
export { buildForwardSubject as _, RawEmailDecodeErrorCode as a, normalizeReceivedEmail as b, WebhookPayloadError as c, WebhookValidationErrorCode as d, WebhookVerificationError as f, ReceivedEmailThread as g, ReceivedEmailAddress as h, RawEmailDecodeError as i, WebhookPayloadErrorCode as l, ReceivedEmail as m, PrimitiveWebhookError as n, VERIFICATION_ERRORS as o, WebhookVerificationErrorCode as p, RAW_EMAIL_ERRORS as r, WebhookErrorCode as s, PAYLOAD_ERRORS as t, WebhookValidationError as u, buildReplySubject as v, parseHeaderAddress as x, formatAddress as y };

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display

//#region src/types.generated.d.ts
/**
* Types for Primitive webhook payloads.
*
* AUTO-GENERATED - DO NOT EDIT
* Run `pnpm generate:types` to regenerate.
*/
/**
* Result for a single forwarded email detected in the message.
*
* Use the `type` and `analyzed` fields to narrow the type:
* - `type: 'inline'` - Inline forward, always analyzed
* - `type: 'attachment'` + `analyzed: true` - Analyzed attachment
* - `type: 'attachment'` + `analyzed: false` - Skipped attachment
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardResult".
*/
type ForwardResult$1 = (ForwardResultInline$1 | ForwardResultAttachmentAnalyzed$1 | ForwardResultAttachmentSkipped$1);
/**
* Webhook payload for the `email.received` event.
*
* This is delivered to your webhook endpoint when Primitive receives an email matching your domain configuration.
*/
interface EmailReceivedEvent$1 {
/**
* Unique delivery event ID.
*
* This ID is stable across retries to the same endpoint - use it as your idempotency/dedupe key. Note that the same email delivered to different endpoints will have different event IDs.
*
* Format: `evt_` prefix followed by a SHA-256 hash (64 hex characters). Example: `evt_a1b2c3d4e5f6...` (68 characters total)
*/
id: string;
/**
* Event type identifier. Always `"email.received"` for this event type.
*/
event: "email.received";
/**
* API version in date format (YYYY-MM-DD). Use this to detect version mismatches between webhook and SDK.
*/
version: string;
/**
* Metadata about this webhook delivery.
*/
delivery: {
/**
* ID of the webhook endpoint receiving this event. Matches the endpoint ID from your Primitive dashboard.
*/
endpoint_id: string;
/**
* Delivery attempt number, starting at 1. Increments with each retry if previous attempts failed.
*/
attempt: number;
/**
* ISO 8601 timestamp (UTC) when this delivery was attempted.
*/
attempted_at: string;
};
/**
* The email that triggered this event.
*/
email: {
/**
* Unique email ID in Primitive. Use this ID when calling Primitive APIs to reference this email.
*/
id: string;
/**
* Conversation thread this email belongs to. Inbound and outbound messages in the same conversation share a thread_id; fetch GET /v1/threads/{thread_id} for the full thread. Null on messages received before threading was enabled.
*/
thread_id?: (string | null);
/**
* ISO 8601 timestamp (UTC) when Primitive received the email.
*/
received_at: string;
/**
* SMTP envelope information. This is the "real" sender/recipient info from the SMTP transaction, which may differ from the headers (e.g., BCC recipients).
*/
smtp: {
/**
* HELO/EHLO hostname from the sending server. Null if not provided during SMTP transaction.
*/
helo: (string | null);
/**
* SMTP envelope sender (MAIL FROM command). This is the bounce address, which may differ from the From header.
*/
mail_from: string;
/**
* SMTP envelope recipients (RCPT TO commands). All addresses that received this email in a single delivery.
*
* @minItems 1
*/
rcpt_to: [string, ...(string)[]];
};
/**
* Parsed email headers. These are extracted from the email content, not the SMTP envelope.
*/
headers: {
/**
* Message-ID header value. Null if the email had no Message-ID header.
*/
message_id: (string | null);
/**
* Subject header value. Null if the email had no Subject header.
*/
subject: (string | null);
/**
* From header value. May include display name: `"John Doe" <john@example.com>`
*/
from: string;
/**
* To header value. May include multiple addresses or display names.
*/
to: string;
/**
* Date header value as it appeared in the email. Null if the email had no Date header.
*/
date: (string | null);
};
/**
* Raw email content and download information.
*/
content: {
/**
* Raw email in RFC 5322 format. May be inline (base64) or download-only depending on size.
*/
raw: (RawContentInline$1 | RawContentDownloadOnly$1);
/**
* Download information for the raw email. Always present, even if raw content is inline.
*/
download: {
/**
* URL to download the raw email as-is in RFC 5322 format. Managed Primitive always issues HTTPS. Self-host deployments may issue HTTP URLs that resolve inside the operator's network (e.g. `http://localhost:4001/...`). Receivers that want to refuse plaintext downloads should check the scheme explicitly.
*/
url: string;
/**
* ISO 8601 timestamp (UTC) when this URL expires. Download before this time or the URL will return 403.
*/
expires_at: string;
};
};
/**
* Parsed email content (body text, HTML, attachments). Check `status` to determine if parsing succeeded.
*/
parsed: (ParsedDataComplete$1 | ParsedDataFailed$1);
analysis: EmailAnalysis$1;
auth: EmailAuth$1;
};
}
/**
* Raw email content included inline (base64 encoded).
*
* When the raw email is small enough (under {@link max_inline_bytes } ), it's included directly in the webhook payload for convenience.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "RawContentInline".
*/
interface RawContentInline$1 {
/**
* Discriminant indicating raw content is included inline.
*/
included: true;
/**
* Encoding used for the data field. Always "base64".
*/
encoding: "base64";
/**
* Maximum size in bytes for inline inclusion. Emails larger than this threshold require download.
*/
max_inline_bytes: number;
/**
* Actual size of the raw email in bytes.
*/
size_bytes: number;
/**
* SHA-256 hash of the raw email content (hex-encoded). Use this to verify integrity after base64 decoding.
*/
sha256: string;
/**
* Base64-encoded raw email (RFC 5322 format). Decode with `Buffer.from(data, 'base64')` in Node.js.
*/
data: string;
}
/**
* Raw email content not included (must be downloaded).
*
* When the raw email exceeds {@link max_inline_bytes } , it's not included in the webhook payload. Use the download URL from {@link EmailReceivedEvent.email.content.download } to fetch it.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "RawContentDownloadOnly".
*/
interface RawContentDownloadOnly$1 {
/**
* Discriminant indicating raw content must be downloaded.
*/
included: false;
/**
* Reason the content wasn't included inline.
*/
reason_code: "size_exceeded";
/**
* Maximum size in bytes for inline inclusion. The email exceeded this threshold.
*/
max_inline_bytes: number;
/**
* Actual size of the raw email in bytes.
*/
size_bytes: number;
/**
* SHA-256 hash of the raw email content (hex-encoded). Use this to verify integrity after download.
*/
sha256: string;
}
/**
* Parsed email content when parsing succeeded.
*
* Use the discriminant `status: "complete"` to narrow from {@link ParsedData } .
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ParsedDataComplete".
*/
interface ParsedDataComplete$1 {
/**
* Discriminant indicating successful parsing.
*/
status: "complete";
/**
* Always null when parsing succeeds.
*/
error: null;
/**
* Plain text body of the email. Null if the email had no text/plain part.
*/
body_text: (string | null);
/**
* HTML body of the email. Null if the email had no text/html part.
*/
body_html: (string | null);
/**
* Parsed Reply-To header addresses. Null if the email had no Reply-To header.
*/
reply_to: (EmailAddress$1[] | null);
/**
* Parsed CC header addresses. Null if the email had no CC header.
*/
cc: (EmailAddress$1[] | null);
/**
* Parsed BCC header addresses. Null if the email had no BCC header. Note: BCC is only available for outgoing emails or when explicitly provided.
*/
bcc: (EmailAddress$1[] | null);
/**
* Parsed To header addresses. Null if the email had no To header.
*/
to_addresses: (EmailAddress$1[] | null);
/**
* In-Reply-To header values (Message-IDs of the email(s) being replied to). Null if the email had no In-Reply-To header. Per RFC 5322, this can contain multiple Message-IDs, though typically just one.
*/
in_reply_to: (string[] | null);
/**
* References header values (Message-IDs of the email thread). Null if the email had no References header.
*/
references: (string[] | null);
/**
* List of attachments with metadata. Use {@link attachments_download_url } to download the actual files.
*/
attachments: WebhookAttachment$1[];
/**
* URL to download all attachments as a tar.gz archive. Null if the email had no attachments. Managed Primitive always issues HTTPS. Self-host deployments may issue HTTP URLs that resolve inside the operator's network. URL expires - check the expiration before downloading.
*/
attachments_download_url: (string | null);
}
/**
* A parsed email address with optional display name.
*
* This structure is used in the `parsed` section of the webhook payload (e.g., `reply_to`, `cc`, `bcc`). For unparsed header strings, see the `headers` section (e.g., `event.email.headers.from`).
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "EmailAddress".
*/
interface EmailAddress$1 {
/**
* The email address portion (e.g., "john@example.com").
*
* This is the raw value from the email header with no validation applied. May contain unusual but valid formats like quoted local parts.
*/
address: string;
/**
* The display name portion, if present. Null if the address had no display name.
*
* May contain any characters including unicode, emoji, or special characters as they appeared in the original email header.
*/
name: (string | null);
}
/**
* Metadata for an email attachment.
*
* Attachment content is not included directly in the webhook payload. Use the `attachments_download_url` from {@link ParsedDataComplete } to download all attachments as a tar.gz archive.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "WebhookAttachment".
*/
interface WebhookAttachment$1 {
/**
* Original filename from the email. May be null if the attachment had no filename specified.
*/
filename: (string | null);
/**
* MIME content type (e.g., "application/pdf", "image/png").
*/
content_type: string;
/**
* Size of the attachment in bytes.
*/
size_bytes: number;
/**
* SHA-256 hash of the attachment content (hex-encoded). Use this to verify attachment integrity after download.
*/
sha256: string;
/**
* Zero-based index of this part in the MIME structure.
*/
part_index: number;
/**
* Path to this attachment within the downloaded tar.gz archive.
*/
tar_path: string;
}
/**
* Parsed email content when parsing failed.
*
* Use the discriminant `status: "failed"` to narrow from {@link ParsedData } .
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ParsedDataFailed".
*/
interface ParsedDataFailed$1 {
/**
* Discriminant indicating parsing failed.
*/
status: "failed";
error: ParsedError$1;
/**
* Always null when parsing fails.
*/
body_text: null;
/**
* Always null when parsing fails.
*/
body_html: null;
/**
* Always null when parsing fails.
*/
reply_to: null;
/**
* Always null when parsing fails.
*/
cc: null;
/**
* Always null when parsing fails.
*/
bcc: null;
/**
* Always null when parsing fails.
*/
to_addresses: null;
/**
* Always null when parsing fails.
*/
in_reply_to: null;
/**
* Always null when parsing fails.
*/
references: null;
/**
* May contain partial attachment metadata even when parsing failed. Useful for debugging or recovering partial data.
*/
attachments: WebhookAttachment$1[];
/**
* Always null when parsing fails.
*/
attachments_download_url: null;
}
/**
* Details about why parsing failed.
*/
interface ParsedError$1 {
/**
* Error code indicating the type of failure.
* - `PARSE_FAILED`: The email could not be parsed (e.g., malformed MIME)
* - `ATTACHMENT_EXTRACTION_FAILED`: Email parsed but attachments couldn't be extracted
*/
code: ("PARSE_FAILED" | "ATTACHMENT_EXTRACTION_FAILED");
/**
* Human-readable error message describing what went wrong.
*/
message: string;
/**
* Whether retrying might succeed. If true, the error was transient (e.g., timeout). If false, the email itself is problematic.
*/
retryable: boolean;
}
/**
* Email analysis and classification results.
*/
interface EmailAnalysis$1 {
/**
* SpamAssassin analysis results.
*
* Optional. Present when the email was processed by a SpamAssassin-equipped pipeline (always present in Primitive's managed service). When absent, spam scoring was not performed on this email.
*/
spamassassin?: {
/**
* Overall spam score (sum of all rule scores). Higher scores indicate higher likelihood of spam. Unbounded - can be negative (ham) or very high (spam).
*/
score: number;
};
forward?: ForwardAnalysis$1;
}
/**
* Forward detection and analysis results.
*
* Optional. Present when the email was processed by a forward-detection pipeline (always present in Primitive's managed service). When absent, forward detection was not performed on this email.
*/
interface ForwardAnalysis$1 {
/**
* Whether any forwards were detected in the email.
*/
detected: boolean;
/**
* Analysis results for each detected forward.
*/
results: ForwardResult$1[];
/**
* Total number of .eml attachments found.
*/
attachments_found: number;
/**
* Number of .eml attachments that were analyzed.
*/
attachments_analyzed: number;
/**
* Maximum number of attachments that will be analyzed, or null if unlimited.
*/
attachments_limit: (number | null);
}
/**
* Result for an inline forward that was detected and analyzed. Inline forwards are always analyzed when forward detection is enabled.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardResultInline".
*/
interface ForwardResultInline$1 {
type: "inline";
/**
* Original sender of the forwarded email, if extractable.
*/
original_sender: (ForwardOriginalSender$1 | null);
verification: ForwardVerification$1;
/**
* Human-readable summary of the forward analysis.
*/
summary: string;
}
/**
* Original sender information extracted from the forwarded email.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardOriginalSender".
*/
interface ForwardOriginalSender$1 {
/**
* Email address of the original sender.
*/
email: string;
/**
* Domain of the original sender.
*/
domain: string;
}
/**
* Verification result for the forwarded email.
*/
interface ForwardVerification$1 {
/**
* Overall verdict on whether the forward is authentic.
*/
verdict: ("legit" | "unknown");
/**
* Confidence level for this verdict.
*/
confidence: ("high" | "medium" | "low");
/**
* Whether a valid DKIM signature was found that verifies the original sender.
*/
dkim_verified: boolean;
/**
* Domain of the DKIM signature that verified the forward, if any.
*/
dkim_domain: (string | null);
/**
* DMARC policy of the original sender's domain.
*/
dmarc_policy: ("reject" | "quarantine" | "none" | null);
}
/**
* Result for an attachment forward that was analyzed.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardResultAttachmentAnalyzed".
*/
interface ForwardResultAttachmentAnalyzed$1 {
type: "attachment";
/**
* Path to the attachment in the attachments tar archive.
*/
attachment_tar_path: string;
/**
* Original filename of the attachment, if available.
*/
attachment_filename: (string | null);
/**
* Whether this attachment was analyzed.
*/
analyzed: true;
/**
* Original sender of the forwarded email, if extractable.
*/
original_sender: (ForwardOriginalSender$1 | null);
verification: ForwardVerification1;
/**
* Human-readable summary of the forward analysis.
*/
summary: string;
}
/**
* Verification result for the forwarded email.
*/
interface ForwardVerification1 {
/**
* Overall verdict on whether the forward is authentic.
*/
verdict: ("legit" | "unknown");
/**
* Confidence level for this verdict.
*/
confidence: ("high" | "medium" | "low");
/**
* Whether a valid DKIM signature was found that verifies the original sender.
*/
dkim_verified: boolean;
/**
* Domain of the DKIM signature that verified the forward, if any.
*/
dkim_domain: (string | null);
/**
* DMARC policy of the original sender's domain.
*/
dmarc_policy: ("reject" | "quarantine" | "none" | null);
}
/**
* Result for an attachment forward that was detected but not analyzed. This occurs when attachment analysis is disabled or the limit was reached.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardResultAttachmentSkipped".
*/
interface ForwardResultAttachmentSkipped$1 {
type: "attachment";
/**
* Path to the attachment in the attachments tar archive.
*/
attachment_tar_path: string;
/**
* Original filename of the attachment, if available.
*/
attachment_filename: (string | null);
/**
* Whether this attachment was analyzed.
*/
analyzed: false;
/**
* Always null when not analyzed.
*/
original_sender: null;
/**
* Always null when not analyzed.
*/
verification: null;
/**
* Human-readable summary explaining why analysis was skipped.
*/
summary: string;
}
/**
* Email authentication results (SPF, DKIM, DMARC).
*/
interface EmailAuth$1 {
/**
* SPF verification result.
*
* SPF checks if the sending IP is authorized by the envelope sender's domain. "pass" means the IP is authorized; "fail" means it's explicitly not allowed.
*/
spf: ("pass" | "fail" | "softfail" | "neutral" | "none" | "temperror" | "permerror");
/**
* DMARC verification result.
*
* DMARC passes if either SPF or DKIM passes AND aligns with the From: domain. "pass" means the email is authenticated according to the sender's policy.
*/
dmarc: ("pass" | "fail" | "none" | "temperror" | "permerror");
/**
* DMARC policy from the sender's DNS record.
*
* - `reject`: Domain wants receivers to reject failing emails
* - `quarantine`: Domain wants failing emails marked as suspicious
* - `none`: Domain is monitoring only (no action requested)
* - `null`: No DMARC record found for this domain
*/
dmarcPolicy: ("reject" | "quarantine" | "none" | null);
/**
* The organizational domain used for DMARC lookups.
*
* For example, if the From: address is `user@mail.example.com`, the DMARC lookup checks `_dmarc.mail.example.com`, then falls back to `_dmarc.example.com`. This field shows which domain's policy was used.
*/
dmarcFromDomain: (string | null);
/**
* Whether SPF aligned with the From: domain for DMARC purposes.
*
* True if the envelope sender domain matches the From: domain (per alignment mode).
*/
dmarcSpfAligned: boolean;
/**
* Whether DKIM aligned with the From: domain for DMARC purposes.
*
* True if at least one DKIM signature's domain matches the From: domain.
*/
dmarcDkimAligned: boolean;
/**
* Whether DMARC SPF alignment mode is strict.
*
* - `true`: Strict alignment required (exact domain match)
* - `false`: Relaxed alignment allowed (organizational domain match)
* - `null`: No DMARC record found
*/
dmarcSpfStrict: (boolean | null);
/**
* Whether DMARC DKIM alignment mode is strict.
*
* - `true`: Strict alignment required (exact domain match)
* - `false`: Relaxed alignment allowed (organizational domain match)
* - `null`: No DMARC record found
*/
dmarcDkimStrict: (boolean | null);
/**
* All DKIM signatures found in the email with their verification results.
*
* May be empty if no DKIM signatures were present.
*/
dkimSignatures: DkimSignature$1[];
}
/**
* Details about a single DKIM signature found in the email.
*
* An email may have multiple DKIM signatures (e.g., one from the sending domain and one from the ESP). Each signature is verified independently.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "DkimSignature".
*/
interface DkimSignature$1 {
/**
* The domain that signed this DKIM signature (d= tag). This may differ from the From: domain (that's what alignment checks).
*/
domain: string;
/**
* The DKIM selector used to locate the public key (s= tag). Combined with the domain to form the DNS lookup: `selector._domainkey.domain`
*
* Optional in self-hosted environments where the milter may not provide selector info.
*/
selector: (string | null);
/**
* Verification result for this specific signature.
*/
result: ("pass" | "fail" | "temperror" | "permerror");
/**
* Whether this signature's domain aligns with the From: domain (for DMARC).
*
* Alignment can be "strict" (exact match) or "relaxed" (organizational domain match). For example, if From: is `user@sub.example.com` and DKIM is signed by `example.com`:
* - Relaxed alignment: true (same organizational domain)
* - Strict alignment: false (not exact match)
*/
aligned: boolean;
/**
* Key size in bits (e.g., 1024, 2048). Null if the key size couldn't be determined.
*
* Optional in self-hosted environments.
*/
keyBits: (number | null);
/**
* Signing algorithm (e.g., "rsa-sha256", "ed25519-sha256").
*
* Optional in self-hosted environments.
*/
algo: (string | null);
}
//#endregion
//#region src/types.d.ts
type EmailReceivedEvent = EmailReceivedEvent$1;
type EventType = EmailReceivedEvent["event"];
declare const EventType: {
readonly EmailReceived: "email.received";
};
type RawContent = EmailReceivedEvent["email"]["content"]["raw"];
type RawContentInline = Extract<RawContent, {
included: true;
}>;
type RawContentDownloadOnly = Extract<RawContent, {
included: false;
}>;
type ParsedData = EmailReceivedEvent["email"]["parsed"];
type ParsedDataComplete = Extract<ParsedData, {
status: "complete";
}>;
type ParsedDataFailed = Extract<ParsedData, {
status: "failed";
}>;
type ParsedStatus = ParsedData["status"];
declare const ParsedStatus: {
readonly Complete: "complete";
readonly Failed: "failed";
};
type ParsedError = ParsedDataFailed["error"];
type EmailAddress = NonNullable<ParsedDataComplete["reply_to"]>[number];
type WebhookAttachment = ParsedDataComplete["attachments"][number];
type EmailAnalysis = EmailReceivedEvent["email"]["analysis"];
type ForwardAnalysis = NonNullable<EmailAnalysis["forward"]>;
type ForwardResult = ForwardAnalysis["results"][number];
type ForwardResultInline = Extract<ForwardResult, {
type: "inline";
}>;
type ForwardResultAttachmentAnalyzed = Extract<ForwardResult, {
type: "attachment";
analyzed: true;
}>;
type ForwardResultAttachmentSkipped = Extract<ForwardResult, {
type: "attachment";
analyzed: false;
}>;
type ForwardOriginalSender = NonNullable<ForwardResultInline["original_sender"]>;
type ForwardVerification = NonNullable<ForwardResultInline["verification"]>;
type ForwardVerdict = ForwardVerification["verdict"];
declare const ForwardVerdict: {
readonly Legit: "legit";
readonly Unknown: "unknown";
};
type EmailAuth = EmailReceivedEvent["email"]["auth"];
type DkimSignature = EmailAuth["dkimSignatures"][number];
type SpfResult = EmailAuth["spf"];
declare const SpfResult: {
readonly Pass: "pass";
readonly Fail: "fail";
readonly Softfail: "softfail";
readonly Neutral: "neutral";
readonly None: "none";
readonly Temperror: "temperror";
readonly Permerror: "permerror";
};
type DmarcResult = EmailAuth["dmarc"];
declare const DmarcResult: {
readonly Pass: "pass";
readonly Fail: "fail";
readonly None: "none";
readonly Temperror: "temperror";
readonly Permerror: "permerror";
};
type DmarcPolicy = EmailAuth["dmarcPolicy"];
declare const DmarcPolicy: {
readonly Reject: "reject";
readonly Quarantine: "quarantine";
readonly None: "none";
};
type DkimResult = DkimSignature["result"];
declare const DkimResult: {
readonly Pass: "pass";
readonly Fail: "fail";
readonly Temperror: "temperror";
readonly Permerror: "permerror";
};
type AuthConfidence = ForwardVerification["confidence"];
declare const AuthConfidence: {
readonly High: "high";
readonly Medium: "medium";
readonly Low: "low";
};
type AuthVerdict = "legit" | "suspicious" | "unknown";
declare const AuthVerdict: {
readonly Legit: "legit";
readonly Suspicious: "suspicious";
readonly Unknown: "unknown";
};
interface ValidateEmailAuthResult {
verdict: AuthVerdict;
confidence: AuthConfidence;
reasons: string[];
}
declare const unknownEventTypeBrand: unique symbol;
type UnknownEventType = string & {
readonly [unknownEventTypeBrand]: true;
};
interface UnknownEvent {
event: UnknownEventType;
id?: string;
version?: string;
[key: string]: unknown;
}
type KnownWebhookEvent = EmailReceivedEvent;
type WebhookEvent = KnownWebhookEvent | UnknownEvent;
//#endregion
export { UnknownEvent as A, ParsedDataFailed as C, RawContentDownloadOnly as D, RawContent as E, WebhookAttachment as M, WebhookEvent as N, RawContentInline as O, ParsedDataComplete as S, ParsedStatus as T, ForwardResultInline as _, DmarcPolicy as a, KnownWebhookEvent as b, EmailAnalysis as c, EventType as d, ForwardAnalysis as f, ForwardResultAttachmentSkipped as g, ForwardResultAttachmentAnalyzed as h, DkimSignature as i, ValidateEmailAuthResult as j, SpfResult as k, EmailAuth as l, ForwardResult as m, AuthVerdict as n, DmarcResult as o, ForwardOriginalSender as p, DkimResult as r, EmailAddress as s, AuthConfidence as t, EmailReceivedEvent as u, ForwardVerdict as v, ParsedError as w, ParsedData as x, ForwardVerification as y };

Sorry, the diff of this file is too big to display

+3
-3

@@ -1,5 +0,5 @@

import { $ as listFunctionLogs, $a as ListSentEmailsResponses, $c as RequestResult, $i as GetWebhookSecretResponse, $n as DeliveryStatus, $o as SendMailInput, $r as FunctionTestRunReply, $s as UpdateAccountErrors, $t as CreateEndpointErrors, A as deleteEndpoint, Aa as ListFiltersError, Ac as VerifyAgentSignupErrors, Ai as GetSendPermissionsData, An as DeleteEmailErrors, Ao as ResendCliSignupVerificationData, Ar as EmailDetailReply, As as StartCliSignupErrors, At as AddDomainError, B as getFunction, Ba as ListFunctionSecretsError, Bc as VerifyDomainData, Bi as GetStorageStatsData, Bn as DeleteFilterErrors, Bo as RotateWebhookSecretResponse, Br as ErrorResponse, Bs as TestEndpointResponses, Bt as CliLoginStartResult, C as cliLogout, Ca as ListEndpointsData, Cc as UpdateFunctionErrors, Ci as GetFunctionTestRunTraceResponse, Cn as DeleteDomainData, Co as ReplyToEmailResponses, Cr as DownloadRawEmailErrors, Cs as StartCliLoginError, Ct as updateFunction, D as createFunctionSecret, Da as ListEndpointsResponses, Dc as VerifiedDomain, Di as GetInboxStatusErrors, Dn as DeleteDomainResponses, Do as ResendAgentSignupVerificationInput, Dr as EmailAttachment, Ds as StartCliLoginResponses, Dt as Account, E as createFunction, Ea as ListEndpointsResponse, Ec as UpdateFunctionResponses, Ei as GetInboxStatusError, En as DeleteDomainResponse, Eo as ResendAgentSignupVerificationErrors, Er as EmailAddress, Es as StartCliLoginResponse, Et as verifyDomain, F as downloadAttachments, Fa as ListFunctionLogsError, Fc as VerifyCliSignupError, Fi as GetSentEmailData, Fn as DeleteEndpointErrors, Fo as ResendCliSignupVerificationResponses, Fr as EmailSearchResult, Fs as SuccessEnvelope, Ft as AgentOrgRef, G as getStorageStats, Ga as ListFunctionsError, Gc as WebhookSecret, Gi as GetThreadData, Gn as DeleteFunctionErrors, Go as SearchEmailsResponse, Gr as FunctionLogRow, Gs as TestFunctionResponses, Gt as CliLogoutResponse, H as getInboxStatus, Ha as ListFunctionSecretsResponse, Hc as VerifyDomainErrors, Hi as GetStorageStatsErrors, Hn as DeleteFilterResponses, Ho as SearchEmailsData, Hr as FunctionDeployStatus, Hs as TestFunctionError, Ht as CliLogoutError, I as downloadDomainZoneFile, Ia as ListFunctionLogsErrors, Ic as VerifyCliSignupErrors, Ii as GetSentEmailError, In as DeleteEndpointResponse, Io as ResourceId, Ir as EmailStatus, Is as TestEndpointData, It as AgentSignupResendResult, J as listDeliveries, Ja as ListFunctionsResponses, Jc as ClientOptions, Ji as GetThreadResponse, Jn as DeleteFunctionSecretData, Jo as SendEmailError, Jr as FunctionTestRun, Js as Thread, Jt as CliSignupResendResult, K as getThread, Ka as ListFunctionsErrors, Kc as createClient, Ki as GetThreadError, Kn as DeleteFunctionResponse, Ko as SearchEmailsResponses, Kr as FunctionSecretListItem, Ks as TestInvocationResult, Kt as CliLogoutResponses, L as downloadRawEmail, La as ListFunctionLogsResponse, Lc as VerifyCliSignupInput, Li as GetSentEmailErrors, Ln as DeleteEndpointResponses, Lo as RotateWebhookSecretData, Lr as EmailSummary, Ls as TestEndpointError, Lt as AgentSignupStartResult, M as deleteFunction, Ma as ListFiltersResponse, Mc as VerifyAgentSignupResponse, Mi as GetSendPermissionsErrors, Mn as DeleteEmailResponses, Mo as ResendCliSignupVerificationErrors, Mr as EmailSearchFacets, Ms as StartCliSignupResponse, Mt as AddDomainInput, N as deleteFunctionSecret, Na as ListFiltersResponses, Nc as VerifyAgentSignupResponses, Ni as GetSendPermissionsResponse, Nn as DeleteEndpointData, No as ResendCliSignupVerificationInput, Nr as EmailSearchHighlights, Ns as StartCliSignupResponses, Nt as AddDomainResponse, O as deleteDomain, Oa as ListEnvelope, Oc as VerifyAgentSignupData, Oi as GetInboxStatusResponse, On as DeleteEmailData, Oo as ResendAgentSignupVerificationResponse, Or as EmailAuth, Os as StartCliSignupData, Ot as AccountUpdated, P as discardEmailContent, Pa as ListFunctionLogsData, Pc as VerifyCliSignupData, Pi as GetSendPermissionsResponses, Pn as DeleteEndpointError, Po as ResendCliSignupVerificationResponse, Pr as EmailSearchMeta, Ps as StorageStats, Pt as AddDomainResponses, Q as listFilters, Qa as ListSentEmailsResponse, Qc as RequestOptions, Qi as GetWebhookSecretErrors, Qn as DeleteFunctionSecretResponses, Qo as SendMailAttachment, Qr as FunctionTestRunOutboundRequest, Qs as UpdateAccountError, Qt as CreateEndpointError, R as getAccount, Ra as ListFunctionLogsResponses, Rc as VerifyCliSignupResponse, Ri as GetSentEmailResponse, Rn as DeleteFilterData, Ro as RotateWebhookSecretError, Rr as EmailWebhookStatus, Rs as TestEndpointErrors, Rt as AgentSignupVerifyResult, S as addDomain, Sa as ListEmailsResponses, Sc as UpdateFunctionError, Si as GetFunctionTestRunTraceErrors, Sn as Cursor, So as ReplyToEmailResponse, Sr as DownloadRawEmailError, Ss as StartCliLoginData, St as updateFilter, T as createFilter, Ta as ListEndpointsErrors, Tc as UpdateFunctionResponse, Ti as GetInboxStatusData, Tn as DeleteDomainErrors, To as ResendAgentSignupVerificationError, Tr as DownloadRawEmailResponses, Ts as StartCliLoginInput, Tt as verifyCliSignup, U as getSendPermissions, Ua as ListFunctionSecretsResponses, Uc as VerifyDomainResponse, Ui as GetStorageStatsResponse, Un as DeleteFunctionData, Uo as SearchEmailsError, Ur as FunctionDetail, Us as TestFunctionErrors, Ut as CliLogoutErrors, V as getFunctionTestRunTrace, Va as ListFunctionSecretsErrors, Vc as VerifyDomainError, Vi as GetStorageStatsError, Vn as DeleteFilterResponse, Vo as RotateWebhookSecretResponses, Vr as Filter, Vs as TestFunctionData, Vt as CliLogoutData, W as getSentEmail, Wa as ListFunctionsData, Wc as VerifyDomainResponses, Wi as GetStorageStatsResponses, Wn as DeleteFunctionError, Wo as SearchEmailsErrors, Wr as FunctionListItem, Ws as TestFunctionResponse, Wt as CliLogoutInput, X as listEmails, Xa as ListSentEmailsError, Xc as CreateClientConfig, Xi as GetWebhookSecretData, Xn as DeleteFunctionSecretErrors, Xo as SendEmailResponse, Xr as FunctionTestRunDeliveryEndpoint, Xs as UnverifiedDomain, Xt as CliSignupVerifyResult, Y as listDomains, Ya as ListSentEmailsData, Yc as Config, Yi as GetThreadResponses, Yn as DeleteFunctionSecretError, Yo as SendEmailErrors, Yr as FunctionTestRunDelivery, Ys as ThreadMessage, Yt as CliSignupStartResult, Z as listEndpoints, Za as ListSentEmailsErrors, Zc as Options, Zi as GetWebhookSecretError, Zn as DeleteFunctionSecretResponse, Zo as SendEmailResponses, Zr as FunctionTestRunInboundEmail, Zs as UpdateAccountData, Zt as CreateEndpointData, _ as PrimitiveApiClientOptions, _a as ListDomainsResponses, _c as UpdateFilterErrors, _i as GetFunctionErrors, _n as CreateFunctionSecretError, _o as ReplayEmailWebhooksResponses, _r as DownloadDomainZoneFileError, _s as StartAgentSignupError, _t as testEndpoint, a as RequestOptions$2, aa as InboxStatusNextAction, ac as UpdateDomainErrors, ai as GetAccountData, an as CreateFilterErrors, ao as PollCliLoginInput, ar as DiscardEmailContentResponse, as as SendPermissionYourDomain, at as replayEmailWebhooks, b as RequestOptions$1, ba as ListEmailsErrors, bc as UpdateFilterResponses, bi as GetFunctionTestRunTraceData, bn as CreateFunctionSecretResponse, bo as ReplyToEmailError, br as DownloadDomainZoneFileResponses, bs as StartAgentSignupResponse, bt as updateDomain, c as SendThreadInput, ca as ListDeliveriesData, cc as UpdateDomainResponses, ci as GetAccountResponse, cn as CreateFilterResponses, co as ReplayDeliveryData, cr as Domain, cs as SentEmailStatus, ct as resendCliSignupVerification, d as PRIMITIVE_SIGNATURE_HEADER, da as ListDeliveriesResponse, dc as UpdateEndpointErrors, di as GetEmailError, dn as CreateFunctionErrors, do as ReplayDeliveryResponse, dr as DownloadAttachmentsData, ds as SetFunctionSecretError, dt as searchEmails, ea as GetWebhookSecretResponses, ec as UpdateAccountInput, ei as FunctionTestRunSend, el as ResponseStyle, en as CreateEndpointInput, eo as PaginationMeta, er as DeliverySummary, es as SendMailResult, et as listFunctionSecrets, f as VerifyOptions, fa as ListDeliveriesResponses, fc as UpdateEndpointInput, fi as GetEmailErrors, fn as CreateFunctionInput, fo as ReplayDeliveryResponses, fr as DownloadAttachmentsError, fs as SetFunctionSecretErrors, ft as sendEmail, g as PrimitiveApiClient, ga as ListDomainsResponse, gc as UpdateFilterError, gi as GetFunctionError, gn as CreateFunctionSecretData, go as ReplayEmailWebhooksResponse, gr as DownloadDomainZoneFileData, gs as StartAgentSignupData, gt as startCliSignup, h as DEFAULT_API_BASE_URL_2, ha as ListDomainsErrors, hc as UpdateFilterData, hi as GetFunctionData, hn as CreateFunctionResult, ho as ReplayEmailWebhooksErrors, hr as DownloadAttachmentsResponses, hs as SetFunctionSecretResponses, ht as startCliLogin, i as ReplyInput, ia as InboxStatusFunctionSummary, ic as UpdateDomainError, ii as GateFix, in as CreateFilterError, io as PollCliLoginErrors, ir as DiscardEmailContentErrors, is as SendPermissionRule, it as replayDelivery, j as deleteFilter, ja as ListFiltersErrors, jc as VerifyAgentSignupInput, ji as GetSendPermissionsError, jn as DeleteEmailResponse, jo as ResendCliSignupVerificationError, jr as EmailSearchFacetBucket, js as StartCliSignupInput, jt as AddDomainErrors, k as deleteEmail, ka as ListFiltersData, kc as VerifyAgentSignupError, ki as GetInboxStatusResponses, kn as DeleteEmailError, ko as ResendAgentSignupVerificationResponses, kr as EmailDetail, ks as StartCliSignupError, kt as AddDomainData, l as client, la as ListDeliveriesError, lc as UpdateEndpointData, li as GetAccountResponses, ln as CreateFunctionData, lo as ReplayDeliveryError, lr as DomainDnsRecord, ls as SentEmailSummary, lt as rotateWebhookSecret, m as DEFAULT_API_BASE_URL_1, ma as ListDomainsError, mc as UpdateEndpointResponses, mi as GetEmailResponses, mn as CreateFunctionResponses, mo as ReplayEmailWebhooksError, mr as DownloadAttachmentsResponse, ms as SetFunctionSecretResponse, mt as startAgentSignup, n as PrimitiveClient, na as InboxStatusDomain, nc as UpdateAccountResponses, ni as FunctionTestRunTrace, nl as Auth, nn as CreateEndpointResponses, no as PollCliLoginData, nr as DiscardEmailContentData, ns as SendPermissionAnyRecipient, nt as listSentEmails, o as SendInput, oa as InboxStatusRecentEmailSummary, oc as UpdateDomainInput, oi as GetAccountError, on as CreateFilterInput, oo as PollCliLoginResponse, or as DiscardEmailContentResponses, os as SendPermissionsMeta, ot as replyToEmail, p as verifyWebhookSignature, pa as ListDomainsData, pc as UpdateEndpointResponse, pi as GetEmailResponse, pn as CreateFunctionResponse, po as ReplayEmailWebhooksData, pr as DownloadAttachmentsErrors, ps as SetFunctionSecretInput, pt as setFunctionSecret, q as getWebhookSecret, qa as ListFunctionsResponse, qc as Client, qi as GetThreadErrors, qn as DeleteFunctionResponses, qo as SendEmailData, qr as FunctionSecretWriteResult, qs as TestResult, qt as CliLogoutResult, r as PrimitiveClientOptions, ra as InboxStatusEndpointSummary, rc as UpdateDomainData, ri as GateDenial, rn as CreateFilterData, ro as PollCliLoginError, rr as DiscardEmailContentError, rs as SendPermissionManagedZone, rt as pollCliLogin, s as SendResult, sa as Limit, sc as UpdateDomainResponse, si as GetAccountErrors, sn as CreateFilterResponse, so as PollCliLoginResponses, sr as DkimSignature, ss as SentEmailDetail, st as resendAgentSignupVerification, t as ForwardInput, ta as InboxStatus, tc as UpdateAccountResponse, ti as FunctionTestRunState, tl as createConfig, tn as CreateEndpointResponse, to as ParsedEmailData, tr as DiscardContentResult, ts as SendPermissionAddress, tt as listFunctions, u as createPrimitiveClient, ua as ListDeliveriesErrors, uc as UpdateEndpointError, ui as GetEmailData, un as CreateFunctionError, uo as ReplayDeliveryErrors, ur as DomainVerifyResult, us as SetFunctionSecretData, ut as sdk_gen_d_exports, v as PrimitiveApiError, va as ListEmailsData, vc as UpdateFilterInput, vi as GetFunctionResponse, vn as CreateFunctionSecretErrors, vo as ReplayResult, vr as DownloadDomainZoneFileErrors, vs as StartAgentSignupErrors, vt as testFunction, w as createEndpoint, wa as ListEndpointsError, wc as UpdateFunctionInput, wi as GetFunctionTestRunTraceResponses, wn as DeleteDomainError, wo as ResendAgentSignupVerificationData, wr as DownloadRawEmailResponse, ws as StartCliLoginErrors, wt as verifyAgentSignup, x as createPrimitiveApiClient, xa as ListEmailsResponse, xc as UpdateFunctionData, xi as GetFunctionTestRunTraceError, xn as CreateFunctionSecretResponses, xo as ReplyToEmailErrors, xr as DownloadRawEmailData, xs as StartAgentSignupResponses, xt as updateEndpoint, y as PrimitiveApiErrorDetails, ya as ListEmailsError, yc as UpdateFilterResponse, yi as GetFunctionResponses, yn as CreateFunctionSecretInput, yo as ReplyToEmailData, yr as DownloadDomainZoneFileResponse, ys as StartAgentSignupInput, yt as updateAccount, z as getEmail, za as ListFunctionSecretsData, zc as VerifyCliSignupResponses, zi as GetSentEmailResponses, zn as DeleteFilterError, zo as RotateWebhookSecretErrors, zr as Endpoint, zs as TestEndpointResponse, zt as CliLoginPollResult } from "../index-EVtXGd3A.js";
import { $ as listFunctionLogs, $a as ListSentEmailsResponses, $c as RequestResult, $i as GetWebhookSecretResponse, $n as DeliveryStatus, $o as SendMailInput, $r as FunctionTestRunReply, $s as UpdateAccountErrors, $t as CreateEndpointErrors, A as deleteEndpoint, Aa as ListFiltersError, Ac as VerifyAgentSignupErrors, Ai as GetSendPermissionsData, An as DeleteEmailErrors, Ao as ResendCliSignupVerificationData, Ar as EmailDetailReply, As as StartCliSignupErrors, At as AddDomainError, B as getFunction, Ba as ListFunctionSecretsError, Bc as VerifyDomainData, Bi as GetStorageStatsData, Bn as DeleteFilterErrors, Bo as RotateWebhookSecretResponse, Br as ErrorResponse, Bs as TestEndpointResponses, Bt as CliLoginStartResult, C as cliLogout, Ca as ListEndpointsData, Cc as UpdateFunctionErrors, Ci as GetFunctionTestRunTraceResponse, Cn as DeleteDomainData, Co as ReplyToEmailResponses, Cr as DownloadRawEmailErrors, Cs as StartCliLoginError, Ct as updateFunction, D as createFunctionSecret, Da as ListEndpointsResponses, Dc as VerifiedDomain, Di as GetInboxStatusErrors, Dn as DeleteDomainResponses, Do as ResendAgentSignupVerificationInput, Dr as EmailAttachment, Ds as StartCliLoginResponses, Dt as Account, E as createFunction, Ea as ListEndpointsResponse, Ec as UpdateFunctionResponses, Ei as GetInboxStatusError, En as DeleteDomainResponse, Eo as ResendAgentSignupVerificationErrors, Er as EmailAddress, Es as StartCliLoginResponse, Et as verifyDomain, F as downloadAttachments, Fa as ListFunctionLogsError, Fc as VerifyCliSignupError, Fi as GetSentEmailData, Fn as DeleteEndpointErrors, Fo as ResendCliSignupVerificationResponses, Fr as EmailSearchResult, Fs as SuccessEnvelope, Ft as AgentOrgRef, G as getStorageStats, Ga as ListFunctionsError, Gc as WebhookSecret, Gi as GetThreadData, Gn as DeleteFunctionErrors, Go as SearchEmailsResponse, Gr as FunctionLogRow, Gs as TestFunctionResponses, Gt as CliLogoutResponse, H as getInboxStatus, Ha as ListFunctionSecretsResponse, Hc as VerifyDomainErrors, Hi as GetStorageStatsErrors, Hn as DeleteFilterResponses, Ho as SearchEmailsData, Hr as FunctionDeployStatus, Hs as TestFunctionError, Ht as CliLogoutError, I as downloadDomainZoneFile, Ia as ListFunctionLogsErrors, Ic as VerifyCliSignupErrors, Ii as GetSentEmailError, In as DeleteEndpointResponse, Io as ResourceId, Ir as EmailStatus, Is as TestEndpointData, It as AgentSignupResendResult, J as listDeliveries, Ja as ListFunctionsResponses, Jc as ClientOptions, Ji as GetThreadResponse, Jn as DeleteFunctionSecretData, Jo as SendEmailError, Jr as FunctionTestRun, Js as Thread, Jt as CliSignupResendResult, K as getThread, Ka as ListFunctionsErrors, Kc as createClient, Ki as GetThreadError, Kn as DeleteFunctionResponse, Ko as SearchEmailsResponses, Kr as FunctionSecretListItem, Ks as TestInvocationResult, Kt as CliLogoutResponses, L as downloadRawEmail, La as ListFunctionLogsResponse, Lc as VerifyCliSignupInput, Li as GetSentEmailErrors, Ln as DeleteEndpointResponses, Lo as RotateWebhookSecretData, Lr as EmailSummary, Ls as TestEndpointError, Lt as AgentSignupStartResult, M as deleteFunction, Ma as ListFiltersResponse, Mc as VerifyAgentSignupResponse, Mi as GetSendPermissionsErrors, Mn as DeleteEmailResponses, Mo as ResendCliSignupVerificationErrors, Mr as EmailSearchFacets, Ms as StartCliSignupResponse, Mt as AddDomainInput, N as deleteFunctionSecret, Na as ListFiltersResponses, Nc as VerifyAgentSignupResponses, Ni as GetSendPermissionsResponse, Nn as DeleteEndpointData, No as ResendCliSignupVerificationInput, Nr as EmailSearchHighlights, Ns as StartCliSignupResponses, Nt as AddDomainResponse, O as deleteDomain, Oa as ListEnvelope, Oc as VerifyAgentSignupData, Oi as GetInboxStatusResponse, On as DeleteEmailData, Oo as ResendAgentSignupVerificationResponse, Or as EmailAuth, Os as StartCliSignupData, Ot as AccountUpdated, P as discardEmailContent, Pa as ListFunctionLogsData, Pc as VerifyCliSignupData, Pi as GetSendPermissionsResponses, Pn as DeleteEndpointError, Po as ResendCliSignupVerificationResponse, Pr as EmailSearchMeta, Ps as StorageStats, Pt as AddDomainResponses, Q as listFilters, Qa as ListSentEmailsResponse, Qc as RequestOptions, Qi as GetWebhookSecretErrors, Qn as DeleteFunctionSecretResponses, Qo as SendMailAttachment, Qr as FunctionTestRunOutboundRequest, Qs as UpdateAccountError, Qt as CreateEndpointError, R as getAccount, Ra as ListFunctionLogsResponses, Rc as VerifyCliSignupResponse, Ri as GetSentEmailResponse, Rn as DeleteFilterData, Ro as RotateWebhookSecretError, Rr as EmailWebhookStatus, Rs as TestEndpointErrors, Rt as AgentSignupVerifyResult, S as addDomain, Sa as ListEmailsResponses, Sc as UpdateFunctionError, Si as GetFunctionTestRunTraceErrors, Sn as Cursor, So as ReplyToEmailResponse, Sr as DownloadRawEmailError, Ss as StartCliLoginData, St as updateFilter, T as createFilter, Ta as ListEndpointsErrors, Tc as UpdateFunctionResponse, Ti as GetInboxStatusData, Tn as DeleteDomainErrors, To as ResendAgentSignupVerificationError, Tr as DownloadRawEmailResponses, Ts as StartCliLoginInput, Tt as verifyCliSignup, U as getSendPermissions, Ua as ListFunctionSecretsResponses, Uc as VerifyDomainResponse, Ui as GetStorageStatsResponse, Un as DeleteFunctionData, Uo as SearchEmailsError, Ur as FunctionDetail, Us as TestFunctionErrors, Ut as CliLogoutErrors, V as getFunctionTestRunTrace, Va as ListFunctionSecretsErrors, Vc as VerifyDomainError, Vi as GetStorageStatsError, Vn as DeleteFilterResponse, Vo as RotateWebhookSecretResponses, Vr as Filter, Vs as TestFunctionData, Vt as CliLogoutData, W as getSentEmail, Wa as ListFunctionsData, Wc as VerifyDomainResponses, Wi as GetStorageStatsResponses, Wn as DeleteFunctionError, Wo as SearchEmailsErrors, Wr as FunctionListItem, Ws as TestFunctionResponse, Wt as CliLogoutInput, X as listEmails, Xa as ListSentEmailsError, Xc as CreateClientConfig, Xi as GetWebhookSecretData, Xn as DeleteFunctionSecretErrors, Xo as SendEmailResponse, Xr as FunctionTestRunDeliveryEndpoint, Xs as UnverifiedDomain, Xt as CliSignupVerifyResult, Y as listDomains, Ya as ListSentEmailsData, Yc as Config, Yi as GetThreadResponses, Yn as DeleteFunctionSecretError, Yo as SendEmailErrors, Yr as FunctionTestRunDelivery, Ys as ThreadMessage, Yt as CliSignupStartResult, Z as listEndpoints, Za as ListSentEmailsErrors, Zc as Options, Zi as GetWebhookSecretError, Zn as DeleteFunctionSecretResponse, Zo as SendEmailResponses, Zr as FunctionTestRunInboundEmail, Zs as UpdateAccountData, Zt as CreateEndpointData, _ as PrimitiveApiClientOptions, _a as ListDomainsResponses, _c as UpdateFilterErrors, _i as GetFunctionErrors, _n as CreateFunctionSecretError, _o as ReplayEmailWebhooksResponses, _r as DownloadDomainZoneFileError, _s as StartAgentSignupError, _t as testEndpoint, a as RequestOptions$2, aa as InboxStatusNextAction, ac as UpdateDomainErrors, ai as GetAccountData, an as CreateFilterErrors, ao as PollCliLoginInput, ar as DiscardEmailContentResponse, as as SendPermissionYourDomain, at as replayEmailWebhooks, b as RequestOptions$1, ba as ListEmailsErrors, bc as UpdateFilterResponses, bi as GetFunctionTestRunTraceData, bn as CreateFunctionSecretResponse, bo as ReplyToEmailError, br as DownloadDomainZoneFileResponses, bs as StartAgentSignupResponse, bt as updateDomain, c as SendThreadInput, ca as ListDeliveriesData, cc as UpdateDomainResponses, ci as GetAccountResponse, cn as CreateFilterResponses, co as ReplayDeliveryData, cr as Domain, cs as SentEmailStatus, ct as resendCliSignupVerification, d as PRIMITIVE_SIGNATURE_HEADER, da as ListDeliveriesResponse, dc as UpdateEndpointErrors, di as GetEmailError, dn as CreateFunctionErrors, do as ReplayDeliveryResponse, dr as DownloadAttachmentsData, ds as SetFunctionSecretError, dt as searchEmails, ea as GetWebhookSecretResponses, ec as UpdateAccountInput, ei as FunctionTestRunSend, el as ResponseStyle, en as CreateEndpointInput, eo as PaginationMeta, er as DeliverySummary, es as SendMailResult, et as listFunctionSecrets, f as VerifyOptions, fa as ListDeliveriesResponses, fc as UpdateEndpointInput, fi as GetEmailErrors, fn as CreateFunctionInput, fo as ReplayDeliveryResponses, fr as DownloadAttachmentsError, fs as SetFunctionSecretErrors, ft as sendEmail, g as PrimitiveApiClient, ga as ListDomainsResponse, gc as UpdateFilterError, gi as GetFunctionError, gn as CreateFunctionSecretData, go as ReplayEmailWebhooksResponse, gr as DownloadDomainZoneFileData, gs as StartAgentSignupData, gt as startCliSignup, h as DEFAULT_API_BASE_URL_2, ha as ListDomainsErrors, hc as UpdateFilterData, hi as GetFunctionData, hn as CreateFunctionResult, ho as ReplayEmailWebhooksErrors, hr as DownloadAttachmentsResponses, hs as SetFunctionSecretResponses, ht as startCliLogin, i as ReplyInput, ia as InboxStatusFunctionSummary, ic as UpdateDomainError, ii as GateFix, in as CreateFilterError, io as PollCliLoginErrors, ir as DiscardEmailContentErrors, is as SendPermissionRule, it as replayDelivery, j as deleteFilter, ja as ListFiltersErrors, jc as VerifyAgentSignupInput, ji as GetSendPermissionsError, jn as DeleteEmailResponse, jo as ResendCliSignupVerificationError, jr as EmailSearchFacetBucket, js as StartCliSignupInput, jt as AddDomainErrors, k as deleteEmail, ka as ListFiltersData, kc as VerifyAgentSignupError, ki as GetInboxStatusResponses, kn as DeleteEmailError, ko as ResendAgentSignupVerificationResponses, kr as EmailDetail, ks as StartCliSignupError, kt as AddDomainData, l as client, la as ListDeliveriesError, lc as UpdateEndpointData, li as GetAccountResponses, ln as CreateFunctionData, lo as ReplayDeliveryError, lr as DomainDnsRecord, ls as SentEmailSummary, lt as rotateWebhookSecret, m as DEFAULT_API_BASE_URL_1, ma as ListDomainsError, mc as UpdateEndpointResponses, mi as GetEmailResponses, mn as CreateFunctionResponses, mo as ReplayEmailWebhooksError, mr as DownloadAttachmentsResponse, ms as SetFunctionSecretResponse, mt as startAgentSignup, n as PrimitiveClient, na as InboxStatusDomain, nc as UpdateAccountResponses, ni as FunctionTestRunTrace, nl as Auth, nn as CreateEndpointResponses, no as PollCliLoginData, nr as DiscardEmailContentData, ns as SendPermissionAnyRecipient, nt as listSentEmails, o as SendInput, oa as InboxStatusRecentEmailSummary, oc as UpdateDomainInput, oi as GetAccountError, on as CreateFilterInput, oo as PollCliLoginResponse, or as DiscardEmailContentResponses, os as SendPermissionsMeta, ot as replyToEmail, p as verifyWebhookSignature, pa as ListDomainsData, pc as UpdateEndpointResponse, pi as GetEmailResponse, pn as CreateFunctionResponse, po as ReplayEmailWebhooksData, pr as DownloadAttachmentsErrors, ps as SetFunctionSecretInput, pt as setFunctionSecret, q as getWebhookSecret, qa as ListFunctionsResponse, qc as Client, qi as GetThreadErrors, qn as DeleteFunctionResponses, qo as SendEmailData, qr as FunctionSecretWriteResult, qs as TestResult, qt as CliLogoutResult, r as PrimitiveClientOptions, ra as InboxStatusEndpointSummary, rc as UpdateDomainData, ri as GateDenial, rn as CreateFilterData, ro as PollCliLoginError, rr as DiscardEmailContentError, rs as SendPermissionManagedZone, rt as pollCliLogin, s as SendResult, sa as Limit, sc as UpdateDomainResponse, si as GetAccountErrors, sn as CreateFilterResponse, so as PollCliLoginResponses, sr as DkimSignature, ss as SentEmailDetail, st as resendAgentSignupVerification, t as ForwardInput, ta as InboxStatus, tc as UpdateAccountResponse, ti as FunctionTestRunState, tl as createConfig, tn as CreateEndpointResponse, to as ParsedEmailData, tr as DiscardContentResult, ts as SendPermissionAddress, tt as listFunctions, u as createPrimitiveClient, ua as ListDeliveriesErrors, uc as UpdateEndpointError, ui as GetEmailData, un as CreateFunctionError, uo as ReplayDeliveryErrors, ur as DomainVerifyResult, us as SetFunctionSecretData, ut as sdk_gen_d_exports, v as PrimitiveApiError, va as ListEmailsData, vc as UpdateFilterInput, vi as GetFunctionResponse, vn as CreateFunctionSecretErrors, vo as ReplayResult, vr as DownloadDomainZoneFileErrors, vs as StartAgentSignupErrors, vt as testFunction, w as createEndpoint, wa as ListEndpointsError, wc as UpdateFunctionInput, wi as GetFunctionTestRunTraceResponses, wn as DeleteDomainError, wo as ResendAgentSignupVerificationData, wr as DownloadRawEmailResponse, ws as StartCliLoginErrors, wt as verifyAgentSignup, x as createPrimitiveApiClient, xa as ListEmailsResponse, xc as UpdateFunctionData, xi as GetFunctionTestRunTraceError, xn as CreateFunctionSecretResponses, xo as ReplyToEmailErrors, xr as DownloadRawEmailData, xs as StartAgentSignupResponses, xt as updateEndpoint, y as PrimitiveApiErrorDetails, ya as ListEmailsError, yc as UpdateFilterResponse, yi as GetFunctionResponses, yn as CreateFunctionSecretInput, yo as ReplyToEmailData, yr as DownloadDomainZoneFileResponse, ys as StartAgentSignupInput, yt as updateAccount, z as getEmail, za as ListFunctionSecretsData, zc as VerifyCliSignupResponses, zi as GetSentEmailResponses, zn as DeleteFilterError, zo as RotateWebhookSecretErrors, zr as Endpoint, zs as TestEndpointResponse, zt as CliLoginPollResult } from "../index-CZjTjNV8.js";
import { i as openapiDocument, n as PrimitiveParameterManifest, r as operationManifest, t as PrimitiveOperationManifest } from "../operations.generated-BAniFZK9.js";
import { u as EmailReceivedEvent } from "../types-BRWDMD7H.js";
import { b as normalizeReceivedEmail, f as WebhookVerificationError, g as ReceivedEmailThread, h as ReceivedEmailAddress, m as ReceivedEmail, p as WebhookVerificationErrorCode } from "../errors-CO-rv_nK.js";
import { u as EmailReceivedEvent } from "../types-yNU-Oiea.js";
import { b as normalizeReceivedEmail, f as WebhookVerificationError, g as ReceivedEmailThread, h as ReceivedEmailAddress, m as ReceivedEmail, p as WebhookVerificationErrorCode } from "../errors-7E9sW9eX.js";
export { Account, AccountUpdated, AddDomainData, AddDomainError, AddDomainErrors, AddDomainInput, AddDomainResponse, AddDomainResponses, AgentOrgRef, AgentSignupResendResult, AgentSignupStartResult, AgentSignupVerifyResult, Auth, CliLoginPollResult, CliLoginStartResult, CliLogoutData, CliLogoutError, CliLogoutErrors, CliLogoutInput, CliLogoutResponse, CliLogoutResponses, CliLogoutResult, CliSignupResendResult, CliSignupStartResult, CliSignupVerifyResult, Client, Client as PrimitiveGeneratedApiClient, ClientOptions, ClientOptions as PrimitiveGeneratedApiClientOptions, Config, Config as PrimitiveGeneratedApiConfig, CreateClientConfig, CreateEndpointData, CreateEndpointError, CreateEndpointErrors, CreateEndpointInput, CreateEndpointResponse, CreateEndpointResponses, CreateFilterData, CreateFilterError, CreateFilterErrors, CreateFilterInput, CreateFilterResponse, CreateFilterResponses, CreateFunctionData, CreateFunctionError, CreateFunctionErrors, CreateFunctionInput, CreateFunctionResponse, CreateFunctionResponses, CreateFunctionResult, CreateFunctionSecretData, CreateFunctionSecretError, CreateFunctionSecretErrors, CreateFunctionSecretInput, CreateFunctionSecretResponse, CreateFunctionSecretResponses, Cursor, DEFAULT_API_BASE_URL_1, DEFAULT_API_BASE_URL_2, DeleteDomainData, DeleteDomainError, DeleteDomainErrors, DeleteDomainResponse, DeleteDomainResponses, DeleteEmailData, DeleteEmailError, DeleteEmailErrors, DeleteEmailResponse, DeleteEmailResponses, DeleteEndpointData, DeleteEndpointError, DeleteEndpointErrors, DeleteEndpointResponse, DeleteEndpointResponses, DeleteFilterData, DeleteFilterError, DeleteFilterErrors, DeleteFilterResponse, DeleteFilterResponses, DeleteFunctionData, DeleteFunctionError, DeleteFunctionErrors, DeleteFunctionResponse, DeleteFunctionResponses, DeleteFunctionSecretData, DeleteFunctionSecretError, DeleteFunctionSecretErrors, DeleteFunctionSecretResponse, DeleteFunctionSecretResponses, DeliveryStatus, DeliverySummary, DiscardContentResult, DiscardEmailContentData, DiscardEmailContentError, DiscardEmailContentErrors, DiscardEmailContentResponse, DiscardEmailContentResponses, DkimSignature, Domain, DomainDnsRecord, DomainVerifyResult, DownloadAttachmentsData, DownloadAttachmentsError, DownloadAttachmentsErrors, DownloadAttachmentsResponse, DownloadAttachmentsResponses, DownloadDomainZoneFileData, DownloadDomainZoneFileError, DownloadDomainZoneFileErrors, DownloadDomainZoneFileResponse, DownloadDomainZoneFileResponses, DownloadRawEmailData, DownloadRawEmailError, DownloadRawEmailErrors, DownloadRawEmailResponse, DownloadRawEmailResponses, EmailAddress, EmailAttachment, EmailAuth, EmailDetail, EmailDetailReply, EmailReceivedEvent, EmailSearchFacetBucket, EmailSearchFacets, EmailSearchHighlights, EmailSearchMeta, EmailSearchResult, EmailStatus, EmailSummary, EmailWebhookStatus, Endpoint, ErrorResponse, Filter, ForwardInput, FunctionDeployStatus, FunctionDetail, FunctionListItem, FunctionLogRow, FunctionSecretListItem, FunctionSecretWriteResult, FunctionTestRun, FunctionTestRunDelivery, FunctionTestRunDeliveryEndpoint, FunctionTestRunInboundEmail, FunctionTestRunOutboundRequest, FunctionTestRunReply, FunctionTestRunSend, FunctionTestRunState, FunctionTestRunTrace, GateDenial, GateFix, GetAccountData, GetAccountError, GetAccountErrors, GetAccountResponse, GetAccountResponses, GetEmailData, GetEmailError, GetEmailErrors, GetEmailResponse, GetEmailResponses, GetFunctionData, GetFunctionError, GetFunctionErrors, GetFunctionResponse, GetFunctionResponses, GetFunctionTestRunTraceData, GetFunctionTestRunTraceError, GetFunctionTestRunTraceErrors, GetFunctionTestRunTraceResponse, GetFunctionTestRunTraceResponses, GetInboxStatusData, GetInboxStatusError, GetInboxStatusErrors, GetInboxStatusResponse, GetInboxStatusResponses, GetSendPermissionsData, GetSendPermissionsError, GetSendPermissionsErrors, GetSendPermissionsResponse, GetSendPermissionsResponses, GetSentEmailData, GetSentEmailError, GetSentEmailErrors, GetSentEmailResponse, GetSentEmailResponses, GetStorageStatsData, GetStorageStatsError, GetStorageStatsErrors, GetStorageStatsResponse, GetStorageStatsResponses, GetThreadData, GetThreadError, GetThreadErrors, GetThreadResponse, GetThreadResponses, GetWebhookSecretData, GetWebhookSecretError, GetWebhookSecretErrors, GetWebhookSecretResponse, GetWebhookSecretResponses, InboxStatus, InboxStatusDomain, InboxStatusEndpointSummary, InboxStatusFunctionSummary, InboxStatusNextAction, InboxStatusRecentEmailSummary, Limit, ListDeliveriesData, ListDeliveriesError, ListDeliveriesErrors, ListDeliveriesResponse, ListDeliveriesResponses, ListDomainsData, ListDomainsError, ListDomainsErrors, ListDomainsResponse, ListDomainsResponses, ListEmailsData, ListEmailsError, ListEmailsErrors, ListEmailsResponse, ListEmailsResponses, ListEndpointsData, ListEndpointsError, ListEndpointsErrors, ListEndpointsResponse, ListEndpointsResponses, ListEnvelope, ListFiltersData, ListFiltersError, ListFiltersErrors, ListFiltersResponse, ListFiltersResponses, ListFunctionLogsData, ListFunctionLogsError, ListFunctionLogsErrors, ListFunctionLogsResponse, ListFunctionLogsResponses, ListFunctionSecretsData, ListFunctionSecretsError, ListFunctionSecretsErrors, ListFunctionSecretsResponse, ListFunctionSecretsResponses, ListFunctionsData, ListFunctionsError, ListFunctionsErrors, ListFunctionsResponse, ListFunctionsResponses, ListSentEmailsData, ListSentEmailsError, ListSentEmailsErrors, ListSentEmailsResponse, ListSentEmailsResponses, Options, Options as PrimitiveGeneratedApiOptions, PRIMITIVE_SIGNATURE_HEADER, PaginationMeta, ParsedEmailData, PollCliLoginData, PollCliLoginError, PollCliLoginErrors, PollCliLoginInput, PollCliLoginResponse, PollCliLoginResponses, PrimitiveApiClient, PrimitiveApiClientOptions, PrimitiveApiError, PrimitiveApiErrorDetails, PrimitiveClient, PrimitiveClientOptions, RequestOptions as PrimitiveGeneratedApiRequestOptions, RequestResult as PrimitiveGeneratedApiRequestResult, RequestResult, PrimitiveOperationManifest, PrimitiveParameterManifest, RequestOptions$1 as PrimitiveRequestOptions, ReceivedEmail, ReceivedEmailAddress, ReceivedEmailThread, ReplayDeliveryData, ReplayDeliveryError, ReplayDeliveryErrors, ReplayDeliveryResponse, ReplayDeliveryResponses, ReplayEmailWebhooksData, ReplayEmailWebhooksError, ReplayEmailWebhooksErrors, ReplayEmailWebhooksResponse, ReplayEmailWebhooksResponses, ReplayResult, ReplyInput, ReplyToEmailData, ReplyToEmailError, ReplyToEmailErrors, ReplyToEmailResponse, ReplyToEmailResponses, RequestOptions$2 as RequestOptions, ResendAgentSignupVerificationData, ResendAgentSignupVerificationError, ResendAgentSignupVerificationErrors, ResendAgentSignupVerificationInput, ResendAgentSignupVerificationResponse, ResendAgentSignupVerificationResponses, ResendCliSignupVerificationData, ResendCliSignupVerificationError, ResendCliSignupVerificationErrors, ResendCliSignupVerificationInput, ResendCliSignupVerificationResponse, ResendCliSignupVerificationResponses, ResourceId, ResponseStyle, RotateWebhookSecretData, RotateWebhookSecretError, RotateWebhookSecretErrors, RotateWebhookSecretResponse, RotateWebhookSecretResponses, SearchEmailsData, SearchEmailsError, SearchEmailsErrors, SearchEmailsResponse, SearchEmailsResponses, SendEmailData, SendEmailError, SendEmailErrors, SendEmailResponse, SendEmailResponses, SendInput, SendMailAttachment, SendMailInput, SendMailResult, SendPermissionAddress, SendPermissionAnyRecipient, SendPermissionManagedZone, SendPermissionRule, SendPermissionYourDomain, SendPermissionsMeta, SendResult, SendThreadInput, SentEmailDetail, SentEmailStatus, SentEmailSummary, SetFunctionSecretData, SetFunctionSecretError, SetFunctionSecretErrors, SetFunctionSecretInput, SetFunctionSecretResponse, SetFunctionSecretResponses, StartAgentSignupData, StartAgentSignupError, StartAgentSignupErrors, StartAgentSignupInput, StartAgentSignupResponse, StartAgentSignupResponses, StartCliLoginData, StartCliLoginError, StartCliLoginErrors, StartCliLoginInput, StartCliLoginResponse, StartCliLoginResponses, StartCliSignupData, StartCliSignupError, StartCliSignupErrors, StartCliSignupInput, StartCliSignupResponse, StartCliSignupResponses, StorageStats, SuccessEnvelope, TestEndpointData, TestEndpointError, TestEndpointErrors, TestEndpointResponse, TestEndpointResponses, TestFunctionData, TestFunctionError, TestFunctionErrors, TestFunctionResponse, TestFunctionResponses, TestInvocationResult, TestResult, Thread, ThreadMessage, UnverifiedDomain, UpdateAccountData, UpdateAccountError, UpdateAccountErrors, UpdateAccountInput, UpdateAccountResponse, UpdateAccountResponses, UpdateDomainData, UpdateDomainError, UpdateDomainErrors, UpdateDomainInput, UpdateDomainResponse, UpdateDomainResponses, UpdateEndpointData, UpdateEndpointError, UpdateEndpointErrors, UpdateEndpointInput, UpdateEndpointResponse, UpdateEndpointResponses, UpdateFilterData, UpdateFilterError, UpdateFilterErrors, UpdateFilterInput, UpdateFilterResponse, UpdateFilterResponses, UpdateFunctionData, UpdateFunctionError, UpdateFunctionErrors, UpdateFunctionInput, UpdateFunctionResponse, UpdateFunctionResponses, VerifiedDomain, VerifyAgentSignupData, VerifyAgentSignupError, VerifyAgentSignupErrors, VerifyAgentSignupInput, VerifyAgentSignupResponse, VerifyAgentSignupResponses, VerifyCliSignupData, VerifyCliSignupError, VerifyCliSignupErrors, VerifyCliSignupInput, VerifyCliSignupResponse, VerifyCliSignupResponses, VerifyDomainData, VerifyDomainError, VerifyDomainErrors, VerifyDomainResponse, VerifyDomainResponses, VerifyOptions as VerifyWebhookSignatureOptions, WebhookSecret, WebhookVerificationError, WebhookVerificationErrorCode, addDomain, cliLogout, client, createClient, createConfig, createEndpoint, createFilter, createFunction, createFunctionSecret, createPrimitiveApiClient, createPrimitiveClient, deleteDomain, deleteEmail, deleteEndpoint, deleteFilter, deleteFunction, deleteFunctionSecret, discardEmailContent, downloadAttachments, downloadDomainZoneFile, downloadRawEmail, getAccount, getEmail, getFunction, getFunctionTestRunTrace, getInboxStatus, getSendPermissions, getSentEmail, getStorageStats, getThread, getWebhookSecret, listDeliveries, listDomains, listEmails, listEndpoints, listFilters, listFunctionLogs, listFunctionSecrets, listFunctions, listSentEmails, normalizeReceivedEmail, openapiDocument, operationManifest, sdk_gen_d_exports as operations, pollCliLogin, replayDelivery, replayEmailWebhooks, replyToEmail, resendAgentSignupVerification, resendCliSignupVerification, rotateWebhookSecret, searchEmails, sendEmail, setFunctionSecret, startAgentSignup, startCliLogin, startCliSignup, testEndpoint, testFunction, updateAccount, updateDomain, updateEndpoint, updateFilter, updateFunction, verifyAgentSignup, verifyCliSignup, verifyDomain, verifyWebhookSignature };

@@ -1,3 +0,3 @@

import { C as ParsedDataFailed, D as RawContentDownloadOnly, M as WebhookAttachment, O as RawContentInline, S as ParsedDataComplete, c as EmailAnalysis, l as EmailAuth, s as EmailAddress, u as EmailReceivedEvent, w as ParsedError } from "../types-BRWDMD7H.js";
import { C as signStandardWebhooksPayload, h as WEBHOOK_VERSION, j as signWebhookPayload, k as SignResult, x as StandardWebhooksSignResult } from "../index-D_v8-0zX.js";
import { C as ParsedDataFailed, D as RawContentDownloadOnly, M as WebhookAttachment, O as RawContentInline, S as ParsedDataComplete, c as EmailAnalysis, l as EmailAuth, s as EmailAddress, u as EmailReceivedEvent, w as ParsedError } from "../types-yNU-Oiea.js";
import { C as signStandardWebhooksPayload, h as WEBHOOK_VERSION, j as signWebhookPayload, k as SignResult, x as StandardWebhooksSignResult } from "../index-DR978rq5.js";

@@ -4,0 +4,0 @@ //#region src/contract/contract.d.ts

@@ -1,2 +0,2 @@

import { E as signStandardWebhooksPayload, L as validateEmailReceivedEvent, M as signWebhookPayload, d as WEBHOOK_VERSION } from "../webhook-D4FTpj38.js";
import { E as signStandardWebhooksPayload, L as validateEmailReceivedEvent, M as signWebhookPayload, d as WEBHOOK_VERSION } from "../webhook-BAwK8EOG.js";
import { createHash } from "node:crypto";

@@ -3,0 +3,0 @@ //#region src/contract/contract.ts

@@ -1,5 +0,5 @@

import { c as SendThreadInput, i as ReplyInput, l as client, n as PrimitiveClient, o as SendInput, r as PrimitiveClientOptions, s as SendResult, t as ForwardInput, u as createPrimitiveClient, v as PrimitiveApiError } from "./index-EVtXGd3A.js";
import { A as UnknownEvent, C as ParsedDataFailed, D as RawContentDownloadOnly, E as RawContent, M as WebhookAttachment, N as WebhookEvent, O as RawContentInline, S as ParsedDataComplete, T as ParsedStatus, _ as ForwardResultInline, a as DmarcPolicy, b as KnownWebhookEvent, c as EmailAnalysis, d as EventType, f as ForwardAnalysis, g as ForwardResultAttachmentSkipped, h as ForwardResultAttachmentAnalyzed, i as DkimSignature, j as ValidateEmailAuthResult, k as SpfResult, l as EmailAuth, m as ForwardResult, n as AuthVerdict, o as DmarcResult, p as ForwardOriginalSender, r as DkimResult, s as EmailAddress, t as AuthConfidence, u as EmailReceivedEvent, v as ForwardVerdict, w as ParsedError, x as ParsedData, y as ForwardVerification } from "./types-BRWDMD7H.js";
import { _ as buildForwardSubject, a as RawEmailDecodeErrorCode, b as normalizeReceivedEmail, c as WebhookPayloadError, d as WebhookValidationErrorCode, f as WebhookVerificationError, g as ReceivedEmailThread, h as ReceivedEmailAddress, i as RawEmailDecodeError, l as WebhookPayloadErrorCode, m as ReceivedEmail, n as PrimitiveWebhookError, o as VERIFICATION_ERRORS, p as WebhookVerificationErrorCode, r as RAW_EMAIL_ERRORS, s as WebhookErrorCode, t as PAYLOAD_ERRORS, u as WebhookValidationError, v as buildReplySubject, x as parseHeaderAddress, y as formatAddress } from "./errors-CO-rv_nK.js";
import { A as VerifyOptions, C as signStandardWebhooksPayload, D as PRIMITIVE_CONFIRMED_HEADER, E as LEGACY_SIGNATURE_HEADER, F as VerifyDownloadTokenResult, I as generateDownloadToken, L as verifyDownloadToken, M as verifyWebhookSignature, N as GenerateDownloadTokenOptions, O as PRIMITIVE_SIGNATURE_HEADER, P as VerifyDownloadTokenOptions, R as safeValidateEmailReceivedEvent, S as StandardWebhooksVerifyOptions, T as LEGACY_CONFIRMED_HEADER, _ as emailReceivedEventJsonSchema, a as confirmedHeaders, b as STANDARD_WEBHOOK_TIMESTAMP_HEADER, c as handleWebhook, d as isRawIncluded, f as parseWebhookEvent, g as validateEmailAuth, h as WEBHOOK_VERSION, i as WebhookHeaders, j as signWebhookPayload, k as SignResult, l as isDownloadExpired, m as verifyRawEmailDownload, n as HandleWebhookOptions, o as decodeRawEmail, p as receive, r as ReceiveRequestOptions, s as getDownloadTimeRemaining, t as DecodeRawEmailOptions, u as isEmailReceivedEvent, v as STANDARD_WEBHOOK_ID_HEADER, w as verifyStandardWebhooksSignature, x as StandardWebhooksSignResult, y as STANDARD_WEBHOOK_SIGNATURE_HEADER, z as validateEmailReceivedEvent } from "./index-D_v8-0zX.js";
import { c as SendThreadInput, i as ReplyInput, l as client, n as PrimitiveClient, o as SendInput, r as PrimitiveClientOptions, s as SendResult, t as ForwardInput, u as createPrimitiveClient, v as PrimitiveApiError } from "./index-CZjTjNV8.js";
import { A as UnknownEvent, C as ParsedDataFailed, D as RawContentDownloadOnly, E as RawContent, M as WebhookAttachment, N as WebhookEvent, O as RawContentInline, S as ParsedDataComplete, T as ParsedStatus, _ as ForwardResultInline, a as DmarcPolicy, b as KnownWebhookEvent, c as EmailAnalysis, d as EventType, f as ForwardAnalysis, g as ForwardResultAttachmentSkipped, h as ForwardResultAttachmentAnalyzed, i as DkimSignature, j as ValidateEmailAuthResult, k as SpfResult, l as EmailAuth, m as ForwardResult, n as AuthVerdict, o as DmarcResult, p as ForwardOriginalSender, r as DkimResult, s as EmailAddress, t as AuthConfidence, u as EmailReceivedEvent, v as ForwardVerdict, w as ParsedError, x as ParsedData, y as ForwardVerification } from "./types-yNU-Oiea.js";
import { _ as buildForwardSubject, a as RawEmailDecodeErrorCode, b as normalizeReceivedEmail, c as WebhookPayloadError, d as WebhookValidationErrorCode, f as WebhookVerificationError, g as ReceivedEmailThread, h as ReceivedEmailAddress, i as RawEmailDecodeError, l as WebhookPayloadErrorCode, m as ReceivedEmail, n as PrimitiveWebhookError, o as VERIFICATION_ERRORS, p as WebhookVerificationErrorCode, r as RAW_EMAIL_ERRORS, s as WebhookErrorCode, t as PAYLOAD_ERRORS, u as WebhookValidationError, v as buildReplySubject, x as parseHeaderAddress, y as formatAddress } from "./errors-7E9sW9eX.js";
import { A as VerifyOptions, C as signStandardWebhooksPayload, D as PRIMITIVE_CONFIRMED_HEADER, E as LEGACY_SIGNATURE_HEADER, F as VerifyDownloadTokenResult, I as generateDownloadToken, L as verifyDownloadToken, M as verifyWebhookSignature, N as GenerateDownloadTokenOptions, O as PRIMITIVE_SIGNATURE_HEADER, P as VerifyDownloadTokenOptions, R as safeValidateEmailReceivedEvent, S as StandardWebhooksVerifyOptions, T as LEGACY_CONFIRMED_HEADER, _ as emailReceivedEventJsonSchema, a as confirmedHeaders, b as STANDARD_WEBHOOK_TIMESTAMP_HEADER, c as handleWebhook, d as isRawIncluded, f as parseWebhookEvent, g as validateEmailAuth, h as WEBHOOK_VERSION, i as WebhookHeaders, j as signWebhookPayload, k as SignResult, l as isDownloadExpired, m as verifyRawEmailDownload, n as HandleWebhookOptions, o as decodeRawEmail, p as receive, r as ReceiveRequestOptions, s as getDownloadTimeRemaining, t as DecodeRawEmailOptions, u as isEmailReceivedEvent, v as STANDARD_WEBHOOK_ID_HEADER, w as verifyStandardWebhooksSignature, x as StandardWebhooksSignResult, y as STANDARD_WEBHOOK_SIGNATURE_HEADER, z as validateEmailReceivedEvent } from "./index-DR978rq5.js";

@@ -6,0 +6,0 @@ //#region src/index.d.ts

import { l as PrimitiveApiError, n as client, r as createPrimitiveClient, t as PrimitiveClient } from "./api-Dto6GBP0.js";
import { a as VERIFICATION_ERRORS, c as WebhookVerificationError, d as formatAddress, f as normalizeReceivedEmail, i as RawEmailDecodeError, l as buildForwardSubject, n as PrimitiveWebhookError, o as WebhookPayloadError, p as parseHeaderAddress, r as RAW_EMAIL_ERRORS, s as WebhookValidationError, t as PAYLOAD_ERRORS, u as buildReplySubject } from "./errors-BPJGp9I6.js";
import { A as PRIMITIVE_CONFIRMED_HEADER, C as STANDARD_WEBHOOK_ID_HEADER, D as verifyStandardWebhooksSignature, E as signStandardWebhooksPayload, F as verifyDownloadToken, I as safeValidateEmailReceivedEvent, L as validateEmailReceivedEvent, M as signWebhookPayload, N as verifyWebhookSignature, O as LEGACY_CONFIRMED_HEADER, P as generateDownloadToken, S as emailReceivedEventJsonSchema, T as STANDARD_WEBHOOK_TIMESTAMP_HEADER, _ as DmarcResult, a as isDownloadExpired, b as ParsedStatus, c as parseWebhookEvent, d as WEBHOOK_VERSION, f as validateEmailAuth, g as DmarcPolicy, h as DkimResult, i as handleWebhook, j as PRIMITIVE_SIGNATURE_HEADER, k as LEGACY_SIGNATURE_HEADER, l as receive, m as AuthVerdict, n as decodeRawEmail, o as isEmailReceivedEvent, p as AuthConfidence, r as getDownloadTimeRemaining, s as isRawIncluded, t as confirmedHeaders, u as verifyRawEmailDownload, v as EventType, w as STANDARD_WEBHOOK_SIGNATURE_HEADER, x as SpfResult, y as ForwardVerdict } from "./webhook-D4FTpj38.js";
import { A as PRIMITIVE_CONFIRMED_HEADER, C as STANDARD_WEBHOOK_ID_HEADER, D as verifyStandardWebhooksSignature, E as signStandardWebhooksPayload, F as verifyDownloadToken, I as safeValidateEmailReceivedEvent, L as validateEmailReceivedEvent, M as signWebhookPayload, N as verifyWebhookSignature, O as LEGACY_CONFIRMED_HEADER, P as generateDownloadToken, S as emailReceivedEventJsonSchema, T as STANDARD_WEBHOOK_TIMESTAMP_HEADER, _ as DmarcResult, a as isDownloadExpired, b as ParsedStatus, c as parseWebhookEvent, d as WEBHOOK_VERSION, f as validateEmailAuth, g as DmarcPolicy, h as DkimResult, i as handleWebhook, j as PRIMITIVE_SIGNATURE_HEADER, k as LEGACY_SIGNATURE_HEADER, l as receive, m as AuthVerdict, n as decodeRawEmail, o as isEmailReceivedEvent, p as AuthConfidence, r as getDownloadTimeRemaining, s as isRawIncluded, t as confirmedHeaders, u as verifyRawEmailDownload, v as EventType, w as STANDARD_WEBHOOK_SIGNATURE_HEADER, x as SpfResult, y as ForwardVerdict } from "./webhook-BAwK8EOG.js";
//#region src/index.ts

@@ -5,0 +5,0 @@ const primitive = {

@@ -1,2 +0,2 @@

import { M as WebhookAttachment, S as ParsedDataComplete, s as EmailAddress } from "../types-BRWDMD7H.js";
import { M as WebhookAttachment, S as ParsedDataComplete, s as EmailAddress } from "../types-yNU-Oiea.js";

@@ -3,0 +3,0 @@ //#region src/parser/address-parser.d.ts

@@ -1,4 +0,4 @@

import { A as UnknownEvent, C as ParsedDataFailed, D as RawContentDownloadOnly, E as RawContent, M as WebhookAttachment, N as WebhookEvent, O as RawContentInline, S as ParsedDataComplete, T as ParsedStatus, _ as ForwardResultInline, a as DmarcPolicy, b as KnownWebhookEvent, c as EmailAnalysis, d as EventType, f as ForwardAnalysis, g as ForwardResultAttachmentSkipped, h as ForwardResultAttachmentAnalyzed, i as DkimSignature, j as ValidateEmailAuthResult, k as SpfResult, l as EmailAuth, m as ForwardResult, n as AuthVerdict, o as DmarcResult, p as ForwardOriginalSender, r as DkimResult, s as EmailAddress, t as AuthConfidence, u as EmailReceivedEvent, v as ForwardVerdict, w as ParsedError, x as ParsedData, y as ForwardVerification } from "../types-BRWDMD7H.js";
import { _ as buildForwardSubject, a as RawEmailDecodeErrorCode, b as normalizeReceivedEmail, c as WebhookPayloadError, d as WebhookValidationErrorCode, f as WebhookVerificationError, g as ReceivedEmailThread, h as ReceivedEmailAddress, i as RawEmailDecodeError, l as WebhookPayloadErrorCode, m as ReceivedEmail, n as PrimitiveWebhookError, o as VERIFICATION_ERRORS, p as WebhookVerificationErrorCode, r as RAW_EMAIL_ERRORS, s as WebhookErrorCode, t as PAYLOAD_ERRORS, u as WebhookValidationError, v as buildReplySubject, x as parseHeaderAddress, y as formatAddress } from "../errors-CO-rv_nK.js";
import { A as VerifyOptions, C as signStandardWebhooksPayload, D as PRIMITIVE_CONFIRMED_HEADER, E as LEGACY_SIGNATURE_HEADER, F as VerifyDownloadTokenResult, I as generateDownloadToken, L as verifyDownloadToken, M as verifyWebhookSignature, N as GenerateDownloadTokenOptions, O as PRIMITIVE_SIGNATURE_HEADER, P as VerifyDownloadTokenOptions, R as safeValidateEmailReceivedEvent, S as StandardWebhooksVerifyOptions, T as LEGACY_CONFIRMED_HEADER, _ as emailReceivedEventJsonSchema, a as confirmedHeaders, b as STANDARD_WEBHOOK_TIMESTAMP_HEADER, c as handleWebhook, d as isRawIncluded, f as parseWebhookEvent, g as validateEmailAuth, h as WEBHOOK_VERSION, i as WebhookHeaders, j as signWebhookPayload, k as SignResult, l as isDownloadExpired, m as verifyRawEmailDownload, n as HandleWebhookOptions, o as decodeRawEmail, p as receive, r as ReceiveRequestOptions, s as getDownloadTimeRemaining, t as DecodeRawEmailOptions, u as isEmailReceivedEvent, v as STANDARD_WEBHOOK_ID_HEADER, w as verifyStandardWebhooksSignature, x as StandardWebhooksSignResult, y as STANDARD_WEBHOOK_SIGNATURE_HEADER, z as validateEmailReceivedEvent } from "../index-D_v8-0zX.js";
import { A as UnknownEvent, C as ParsedDataFailed, D as RawContentDownloadOnly, E as RawContent, M as WebhookAttachment, N as WebhookEvent, O as RawContentInline, S as ParsedDataComplete, T as ParsedStatus, _ as ForwardResultInline, a as DmarcPolicy, b as KnownWebhookEvent, c as EmailAnalysis, d as EventType, f as ForwardAnalysis, g as ForwardResultAttachmentSkipped, h as ForwardResultAttachmentAnalyzed, i as DkimSignature, j as ValidateEmailAuthResult, k as SpfResult, l as EmailAuth, m as ForwardResult, n as AuthVerdict, o as DmarcResult, p as ForwardOriginalSender, r as DkimResult, s as EmailAddress, t as AuthConfidence, u as EmailReceivedEvent, v as ForwardVerdict, w as ParsedError, x as ParsedData, y as ForwardVerification } from "../types-yNU-Oiea.js";
import { _ as buildForwardSubject, a as RawEmailDecodeErrorCode, b as normalizeReceivedEmail, c as WebhookPayloadError, d as WebhookValidationErrorCode, f as WebhookVerificationError, g as ReceivedEmailThread, h as ReceivedEmailAddress, i as RawEmailDecodeError, l as WebhookPayloadErrorCode, m as ReceivedEmail, n as PrimitiveWebhookError, o as VERIFICATION_ERRORS, p as WebhookVerificationErrorCode, r as RAW_EMAIL_ERRORS, s as WebhookErrorCode, t as PAYLOAD_ERRORS, u as WebhookValidationError, v as buildReplySubject, x as parseHeaderAddress, y as formatAddress } from "../errors-7E9sW9eX.js";
import { A as VerifyOptions, C as signStandardWebhooksPayload, D as PRIMITIVE_CONFIRMED_HEADER, E as LEGACY_SIGNATURE_HEADER, F as VerifyDownloadTokenResult, I as generateDownloadToken, L as verifyDownloadToken, M as verifyWebhookSignature, N as GenerateDownloadTokenOptions, O as PRIMITIVE_SIGNATURE_HEADER, P as VerifyDownloadTokenOptions, R as safeValidateEmailReceivedEvent, S as StandardWebhooksVerifyOptions, T as LEGACY_CONFIRMED_HEADER, _ as emailReceivedEventJsonSchema, a as confirmedHeaders, b as STANDARD_WEBHOOK_TIMESTAMP_HEADER, c as handleWebhook, d as isRawIncluded, f as parseWebhookEvent, g as validateEmailAuth, h as WEBHOOK_VERSION, i as WebhookHeaders, j as signWebhookPayload, k as SignResult, l as isDownloadExpired, m as verifyRawEmailDownload, n as HandleWebhookOptions, o as decodeRawEmail, p as receive, r as ReceiveRequestOptions, s as getDownloadTimeRemaining, t as DecodeRawEmailOptions, u as isEmailReceivedEvent, v as STANDARD_WEBHOOK_ID_HEADER, w as verifyStandardWebhooksSignature, x as StandardWebhooksSignResult, y as STANDARD_WEBHOOK_SIGNATURE_HEADER, z as validateEmailReceivedEvent } from "../index-DR978rq5.js";
export { AuthConfidence, AuthVerdict, DecodeRawEmailOptions, DkimResult, DkimSignature, DmarcPolicy, DmarcResult, EmailAddress, EmailAnalysis, EmailAuth, EmailReceivedEvent, EventType, ForwardAnalysis, ForwardOriginalSender, ForwardResult, ForwardResultAttachmentAnalyzed, ForwardResultAttachmentSkipped, ForwardResultInline, ForwardVerdict, ForwardVerification, GenerateDownloadTokenOptions, HandleWebhookOptions, KnownWebhookEvent, LEGACY_CONFIRMED_HEADER, LEGACY_SIGNATURE_HEADER, PAYLOAD_ERRORS, PRIMITIVE_CONFIRMED_HEADER, PRIMITIVE_SIGNATURE_HEADER, ParsedData, ParsedDataComplete, ParsedDataFailed, ParsedError, ParsedStatus, PrimitiveWebhookError, RAW_EMAIL_ERRORS, RawContent, RawContentDownloadOnly, RawContentInline, RawEmailDecodeError, RawEmailDecodeErrorCode, ReceiveRequestOptions, ReceivedEmail, ReceivedEmailAddress, ReceivedEmailThread, STANDARD_WEBHOOK_ID_HEADER, STANDARD_WEBHOOK_SIGNATURE_HEADER, STANDARD_WEBHOOK_TIMESTAMP_HEADER, SignResult, SpfResult, StandardWebhooksSignResult, StandardWebhooksVerifyOptions, UnknownEvent, VERIFICATION_ERRORS, ValidateEmailAuthResult, VerifyDownloadTokenOptions, VerifyDownloadTokenResult, VerifyOptions, WEBHOOK_VERSION, WebhookAttachment, WebhookErrorCode, WebhookEvent, WebhookHeaders, WebhookPayloadError, WebhookPayloadErrorCode, WebhookValidationError, WebhookValidationErrorCode, WebhookVerificationError, WebhookVerificationErrorCode, buildForwardSubject, buildReplySubject, confirmedHeaders, decodeRawEmail, emailReceivedEventJsonSchema, formatAddress, generateDownloadToken, getDownloadTimeRemaining, handleWebhook, isDownloadExpired, isEmailReceivedEvent, isRawIncluded, normalizeReceivedEmail, parseHeaderAddress, parseWebhookEvent, receive, safeValidateEmailReceivedEvent, signStandardWebhooksPayload, signWebhookPayload, validateEmailAuth, validateEmailReceivedEvent, verifyDownloadToken, verifyRawEmailDownload, verifyStandardWebhooksSignature, verifyWebhookSignature };
import { a as VERIFICATION_ERRORS, c as WebhookVerificationError, d as formatAddress, f as normalizeReceivedEmail, i as RawEmailDecodeError, l as buildForwardSubject, n as PrimitiveWebhookError, o as WebhookPayloadError, p as parseHeaderAddress, r as RAW_EMAIL_ERRORS, s as WebhookValidationError, t as PAYLOAD_ERRORS, u as buildReplySubject } from "../errors-BPJGp9I6.js";
import { A as PRIMITIVE_CONFIRMED_HEADER, C as STANDARD_WEBHOOK_ID_HEADER, D as verifyStandardWebhooksSignature, E as signStandardWebhooksPayload, F as verifyDownloadToken, I as safeValidateEmailReceivedEvent, L as validateEmailReceivedEvent, M as signWebhookPayload, N as verifyWebhookSignature, O as LEGACY_CONFIRMED_HEADER, P as generateDownloadToken, S as emailReceivedEventJsonSchema, T as STANDARD_WEBHOOK_TIMESTAMP_HEADER, _ as DmarcResult, a as isDownloadExpired, b as ParsedStatus, c as parseWebhookEvent, d as WEBHOOK_VERSION, f as validateEmailAuth, g as DmarcPolicy, h as DkimResult, i as handleWebhook, j as PRIMITIVE_SIGNATURE_HEADER, k as LEGACY_SIGNATURE_HEADER, l as receive, m as AuthVerdict, n as decodeRawEmail, o as isEmailReceivedEvent, p as AuthConfidence, r as getDownloadTimeRemaining, s as isRawIncluded, t as confirmedHeaders, u as verifyRawEmailDownload, v as EventType, w as STANDARD_WEBHOOK_SIGNATURE_HEADER, x as SpfResult, y as ForwardVerdict } from "../webhook-D4FTpj38.js";
import { A as PRIMITIVE_CONFIRMED_HEADER, C as STANDARD_WEBHOOK_ID_HEADER, D as verifyStandardWebhooksSignature, E as signStandardWebhooksPayload, F as verifyDownloadToken, I as safeValidateEmailReceivedEvent, L as validateEmailReceivedEvent, M as signWebhookPayload, N as verifyWebhookSignature, O as LEGACY_CONFIRMED_HEADER, P as generateDownloadToken, S as emailReceivedEventJsonSchema, T as STANDARD_WEBHOOK_TIMESTAMP_HEADER, _ as DmarcResult, a as isDownloadExpired, b as ParsedStatus, c as parseWebhookEvent, d as WEBHOOK_VERSION, f as validateEmailAuth, g as DmarcPolicy, h as DkimResult, i as handleWebhook, j as PRIMITIVE_SIGNATURE_HEADER, k as LEGACY_SIGNATURE_HEADER, l as receive, m as AuthVerdict, n as decodeRawEmail, o as isEmailReceivedEvent, p as AuthConfidence, r as getDownloadTimeRemaining, s as isRawIncluded, t as confirmedHeaders, u as verifyRawEmailDownload, v as EventType, w as STANDARD_WEBHOOK_SIGNATURE_HEADER, x as SpfResult, y as ForwardVerdict } from "../webhook-BAwK8EOG.js";
export { AuthConfidence, AuthVerdict, DkimResult, DmarcPolicy, DmarcResult, EventType, ForwardVerdict, LEGACY_CONFIRMED_HEADER, LEGACY_SIGNATURE_HEADER, PAYLOAD_ERRORS, PRIMITIVE_CONFIRMED_HEADER, PRIMITIVE_SIGNATURE_HEADER, ParsedStatus, PrimitiveWebhookError, RAW_EMAIL_ERRORS, RawEmailDecodeError, STANDARD_WEBHOOK_ID_HEADER, STANDARD_WEBHOOK_SIGNATURE_HEADER, STANDARD_WEBHOOK_TIMESTAMP_HEADER, SpfResult, VERIFICATION_ERRORS, WEBHOOK_VERSION, WebhookPayloadError, WebhookValidationError, WebhookVerificationError, buildForwardSubject, buildReplySubject, confirmedHeaders, decodeRawEmail, emailReceivedEventJsonSchema, formatAddress, generateDownloadToken, getDownloadTimeRemaining, handleWebhook, isDownloadExpired, isEmailReceivedEvent, isRawIncluded, normalizeReceivedEmail, parseHeaderAddress, parseWebhookEvent, receive, safeValidateEmailReceivedEvent, signStandardWebhooksPayload, signWebhookPayload, validateEmailAuth, validateEmailReceivedEvent, verifyDownloadToken, verifyRawEmailDownload, verifyStandardWebhooksSignature, verifyWebhookSignature };
{
"name": "@primitivedotdev/sdk",
"version": "0.31.8",
"version": "0.32.0",
"description": "Official Primitive Node.js SDK: webhook, api, openapi, contract, and parser runtime modules.",

@@ -5,0 +5,0 @@ "type": "module",

import { M as WebhookAttachment, c as EmailAnalysis, l as EmailAuth, u as EmailReceivedEvent } from "./types-BRWDMD7H.js";
import { ErrorObject } from "ajv";
//#region src/webhook/received-email.d.ts
interface ReceivedEmailAddress {
address: string;
name: string | null;
}
interface ReceivedEmailThread {
messageId: string | null;
inReplyTo: string[];
references: string[];
}
interface ReceivedEmail {
id: string;
eventId: string;
receivedAt: string;
sender: ReceivedEmailAddress;
replyTarget: ReceivedEmailAddress;
receivedBy: string;
receivedByAll: string[];
subject: string | null;
replySubject: string;
forwardSubject: string;
text: string | null;
thread: ReceivedEmailThread;
attachments: WebhookAttachment[];
auth: EmailAuth;
analysis: EmailAnalysis;
raw: EmailReceivedEvent;
}
declare function normalizeReceivedEmail(event: EmailReceivedEvent): ReceivedEmail;
declare function buildReplySubject(subject: string | null | undefined): string;
declare function buildForwardSubject(subject: string | null | undefined): string;
declare function formatAddress(address: ReceivedEmailAddress): string;
declare function parseHeaderAddress(value: string | null | undefined): ReceivedEmailAddress | null;
//#endregion
//#region src/webhook/errors.d.ts
/**
* Verification error definitions.
* Use these for documentation, dashboards, and i18n.
*/
declare const VERIFICATION_ERRORS: {
readonly INVALID_SIGNATURE_HEADER: {
readonly message: "Missing or malformed Primitive-Signature header";
readonly suggestion: "Check that you're reading the correct header (Primitive-Signature) and it's being passed correctly from your web framework.";
};
readonly TIMESTAMP_OUT_OF_RANGE: {
readonly message: "Timestamp is too old (possible replay attack)";
readonly suggestion: "This could indicate a replay attack, network delay, or server clock drift. Check your server's time is synced.";
};
readonly SIGNATURE_MISMATCH: {
readonly message: "Signature doesn't match expected value";
readonly suggestion: "Verify the webhook secret matches and you're using the raw request body (not re-serialized JSON).";
};
readonly MISSING_SECRET: {
readonly message: "No webhook secret was provided";
readonly suggestion: "Pass your webhook secret from the Primitive dashboard. Check that the environment variable is set.";
};
};
/**
* Payload parsing error definitions.
* Use these for documentation, dashboards, and i18n.
*/
declare const PAYLOAD_ERRORS: {
readonly PAYLOAD_NULL: {
readonly message: "Webhook payload is null";
readonly suggestion: "Ensure you're passing the parsed JSON body, not null. Check your framework's body parsing middleware.";
};
readonly PAYLOAD_UNDEFINED: {
readonly message: "Webhook payload is undefined";
readonly suggestion: "The payload was not provided. Make sure you're passing the request body to the handler.";
};
readonly PAYLOAD_WRONG_TYPE: {
readonly message: "Webhook payload must be an object";
readonly suggestion: "The payload should be a parsed JSON object. Check that you're not passing a string or other primitive.";
};
readonly PAYLOAD_IS_ARRAY: {
readonly message: "Webhook payload is an array, expected object";
readonly suggestion: "Primitive webhooks are single event objects, not arrays. Check the payload structure.";
};
readonly PAYLOAD_MISSING_EVENT: {
readonly message: "Webhook payload missing 'event' field";
readonly suggestion: "All webhook payloads must have an 'event' field. This may not be a valid Primitive webhook.";
};
readonly PAYLOAD_UNKNOWN_EVENT: {
readonly message: "Unknown webhook event type";
readonly suggestion: "This event type is not recognized. You may need to update your SDK or handle unknown events gracefully.";
};
readonly PAYLOAD_EMPTY_BODY: {
readonly message: "Request body is empty";
readonly suggestion: "The request body was empty. Ensure the webhook is sending data and your framework is parsing it correctly.";
};
readonly JSON_PARSE_FAILED: {
readonly message: "Failed to parse JSON body";
readonly suggestion: "The request body is not valid JSON. Check the raw body content and Content-Type header.";
};
readonly INVALID_ENCODING: {
readonly message: "Invalid body encoding";
readonly suggestion: "The request body encoding is not supported. Primitive webhooks use UTF-8 encoded JSON.";
};
};
/**
* Raw email decode error definitions.
* Use these for documentation, dashboards, and i18n.
*/
declare const RAW_EMAIL_ERRORS: {
readonly NOT_INCLUDED: {
readonly message: "Raw email content not included inline";
readonly suggestion: "Use the download URL at event.email.content.download.url to fetch the raw email.";
};
readonly INVALID_BASE64: {
readonly message: "Raw email content is not valid base64";
readonly suggestion: "The raw email data is malformed. Fetch the raw email from the download URL or regenerate the webhook payload.";
};
readonly HASH_MISMATCH: {
readonly message: "SHA-256 hash verification failed";
readonly suggestion: "The raw email data may be corrupted. Try downloading from the URL instead.";
};
};
/**
* All error codes that can be thrown by the SDK.
*/
type WebhookErrorCode = WebhookVerificationErrorCode | WebhookPayloadErrorCode | WebhookValidationErrorCode | RawEmailDecodeErrorCode;
type RawEmailDecodeErrorCode = keyof typeof RAW_EMAIL_ERRORS;
/**
* Base class for all Primitive webhook errors.
*
* Catch this to handle any error from the SDK in a single catch block.
*
* @example
* ```typescript
* import { handleWebhook, PrimitiveWebhookError } from '@primitivedotdev/sdk';
*
* try {
* const event = handleWebhook({ body, headers, secret });
* } catch (err) {
* if (err instanceof PrimitiveWebhookError) {
* console.error(`[${err.code}] ${err.message}`);
* return res.status(400).json({ error: err.code });
* }
* throw err;
* }
* ```
*/
declare abstract class PrimitiveWebhookError extends Error {
/** Programmatic error code for monitoring and handling */
abstract readonly code: WebhookErrorCode;
/** Actionable guidance for fixing the issue */
abstract readonly suggestion: string;
/**
* Formats the error for logging/display.
*/
toString(): string;
/**
* Serializes cleanly for structured logging (Datadog, CloudWatch, etc.)
*/
toJSON(): {
name: string;
code: WebhookErrorCode;
message: string;
suggestion: string;
};
}
/**
* Error codes for webhook verification failures.
* Derived from VERIFICATION_ERRORS keys.
*/
type WebhookVerificationErrorCode = keyof typeof VERIFICATION_ERRORS;
/**
* Error thrown when webhook signature verification fails.
*
* Use the `code` property to programmatically handle specific error cases.
*/
declare class WebhookVerificationError extends PrimitiveWebhookError {
readonly code: WebhookVerificationErrorCode;
readonly suggestion: string;
constructor(code: WebhookVerificationErrorCode, message?: string, suggestion?: string);
}
/**
* Error codes for webhook payload parsing failures.
* Derived from PAYLOAD_ERRORS keys.
*/
type WebhookPayloadErrorCode = keyof typeof PAYLOAD_ERRORS;
/**
* Error thrown when webhook payload parsing fails (lightweight parser).
*
* Use the `code` property for programmatic handling and monitoring.
* The `suggestion` property contains actionable guidance for fixing the issue.
*/
declare class WebhookPayloadError extends PrimitiveWebhookError {
readonly code: WebhookPayloadErrorCode;
readonly suggestion: string;
/** Original error if this wraps another error (e.g., JSON.parse failure) */
readonly cause?: Error;
constructor(code: WebhookPayloadErrorCode, message?: string, suggestion?: string, cause?: Error);
}
/**
* Error code for schema validation failures.
*/
type WebhookValidationErrorCode = "SCHEMA_VALIDATION_FAILED";
/**
* Error thrown when schema validation fails.
*/
declare class WebhookValidationError extends PrimitiveWebhookError {
readonly code: WebhookValidationErrorCode;
readonly suggestion: string;
/** The specific field path that failed (e.g., "email.headers.from") */
readonly field: string;
/** Original schema validation errors for advanced debugging */
readonly validationErrors: readonly ErrorObject[];
/** Number of additional validation errors beyond the first */
readonly additionalErrorCount: number;
constructor(field: string, message: string, suggestion: string, validationErrors: readonly ErrorObject[]);
/**
* Formats the error for logging/display.
* Includes error count and suggestion.
*/
toString(): string;
/**
* Serializes cleanly for structured logging (Datadog, CloudWatch, etc.)
*/
toJSON(): {
name: string;
code: "SCHEMA_VALIDATION_FAILED";
field: string;
message: string;
suggestion: string;
additionalErrorCount: number;
};
}
/**
* Error thrown when raw email decoding or verification fails.
*
* Use the `code` property to determine the failure reason:
* - `NOT_INCLUDED`: Raw email not inline, must download from URL
* - `HASH_MISMATCH`: SHA-256 verification failed, content may be corrupted
*/
declare class RawEmailDecodeError extends PrimitiveWebhookError {
readonly code: RawEmailDecodeErrorCode;
readonly suggestion: string;
constructor(code: RawEmailDecodeErrorCode, message?: string);
}
//#endregion
export { buildForwardSubject as _, RawEmailDecodeErrorCode as a, normalizeReceivedEmail as b, WebhookPayloadError as c, WebhookValidationErrorCode as d, WebhookVerificationError as f, ReceivedEmailThread as g, ReceivedEmailAddress as h, RawEmailDecodeError as i, WebhookPayloadErrorCode as l, ReceivedEmail as m, PrimitiveWebhookError as n, VERIFICATION_ERRORS as o, WebhookVerificationErrorCode as p, RAW_EMAIL_ERRORS as r, WebhookErrorCode as s, PAYLOAD_ERRORS as t, WebhookValidationError as u, buildReplySubject as v, parseHeaderAddress as x, formatAddress as y };
import { N as WebhookEvent, j as ValidateEmailAuthResult, l as EmailAuth, u as EmailReceivedEvent } from "./types-BRWDMD7H.js";
import { m as ReceivedEmail, u as WebhookValidationError } from "./errors-CO-rv_nK.js";
//#region src/validation.d.ts
interface ValidationSuccess<T> {
success: true;
data: T;
}
interface ValidationFailure {
success: false;
error: WebhookValidationError;
}
type ValidationResult<T> = ValidationSuccess<T> | ValidationFailure;
declare function validateEmailReceivedEvent(input: unknown): EmailReceivedEvent;
declare function safeValidateEmailReceivedEvent(input: unknown): ValidationResult<EmailReceivedEvent>;
//#endregion
//#region src/webhook/download-tokens.d.ts
/**
* Signed download tokens.
*
* A download token is a self-describing bearer credential for fetching a
* specific email's raw bytes or attachment bundle from a per-deployment
* download endpoint. It binds:
*
* - `email_id`: the specific email the token authorizes.
* - `aud`: a caller-chosen audience label (e.g. the resource kind being
* downloaded). Tokens minted for one audience will not verify under another.
* - `exp`: an absolute expiration time (unix seconds).
*
* Format: `<base64url(payload)>.<base64url(signature)>` where `signature`
* is HMAC-SHA256 over the base64url-encoded payload using the shared secret.
*
* The audience is an opaque caller-chosen string. Both the issuer and the
* verifier must agree on the exact bytes; the SDK does not prescribe a
* convention. New integrations are encouraged to namespace audiences
* (e.g. `primitive:raw-download`).
*
* Tokens are stateless: verification needs only the shared secret. Keep
* expirations as short as operationally tolerable.
*/
/**
* Input for issuing a download token.
*/
interface GenerateDownloadTokenOptions {
/** The email ID the token authorizes. */
emailId: string;
/** Absolute expiration as unix seconds (not a TTL). */
expiresAt: number;
/** Caller-chosen audience label; the verifier must supply the same value. */
audience: string;
/** Shared HMAC secret. */
secret: string;
}
/**
* Issue a signed download token.
*
* The resulting token is `<base64url-payload>.<base64url-signature>`, where
* the payload is `{"email_id":"...","exp":...,"aud":"..."}` (snake_case,
* field order fixed) and the signature is HMAC-SHA256 of the base64url
* payload string using `secret`.
*
* @param params - Token inputs.
* @returns The signed token string.
*/
declare function generateDownloadToken(params: GenerateDownloadTokenOptions): string;
/**
* Input for verifying a download token.
*/
interface VerifyDownloadTokenOptions {
/** The token string to verify. */
token: string;
/** Expected email ID. Must match the token payload exactly. */
emailId: string;
/** Expected audience. Must match the token payload exactly. */
audience: string;
/** Shared HMAC secret. */
secret: string;
/** Override the current time (unix seconds) for deterministic tests. */
nowSeconds?: number;
}
/**
* Result of verifying a download token.
*
* On failure, `error` is a short human-readable reason suitable for logs.
* Do not surface it to untrusted clients; it may reveal which check failed.
*/
type VerifyDownloadTokenResult = {
valid: true;
} | {
valid: false;
error: string;
};
/**
* Verify a signed download token.
*
* Returns a discriminated-union result. The function never throws for
* verification failures. Only malformed inputs at the crypto layer would
* surface. Callers should check `result.valid` and log `result.error`.
*
* @param params - Verification inputs.
* @returns Whether the token is valid, plus a reason on failure.
*/
declare function verifyDownloadToken(params: VerifyDownloadTokenOptions): VerifyDownloadTokenResult;
//#endregion
//#region src/webhook/signing.d.ts
/**
* Webhook HMAC Signing (Stripe-style format)
*
* Implements HMAC-SHA256 signature for webhook security with timestamp validation.
* Prevents replay attacks by including timestamp in signature.
*
* Header format:
* Primitive-Signature: t=<unix_seconds>,v1=<hex_hmac_sha256>
*
* Signed payload format: "{timestamp}.{raw_body}"
*
* This format matches Stripe's webhook signature scheme, which is widely understood
* and easy to implement in any language with ~15 lines of code.
*/
/** Header name for incoming webhook signature */
declare const PRIMITIVE_SIGNATURE_HEADER = "Primitive-Signature";
/** Legacy header name kept for backward compatibility with older servers */
declare const LEGACY_SIGNATURE_HEADER = "MyMX-Signature";
/** Header name to confirm webhook was processed (prevents retries) */
declare const PRIMITIVE_CONFIRMED_HEADER = "X-Primitive-Confirmed";
/** Legacy confirmed header name kept for backward compatibility */
declare const LEGACY_CONFIRMED_HEADER = "X-MyMX-Confirmed";
/**
* Result from signing a webhook payload
*/
interface SignResult {
/** Full header value ready to set on Primitive-Signature */
header: string;
/** Unix timestamp used for signing */
timestamp: number;
/** Raw hex signature (useful for debugging/tests) */
v1: string;
}
/**
* Options for verifying a webhook signature
*/
interface VerifyOptions {
/** The raw HTTP request body (must be the exact bytes, not re-serialized JSON) */
rawBody: string | Buffer;
/** The full Primitive-Signature header value */
signatureHeader: string;
/** Your webhook secret */
secret: string | Buffer;
/** Max age in seconds (default: 300) */
toleranceSeconds?: number;
/** Override current time for testing (unix seconds) */
nowSeconds?: number;
}
/**
* Sign a webhook payload using HMAC-SHA256.
*
* Useful for:
* - Internal testing and dogfooding
* - Generating test vectors
* - Integration tests
*
* @param rawBody - The raw JSON body string to sign
* @param secret - The webhook secret key
* @param timestamp - Unix timestamp in seconds (defaults to current time)
*/
declare function signWebhookPayload(rawBody: string | Buffer, secret: string | Buffer, timestamp?: number): SignResult;
/**
* Verify a webhook signature.
*
* Throws `WebhookVerificationError` on failure with a specific error code.
*
* @example
* ```typescript
* import { verifyWebhookSignature, WebhookVerificationError } from '@primitivedotdev/sdk';
*
* try {
* const signatureHeader = req.headers['primitive-signature'];
* if (typeof signatureHeader !== 'string') {
* throw new Error('Missing Primitive-Signature header');
* }
* verifyWebhookSignature({
* rawBody: req.body, // raw string, NOT parsed JSON
* signatureHeader,
* secret: process.env.PRIMITIVE_WEBHOOK_SECRET!,
* });
* // Signature is valid, process the webhook
* } catch (err) {
* if (err instanceof WebhookVerificationError) {
* console.error('Invalid webhook:', err.code, err.message);
* }
* return res.status(400).send('Invalid signature');
* }
* ```
*/
declare function verifyWebhookSignature(opts: VerifyOptions): true;
//#endregion
//#region src/webhook/standard-webhooks.d.ts
/**
* Standard Webhooks Verification & Signing
*
* Implements the Standard Webhooks spec (standardwebhooks.com) for webhook
* signature verification and payload signing.
*
* Header format:
* webhook-id: <msg_id>
* webhook-timestamp: <unix_seconds>
* webhook-signature: v1,<base64_hmac_sha256> [v1,<base64_2> ...]
*
* Signed payload format: "{msg_id}.{timestamp}.{raw_body}"
*
* Secrets are base64-encoded, optionally prefixed with "whsec_".
*/
/** Standard Webhooks header names */
declare const STANDARD_WEBHOOK_ID_HEADER = "webhook-id";
declare const STANDARD_WEBHOOK_TIMESTAMP_HEADER = "webhook-timestamp";
declare const STANDARD_WEBHOOK_SIGNATURE_HEADER = "webhook-signature";
/**
* Result from signing a payload in Standard Webhooks format.
*/
interface StandardWebhooksSignResult {
/** The webhook-signature header value (e.g. "v1,<base64>") */
signature: string;
/** The message ID used for signing */
msgId: string;
/** Unix timestamp used for signing */
timestamp: number;
}
/**
* Options for verifying a Standard Webhooks signature.
*/
interface StandardWebhooksVerifyOptions {
/** The raw HTTP request body */
rawBody: string | Buffer;
/** The webhook-id header value */
msgId: string;
/** The webhook-timestamp header value (string, parsed to number internally) */
timestamp: string;
/** The webhook-signature header value */
signatureHeader: string;
/** Your webhook secret (with or without whsec_ prefix) */
secret: string | Buffer;
/** Max age in seconds (default: 300) */
toleranceSeconds?: number;
/** Override current time for testing (unix seconds) */
nowSeconds?: number;
}
/**
* Sign a webhook payload using the Standard Webhooks format.
*
* @param rawBody - The raw JSON body string to sign
* @param secret - The webhook secret (with or without whsec_ prefix)
* @param msgId - The message ID (used in webhook-id header)
* @param timestamp - Unix timestamp in seconds (defaults to current time)
*/
declare function signStandardWebhooksPayload(rawBody: string | Buffer, secret: string | Buffer, msgId: string, timestamp?: number): StandardWebhooksSignResult;
/**
* Verify a Standard Webhooks signature.
*
* Throws `WebhookVerificationError` on failure with a specific error code.
*/
declare function verifyStandardWebhooksSignature(opts: StandardWebhooksVerifyOptions): true;
//#endregion
//#region src/schema.generated.d.ts
/**
* JSON Schema for EmailReceivedEvent.
*
* AUTO-GENERATED - DO NOT EDIT
* Run `pnpm generate:schema` to regenerate.
*/
declare const emailReceivedEventJsonSchema: {
readonly $schema: "http://json-schema.org/draft-07/schema#";
readonly $ref: "#/definitions/EmailReceivedEvent";
readonly definitions: {
readonly EmailReceivedEvent: {
readonly type: "object";
readonly properties: {
readonly id: {
readonly type: "string";
readonly pattern: "^evt_[a-f0-9]{64}$";
readonly description: "Unique delivery event ID.\n\nThis ID is stable across retries to the same endpoint - use it as your idempotency/dedupe key. Note that the same email delivered to different endpoints will have different event IDs.\n\nFormat: `evt_` prefix followed by a SHA-256 hash (64 hex characters). Example: `evt_a1b2c3d4e5f6...` (68 characters total)";
};
readonly event: {
readonly type: "string";
readonly const: "email.received";
readonly description: "Event type identifier. Always `\"email.received\"` for this event type.";
};
readonly version: {
readonly $ref: "#/definitions/WebhookVersion";
readonly description: "API version in date format (YYYY-MM-DD). Use this to detect version mismatches between webhook and SDK.";
};
readonly delivery: {
readonly type: "object";
readonly properties: {
readonly endpoint_id: {
readonly type: "string";
readonly description: "ID of the webhook endpoint receiving this event. Matches the endpoint ID from your Primitive dashboard.";
};
readonly attempt: {
readonly type: "integer";
readonly minimum: 1;
readonly description: "Delivery attempt number, starting at 1. Increments with each retry if previous attempts failed.";
};
readonly attempted_at: {
readonly type: "string";
readonly format: "date-time";
readonly description: "ISO 8601 timestamp (UTC) when this delivery was attempted.";
readonly examples: ["2025-01-15T10:30:00.000Z"];
};
};
readonly required: ["endpoint_id", "attempt", "attempted_at"];
readonly description: "Metadata about this webhook delivery.";
};
readonly email: {
readonly type: "object";
readonly properties: {
readonly id: {
readonly type: "string";
readonly description: "Unique email ID in Primitive. Use this ID when calling Primitive APIs to reference this email.";
};
readonly received_at: {
readonly type: "string";
readonly format: "date-time";
readonly description: "ISO 8601 timestamp (UTC) when Primitive received the email.";
readonly examples: ["2025-01-15T10:29:55.123Z"];
};
readonly smtp: {
readonly type: "object";
readonly properties: {
readonly helo: {
readonly type: ["string", "null"];
readonly description: "HELO/EHLO hostname from the sending server. Null if not provided during SMTP transaction.";
};
readonly mail_from: {
readonly type: "string";
readonly description: "SMTP envelope sender (MAIL FROM command). This is the bounce address, which may differ from the From header.";
};
readonly rcpt_to: {
readonly type: "array";
readonly items: {
readonly type: "string";
};
readonly minItems: 1;
readonly description: "SMTP envelope recipients (RCPT TO commands). All addresses that received this email in a single delivery.";
};
};
readonly required: ["helo", "mail_from", "rcpt_to"];
readonly description: "SMTP envelope information. This is the \"real\" sender/recipient info from the SMTP transaction, which may differ from the headers (e.g., BCC recipients).";
};
readonly headers: {
readonly type: "object";
readonly properties: {
readonly message_id: {
readonly type: ["string", "null"];
readonly description: "Message-ID header value. Null if the email had no Message-ID header.";
};
readonly subject: {
readonly type: ["string", "null"];
readonly description: "Subject header value. Null if the email had no Subject header.";
};
readonly from: {
readonly type: "string";
readonly minLength: 1;
readonly description: "From header value. May include display name: `\"John Doe\" <john@example.com>`";
};
readonly to: {
readonly type: "string";
readonly minLength: 1;
readonly description: "To header value. May include multiple addresses or display names.";
};
readonly date: {
readonly type: ["string", "null"];
readonly description: "Date header value as it appeared in the email. Null if the email had no Date header.";
};
};
readonly required: ["message_id", "subject", "from", "to", "date"];
readonly description: "Parsed email headers. These are extracted from the email content, not the SMTP envelope.";
};
readonly content: {
readonly type: "object";
readonly properties: {
readonly raw: {
readonly $ref: "#/definitions/RawContent";
readonly description: "Raw email in RFC 5322 format. May be inline (base64) or download-only depending on size.";
};
readonly download: {
readonly type: "object";
readonly properties: {
readonly url: {
readonly type: "string";
readonly format: "uri";
readonly pattern: "^https?://";
readonly description: "URL to download the raw email as-is in RFC 5322 format. Managed Primitive always issues HTTPS. Self-host deployments may issue HTTP URLs that resolve inside the operator's network (e.g. `http://localhost:4001/...`). Receivers that want to refuse plaintext downloads should check the scheme explicitly.";
};
readonly expires_at: {
readonly type: "string";
readonly format: "date-time";
readonly description: "ISO 8601 timestamp (UTC) when this URL expires. Download before this time or the URL will return 403.";
};
};
readonly required: ["url", "expires_at"];
readonly description: "Download information for the raw email. Always present, even if raw content is inline.";
};
};
readonly required: ["raw", "download"];
readonly description: "Raw email content and download information.";
};
readonly parsed: {
readonly $ref: "#/definitions/ParsedData";
readonly description: "Parsed email content (body text, HTML, attachments). Check `status` to determine if parsing succeeded.";
};
readonly analysis: {
readonly $ref: "#/definitions/EmailAnalysis";
readonly description: "Email analysis and classification results.";
};
readonly auth: {
readonly $ref: "#/definitions/EmailAuth";
readonly description: "Email authentication results (SPF, DKIM, DMARC).";
};
};
readonly required: ["id", "received_at", "smtp", "headers", "content", "parsed", "analysis", "auth"];
readonly description: "The email that triggered this event.";
};
};
readonly required: ["id", "event", "version", "delivery", "email"];
readonly description: "Webhook payload for the `email.received` event.\n\nThis is delivered to your webhook endpoint when Primitive receives an email matching your domain configuration.";
};
readonly WebhookVersion: {
readonly type: "string";
readonly pattern: "^(?:(?:\\d{4}-(?:(?:01|03|05|07|08|10|12)-(?:0[1-9]|[12]\\d|3[01])|(?:04|06|09|11)-(?:0[1-9]|[12]\\d|30)|02-(?:0[1-9]|1\\d|2[0-8])))|(?:(?:[02468][048]00|[13579][26]00|\\d{2}(?:0[48]|[2468][048]|[13579][26]))-02-29))$";
readonly description: "Valid webhook version format (YYYY-MM-DD date string). The SDK accepts any valid date-formatted version, not just the current one, for forward and backward compatibility.";
};
readonly RawContent: {
readonly anyOf: [{
readonly $ref: "#/definitions/RawContentInline";
}, {
readonly $ref: "#/definitions/RawContentDownloadOnly";
}];
readonly description: "Raw email content - a discriminated union on `included`.";
};
readonly RawContentInline: {
readonly type: "object";
readonly properties: {
readonly included: {
readonly type: "boolean";
readonly const: true;
readonly description: "Discriminant indicating raw content is included inline.";
};
readonly encoding: {
readonly type: "string";
readonly const: "base64";
readonly description: "Encoding used for the data field. Always \"base64\".";
};
readonly max_inline_bytes: {
readonly type: "integer";
readonly minimum: 1;
readonly description: "Maximum size in bytes for inline inclusion. Emails larger than this threshold require download.";
};
readonly size_bytes: {
readonly type: "integer";
readonly minimum: 0;
readonly description: "Actual size of the raw email in bytes.";
};
readonly sha256: {
readonly type: "string";
readonly pattern: "^[a-fA-F0-9]{64}$";
readonly description: "SHA-256 hash of the raw email content (hex-encoded). Use this to verify integrity after base64 decoding.";
};
readonly data: {
readonly type: "string";
readonly description: "Base64-encoded raw email (RFC 5322 format). Decode with `Buffer.from(data, 'base64')` in Node.js.";
};
};
readonly required: ["included", "encoding", "max_inline_bytes", "size_bytes", "sha256", "data"];
readonly description: "Raw email content included inline (base64 encoded).\n\nWhen the raw email is small enough (under {@link max_inline_bytes } ), it's included directly in the webhook payload for convenience.";
};
readonly RawContentDownloadOnly: {
readonly type: "object";
readonly properties: {
readonly included: {
readonly type: "boolean";
readonly const: false;
readonly description: "Discriminant indicating raw content must be downloaded.";
};
readonly reason_code: {
readonly type: "string";
readonly const: "size_exceeded";
readonly description: "Reason the content wasn't included inline.";
};
readonly max_inline_bytes: {
readonly type: "integer";
readonly minimum: 1;
readonly description: "Maximum size in bytes for inline inclusion. The email exceeded this threshold.";
};
readonly size_bytes: {
readonly type: "integer";
readonly minimum: 0;
readonly description: "Actual size of the raw email in bytes.";
};
readonly sha256: {
readonly type: "string";
readonly pattern: "^[a-fA-F0-9]{64}$";
readonly description: "SHA-256 hash of the raw email content (hex-encoded). Use this to verify integrity after download.";
};
};
readonly required: ["included", "reason_code", "max_inline_bytes", "size_bytes", "sha256"];
readonly description: "Raw email content not included (must be downloaded).\n\nWhen the raw email exceeds {@link max_inline_bytes } , it's not included in the webhook payload. Use the download URL from {@link EmailReceivedEvent.email.content.download } to fetch it.";
};
readonly ParsedData: {
readonly anyOf: [{
readonly $ref: "#/definitions/ParsedDataComplete";
}, {
readonly $ref: "#/definitions/ParsedDataFailed";
}];
readonly description: "Parsed email content - a discriminated union on `status`.";
};
readonly ParsedDataComplete: {
readonly type: "object";
readonly properties: {
readonly status: {
readonly type: "string";
readonly const: "complete";
readonly description: "Discriminant indicating successful parsing.";
};
readonly error: {
readonly type: "null";
readonly description: "Always null when parsing succeeds.";
};
readonly body_text: {
readonly type: ["string", "null"];
readonly description: "Plain text body of the email. Null if the email had no text/plain part.";
};
readonly body_html: {
readonly type: ["string", "null"];
readonly description: "HTML body of the email. Null if the email had no text/html part.";
};
readonly reply_to: {
readonly anyOf: [{
readonly type: "array";
readonly items: {
readonly $ref: "#/definitions/EmailAddress";
};
}, {
readonly type: "null";
}];
readonly description: "Parsed Reply-To header addresses. Null if the email had no Reply-To header.";
};
readonly cc: {
readonly anyOf: [{
readonly type: "array";
readonly items: {
readonly $ref: "#/definitions/EmailAddress";
};
}, {
readonly type: "null";
}];
readonly description: "Parsed CC header addresses. Null if the email had no CC header.";
};
readonly bcc: {
readonly anyOf: [{
readonly type: "array";
readonly items: {
readonly $ref: "#/definitions/EmailAddress";
};
}, {
readonly type: "null";
}];
readonly description: "Parsed BCC header addresses. Null if the email had no BCC header. Note: BCC is only available for outgoing emails or when explicitly provided.";
};
readonly to_addresses: {
readonly anyOf: [{
readonly type: "array";
readonly items: {
readonly $ref: "#/definitions/EmailAddress";
};
}, {
readonly type: "null";
}];
readonly description: "Parsed To header addresses. Null if the email had no To header.";
};
readonly in_reply_to: {
readonly anyOf: [{
readonly type: "array";
readonly items: {
readonly type: "string";
};
}, {
readonly type: "null";
}];
readonly description: "In-Reply-To header values (Message-IDs of the email(s) being replied to). Null if the email had no In-Reply-To header. Per RFC 5322, this can contain multiple Message-IDs, though typically just one.";
readonly examples: [["<original-message-id@example.com>"]];
};
readonly references: {
readonly anyOf: [{
readonly type: "array";
readonly items: {
readonly type: "string";
};
}, {
readonly type: "null";
}];
readonly description: "References header values (Message-IDs of the email thread). Null if the email had no References header.";
readonly examples: [["<msg1@example.com>", "<msg2@example.com>"]];
};
readonly attachments: {
readonly type: "array";
readonly items: {
readonly $ref: "#/definitions/WebhookAttachment";
};
readonly description: "List of attachments with metadata. Use {@link attachments_download_url } to download the actual files.";
};
readonly attachments_download_url: {
readonly type: ["string", "null"];
readonly format: "uri";
readonly pattern: "^https?://";
readonly description: "URL to download all attachments as a tar.gz archive. Null if the email had no attachments. Managed Primitive always issues HTTPS. Self-host deployments may issue HTTP URLs that resolve inside the operator's network. URL expires - check the expiration before downloading.";
};
};
readonly required: ["status", "error", "body_text", "body_html", "reply_to", "cc", "bcc", "to_addresses", "in_reply_to", "references", "attachments", "attachments_download_url"];
readonly description: "Parsed email content when parsing succeeded.\n\nUse the discriminant `status: \"complete\"` to narrow from {@link ParsedData } .";
};
readonly EmailAddress: {
readonly type: "object";
readonly properties: {
readonly address: {
readonly type: "string";
readonly description: "The email address portion (e.g., \"john@example.com\").\n\nThis is the raw value from the email header with no validation applied. May contain unusual but valid formats like quoted local parts.";
};
readonly name: {
readonly type: ["string", "null"];
readonly description: "The display name portion, if present. Null if the address had no display name.\n\nMay contain any characters including unicode, emoji, or special characters as they appeared in the original email header.";
};
};
readonly required: ["address", "name"];
readonly description: "A parsed email address with optional display name.\n\nThis structure is used in the `parsed` section of the webhook payload (e.g., `reply_to`, `cc`, `bcc`). For unparsed header strings, see the `headers` section (e.g., `event.email.headers.from`).";
};
readonly WebhookAttachment: {
readonly type: "object";
readonly properties: {
readonly filename: {
readonly type: ["string", "null"];
readonly description: "Original filename from the email. May be null if the attachment had no filename specified.";
};
readonly content_type: {
readonly type: "string";
readonly description: "MIME content type (e.g., \"application/pdf\", \"image/png\").";
};
readonly size_bytes: {
readonly type: "integer";
readonly minimum: 0;
readonly description: "Size of the attachment in bytes.";
};
readonly sha256: {
readonly type: "string";
readonly pattern: "^[a-fA-F0-9]{64}$";
readonly description: "SHA-256 hash of the attachment content (hex-encoded). Use this to verify attachment integrity after download.";
};
readonly part_index: {
readonly type: "integer";
readonly minimum: 0;
readonly description: "Zero-based index of this part in the MIME structure.";
};
readonly tar_path: {
readonly type: "string";
readonly description: "Path to this attachment within the downloaded tar.gz archive.";
};
};
readonly required: ["filename", "content_type", "size_bytes", "sha256", "part_index", "tar_path"];
readonly description: "Metadata for an email attachment.\n\nAttachment content is not included directly in the webhook payload. Use the `attachments_download_url` from {@link ParsedDataComplete } to download all attachments as a tar.gz archive.";
};
readonly ParsedDataFailed: {
readonly type: "object";
readonly properties: {
readonly status: {
readonly type: "string";
readonly const: "failed";
readonly description: "Discriminant indicating parsing failed.";
};
readonly error: {
readonly $ref: "#/definitions/ParsedError";
readonly description: "Details about why parsing failed.";
};
readonly body_text: {
readonly type: "null";
readonly description: "Always null when parsing fails.";
};
readonly body_html: {
readonly type: "null";
readonly description: "Always null when parsing fails.";
};
readonly reply_to: {
readonly type: "null";
readonly description: "Always null when parsing fails.";
};
readonly cc: {
readonly type: "null";
readonly description: "Always null when parsing fails.";
};
readonly bcc: {
readonly type: "null";
readonly description: "Always null when parsing fails.";
};
readonly to_addresses: {
readonly type: "null";
readonly description: "Always null when parsing fails.";
};
readonly in_reply_to: {
readonly type: "null";
readonly description: "Always null when parsing fails.";
};
readonly references: {
readonly type: "null";
readonly description: "Always null when parsing fails.";
};
readonly attachments: {
readonly type: "array";
readonly items: {
readonly $ref: "#/definitions/WebhookAttachment";
};
readonly description: "May contain partial attachment metadata even when parsing failed. Useful for debugging or recovering partial data.";
};
readonly attachments_download_url: {
readonly type: "null";
readonly description: "Always null when parsing fails.";
};
};
readonly required: ["status", "error", "body_text", "body_html", "reply_to", "cc", "bcc", "to_addresses", "in_reply_to", "references", "attachments", "attachments_download_url"];
readonly description: "Parsed email content when parsing failed.\n\nUse the discriminant `status: \"failed\"` to narrow from {@link ParsedData } .";
};
readonly ParsedError: {
readonly type: "object";
readonly properties: {
readonly code: {
readonly type: "string";
readonly enum: ["PARSE_FAILED", "ATTACHMENT_EXTRACTION_FAILED"];
readonly description: "Error code indicating the type of failure.\n- `PARSE_FAILED`: The email could not be parsed (e.g., malformed MIME)\n- `ATTACHMENT_EXTRACTION_FAILED`: Email parsed but attachments couldn't be extracted";
};
readonly message: {
readonly type: "string";
readonly description: "Human-readable error message describing what went wrong.";
};
readonly retryable: {
readonly type: "boolean";
readonly description: "Whether retrying might succeed. If true, the error was transient (e.g., timeout). If false, the email itself is problematic.";
};
};
readonly required: ["code", "message", "retryable"];
readonly description: "Error details when email parsing fails.";
};
readonly EmailAnalysis: {
readonly type: "object";
readonly properties: {
readonly spamassassin: {
readonly type: "object";
readonly properties: {
readonly score: {
readonly type: "number";
readonly description: "Overall spam score (sum of all rule scores). Higher scores indicate higher likelihood of spam. Unbounded - can be negative (ham) or very high (spam).";
};
};
readonly required: ["score"];
readonly description: "SpamAssassin analysis results.\n\nOptional. Present when the email was processed by a SpamAssassin-equipped pipeline (always present in Primitive's managed service). When absent, spam scoring was not performed on this email.";
};
readonly forward: {
readonly $ref: "#/definitions/ForwardAnalysis";
readonly description: "Forward detection and analysis results.\n\nOptional. Present when the email was processed by a forward-detection pipeline (always present in Primitive's managed service). When absent, forward detection was not performed on this email.";
};
};
readonly description: "Email analysis and classification results.\n\nAll properties in this object are optional. Which fields are present depends on the analysis pipeline processing the email. Primitive's managed service populates all fields. Self-hosted or third-party deployments may include some, all, or none of these fields depending on their pipeline configuration.\n\nWhen a field is absent, it means that particular analysis was not performed, not that the analysis produced no results. For example, a missing `spamassassin` field means SpamAssassin was not run, not that the email scored 0.\n\nThese fields may be omitted from the payload entirely but must not be set to null.";
};
readonly ForwardAnalysis: {
readonly type: "object";
readonly properties: {
readonly detected: {
readonly type: "boolean";
readonly description: "Whether any forwards were detected in the email.";
};
readonly results: {
readonly type: "array";
readonly items: {
readonly $ref: "#/definitions/ForwardResult";
};
readonly description: "Analysis results for each detected forward.";
};
readonly attachments_found: {
readonly type: "integer";
readonly minimum: 0;
readonly description: "Total number of .eml attachments found.";
};
readonly attachments_analyzed: {
readonly type: "integer";
readonly minimum: 0;
readonly description: "Number of .eml attachments that were analyzed.";
};
readonly attachments_limit: {
readonly type: ["integer", "null"];
readonly minimum: 1;
readonly description: "Maximum number of attachments that will be analyzed, or null if unlimited.";
};
};
readonly required: ["detected", "results", "attachments_found", "attachments_analyzed", "attachments_limit"];
readonly description: "Forward detection and analysis results.";
};
readonly ForwardResult: {
readonly anyOf: [{
readonly $ref: "#/definitions/ForwardResultInline";
}, {
readonly $ref: "#/definitions/ForwardResultAttachmentAnalyzed";
}, {
readonly $ref: "#/definitions/ForwardResultAttachmentSkipped";
}];
readonly description: "Result for a single forwarded email detected in the message.\n\nUse the `type` and `analyzed` fields to narrow the type:\n- `type: 'inline'` - Inline forward, always analyzed\n- `type: 'attachment'` + `analyzed: true` - Analyzed attachment\n- `type: 'attachment'` + `analyzed: false` - Skipped attachment";
};
readonly ForwardResultInline: {
readonly type: "object";
readonly properties: {
readonly type: {
readonly type: "string";
readonly const: "inline";
};
readonly original_sender: {
readonly anyOf: [{
readonly $ref: "#/definitions/ForwardOriginalSender";
}, {
readonly type: "null";
}];
readonly description: "Original sender of the forwarded email, if extractable.";
};
readonly verification: {
readonly $ref: "#/definitions/ForwardVerification";
readonly description: "Verification result for the forwarded email.";
};
readonly summary: {
readonly type: "string";
readonly description: "Human-readable summary of the forward analysis.";
};
};
readonly required: ["type", "original_sender", "verification", "summary"];
readonly description: "Result for an inline forward that was detected and analyzed. Inline forwards are always analyzed when forward detection is enabled.";
};
readonly ForwardOriginalSender: {
readonly type: "object";
readonly properties: {
readonly email: {
readonly type: "string";
readonly description: "Email address of the original sender.";
};
readonly domain: {
readonly type: "string";
readonly description: "Domain of the original sender.";
};
};
readonly required: ["email", "domain"];
readonly description: "Original sender information extracted from the forwarded email.";
};
readonly ForwardVerification: {
readonly type: "object";
readonly properties: {
readonly verdict: {
readonly $ref: "#/definitions/ForwardVerdict";
readonly description: "Overall verdict on whether the forward is authentic.";
};
readonly confidence: {
readonly $ref: "#/definitions/AuthConfidence";
readonly description: "Confidence level for this verdict.";
};
readonly dkim_verified: {
readonly type: "boolean";
readonly description: "Whether a valid DKIM signature was found that verifies the original sender.";
};
readonly dkim_domain: {
readonly type: ["string", "null"];
readonly description: "Domain of the DKIM signature that verified the forward, if any.";
};
readonly dmarc_policy: {
readonly $ref: "#/definitions/DmarcPolicy";
readonly description: "DMARC policy of the original sender's domain.";
};
};
readonly required: ["verdict", "confidence", "dkim_verified", "dkim_domain", "dmarc_policy"];
readonly description: "Verification result for a forwarded email.";
};
readonly ForwardVerdict: {
readonly type: "string";
readonly enum: ["legit", "unknown"];
readonly description: "Verdict for forwarded email verification.\n\n- `legit`: DKIM signature verified the original sender\n- `unknown`: Could not verify the forwarded email's authenticity";
};
readonly AuthConfidence: {
readonly type: "string";
readonly enum: ["high", "medium", "low"];
readonly description: "Confidence level for the authentication verdict.\n\n- `high`: Strong cryptographic evidence (DKIM aligned + DMARC pass)\n- `medium`: Good evidence but with caveats (SPF-only alignment)\n- `low`: Weak evidence (missing authentication or unclear results)";
};
readonly DmarcPolicy: {
readonly type: ["string", "null"];
readonly enum: ["reject", "quarantine", "none", null];
readonly description: "DMARC policy action specified in the domain's DMARC record.\n\n- `reject`: The domain owner requests that receivers reject failing emails\n- `quarantine`: The domain owner requests that failing emails be treated as suspicious\n- `none`: The domain owner is only monitoring (no action requested)\n- `null`: No DMARC policy was found for the domain";
};
readonly ForwardResultAttachmentAnalyzed: {
readonly type: "object";
readonly properties: {
readonly type: {
readonly type: "string";
readonly const: "attachment";
};
readonly attachment_tar_path: {
readonly type: "string";
readonly description: "Path to the attachment in the attachments tar archive.";
};
readonly attachment_filename: {
readonly type: ["string", "null"];
readonly description: "Original filename of the attachment, if available.";
};
readonly analyzed: {
readonly type: "boolean";
readonly const: true;
readonly description: "Whether this attachment was analyzed.";
};
readonly original_sender: {
readonly anyOf: [{
readonly $ref: "#/definitions/ForwardOriginalSender";
}, {
readonly type: "null";
}];
readonly description: "Original sender of the forwarded email, if extractable.";
};
readonly verification: {
readonly $ref: "#/definitions/ForwardVerification";
readonly description: "Verification result for the forwarded email.";
};
readonly summary: {
readonly type: "string";
readonly description: "Human-readable summary of the forward analysis.";
};
};
readonly required: ["type", "attachment_tar_path", "attachment_filename", "analyzed", "original_sender", "verification", "summary"];
readonly description: "Result for an attachment forward that was analyzed.";
};
readonly ForwardResultAttachmentSkipped: {
readonly type: "object";
readonly properties: {
readonly type: {
readonly type: "string";
readonly const: "attachment";
};
readonly attachment_tar_path: {
readonly type: "string";
readonly description: "Path to the attachment in the attachments tar archive.";
};
readonly attachment_filename: {
readonly type: ["string", "null"];
readonly description: "Original filename of the attachment, if available.";
};
readonly analyzed: {
readonly type: "boolean";
readonly const: false;
readonly description: "Whether this attachment was analyzed.";
};
readonly original_sender: {
readonly type: "null";
readonly description: "Always null when not analyzed.";
};
readonly verification: {
readonly type: "null";
readonly description: "Always null when not analyzed.";
};
readonly summary: {
readonly type: "string";
readonly description: "Human-readable summary explaining why analysis was skipped.";
};
};
readonly required: ["type", "attachment_tar_path", "attachment_filename", "analyzed", "original_sender", "verification", "summary"];
readonly description: "Result for an attachment forward that was detected but not analyzed. This occurs when attachment analysis is disabled or the limit was reached.";
};
readonly EmailAuth: {
readonly type: "object";
readonly properties: {
readonly spf: {
readonly $ref: "#/definitions/SpfResult";
readonly description: "SPF verification result.\n\nSPF checks if the sending IP is authorized by the envelope sender's domain. \"pass\" means the IP is authorized; \"fail\" means it's explicitly not allowed.";
};
readonly dmarc: {
readonly $ref: "#/definitions/DmarcResult";
readonly description: "DMARC verification result.\n\nDMARC passes if either SPF or DKIM passes AND aligns with the From: domain. \"pass\" means the email is authenticated according to the sender's policy.";
};
readonly dmarcPolicy: {
readonly $ref: "#/definitions/DmarcPolicy";
readonly description: "DMARC policy from the sender's DNS record.\n\n- `reject`: Domain wants receivers to reject failing emails\n- `quarantine`: Domain wants failing emails marked as suspicious\n- `none`: Domain is monitoring only (no action requested)\n- `null`: No DMARC record found for this domain";
};
readonly dmarcFromDomain: {
readonly type: ["string", "null"];
readonly description: "The organizational domain used for DMARC lookups.\n\nFor example, if the From: address is `user@mail.example.com`, the DMARC lookup checks `_dmarc.mail.example.com`, then falls back to `_dmarc.example.com`. This field shows which domain's policy was used.";
};
readonly dmarcSpfAligned: {
readonly type: "boolean";
readonly description: "Whether SPF aligned with the From: domain for DMARC purposes.\n\nTrue if the envelope sender domain matches the From: domain (per alignment mode).";
};
readonly dmarcDkimAligned: {
readonly type: "boolean";
readonly description: "Whether DKIM aligned with the From: domain for DMARC purposes.\n\nTrue if at least one DKIM signature's domain matches the From: domain.";
};
readonly dmarcSpfStrict: {
readonly type: ["boolean", "null"];
readonly description: "Whether DMARC SPF alignment mode is strict.\n\n- `true`: Strict alignment required (exact domain match)\n- `false`: Relaxed alignment allowed (organizational domain match)\n- `null`: No DMARC record found";
};
readonly dmarcDkimStrict: {
readonly type: ["boolean", "null"];
readonly description: "Whether DMARC DKIM alignment mode is strict.\n\n- `true`: Strict alignment required (exact domain match)\n- `false`: Relaxed alignment allowed (organizational domain match)\n- `null`: No DMARC record found";
};
readonly dkimSignatures: {
readonly type: "array";
readonly items: {
readonly $ref: "#/definitions/DkimSignature";
};
readonly description: "All DKIM signatures found in the email with their verification results.\n\nMay be empty if no DKIM signatures were present.";
};
};
readonly required: ["spf", "dmarc", "dmarcPolicy", "dmarcFromDomain", "dmarcSpfAligned", "dmarcDkimAligned", "dmarcSpfStrict", "dmarcDkimStrict", "dkimSignatures"];
readonly description: "Email authentication results for SPF, DKIM, and DMARC.\n\nUse `validateEmailAuth()` to compute a verdict based on these results.";
};
readonly SpfResult: {
readonly type: "string";
readonly enum: ["pass", "fail", "softfail", "neutral", "none", "temperror", "permerror"];
readonly description: "SPF verification result.";
};
readonly DmarcResult: {
readonly type: "string";
readonly enum: ["pass", "fail", "none", "temperror", "permerror"];
readonly description: "DMARC verification result.";
};
readonly DkimSignature: {
readonly type: "object";
readonly properties: {
readonly domain: {
readonly type: "string";
readonly description: "The domain that signed this DKIM signature (d= tag). This may differ from the From: domain (that's what alignment checks).";
};
readonly selector: {
readonly type: ["string", "null"];
readonly description: "The DKIM selector used to locate the public key (s= tag). Combined with the domain to form the DNS lookup: `selector._domainkey.domain`\n\nOptional in self-hosted environments where the milter may not provide selector info.";
};
readonly result: {
readonly $ref: "#/definitions/DkimResult";
readonly description: "Verification result for this specific signature.";
};
readonly aligned: {
readonly type: "boolean";
readonly description: "Whether this signature's domain aligns with the From: domain (for DMARC).\n\nAlignment can be \"strict\" (exact match) or \"relaxed\" (organizational domain match). For example, if From: is `user@sub.example.com` and DKIM is signed by `example.com`:\n- Relaxed alignment: true (same organizational domain)\n- Strict alignment: false (not exact match)";
};
readonly keyBits: {
readonly type: ["integer", "null"];
readonly minimum: 1;
readonly maximum: 16384;
readonly description: "Key size in bits (e.g., 1024, 2048). Null if the key size couldn't be determined.\n\nOptional in self-hosted environments.";
};
readonly algo: {
readonly type: ["string", "null"];
readonly description: "Signing algorithm (e.g., \"rsa-sha256\", \"ed25519-sha256\").\n\nOptional in self-hosted environments.";
};
};
readonly required: ["domain", "selector", "result", "aligned", "keyBits", "algo"];
readonly description: "Details about a single DKIM signature found in the email.\n\nAn email may have multiple DKIM signatures (e.g., one from the sending domain and one from the ESP). Each signature is verified independently.";
};
readonly DkimResult: {
readonly type: "string";
readonly enum: ["pass", "fail", "temperror", "permerror"];
readonly description: "DKIM signature verification result for a single signature.";
};
};
};
//#endregion
//#region src/webhook/auth.d.ts
/**
* Validate email authentication and compute a verdict.
*
* This function analyzes SPF, DKIM, and DMARC results to determine
* whether an email is likely authentic ("legit"), potentially spoofed
* ("suspicious"), or indeterminate ("unknown").
*
* ## Verdict Logic
*
* **Legit (high confidence):**
* - DMARC pass with DKIM alignment (cryptographic proof of authenticity)
*
* **Legit (medium confidence):**
* - DMARC pass with SPF alignment only (no DKIM)
* - Note: SPF can break through forwarding, but DMARC pass is still meaningful
*
* **Suspicious (high confidence):**
* - DMARC fail when domain has `reject` or `quarantine` policy
* - The domain owner explicitly says to distrust failing emails
* - SPF explicitly fails (IP not authorized by sender)
*
* **Suspicious (low confidence):**
* - DMARC fail when domain has `none` policy (monitoring mode)
* - No DMARC record but SPF/DKIM fail
*
* **Unknown:**
* - No DMARC record and no clear pass/fail
* - Temporary errors during authentication
* - No authentication data available
*
* @param auth - Email authentication results from the webhook
* @returns Verdict, confidence level, and explanatory reasons
*
* @example
* ```typescript
* const result = validateEmailAuth({
* spf: 'pass',
* dmarc: 'pass',
* dmarcPolicy: 'reject',
* dmarcFromDomain: 'example.com',
* dmarcSpfAligned: true,
* dmarcDkimAligned: true,
* dmarcSpfStrict: false,
* dmarcDkimStrict: false,
* dkimSignatures: [{
* domain: 'example.com',
* selector: 'default',
* result: 'pass',
* aligned: true,
* keyBits: 2048,
* algo: 'rsa-sha256',
* }],
* });
*
* // result.verdict === 'legit'
* // result.confidence === 'high'
* // result.reasons === ['DMARC passed with DKIM alignment']
* ```
*/
declare function validateEmailAuth(auth: EmailAuth): ValidateEmailAuthResult;
//#endregion
//#region src/webhook/version.d.ts
/**
* Webhook API Version
*
* Single source of truth for the webhook version.
* Update this file when bumping the API version.
*/
/**
* The current webhook API version this SDK is built for.
* Webhooks may be sent with different versions - the SDK accepts any valid
* YYYY-MM-DD formatted version string. Compare against this constant if you
* need to handle version-specific behavior.
*/
declare const WEBHOOK_VERSION = "2025-12-14";
//#endregion
//#region src/webhook/index.d.ts
/**
* Parse a webhook payload, returning typed events for known types
* and UnknownEvent for future event types.
*
* This provides forward-compatibility: when Primitive adds new event types,
* your code won't break - you'll receive an UnknownEvent that you can
* handle or ignore.
*
* Known event types are validated against the canonical schema. Unknown
* event types are returned as-is for forward compatibility.
*
* For most use cases, prefer `handleWebhook()` which also verifies the
* signature before parsing the payload.
*
* @param input - The parsed JSON payload
* @returns Typed event for known types, UnknownEvent for unknown types
* @throws WebhookPayloadError if the input is not a valid webhook structure
* @throws WebhookValidationError if a known event fails schema validation
*
* @example
* ```typescript
* import { parseWebhookEvent } from '@primitivedotdev/sdk';
*
* const event = parseWebhookEvent(JSON.parse(rawBody));
*
* if (event.event === "email.received") {
* // TypeScript knows this is EmailReceivedEvent
* console.log(event.email.headers.subject);
* } else {
* // Handle or log unknown event types
* console.log("Unknown event:", event.event);
* }
* ```
*/
declare function parseWebhookEvent(input: unknown): WebhookEvent;
/**
* Type guard to check if a webhook event is an EmailReceivedEvent.
*
* @example
* ```typescript
* const event = parseWebhookEvent(payload);
* if (isEmailReceivedEvent(event)) {
* // TypeScript knows event is EmailReceivedEvent
* console.log(event.email.headers.subject);
* }
* ```
*/
declare function isEmailReceivedEvent(event: WebhookEvent | unknown): event is EmailReceivedEvent;
/**
* Request headers in any common format.
*
* Accepts:
* - **Plain object** from Express/Node.js (`req.headers`)
* - **Fetch API `Headers`** from Next.js App Router, Cloudflare Workers (`request.headers`)
*
* Header lookup is case-insensitive per RFC 7230.
*/
type WebhookHeaders = Record<string, string | string[] | undefined> | Headers;
/**
* Options for the handleWebhook function.
*/
interface HandleWebhookOptions {
/**
* The raw request body (before JSON parsing).
* Must be the exact bytes received - do not re-serialize.
*/
body: string | Buffer;
/**
* The request headers object.
* Works with Express (req.headers), Fetch API (Request.headers), or any
* object with string keys. The SDK will find the Primitive-Signature header.
*/
headers: WebhookHeaders;
/**
* Your webhook secret from the Primitive dashboard.
*/
secret: string;
/**
* Maximum age of the webhook in seconds.
* Webhooks older than this will be rejected as potential replay attacks.
* @default 300 (5 minutes)
*/
toleranceSeconds?: number;
}
/**
* Verify, parse, and validate a webhook in one call.
*
* This is the recommended way to handle Primitive webhooks. It:
* 1. Verifies the signature to ensure the webhook is authentic
* 2. Parses the JSON body
* 3. Validates the payload against the canonical JSON schema
* 4. Returns a fully typed EmailReceivedEvent
*
* @param options - The webhook data and secret
* @returns A validated EmailReceivedEvent
* @throws {WebhookVerificationError} If signature verification fails
* @throws {WebhookPayloadError} If JSON parsing fails
* @throws {WebhookValidationError} If schema validation fails
*
* @example
* ```typescript
* import { handleWebhook, PrimitiveWebhookError } from '@primitivedotdev/sdk';
*
* app.post('/webhooks/email', express.raw({ type: 'application/json' }), (req, res) => {
* try {
* const event = handleWebhook({
* body: req.body,
* headers: req.headers,
* secret: process.env.PRIMITIVE_WEBHOOK_SECRET,
* });
*
* console.log('Email from:', event.email.headers.from);
* res.json({ received: true });
* } catch (err) {
* if (err instanceof PrimitiveWebhookError) {
* console.error(`[${err.code}] ${err.message}`);
* return res.status(400).json({ error: err.code });
* }
* throw err;
* }
* });
* ```
*/
declare function handleWebhook(options: HandleWebhookOptions): EmailReceivedEvent;
interface ReceiveRequestOptions {
secret: string;
toleranceSeconds?: number;
}
declare function receive(options: HandleWebhookOptions): ReceivedEmail;
declare function receive(request: Request, options: ReceiveRequestOptions): Promise<ReceivedEmail>;
/**
* Returns headers for the optional "content discard" feature.
*
* If you have the "content discard" setting enabled in your Primitive dashboard,
* returning this header tells Primitive to permanently delete the email content
* after successful delivery. Requires BOTH the dashboard setting AND this header.
*
* **Warning:** Only use this if you can durably guarantee you've processed the email.
* Once discarded, the email content is gone forever.
*
* @returns Headers object to spread into your response
*
* @example Express (only if using content discard)
* ```typescript
* app.post('/webhook', async (req, res) => {
* const event = handleWebhook({ ... });
* // Durably save the email first!
* await db.saveEmail(event);
* res.set(confirmedHeaders()).json({ received: true });
* });
* ```
*
* @example Fetch API / Next.js (only if using content discard)
* ```typescript
* return new Response(JSON.stringify({ received: true }), {
* status: 200,
* headers: {
* 'Content-Type': 'application/json',
* ...confirmedHeaders(),
* },
* });
* ```
*/
declare function confirmedHeaders(): {
"X-Primitive-Confirmed": "true";
"X-MyMX-Confirmed": "true";
};
/**
* Check if the download URL for a webhook event has expired.
*
* @param event - The webhook event
* @param now - Optional current time for testing (defaults to Date.now())
* @returns true if the download URL has expired
*
* @example
* ```typescript
* if (isDownloadExpired(event)) {
* console.log("Download URL has expired, cannot fetch raw email");
* } else {
* const response = await fetch(event.email.content.download.url);
* }
* ```
*/
declare function isDownloadExpired(event: EmailReceivedEvent, now?: number): boolean;
/**
* Get the time remaining (in milliseconds) before the download URL expires.
* Returns 0 if already expired.
*
* @param event - The webhook event
* @param now - Optional current time for testing (defaults to Date.now())
* @returns Milliseconds until expiration, or 0 if expired
*
* @example
* ```typescript
* const remaining = getDownloadTimeRemaining(event);
* if (remaining > 60000) {
* // More than 1 minute left, safe to download
* }
* ```
*/
declare function getDownloadTimeRemaining(event: EmailReceivedEvent, now?: number): number;
/**
* Check if the raw email content is included inline in the event.
*
* Use this to check before calling `decodeRawEmail()` to avoid try/catch.
*
* @param event - The webhook event
* @returns true if raw content is included inline, false if download required
*
* @example
* ```typescript
* if (isRawIncluded(event)) {
* const rawEmail = decodeRawEmail(event);
* } else {
* const response = await fetch(event.email.content.download.url);
* }
* ```
*/
declare function isRawIncluded(event: EmailReceivedEvent): boolean;
/**
* Options for decoding raw email content.
*/
interface DecodeRawEmailOptions {
/**
* Whether to verify the SHA-256 hash after decoding.
* @default true
*/
verify?: boolean;
}
/**
* Decode the raw email content from an EmailReceivedEvent.
*
* Throws if the raw content is not included inline (i.e., must be downloaded).
* By default, verifies the SHA-256 hash matches after decoding.
*
* NOTE: This function assumes a well-formed event from `handleWebhook()`.
* Passing a manually constructed event with missing fields (e.g., `raw.data`
* undefined when `raw.included` is true) will result in undefined behavior.
*
* @param event - The webhook event containing the raw email
* @param options - Decoding options
* @returns The decoded raw email as a Buffer
* @throws {RawEmailDecodeError} If content not included or hash mismatch
*
* @example
* ```typescript
* import { handleWebhook, decodeRawEmail, isRawIncluded } from '@primitivedotdev/sdk';
*
* const event = handleWebhook({ body, headers, secret });
*
* if (isRawIncluded(event)) {
* const rawEmail = decodeRawEmail(event);
* // rawEmail is a Buffer containing the RFC 5322 email
* } else {
* // Must download from event.email.content.download.url
* }
* ```
*/
declare function decodeRawEmail(event: EmailReceivedEvent, options?: DecodeRawEmailOptions): Buffer;
/**
* Verify downloaded raw email content against the SHA-256 hash in the event.
*
* Use this after fetching from `event.email.content.download.url` to ensure
* the downloaded content matches what Primitive received.
*
* @param downloaded - The downloaded raw email content (Buffer, ArrayBuffer, or Uint8Array)
* @param event - The webhook event containing the expected hash
* @returns The verified content as a Buffer
* @throws {RawEmailDecodeError} If hash doesn't match
*
* @example
* ```typescript
* import { handleWebhook, verifyRawEmailDownload, isRawIncluded } from '@primitivedotdev/sdk';
*
* const event = handleWebhook({ body, headers, secret });
*
* if (!isRawIncluded(event)) {
* const response = await fetch(event.email.content.download.url);
* const arrayBuffer = await response.arrayBuffer();
* const verified = verifyRawEmailDownload(arrayBuffer, event);
* // verified is a Buffer containing the RFC 5322 email
* }
* ```
*/
declare function verifyRawEmailDownload(downloaded: Buffer | ArrayBuffer | Uint8Array, event: EmailReceivedEvent): Buffer;
//#endregion
export { VerifyOptions as A, signStandardWebhooksPayload as C, PRIMITIVE_CONFIRMED_HEADER as D, LEGACY_SIGNATURE_HEADER as E, VerifyDownloadTokenResult as F, generateDownloadToken as I, verifyDownloadToken as L, verifyWebhookSignature as M, GenerateDownloadTokenOptions as N, PRIMITIVE_SIGNATURE_HEADER as O, VerifyDownloadTokenOptions as P, safeValidateEmailReceivedEvent as R, StandardWebhooksVerifyOptions as S, LEGACY_CONFIRMED_HEADER as T, emailReceivedEventJsonSchema as _, confirmedHeaders as a, STANDARD_WEBHOOK_TIMESTAMP_HEADER as b, handleWebhook as c, isRawIncluded as d, parseWebhookEvent as f, validateEmailAuth as g, WEBHOOK_VERSION as h, WebhookHeaders as i, signWebhookPayload as j, SignResult as k, isDownloadExpired as l, verifyRawEmailDownload as m, HandleWebhookOptions as n, decodeRawEmail as o, receive as p, ReceiveRequestOptions as r, getDownloadTimeRemaining as s, DecodeRawEmailOptions as t, isEmailReceivedEvent as u, STANDARD_WEBHOOK_ID_HEADER as v, verifyStandardWebhooksSignature as w, StandardWebhooksSignResult as x, STANDARD_WEBHOOK_SIGNATURE_HEADER as y, validateEmailReceivedEvent as z };

Sorry, the diff of this file is too big to display

//#region src/types.generated.d.ts
/**
* Types for Primitive webhook payloads.
*
* AUTO-GENERATED - DO NOT EDIT
* Run `pnpm generate:types` to regenerate.
*/
/**
* Result for a single forwarded email detected in the message.
*
* Use the `type` and `analyzed` fields to narrow the type:
* - `type: 'inline'` - Inline forward, always analyzed
* - `type: 'attachment'` + `analyzed: true` - Analyzed attachment
* - `type: 'attachment'` + `analyzed: false` - Skipped attachment
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardResult".
*/
type ForwardResult$1 = (ForwardResultInline$1 | ForwardResultAttachmentAnalyzed$1 | ForwardResultAttachmentSkipped$1);
/**
* Webhook payload for the `email.received` event.
*
* This is delivered to your webhook endpoint when Primitive receives an email matching your domain configuration.
*/
interface EmailReceivedEvent$1 {
/**
* Unique delivery event ID.
*
* This ID is stable across retries to the same endpoint - use it as your idempotency/dedupe key. Note that the same email delivered to different endpoints will have different event IDs.
*
* Format: `evt_` prefix followed by a SHA-256 hash (64 hex characters). Example: `evt_a1b2c3d4e5f6...` (68 characters total)
*/
id: string;
/**
* Event type identifier. Always `"email.received"` for this event type.
*/
event: "email.received";
/**
* API version in date format (YYYY-MM-DD). Use this to detect version mismatches between webhook and SDK.
*/
version: string;
/**
* Metadata about this webhook delivery.
*/
delivery: {
/**
* ID of the webhook endpoint receiving this event. Matches the endpoint ID from your Primitive dashboard.
*/
endpoint_id: string;
/**
* Delivery attempt number, starting at 1. Increments with each retry if previous attempts failed.
*/
attempt: number;
/**
* ISO 8601 timestamp (UTC) when this delivery was attempted.
*/
attempted_at: string;
};
/**
* The email that triggered this event.
*/
email: {
/**
* Unique email ID in Primitive. Use this ID when calling Primitive APIs to reference this email.
*/
id: string;
/**
* ISO 8601 timestamp (UTC) when Primitive received the email.
*/
received_at: string;
/**
* SMTP envelope information. This is the "real" sender/recipient info from the SMTP transaction, which may differ from the headers (e.g., BCC recipients).
*/
smtp: {
/**
* HELO/EHLO hostname from the sending server. Null if not provided during SMTP transaction.
*/
helo: (string | null);
/**
* SMTP envelope sender (MAIL FROM command). This is the bounce address, which may differ from the From header.
*/
mail_from: string;
/**
* SMTP envelope recipients (RCPT TO commands). All addresses that received this email in a single delivery.
*
* @minItems 1
*/
rcpt_to: [string, ...(string)[]];
};
/**
* Parsed email headers. These are extracted from the email content, not the SMTP envelope.
*/
headers: {
/**
* Message-ID header value. Null if the email had no Message-ID header.
*/
message_id: (string | null);
/**
* Subject header value. Null if the email had no Subject header.
*/
subject: (string | null);
/**
* From header value. May include display name: `"John Doe" <john@example.com>`
*/
from: string;
/**
* To header value. May include multiple addresses or display names.
*/
to: string;
/**
* Date header value as it appeared in the email. Null if the email had no Date header.
*/
date: (string | null);
};
/**
* Raw email content and download information.
*/
content: {
/**
* Raw email in RFC 5322 format. May be inline (base64) or download-only depending on size.
*/
raw: (RawContentInline$1 | RawContentDownloadOnly$1);
/**
* Download information for the raw email. Always present, even if raw content is inline.
*/
download: {
/**
* URL to download the raw email as-is in RFC 5322 format. Managed Primitive always issues HTTPS. Self-host deployments may issue HTTP URLs that resolve inside the operator's network (e.g. `http://localhost:4001/...`). Receivers that want to refuse plaintext downloads should check the scheme explicitly.
*/
url: string;
/**
* ISO 8601 timestamp (UTC) when this URL expires. Download before this time or the URL will return 403.
*/
expires_at: string;
};
};
/**
* Parsed email content (body text, HTML, attachments). Check `status` to determine if parsing succeeded.
*/
parsed: (ParsedDataComplete$1 | ParsedDataFailed$1);
analysis: EmailAnalysis$1;
auth: EmailAuth$1;
};
}
/**
* Raw email content included inline (base64 encoded).
*
* When the raw email is small enough (under {@link max_inline_bytes } ), it's included directly in the webhook payload for convenience.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "RawContentInline".
*/
interface RawContentInline$1 {
/**
* Discriminant indicating raw content is included inline.
*/
included: true;
/**
* Encoding used for the data field. Always "base64".
*/
encoding: "base64";
/**
* Maximum size in bytes for inline inclusion. Emails larger than this threshold require download.
*/
max_inline_bytes: number;
/**
* Actual size of the raw email in bytes.
*/
size_bytes: number;
/**
* SHA-256 hash of the raw email content (hex-encoded). Use this to verify integrity after base64 decoding.
*/
sha256: string;
/**
* Base64-encoded raw email (RFC 5322 format). Decode with `Buffer.from(data, 'base64')` in Node.js.
*/
data: string;
}
/**
* Raw email content not included (must be downloaded).
*
* When the raw email exceeds {@link max_inline_bytes } , it's not included in the webhook payload. Use the download URL from {@link EmailReceivedEvent.email.content.download } to fetch it.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "RawContentDownloadOnly".
*/
interface RawContentDownloadOnly$1 {
/**
* Discriminant indicating raw content must be downloaded.
*/
included: false;
/**
* Reason the content wasn't included inline.
*/
reason_code: "size_exceeded";
/**
* Maximum size in bytes for inline inclusion. The email exceeded this threshold.
*/
max_inline_bytes: number;
/**
* Actual size of the raw email in bytes.
*/
size_bytes: number;
/**
* SHA-256 hash of the raw email content (hex-encoded). Use this to verify integrity after download.
*/
sha256: string;
}
/**
* Parsed email content when parsing succeeded.
*
* Use the discriminant `status: "complete"` to narrow from {@link ParsedData } .
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ParsedDataComplete".
*/
interface ParsedDataComplete$1 {
/**
* Discriminant indicating successful parsing.
*/
status: "complete";
/**
* Always null when parsing succeeds.
*/
error: null;
/**
* Plain text body of the email. Null if the email had no text/plain part.
*/
body_text: (string | null);
/**
* HTML body of the email. Null if the email had no text/html part.
*/
body_html: (string | null);
/**
* Parsed Reply-To header addresses. Null if the email had no Reply-To header.
*/
reply_to: (EmailAddress$1[] | null);
/**
* Parsed CC header addresses. Null if the email had no CC header.
*/
cc: (EmailAddress$1[] | null);
/**
* Parsed BCC header addresses. Null if the email had no BCC header. Note: BCC is only available for outgoing emails or when explicitly provided.
*/
bcc: (EmailAddress$1[] | null);
/**
* Parsed To header addresses. Null if the email had no To header.
*/
to_addresses: (EmailAddress$1[] | null);
/**
* In-Reply-To header values (Message-IDs of the email(s) being replied to). Null if the email had no In-Reply-To header. Per RFC 5322, this can contain multiple Message-IDs, though typically just one.
*/
in_reply_to: (string[] | null);
/**
* References header values (Message-IDs of the email thread). Null if the email had no References header.
*/
references: (string[] | null);
/**
* List of attachments with metadata. Use {@link attachments_download_url } to download the actual files.
*/
attachments: WebhookAttachment$1[];
/**
* URL to download all attachments as a tar.gz archive. Null if the email had no attachments. Managed Primitive always issues HTTPS. Self-host deployments may issue HTTP URLs that resolve inside the operator's network. URL expires - check the expiration before downloading.
*/
attachments_download_url: (string | null);
}
/**
* A parsed email address with optional display name.
*
* This structure is used in the `parsed` section of the webhook payload (e.g., `reply_to`, `cc`, `bcc`). For unparsed header strings, see the `headers` section (e.g., `event.email.headers.from`).
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "EmailAddress".
*/
interface EmailAddress$1 {
/**
* The email address portion (e.g., "john@example.com").
*
* This is the raw value from the email header with no validation applied. May contain unusual but valid formats like quoted local parts.
*/
address: string;
/**
* The display name portion, if present. Null if the address had no display name.
*
* May contain any characters including unicode, emoji, or special characters as they appeared in the original email header.
*/
name: (string | null);
}
/**
* Metadata for an email attachment.
*
* Attachment content is not included directly in the webhook payload. Use the `attachments_download_url` from {@link ParsedDataComplete } to download all attachments as a tar.gz archive.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "WebhookAttachment".
*/
interface WebhookAttachment$1 {
/**
* Original filename from the email. May be null if the attachment had no filename specified.
*/
filename: (string | null);
/**
* MIME content type (e.g., "application/pdf", "image/png").
*/
content_type: string;
/**
* Size of the attachment in bytes.
*/
size_bytes: number;
/**
* SHA-256 hash of the attachment content (hex-encoded). Use this to verify attachment integrity after download.
*/
sha256: string;
/**
* Zero-based index of this part in the MIME structure.
*/
part_index: number;
/**
* Path to this attachment within the downloaded tar.gz archive.
*/
tar_path: string;
}
/**
* Parsed email content when parsing failed.
*
* Use the discriminant `status: "failed"` to narrow from {@link ParsedData } .
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ParsedDataFailed".
*/
interface ParsedDataFailed$1 {
/**
* Discriminant indicating parsing failed.
*/
status: "failed";
error: ParsedError$1;
/**
* Always null when parsing fails.
*/
body_text: null;
/**
* Always null when parsing fails.
*/
body_html: null;
/**
* Always null when parsing fails.
*/
reply_to: null;
/**
* Always null when parsing fails.
*/
cc: null;
/**
* Always null when parsing fails.
*/
bcc: null;
/**
* Always null when parsing fails.
*/
to_addresses: null;
/**
* Always null when parsing fails.
*/
in_reply_to: null;
/**
* Always null when parsing fails.
*/
references: null;
/**
* May contain partial attachment metadata even when parsing failed. Useful for debugging or recovering partial data.
*/
attachments: WebhookAttachment$1[];
/**
* Always null when parsing fails.
*/
attachments_download_url: null;
}
/**
* Details about why parsing failed.
*/
interface ParsedError$1 {
/**
* Error code indicating the type of failure.
* - `PARSE_FAILED`: The email could not be parsed (e.g., malformed MIME)
* - `ATTACHMENT_EXTRACTION_FAILED`: Email parsed but attachments couldn't be extracted
*/
code: ("PARSE_FAILED" | "ATTACHMENT_EXTRACTION_FAILED");
/**
* Human-readable error message describing what went wrong.
*/
message: string;
/**
* Whether retrying might succeed. If true, the error was transient (e.g., timeout). If false, the email itself is problematic.
*/
retryable: boolean;
}
/**
* Email analysis and classification results.
*/
interface EmailAnalysis$1 {
/**
* SpamAssassin analysis results.
*
* Optional. Present when the email was processed by a SpamAssassin-equipped pipeline (always present in Primitive's managed service). When absent, spam scoring was not performed on this email.
*/
spamassassin?: {
/**
* Overall spam score (sum of all rule scores). Higher scores indicate higher likelihood of spam. Unbounded - can be negative (ham) or very high (spam).
*/
score: number;
};
forward?: ForwardAnalysis$1;
}
/**
* Forward detection and analysis results.
*
* Optional. Present when the email was processed by a forward-detection pipeline (always present in Primitive's managed service). When absent, forward detection was not performed on this email.
*/
interface ForwardAnalysis$1 {
/**
* Whether any forwards were detected in the email.
*/
detected: boolean;
/**
* Analysis results for each detected forward.
*/
results: ForwardResult$1[];
/**
* Total number of .eml attachments found.
*/
attachments_found: number;
/**
* Number of .eml attachments that were analyzed.
*/
attachments_analyzed: number;
/**
* Maximum number of attachments that will be analyzed, or null if unlimited.
*/
attachments_limit: (number | null);
}
/**
* Result for an inline forward that was detected and analyzed. Inline forwards are always analyzed when forward detection is enabled.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardResultInline".
*/
interface ForwardResultInline$1 {
type: "inline";
/**
* Original sender of the forwarded email, if extractable.
*/
original_sender: (ForwardOriginalSender$1 | null);
verification: ForwardVerification$1;
/**
* Human-readable summary of the forward analysis.
*/
summary: string;
}
/**
* Original sender information extracted from the forwarded email.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardOriginalSender".
*/
interface ForwardOriginalSender$1 {
/**
* Email address of the original sender.
*/
email: string;
/**
* Domain of the original sender.
*/
domain: string;
}
/**
* Verification result for the forwarded email.
*/
interface ForwardVerification$1 {
/**
* Overall verdict on whether the forward is authentic.
*/
verdict: ("legit" | "unknown");
/**
* Confidence level for this verdict.
*/
confidence: ("high" | "medium" | "low");
/**
* Whether a valid DKIM signature was found that verifies the original sender.
*/
dkim_verified: boolean;
/**
* Domain of the DKIM signature that verified the forward, if any.
*/
dkim_domain: (string | null);
/**
* DMARC policy of the original sender's domain.
*/
dmarc_policy: ("reject" | "quarantine" | "none" | null);
}
/**
* Result for an attachment forward that was analyzed.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardResultAttachmentAnalyzed".
*/
interface ForwardResultAttachmentAnalyzed$1 {
type: "attachment";
/**
* Path to the attachment in the attachments tar archive.
*/
attachment_tar_path: string;
/**
* Original filename of the attachment, if available.
*/
attachment_filename: (string | null);
/**
* Whether this attachment was analyzed.
*/
analyzed: true;
/**
* Original sender of the forwarded email, if extractable.
*/
original_sender: (ForwardOriginalSender$1 | null);
verification: ForwardVerification1;
/**
* Human-readable summary of the forward analysis.
*/
summary: string;
}
/**
* Verification result for the forwarded email.
*/
interface ForwardVerification1 {
/**
* Overall verdict on whether the forward is authentic.
*/
verdict: ("legit" | "unknown");
/**
* Confidence level for this verdict.
*/
confidence: ("high" | "medium" | "low");
/**
* Whether a valid DKIM signature was found that verifies the original sender.
*/
dkim_verified: boolean;
/**
* Domain of the DKIM signature that verified the forward, if any.
*/
dkim_domain: (string | null);
/**
* DMARC policy of the original sender's domain.
*/
dmarc_policy: ("reject" | "quarantine" | "none" | null);
}
/**
* Result for an attachment forward that was detected but not analyzed. This occurs when attachment analysis is disabled or the limit was reached.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "ForwardResultAttachmentSkipped".
*/
interface ForwardResultAttachmentSkipped$1 {
type: "attachment";
/**
* Path to the attachment in the attachments tar archive.
*/
attachment_tar_path: string;
/**
* Original filename of the attachment, if available.
*/
attachment_filename: (string | null);
/**
* Whether this attachment was analyzed.
*/
analyzed: false;
/**
* Always null when not analyzed.
*/
original_sender: null;
/**
* Always null when not analyzed.
*/
verification: null;
/**
* Human-readable summary explaining why analysis was skipped.
*/
summary: string;
}
/**
* Email authentication results (SPF, DKIM, DMARC).
*/
interface EmailAuth$1 {
/**
* SPF verification result.
*
* SPF checks if the sending IP is authorized by the envelope sender's domain. "pass" means the IP is authorized; "fail" means it's explicitly not allowed.
*/
spf: ("pass" | "fail" | "softfail" | "neutral" | "none" | "temperror" | "permerror");
/**
* DMARC verification result.
*
* DMARC passes if either SPF or DKIM passes AND aligns with the From: domain. "pass" means the email is authenticated according to the sender's policy.
*/
dmarc: ("pass" | "fail" | "none" | "temperror" | "permerror");
/**
* DMARC policy from the sender's DNS record.
*
* - `reject`: Domain wants receivers to reject failing emails
* - `quarantine`: Domain wants failing emails marked as suspicious
* - `none`: Domain is monitoring only (no action requested)
* - `null`: No DMARC record found for this domain
*/
dmarcPolicy: ("reject" | "quarantine" | "none" | null);
/**
* The organizational domain used for DMARC lookups.
*
* For example, if the From: address is `user@mail.example.com`, the DMARC lookup checks `_dmarc.mail.example.com`, then falls back to `_dmarc.example.com`. This field shows which domain's policy was used.
*/
dmarcFromDomain: (string | null);
/**
* Whether SPF aligned with the From: domain for DMARC purposes.
*
* True if the envelope sender domain matches the From: domain (per alignment mode).
*/
dmarcSpfAligned: boolean;
/**
* Whether DKIM aligned with the From: domain for DMARC purposes.
*
* True if at least one DKIM signature's domain matches the From: domain.
*/
dmarcDkimAligned: boolean;
/**
* Whether DMARC SPF alignment mode is strict.
*
* - `true`: Strict alignment required (exact domain match)
* - `false`: Relaxed alignment allowed (organizational domain match)
* - `null`: No DMARC record found
*/
dmarcSpfStrict: (boolean | null);
/**
* Whether DMARC DKIM alignment mode is strict.
*
* - `true`: Strict alignment required (exact domain match)
* - `false`: Relaxed alignment allowed (organizational domain match)
* - `null`: No DMARC record found
*/
dmarcDkimStrict: (boolean | null);
/**
* All DKIM signatures found in the email with their verification results.
*
* May be empty if no DKIM signatures were present.
*/
dkimSignatures: DkimSignature$1[];
}
/**
* Details about a single DKIM signature found in the email.
*
* An email may have multiple DKIM signatures (e.g., one from the sending domain and one from the ESP). Each signature is verified independently.
*
* This interface was referenced by `EmailReceivedEvent`'s JSON-Schema
* via the `definition` "DkimSignature".
*/
interface DkimSignature$1 {
/**
* The domain that signed this DKIM signature (d= tag). This may differ from the From: domain (that's what alignment checks).
*/
domain: string;
/**
* The DKIM selector used to locate the public key (s= tag). Combined with the domain to form the DNS lookup: `selector._domainkey.domain`
*
* Optional in self-hosted environments where the milter may not provide selector info.
*/
selector: (string | null);
/**
* Verification result for this specific signature.
*/
result: ("pass" | "fail" | "temperror" | "permerror");
/**
* Whether this signature's domain aligns with the From: domain (for DMARC).
*
* Alignment can be "strict" (exact match) or "relaxed" (organizational domain match). For example, if From: is `user@sub.example.com` and DKIM is signed by `example.com`:
* - Relaxed alignment: true (same organizational domain)
* - Strict alignment: false (not exact match)
*/
aligned: boolean;
/**
* Key size in bits (e.g., 1024, 2048). Null if the key size couldn't be determined.
*
* Optional in self-hosted environments.
*/
keyBits: (number | null);
/**
* Signing algorithm (e.g., "rsa-sha256", "ed25519-sha256").
*
* Optional in self-hosted environments.
*/
algo: (string | null);
}
//#endregion
//#region src/types.d.ts
type EmailReceivedEvent = EmailReceivedEvent$1;
type EventType = EmailReceivedEvent["event"];
declare const EventType: {
readonly EmailReceived: "email.received";
};
type RawContent = EmailReceivedEvent["email"]["content"]["raw"];
type RawContentInline = Extract<RawContent, {
included: true;
}>;
type RawContentDownloadOnly = Extract<RawContent, {
included: false;
}>;
type ParsedData = EmailReceivedEvent["email"]["parsed"];
type ParsedDataComplete = Extract<ParsedData, {
status: "complete";
}>;
type ParsedDataFailed = Extract<ParsedData, {
status: "failed";
}>;
type ParsedStatus = ParsedData["status"];
declare const ParsedStatus: {
readonly Complete: "complete";
readonly Failed: "failed";
};
type ParsedError = ParsedDataFailed["error"];
type EmailAddress = NonNullable<ParsedDataComplete["reply_to"]>[number];
type WebhookAttachment = ParsedDataComplete["attachments"][number];
type EmailAnalysis = EmailReceivedEvent["email"]["analysis"];
type ForwardAnalysis = NonNullable<EmailAnalysis["forward"]>;
type ForwardResult = ForwardAnalysis["results"][number];
type ForwardResultInline = Extract<ForwardResult, {
type: "inline";
}>;
type ForwardResultAttachmentAnalyzed = Extract<ForwardResult, {
type: "attachment";
analyzed: true;
}>;
type ForwardResultAttachmentSkipped = Extract<ForwardResult, {
type: "attachment";
analyzed: false;
}>;
type ForwardOriginalSender = NonNullable<ForwardResultInline["original_sender"]>;
type ForwardVerification = NonNullable<ForwardResultInline["verification"]>;
type ForwardVerdict = ForwardVerification["verdict"];
declare const ForwardVerdict: {
readonly Legit: "legit";
readonly Unknown: "unknown";
};
type EmailAuth = EmailReceivedEvent["email"]["auth"];
type DkimSignature = EmailAuth["dkimSignatures"][number];
type SpfResult = EmailAuth["spf"];
declare const SpfResult: {
readonly Pass: "pass";
readonly Fail: "fail";
readonly Softfail: "softfail";
readonly Neutral: "neutral";
readonly None: "none";
readonly Temperror: "temperror";
readonly Permerror: "permerror";
};
type DmarcResult = EmailAuth["dmarc"];
declare const DmarcResult: {
readonly Pass: "pass";
readonly Fail: "fail";
readonly None: "none";
readonly Temperror: "temperror";
readonly Permerror: "permerror";
};
type DmarcPolicy = EmailAuth["dmarcPolicy"];
declare const DmarcPolicy: {
readonly Reject: "reject";
readonly Quarantine: "quarantine";
readonly None: "none";
};
type DkimResult = DkimSignature["result"];
declare const DkimResult: {
readonly Pass: "pass";
readonly Fail: "fail";
readonly Temperror: "temperror";
readonly Permerror: "permerror";
};
type AuthConfidence = ForwardVerification["confidence"];
declare const AuthConfidence: {
readonly High: "high";
readonly Medium: "medium";
readonly Low: "low";
};
type AuthVerdict = "legit" | "suspicious" | "unknown";
declare const AuthVerdict: {
readonly Legit: "legit";
readonly Suspicious: "suspicious";
readonly Unknown: "unknown";
};
interface ValidateEmailAuthResult {
verdict: AuthVerdict;
confidence: AuthConfidence;
reasons: string[];
}
declare const unknownEventTypeBrand: unique symbol;
type UnknownEventType = string & {
readonly [unknownEventTypeBrand]: true;
};
interface UnknownEvent {
event: UnknownEventType;
id?: string;
version?: string;
[key: string]: unknown;
}
type KnownWebhookEvent = EmailReceivedEvent;
type WebhookEvent = KnownWebhookEvent | UnknownEvent;
//#endregion
export { UnknownEvent as A, ParsedDataFailed as C, RawContentDownloadOnly as D, RawContent as E, WebhookAttachment as M, WebhookEvent as N, RawContentInline as O, ParsedDataComplete as S, ParsedStatus as T, ForwardResultInline as _, DmarcPolicy as a, KnownWebhookEvent as b, EmailAnalysis as c, EventType as d, ForwardAnalysis as f, ForwardResultAttachmentSkipped as g, ForwardResultAttachmentAnalyzed as h, DkimSignature as i, ValidateEmailAuthResult as j, SpfResult as k, EmailAuth as l, ForwardResult as m, AuthVerdict as n, DmarcResult as o, ForwardOriginalSender as p, DkimResult as r, EmailAddress as s, AuthConfidence as t, EmailReceivedEvent as u, ForwardVerdict as v, ParsedError as w, ParsedData as x, ForwardVerification as y };

Sorry, the diff of this file is too big to display