@crvouga/mockingbird-service-customerio 3.16.0 → 3.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1651 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
18
+
19
+ // <define:__MOCKINGBIRD_ADMIN_BRAND__>
20
+ var define_MOCKINGBIRD_ADMIN_BRAND_default = { vendor: "Customer.io", website: "https://customer.io", docs: "https://docs.customer.io/api/", guide: "https://mockingbird.chrisvouga.dev/services/customerio", logo: "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwMCIgaGVpZ2h0PSIxMDAwIiB2aWV3Qm94PSIwIDAgMTAwMCAxMDAwIiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgo8ZyBjbGlwLXBhdGg9InVybCgjY2xpcDBfNTg0NV80MTc4KSI+CjxnIGNsaXAtcGF0aD0idXJsKCNjbGlwMV81ODQ1XzQxNzgpIj4KPG1hc2sgaWQ9Im1hc2swXzU4NDVfNDE3OCIgc3R5bGU9Im1hc2stdHlwZTpsdW1pbmFuY2UiIG1hc2tVbml0cz0idXNlclNwYWNlT25Vc2UiIHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMDAiPgo8cGF0aCBkPSJNODUwIDBIMTUwQzY3LjE1NzMgMCAwIDY3LjE1NzMgMCAxNTBWODUwQzAgOTMyLjg0MyA2Ny4xNTczIDEwMDAgMTUwIDEwMDBIODUwQzkzMi44NDMgMTAwMCAxMDAwIDkzMi44NDMgMTAwMCA4NTBWMTUwQzEwMDAgNjcuMTU3MyA5MzIuODQzIDAgODUwIDBaIiBmaWxsPSJ3aGl0ZSIvPgo8L21hc2s+CjxnIG1hc2s9InVybCgjbWFzazBfNTg0NV80MTc4KSI+CjxwYXRoIGQ9Ik0xMDAwIDBIMFYxMDAwSDEwMDBWMFoiIGZpbGw9IiMwMDI2MkIiLz4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAyXzU4NDVfNDE3OCkiPgo8cGF0aCBkPSJNMzUwLjY2NCA1MDBMNTAwIDY0OS4zMzhMMzUwLjY2NCA3OTguNjczSDIwMS4zMjdWNjQ5LjMzOEwzNTAuNjY0IDUwMFoiIGZpbGw9IiNCREZGQkQiLz4KPHBhdGggZD0iTTM1MC42NjQgNTAwTDUwMCAzNTAuNjY0TDM1MC42NjQgMjAxLjMyN0gyMDEuMzI3VjM1MC42NjRMMzUwLjY2NCA1MDBaIiBmaWxsPSIjQkRGRkJEIi8+CjxwYXRoIGQ9Ik03OTguNjczIDM1MC42NjRMNjQ5LjMzOCAyMDEuMzI3SDUwMFYzNTAuNjY0TDY0OS4zMzggNTAwTDUwMCA2NDkuMzM4Vjc5OC42NzNINjQ5LjMzOEw3OTguNjczIDY0OS4zMzhWMzUwLjY2NFoiIGZpbGw9IiNCREZGQkQiLz4KPC9nPgo8L2c+CjwvZz4KPGcgY2xpcC1wYXRoPSJ1cmwoI2NsaXAzXzU4NDVfNDE3OCkiPgo8bWFzayBpZD0ibWFzazFfNTg0NV80MTc4IiBzdHlsZT0ibWFzay10eXBlOmx1bWluYW5jZSIgbWFza1VuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeD0iMCIgeT0iMCIgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCI+CjxwYXRoIGQ9Ik04NTAgMEgxNTBDNjcuMTU3MyAwIDAgNjcuMTU3MyAwIDE1MFY4NTBDMCA5MzIuODQzIDY3LjE1NzMgMTAwMCAxNTAgMTAwMEg4NTBDOTMyLjg0MyAxMDAwIDEwMDAgOTMyLjg0MyAxMDAwIDg1MFYxNTBDMTAwMCA2Ny4xNTczIDkzMi44NDMgMCA4NTAgMFoiIGZpbGw9IndoaXRlIi8+CjwvbWFzaz4KPGcgbWFzaz0idXJsKCNtYXNrMV81ODQ1XzQxNzgpIj4KPHBhdGggZD0iTTEwMDAgMEgwVjEwMDBIMTAwMFYwWiIgZmlsbD0iI0JERkZCRCIvPgo8ZyBjbGlwLXBhdGg9InVybCgjY2xpcDRfNTg0NV80MTc4KSI+CjxwYXRoIGQ9Ik0zNTAuNjY0IDUwMEw1MDAgNjQ5LjMzOEwzNTAuNjY0IDc5OC42NzNIMjAxLjMyN1Y2NDkuMzM4TDM1MC42NjQgNTAwWiIgZmlsbD0iIzAwMjYyQiIvPgo8cGF0aCBkPSJNMzUwLjY2NCA1MDBMNTAwIDM1MC42NjRMMzUwLjY2NCAyMDEuMzI3SDIwMS4zMjdWMzUwLjY2NEwzNTAuNjY0IDUwMFoiIGZpbGw9IiMwMDI2MkIiLz4KPHBhdGggZD0iTTc5OC42NzMgMzUwLjY2NEw2NDkuMzM4IDIwMS4zMjdINTAwVjM1MC42NjRMNjQ5LjMzOCA1MDBMNTAwIDY0OS4zMzhWNzk4LjY3M0g2NDkuMzM4TDc5OC42NzMgNjQ5LjMzOFYzNTAuNjY0WiIgZmlsbD0iIzAwMjYyQiIvPgo8L2c+CjwvZz4KPC9nPgo8L2c+CjxkZWZzPgo8Y2xpcFBhdGggaWQ9ImNsaXAwXzU4NDVfNDE3OCI+CjxyZWN0IHdpZHRoPSIxMDAwIiBoZWlnaHQ9IjEwMDAiIGZpbGw9IndoaXRlIi8+CjwvY2xpcFBhdGg+CjxjbGlwUGF0aCBpZD0iY2xpcDFfNTg0NV80MTc4Ij4KPHJlY3Qgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPGNsaXBQYXRoIGlkPSJjbGlwMl81ODQ1XzQxNzgiPgo8cmVjdCB3aWR0aD0iODAwIiBoZWlnaHQ9IjgwMCIgZmlsbD0id2hpdGUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEwMCAxMDApIi8+CjwvY2xpcFBhdGg+CjxjbGlwUGF0aCBpZD0iY2xpcDNfNTg0NV80MTc4Ij4KPHJlY3Qgd2lkdGg9IjEwMDAiIGhlaWdodD0iMTAwMCIgZmlsbD0id2hpdGUiLz4KPC9jbGlwUGF0aD4KPGNsaXBQYXRoIGlkPSJjbGlwNF81ODQ1XzQxNzgiPgo8cmVjdCB3aWR0aD0iODAwIiBoZWlnaHQ9IjgwMCIgZmlsbD0id2hpdGUiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEwMCAxMDApIi8+CjwvY2xpcFBhdGg+CjwvZGVmcz4KPC9zdmc+Cg==", color: null, description: "Customer.io is a customer engagement platform for creating personalized journeys and better business outcomes across email, push, SMS, and in-app messaging." };
21
+
22
+ // mockingbird-service-runtime:@crvouga/mockingbird-runtime/service
23
+ var service_exports = {};
24
+ __export(service_exports, {
25
+ PACKAGE_VERSION: () => PACKAGE_VERSION,
26
+ createRuntime: () => createRuntime
27
+ });
28
+ __reExport(service_exports, service_star);
29
+ import * as service_star from "@crvouga/mockingbird-runtime/service";
30
+ import { PACKAGE_VERSION as SHARED_VERSION, createRuntime as sharedRuntime } from "@crvouga/mockingbird-runtime/service";
31
+ var PACKAGE_VERSION = true ? "3.17.0" : SHARED_VERSION;
32
+ var ADMIN_BRAND = typeof define_MOCKINGBIRD_ADMIN_BRAND_default === "object" ? define_MOCKINGBIRD_ADMIN_BRAND_default : void 0;
33
+ var createRuntime = (options) => sharedRuntime({
34
+ ...options,
35
+ version: options.version ?? PACKAGE_VERSION,
36
+ adminBrand: options.adminBrand ?? ADMIN_BRAND
37
+ });
38
+
39
+ // src/generated/openapi.ts
40
+ var document = JSON.parse(`{"openapi":"3.1.0","info":{"title":"Customer.io CDP + App API (Mockingbird subset)","description":"Stateful emulator subset of Customer.io: the Segment-compatible CDP ingestion endpoints\\n(\`identify\`, \`track\`, \`batch\`, as \`@customerio/cdp-analytics-node\` posts them), the App API\\ntransactional sends (email, SMS, push, inbox message), transactional-message catalog, profile\\nattribute reads (with the device list the CDP device events build), delivery-status reads, and the link-tracking click endpoint. One process\\nserves all three hosts (\`cdp.customer.io\`, \`api.customer.io\`, the tracking domain); their\\npaths do not collide.\\n","version":"1","x-mockingbird-upstream":{"note":"Hand-authored from Customer.io's CDP (Segment spec) and App API reference, trimmed to what our consumer sends: customer-io.client.service.ts / notification-adapter.ts / transactional-email-adapter.ts (backend), transactional-client.ts (notification-processor), customerio-trigger-name-validator.ts (notification-service) and mobile-links-click-reporter.service.ts."}},"servers":[{"url":"https://api.customer.io"},{"url":"https://cdp.customer.io"}],"paths":{"/v1/identify":{"post":{"operationId":"CdpIdentify","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/IdentifyEvent"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/track":{"post":{"operationId":"CdpTrack","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/TrackEvent"}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed event","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/batch":{"post":{"operationId":"CdpBatch","description":"What \`@customerio/cdp-analytics-node\` posts: \`{batch: [...]}\`.","security":[{"cdpWriteKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["batch"],"properties":{"batch":{"type":"array","maxItems":5,"items":{"anyOf":[{"$ref":"#/components/schemas/IdentifyEvent"},{"$ref":"#/components/schemas/TrackEvent"}]}},"sentAt":{"type":"string"},"context":{"type":"object"}}}}}},"responses":{"200":{"description":"Accepted","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpSuccess"}}}},"400":{"description":"Malformed batch","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}},"401":{"description":"Missing or unknown write key","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CdpError"}}}}}}},"/v1/send/email":{"post":{"operationId":"SendEmail","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendEmailRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/send/sms":{"post":{"operationId":"SendSms","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendSmsRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/send/push":{"post":{"operationId":"SendPush","description":"Transactional push (https://docs.customer.io/messaging/send/transactional/push/,\\nApp API \`sendPush\`). \`to\` is \`all\` (default), \`last_used\`, or one device token from the\\nperson's device list. Behaviour for a token not on the profile, a person with no\\nprofile, and non-string \`custom_data\` values is a best guess (see README).\\n","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendPushRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/send/inbox_message":{"post":{"operationId":"SendInboxMessage","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"$ref":"#/components/schemas/SendInboxRequest"}}}},"responses":{"200":{"$ref":"#/components/responses/Queued"},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/transactional":{"get":{"operationId":"ListTransactionalMessages","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Every transactional message in the workspace (no pagination)","content":{"application/json":{"schema":{"type":"object","required":["messages"],"properties":{"messages":{"type":"array","items":{"$ref":"#/components/schemas/TransactionalMessage"}}}}}}},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/transactional/{transactional_id}":{"parameters":[{"name":"transactional_id","in":"path","required":true,"schema":{"type":"string","x-mockingbird-resource-ref":{"type":"transactional_message","missing":"999999"}}}],"get":{"operationId":"GetTransactionalMessage","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"One transactional message","content":{"application/json":{"schema":{"type":"object","required":["message"],"properties":{"message":{"$ref":"#/components/schemas/TransactionalMessage"}}}}}},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/customers/{customer_id}/attributes":{"parameters":[{"name":"customer_id","in":"path","required":true,"schema":{"type":"string","minLength":1,"maxLength":150}},{"name":"id_type","in":"query","required":false,"schema":{"type":"string","enum":["id","email","cio_id"]}}],"get":{"operationId":"GetCustomerAttributes","description":"App API profile read. \`id_type\` selects which identifier \`customer_id\` is\\n(\`id\` by default, or \`email\`, or \`cio_id\`).\\n","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The customer's identifiers and attributes","content":{"application/json":{"schema":{"$ref":"#/components/schemas/CustomerAttributes"}}}},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/optouts":{"get":{"operationId":"ListOptOuts","description":"Sender-specific SMS and WhatsApp opt-outs, paginated by an opaque start cursor.","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"limit","in":"query","schema":{"type":"integer","minimum":1,"maximum":1000,"default":100}},{"name":"start","in":"query","schema":{"type":"string"}},{"name":"from","in":"query","schema":{"type":"string"}}],"responses":{"200":{"description":"A page of opted-out customers","content":{"application/json":{"schema":{"type":"object","required":["optouts"],"properties":{"next":{"type":"string"},"optouts":{"type":"array","items":{"type":"object","required":["customer_id","cio_id","optouts"],"properties":{"customer_id":{"type":"string"},"cio_id":{"type":"string"},"optouts":{"type":"array","items":{"$ref":"#/components/schemas/SenderOptOut"}}}}}}}}}},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/customers/{customer_id}/optouts":{"get":{"operationId":"GetCustomerOptOuts","description":"Sender opt-outs for an existing person; marketing preferences are separate.","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"parameters":[{"name":"customer_id","in":"path","required":true,"schema":{"type":"string","minLength":1}},{"name":"id_type","in":"query","schema":{"type":"string","enum":["id","email","cio_id"],"default":"id"}}],"responses":{"200":{"description":"The customer's sender opt-outs","content":{"application/json":{"schema":{"type":"object","required":["optouts"],"properties":{"optouts":{"type":"array","items":{"$ref":"#/components/schemas/SenderOptOut"}}}}}}},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/messages/{message_id}":{"parameters":[{"name":"message_id","in":"path","required":true,"schema":{"type":"string","minLength":1,"maxLength":80,"x-mockingbird-resource-ref":{"type":"delivery","missing":"missingdelivery00000000000000"}}}],"get":{"operationId":"GetMessage","description":"Delivery status for one transactional send. Missing ids, and ids still inside the\\nemulator's visibility delay, are 404. The body never includes \`message_data\`.\\n","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Delivery status","content":{"application/json":{"schema":{"$ref":"#/components/schemas/DeliveryMessage"}}}},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/reporting_webhooks":{"get":{"operationId":"ListReportingWebhooks","description":"The workspace's reporting webhooks (App API \`listWebhooks\`). Seeded through\\n\`PUT /__admin/content\`; empty by default. Best guess from vendor docs, not oracle-verified.\\n","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"reason":"Best guess from vendor docs, not oracle-verified.","parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Every reporting webhook","content":{"application/json":{"schema":{"type":"object","required":["reporting_webhooks"],"properties":{"reporting_webhooks":{"type":"array","items":{"$ref":"#/components/schemas/ReportingWebhook"}}}}}}},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/subscription_topics":{"get":{"operationId":"ListSubscriptionTopics","description":"The workspace's subscription-center topics (App API \`getTopics\`); an empty array when\\nthere are none. Best guess from vendor docs, not oracle-verified.\\n","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"reason":"Best guess from vendor docs, not oracle-verified.","parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Every subscription topic","content":{"application/json":{"schema":{"type":"object","required":["topics"],"properties":{"topics":{"type":"array","items":{"$ref":"#/components/schemas/SubscriptionTopic"}}}}}}},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/exports/customers":{"post":{"operationId":"ExportCustomers","description":"Export the people matching \`filters\` (App API \`exportPeopleData\`). The emulator evaluates\\n\`and\` / \`or\` / \`not\` / \`attribute\` (\`eq\`, \`exists\`, \`inverse\`) filters against its\\nprofiles and finishes the export at once (\`status: done\`). \`segment\` filters answer 400\\n(no segments are modelled). Best guess from vendor docs, not oracle-verified.\\n","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"reason":"Best guess from vendor docs, not oracle-verified.","parity":{"enabled":true,"safe":false}},"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","required":["filters"],"properties":{"filters":{"description":"One filter node: \`{and: [...]}\`, \`{or: [...]}\`, \`{not: {...}}\`, \`{segment: {id}}\` or \`{attribute: {field, operator: eq|exists, value?, inverse?}}\`.","type":"object","additionalProperties":true},"attributes":{"description":"Attribute names added as CSV columns after \`id\`, \`cio_id\` and \`email\`.","type":"array","items":{"type":"string"}}}}}}},"responses":{"200":{"description":"The export","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExportEnvelope"}}}},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/exports/{export_id}":{"parameters":[{"name":"export_id","in":"path","required":true,"schema":{"type":"integer","minimum":1}}],"get":{"operationId":"GetExport","description":"One export (App API \`getExport\`). Best guess from vendor docs, not oracle-verified.","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"reason":"Best guess from vendor docs, not oracle-verified.","parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The export","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ExportEnvelope"}}}},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/exports/{export_id}/download":{"parameters":[{"name":"export_id","in":"path","required":true,"schema":{"type":"integer","minimum":1}}],"get":{"operationId":"DownloadExport","description":"A link to the export file (App API \`downloadExport\`; the vendor signs a link that expires\\nafter 15 minutes). The emulator's link is its own CSV route under the admin prefix and\\ncounts a download. Best guess from vendor docs, not oracle-verified.\\n","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"reason":"Best guess from vendor docs, not oracle-verified.","parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"The download link","content":{"application/json":{"schema":{"type":"object","required":["url"],"properties":{"url":{"type":"string","format":"uri","x-mockingbird-volatile":{"kind":"url"}}}}}}},"401":{"$ref":"#/components/responses/AppError"},"404":{"$ref":"#/components/responses/AppError"}}}},"/v1/snippets":{"get":{"operationId":"ListSnippets","description":"The workspace's snippets (App API \`listSnippets\`). Best guess from vendor docs, not oracle-verified.","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"reason":"Best guess from vendor docs, not oracle-verified.","parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Every snippet","content":{"application/json":{"schema":{"type":"object","required":["snippets"],"properties":{"snippets":{"type":"array","items":{"$ref":"#/components/schemas/Snippet"}}}}}}},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/campaigns":{"get":{"operationId":"ListCampaigns","description":"The workspace's automations (App API \`listCampaigns\`), read-only. Best guess from vendor docs, not oracle-verified.","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"reason":"Best guess from vendor docs, not oracle-verified.","parity":{"enabled":true,"safe":true}},"responses":{"200":{"description":"Every automation","content":{"application/json":{"schema":{"type":"object","required":["campaigns"],"properties":{"campaigns":{"type":"array","items":{"$ref":"#/components/schemas/Campaign"}}}}}}},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/newsletters":{"get":{"operationId":"ListNewsletters","description":"The workspace's one-time sends (App API \`listNewsletters\`), paginated by \`limit\` and an\\nopaque \`start\` cursor (\`next\`), \`sort\` asc (default) or desc. Best guess from vendor docs,\\nnot oracle-verified.\\n","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"reason":"Best guess from vendor docs, not oracle-verified.","parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/PageLimit"},{"$ref":"#/components/parameters/PageSort"},{"$ref":"#/components/parameters/PageStart"}],"responses":{"200":{"description":"A page of one-time sends","content":{"application/json":{"schema":{"type":"object","required":["newsletters"],"properties":{"next":{"type":"string"},"newsletters":{"type":"array","items":{"$ref":"#/components/schemas/Newsletter"}}}}}}},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"}}}},"/v1/sender_identities":{"get":{"operationId":"ListSenderIdentities","description":"The workspace's senders (App API \`listSenders\`), paginated like newsletters. Hidden senders\\nare listed only with \`hidden=true\`. Best guess from vendor docs, not oracle-verified.\\n","security":[{"appApiKey":[]}],"x-mockingbird":{"supported":true,"reason":"Best guess from vendor docs, not oracle-verified.","parity":{"enabled":true,"safe":true}},"parameters":[{"$ref":"#/components/parameters/PageLimit"},{"$ref":"#/components/parameters/PageSort"},{"$ref":"#/components/parameters/PageStart"},{"name":"hidden","in":"query","schema":{"type":"boolean"}}],"responses":{"200":{"description":"A page of senders","content":{"application/json":{"schema":{"type":"object","required":["sender_identities"],"properties":{"next":{"type":"string"},"sender_identities":{"type":"array","items":{"$ref":"#/components/schemas/SenderIdentity"}}}}}}},"400":{"$ref":"#/components/responses/AppError"},"401":{"$ref":"#/components/responses/AppError"}}}},"/click/{linkId}":{"parameters":[{"name":"linkId","in":"path","required":true,"schema":{"type":"string","pattern":"^[A-Za-z0-9_~-][A-Za-z0-9._~-]{0,63}$"}}],"post":{"operationId":"ReportClick","description":"Link-tracking click report on the tracking domain (our backend posts it when a smart\\nlink opens the app directly). Unauthenticated.\\n","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"200":{"description":"Click recorded (no body)"},"404":{"description":"Unknown link","content":{"text/plain":{"schema":{"type":"string"}}}}}},"get":{"operationId":"FollowClick","description":"A browser following a tracked link; redirects to the original URL.","security":[],"x-mockingbird":{"supported":true,"parity":{"enabled":true,"safe":false}},"responses":{"302":{"description":"Redirect to the original URL"},"404":{"description":"Unknown link","content":{"text/plain":{"schema":{"type":"string"}}}}}}}},"components":{"securitySchemes":{"cdpWriteKey":{"type":"http","scheme":"basic","description":"\`Basic base64(<write key>:)\` (the CDP source write key as the username)."},"appApiKey":{"type":"http","scheme":"bearer","description":"\`Bearer <App API key>\`."}},"parameters":{"PageLimit":{"name":"limit","in":"query","schema":{"type":"integer","minimum":1}},"PageSort":{"name":"sort","in":"query","schema":{"type":"string","enum":["asc","desc"]}},"PageStart":{"name":"start","in":"query","schema":{"type":"string"}}},"responses":{"Queued":{"description":"Queued for delivery","content":{"application/json":{"schema":{"type":"object","required":["delivery_id","queued_at"],"properties":{"delivery_id":{"type":"string","x-mockingbird-resource":{"type":"delivery","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"queued_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}}}}}}},"AppError":{"description":"An App API error","content":{"application/json":{"schema":{"type":"object","required":["meta"],"properties":{"meta":{"type":"object","required":["error"],"properties":{"error":{"type":"string"}}}}}}}}},"schemas":{"ReportingWebhook":{"type":"object","required":["name","endpoint","events"],"additionalProperties":true,"properties":{"id":{"type":"integer"},"name":{"type":"string"},"endpoint":{"type":"string"},"events":{"type":"array","items":{"type":"string"}},"type":{"type":"string","enum":["webhook","js"]},"disabled":{"type":"boolean"},"full_resolution":{"type":"boolean"},"with_content":{"type":"boolean"}}},"SubscriptionTopic":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"integer"},"identifier":{"type":"string"},"name":{"type":"string"},"description":{"type":"string"},"subscribed_by_default":{"type":"boolean"}}},"Snippet":{"type":"object","required":["name","value"],"additionalProperties":true,"properties":{"name":{"type":"string"},"value":{"type":"string"},"updated_at":{"type":"integer"}}},"Campaign":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"integer"},"name":{"type":"string"},"type":{"type":"string"},"state":{"type":"string"},"active":{"type":"boolean"},"created":{"type":"integer"},"updated":{"type":"integer"},"tags":{"type":"array","items":{"type":"string"}}}},"Newsletter":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"integer"},"name":{"type":"string"},"type":{"type":"string"},"send_state":{"type":"string"},"created":{"type":"integer"},"updated":{"type":"integer"},"tags":{"type":"array","items":{"type":"string"}}}},"SenderIdentity":{"type":"object","additionalProperties":true,"properties":{"id":{"type":"integer"},"name":{"type":"string"},"email":{"type":"string"},"address":{"type":"string"},"phone":{"type":"string"},"template_type":{"type":"string"},"hidden":{"type":"boolean"},"auto_generated":{"type":"boolean"},"deduplicate_id":{"type":"string"}}},"ExportEnvelope":{"type":"object","required":["export"],"properties":{"export":{"type":"object","required":["id","type","status","failed","total","downloads","created_at","updated_at","deduplicate_id"],"properties":{"id":{"type":"integer"},"type":{"type":"string","enum":["customers","deliveries"]},"status":{"type":"string","enum":["done","pending","failed"]},"failed":{"type":"boolean"},"total":{"type":"integer"},"downloads":{"type":"integer"},"created_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"updated_at":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"deduplicate_id":{"type":"string","x-mockingbird-volatile":{"kind":"id"}}}}}},"SenderOptOut":{"type":"object","required":["channel","from"],"properties":{"channel":{"type":"string","enum":["sms","whatsapp"]},"from":{"type":"string"}}},"CdpSuccess":{"type":"object","required":["success"],"properties":{"success":{"type":"boolean"}}},"CdpError":{"type":"object","required":["error"],"properties":{"error":{"type":"string"}}},"IdentifyEvent":{"type":"object","properties":{"type":{"type":"string","enum":["identify"]},"userId":{"type":"string","minLength":1,"maxLength":64},"anonymousId":{"type":"string","minLength":1,"maxLength":64},"traits":{"type":"object","additionalProperties":true},"context":{"type":"object"},"integrations":{"type":"object"},"timestamp":{"type":"string"},"messageId":{"type":"string","maxLength":128},"_metadata":{"type":"object"}}},"TrackEvent":{"type":"object","required":["event"],"properties":{"type":{"type":"string","enum":["track"]},"userId":{"type":"string","minLength":1,"maxLength":64},"anonymousId":{"type":"string","minLength":1,"maxLength":64},"event":{"type":"string","minLength":1,"maxLength":150},"properties":{"type":"object","additionalProperties":true},"context":{"type":"object"},"integrations":{"type":"object"},"timestamp":{"type":"string"},"messageId":{"type":"string","maxLength":128},"_metadata":{"type":"object"}}},"Identifiers":{"type":"object","properties":{"id":{"type":"string","minLength":1,"maxLength":64},"email":{"type":"string","format":"email","maxLength":120},"cio_id":{"type":"string","maxLength":64}}},"TransactionalMessageId":{"oneOf":[{"type":"string","minLength":1,"maxLength":150},{"type":"integer","minimum":1}]},"SendEmailRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"to":{"type":"string","maxLength":200},"from":{"type":"string","maxLength":200},"subject":{"type":"string","maxLength":300},"body":{"type":"string"},"message_data":{"type":"object","additionalProperties":true},"send_to_unsubscribed":{"type":"boolean"},"tracked":{"type":"boolean"},"disable_message_retention":{"type":"boolean"},"headers":{"type":"object","additionalProperties":{"type":"string"}},"attachments":{"description":"Customer.io documents a \`{filename: base64}\` map; our backend sends an array of \`{filename, content, content_type}\`. Both are accepted.","oneOf":[{"type":"object","additionalProperties":{"type":"string"}},{"type":"array","items":{"type":"object","required":["filename","content"],"properties":{"filename":{"type":"string"},"content":{"type":"string"},"content_type":{"type":"string"}}}}]}}},"SendSmsRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"to":{"type":"string","maxLength":20},"message_data":{"type":"object","additionalProperties":true},"send_to_unsubscribed":{"type":"boolean"},"tracked":{"type":"boolean"},"disable_message_retention":{"type":"boolean"}}},"SendPushRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"to":{"type":"string","minLength":1,"maxLength":4096},"platform":{"type":"string","enum":["all","ios","android","web","all_and_web"]},"title":{"type":"string"},"message":{"type":"string"},"image_url":{"type":"string"},"link":{"type":"string"},"sound":{"type":"string","enum":["default","none"]},"language":{"type":"string"},"message_data":{"type":"object","additionalProperties":true},"custom_data":{"description":"Firebase only supports string values (vendor docs); the emulator answers 400 for any other value type (best guess).","type":"object","additionalProperties":true},"custom_payload":{"type":"object","additionalProperties":true,"properties":{"ios":{"type":"object","additionalProperties":true},"android":{"type":"object","additionalProperties":true}}},"custom_device":{"type":"object","required":["token"],"properties":{"token":{"type":"string","minLength":1,"maxLength":4096},"platform":{"type":"string"},"last_used":{"type":"integer"},"attributes":{"type":"object","additionalProperties":true}}},"send_to_unsubscribed":{"type":"boolean"},"disable_message_retention":{"type":"boolean"},"queue_draft":{"type":"boolean"}}},"SendInboxRequest":{"type":"object","required":["transactional_message_id","identifiers"],"properties":{"transactional_message_id":{"$ref":"#/components/schemas/TransactionalMessageId"},"identifiers":{"$ref":"#/components/schemas/Identifiers"},"message_data":{"type":"object","additionalProperties":true}}},"TransactionalMessage":{"type":"object","required":["id","name"],"properties":{"id":{"type":"integer"},"name":{"type":"string"},"trigger_name":{"type":"string","x-mockingbird-resource":{"type":"transactional_message","identity":true}},"description":{"type":"string"},"send_to_unsubscribed":{"type":"boolean"},"link_tracking":{"type":"boolean"},"open_tracking":{"type":"boolean"},"hide_message_body":{"type":"boolean"},"queue_drafts":{"type":"boolean"},"created_at":{"type":"integer"},"updated_at":{"type":"integer"}}},"CustomerAttributes":{"type":"object","required":["customer"],"properties":{"customer":{"type":"object","required":["identifiers","attributes"],"properties":{"identifiers":{"type":"object","required":["id"],"additionalProperties":true,"properties":{"id":{"type":"string"},"email":{"type":"string"},"cio_id":{"type":"string"}}},"attributes":{"type":"object","additionalProperties":true},"devices":{"type":"array","items":{"type":"object","required":["id","platform","last_used"],"additionalProperties":true,"properties":{"id":{"type":"string","description":"The device token."},"platform":{"type":"string"},"last_used":{"type":"integer"},"attributes":{"type":"object","additionalProperties":true}}}}}}}},"DeliveryMessage":{"type":"object","required":["message"],"properties":{"message":{"type":"object","required":["id","state","status","metrics","created"],"additionalProperties":true,"properties":{"id":{"type":"string","x-mockingbird-resource":{"type":"delivery","identity":true},"x-mockingbird-volatile":{"kind":"id"}},"type":{"type":"string"},"recipient":{"type":["string","null"]},"customer_id":{"type":["string","null"]},"created":{"type":"integer","x-mockingbird-volatile":{"kind":"timestamp"}},"state":{"type":"string"},"status":{"type":"string"},"metrics":{"type":"object","additionalProperties":{"type":"integer"}},"failure_message":{"type":["string","null"]},"rejection_reason":{"type":["string","null"]},"error":{"type":["string","null"]}}}}}}}}`);
41
+ var operationIds = ["CdpIdentify", "CdpTrack", "CdpBatch", "SendEmail", "SendSms", "SendPush", "SendInboxMessage", "ListTransactionalMessages", "GetTransactionalMessage", "GetCustomerAttributes", "ListOptOuts", "GetCustomerOptOuts", "GetMessage", "ListReportingWebhooks", "ListSubscriptionTopics", "ExportCustomers", "GetExport", "DownloadExport", "ListSnippets", "ListCampaigns", "ListNewsletters", "ListSenderIdentities", "FollowClick", "ReportClick"];
42
+ var supportedOperationIds = ["CdpIdentify", "CdpTrack", "CdpBatch", "SendEmail", "SendSms", "SendPush", "SendInboxMessage", "ListTransactionalMessages", "GetTransactionalMessage", "GetCustomerAttributes", "ListOptOuts", "GetCustomerOptOuts", "GetMessage", "ListReportingWebhooks", "ListSubscriptionTopics", "ExportCustomers", "GetExport", "DownloadExport", "ListSnippets", "ListCampaigns", "ListNewsletters", "ListSenderIdentities", "FollowClick", "ReportClick"];
43
+
44
+ // src/state.ts
45
+ var DELIVERY_STATES = [
46
+ "pending",
47
+ "sent",
48
+ "delivered",
49
+ "bounced",
50
+ "dropped",
51
+ "failed",
52
+ "spammed",
53
+ "undeliverable",
54
+ "suppressed"
55
+ ];
56
+ var FAILURE_STATES = /* @__PURE__ */ new Set([
57
+ "bounced",
58
+ "dropped",
59
+ "failed",
60
+ "spammed",
61
+ "undeliverable",
62
+ "suppressed"
63
+ ]);
64
+ var MAX_DEVICES_PER_PERSON = 25;
65
+ var CONTENT_LISTS = [
66
+ "reporting_webhooks",
67
+ "topics",
68
+ "snippets",
69
+ "campaigns",
70
+ "newsletters",
71
+ "sender_identities"
72
+ ];
73
+ var DEFAULT_SETTINGS = {
74
+ strictMessages: false,
75
+ trackingBase: "https://links.customer.io",
76
+ keys: [],
77
+ statusVisibleAfterMs: 0,
78
+ clockOffsetMs: 0,
79
+ retainMessageDataForTests: false,
80
+ transactionalListKey: "messages",
81
+ pushUnknownTargets: "accept",
82
+ deviceTokenOwnership: "move"
83
+ };
84
+ var TRANSACTIONAL_EMAIL_KEYS = [
85
+ "welcome",
86
+ "bloodwork_reminder",
87
+ "appointment",
88
+ "keys",
89
+ "forms",
90
+ "billing",
91
+ "bloodwork",
92
+ "provider_bloodwork",
93
+ "bloodwork_results",
94
+ "payment_failed",
95
+ "payment_charged",
96
+ "subscription_renewal",
97
+ "new_message_email",
98
+ "requisition_pdf",
99
+ "post_wellness_visit",
100
+ "post_provider_visit",
101
+ "post_bloodwork_review",
102
+ "event_bloodwork_scheduled",
103
+ "event_bloodwork_booth_location"
104
+ ];
105
+ var CATALOG_EPOCH = 1735689600;
106
+ var DEFAULT_TRANSACTIONAL_MESSAGES = [
107
+ ...TRANSACTIONAL_EMAIL_KEYS.map((key) => `acme_${key}`),
108
+ "acme_inbox_message",
109
+ "acme_playground_notification"
110
+ ].map((trigger, index) => ({
111
+ id: index + 1,
112
+ name: trigger.replace(/^acme_/, "Acme ").replace(/_/g, " "),
113
+ trigger_name: trigger,
114
+ description: "",
115
+ send_to_unsubscribed: true,
116
+ link_tracking: false,
117
+ open_tracking: true,
118
+ hide_message_body: false,
119
+ queue_drafts: false,
120
+ created_at: CATALOG_EPOCH,
121
+ updated_at: CATALOG_EPOCH
122
+ }));
123
+ var CustomerIoState = class {
124
+ constructor(sqlite, namespace, seed) {
125
+ this.seed = seed;
126
+ this.deliveries = new service_exports.OutboxStore(sqlite, namespace, "deliveries");
127
+ this.cdp = new service_exports.Collection(sqlite, namespace, "cdp");
128
+ this.profiles = new service_exports.Collection(sqlite, namespace, "profiles");
129
+ this.optouts = new service_exports.Collection(sqlite, namespace, "optouts");
130
+ this.messages = new service_exports.Collection(sqlite, namespace, "transactional");
131
+ this.links = new service_exports.Collection(sqlite, namespace, "links");
132
+ this.devices = new service_exports.Collection(sqlite, namespace, "devices");
133
+ this.settings = new service_exports.Collection(sqlite, namespace, "settings");
134
+ this.content = new service_exports.Collection(sqlite, namespace, "content");
135
+ this.exports = new service_exports.Collection(sqlite, namespace, "exports");
136
+ this.ids = new service_exports.IdSequence(sqlite, namespace, "customerio");
137
+ this.ensureSeeded();
138
+ }
139
+ seed;
140
+ deliveries;
141
+ cdp;
142
+ profiles;
143
+ optouts;
144
+ messages;
145
+ links;
146
+ devices;
147
+ settings;
148
+ content;
149
+ exports;
150
+ ids;
151
+ ensureSeeded() {
152
+ if (this.messages.count() === 0) {
153
+ for (const message of this.seed.messages) this.messages.insert(String(message.id), message);
154
+ }
155
+ if (!this.settings.has("settings")) {
156
+ this.settings.insert("settings", { ...DEFAULT_SETTINGS, ...this.seed.settings });
157
+ }
158
+ }
159
+ current() {
160
+ return this.settings.get("settings") ?? DEFAULT_SETTINGS;
161
+ }
162
+ update(patch) {
163
+ const next = { ...this.current(), ...patch };
164
+ this.settings.insert("settings", next);
165
+ return next;
166
+ }
167
+ /** One workspace content list, in stored order (empty when never seeded). */
168
+ contentOf(list) {
169
+ return this.content.get(list)?.items ?? [];
170
+ }
171
+ setContent(list, items) {
172
+ if (this.content.has(list)) this.content.update(list, { list, items });
173
+ else this.content.insert(list, { list, items });
174
+ }
175
+ catalog() {
176
+ return this.messages.list({ order: "oldest" }).map((row) => row.value);
177
+ }
178
+ /** A catalog message by numeric id or (case-insensitive) trigger name. */
179
+ message(idOrTrigger) {
180
+ const byId = /^\d+$/.test(idOrTrigger) ? this.messages.get(String(Number(idOrTrigger))) : void 0;
181
+ if (byId) return byId;
182
+ const lower = idOrTrigger.toLowerCase();
183
+ return this.catalog().find((m) => m.trigger_name.toLowerCase() === lower);
184
+ }
185
+ setOptOut(customerId, from, channel, optout) {
186
+ if (!this.profile(customerId)) return void 0;
187
+ const sender = from.trim().toLowerCase();
188
+ const current = this.optouts.get(customerId);
189
+ const optouts = (current?.optouts ?? []).filter(
190
+ (item) => item.channel !== channel || item.from !== sender
191
+ );
192
+ if (optout) optouts.push({ channel, from: sender });
193
+ const next = { customerId, optouts };
194
+ if (current) this.optouts.update(customerId, next);
195
+ else this.optouts.insert(customerId, next);
196
+ return next;
197
+ }
198
+ profile(id) {
199
+ return this.profiles.get(id);
200
+ }
201
+ profileByEmail(email) {
202
+ const lower = email.toLowerCase();
203
+ return this.profiles.list({ where: (p) => p.email?.toLowerCase() === lower }).at(0)?.value;
204
+ }
205
+ profileByCioId(cioId) {
206
+ return this.profiles.list({ where: (p) => p.cioId === cioId }).at(0)?.value;
207
+ }
208
+ /** The profile an App API `identifiers` object names (id, else cio_id, else email). */
209
+ profileFor(identifiers) {
210
+ if (identifiers.id) return this.profile(identifiers.id);
211
+ if (identifiers.cio_id) return this.profileByCioId(identifiers.cio_id);
212
+ if (identifiers.email) return this.profileByEmail(identifiers.email);
213
+ return void 0;
214
+ }
215
+ upsertProfile(id, patch, at) {
216
+ const existing = this.profile(id);
217
+ const next = {
218
+ id,
219
+ cioId: existing?.cioId ?? this.ids.next("cio", 8),
220
+ email: existing?.email ?? null,
221
+ traits: existing?.traits ?? {},
222
+ unsubscribed: existing?.unsubscribed ?? false,
223
+ channelsOff: existing?.channelsOff ?? [],
224
+ preferences: existing?.preferences ?? { channels: {}, topics: {} },
225
+ ...patch,
226
+ updatedAt: at
227
+ };
228
+ this.profiles.insert(id, next);
229
+ return next;
230
+ }
231
+ devicesOf(userId) {
232
+ return this.devices.get(userId)?.devices ?? [];
233
+ }
234
+ /** Replace a person's device list (oldest first, capped at {@link MAX_DEVICES_PER_PERSON}). */
235
+ setDevices(userId, devices) {
236
+ const kept = [...devices];
237
+ while (kept.length > MAX_DEVICES_PER_PERSON) {
238
+ let oldest = 0;
239
+ for (const [index, device] of kept.entries()) {
240
+ if (device.last_used < kept[oldest].last_used) oldest = index;
241
+ }
242
+ kept.splice(oldest, 1);
243
+ }
244
+ if (this.devices.has(userId)) this.devices.update(userId, { userId, devices: kept });
245
+ else this.devices.insert(userId, { userId, devices: kept });
246
+ return kept;
247
+ }
248
+ /** Take tokens off everyone except `userId` (the `move` ownership rule). */
249
+ releaseTokens(userId, tokens) {
250
+ if (this.current().deviceTokenOwnership !== "move" || tokens.length === 0) return;
251
+ for (const row of this.devices.list()) {
252
+ if (row.value.userId === userId) continue;
253
+ const rest = row.value.devices.filter((device) => !tokens.includes(device.id));
254
+ if (rest.length !== row.value.devices.length) this.setDevices(row.value.userId, rest);
255
+ }
256
+ }
257
+ /** Add or refresh one device; it becomes the newest entry. */
258
+ upsertDevice(userId, device) {
259
+ this.releaseTokens(userId, [device.id]);
260
+ const rest = this.devicesOf(userId).filter((existing) => existing.id !== device.id);
261
+ return this.setDevices(userId, [...rest, device]);
262
+ }
263
+ removeDevice(userId, token) {
264
+ const current = this.devicesOf(userId);
265
+ if (!current.some((device) => device.id === token)) return current;
266
+ return this.setDevices(
267
+ userId,
268
+ current.filter((device) => device.id !== token)
269
+ );
270
+ }
271
+ deliveryId() {
272
+ return this.ids.next("", 28);
273
+ }
274
+ linkId() {
275
+ return this.ids.next("l", 15);
276
+ }
277
+ eventId() {
278
+ return this.ids.next("01J", 23).toUpperCase();
279
+ }
280
+ };
281
+
282
+ // src/runtime.ts
283
+ var REPORTING_WEBHOOK_PATH = "/v1/customer-io/reporting-webhook";
284
+ var signReporting = (secret, timestampSeconds, body) => (0, service_exports.hmac)("SHA-256", secret, `v0:${timestampSeconds}:${body}`, "hex");
285
+ var WORKSPACE_READS = [
286
+ "ListReportingWebhooks",
287
+ "ListSubscriptionTopics",
288
+ "ExportCustomers",
289
+ "GetExport",
290
+ "DownloadExport",
291
+ "ListSnippets",
292
+ "ListCampaigns",
293
+ "ListNewsletters",
294
+ "ListSenderIdentities"
295
+ ];
296
+ var SENDS = ["SendEmail", "SendSms", "SendPush", "SendInboxMessage"];
297
+ var CDP = ["CdpIdentify", "CdpTrack", "CdpBatch"];
298
+ var onSends = (rule) => SENDS.map((operationId) => ({ operationId, ...rule }));
299
+ var onCdp = (rule) => CDP.map((operationId) => ({ operationId, ...rule }));
300
+ var CUSTOMERIO_PRESETS = {
301
+ transactional_message_missing: {
302
+ description: 'Sends answer 400 {meta: {error: "transactional_message_id not found"}} (trigger_name_missing, then fallback)',
303
+ rules: onSends({
304
+ status: 400,
305
+ body: { meta: { error: "transactional_message_id not found" } }
306
+ })
307
+ },
308
+ transactional_404: {
309
+ description: "Sends answer 404 (also read as trigger_name_missing)",
310
+ rules: onSends({ status: 404, body: { meta: { error: "not found" } } })
311
+ },
312
+ request_timeout_408: {
313
+ description: "Sends answer 408 before the handler runs (no delivery). Ambiguous: the caller keeps its reservation",
314
+ rules: onSends({ status: 408, body: { meta: { error: "request timeout" } } })
315
+ },
316
+ server_error: {
317
+ description: "Sends answer 500 before the handler runs (no delivery). Ambiguous: the caller keeps its reservation",
318
+ rules: onSends({ status: 500, body: { meta: { error: "internal server error" } } })
319
+ },
320
+ accepted_but_500: {
321
+ description: "Sends queue the message (it lands in the outbox), then answer 500",
322
+ rules: SENDS.map((operationId) => ({ operationId, effect: "accepted_but_500" }))
323
+ },
324
+ rate_limited: {
325
+ description: "Sends answer 429: definite, safe to re-POST on the next attempt",
326
+ rules: onSends({
327
+ status: 429,
328
+ headers: { "retry-after": "1" },
329
+ body: { meta: { error: "rate limit exceeded" } }
330
+ })
331
+ },
332
+ invalid_app_key: {
333
+ description: "App API calls answer 401",
334
+ rules: [
335
+ ...onSends({ status: 401, body: { meta: { error: "Unauthorized request" } } }),
336
+ {
337
+ pathPrefix: "/v1/transactional",
338
+ status: 401,
339
+ body: { meta: { error: "Unauthorized request" } }
340
+ },
341
+ {
342
+ operationId: "GetCustomerAttributes",
343
+ status: 401,
344
+ body: { meta: { error: "Unauthorized request" } }
345
+ },
346
+ {
347
+ operationId: "GetMessage",
348
+ status: 401,
349
+ body: { meta: { error: "Unauthorized request" } }
350
+ },
351
+ ...WORKSPACE_READS.map((operationId) => ({
352
+ operationId,
353
+ status: 401,
354
+ body: { meta: { error: "Unauthorized request" } }
355
+ }))
356
+ ]
357
+ },
358
+ send_drop: {
359
+ description: "Sends drop the connection before the handler runs: ambiguous, no delivery",
360
+ rules: SENDS.map((operationId) => ({ operationId, drop: true }))
361
+ },
362
+ send_drop_before_accept: {
363
+ description: "Sends drop the connection before enqueue: ambiguous, no delivery",
364
+ rules: SENDS.map((operationId) => ({ operationId, drop: true }))
365
+ },
366
+ send_drop_after_accept: {
367
+ description: "Sends record the delivery, then drop the connection: ambiguous, exactly one delivery",
368
+ rules: SENDS.map((operationId) => ({ operationId, effect: "send_drop_after_accept" }))
369
+ },
370
+ push_unknown_targets_rejected: {
371
+ description: "Push sends answer 400 (no delivery) when `to` names a token not on the profile, the person has no profile, or no devices",
372
+ rules: [{ operationId: "SendPush", effect: "push_unknown_targets_rejected" }]
373
+ },
374
+ cdp_unavailable: {
375
+ description: "CDP calls answer 503 (the SDK retries, then fails the callback)",
376
+ rules: onCdp({ status: 503, body: { error: "Service Unavailable" } })
377
+ },
378
+ cdp_bad_request: {
379
+ description: "CDP calls answer 400 (the SDK does not retry; the callback fails)",
380
+ rules: onCdp({ status: 400, body: { error: "Bad Request" } })
381
+ },
382
+ cdp_slow: {
383
+ description: "CDP calls take 15 s (our 10 s delivery timeout fires first)",
384
+ rules: onCdp({ latencyMs: 15e3 })
385
+ },
386
+ transactional_list_unavailable: {
387
+ description: "GET /v1/transactional answers 503 (the trigger-name validator records an error)",
388
+ rules: [
389
+ {
390
+ operationId: "ListTransactionalMessages",
391
+ status: 503,
392
+ body: { meta: { error: "service unavailable" } }
393
+ }
394
+ ]
395
+ },
396
+ omit_trigger_names: {
397
+ description: "GET /v1/transactional lists messages without trigger_name (the validator reads each by id)",
398
+ rules: [{ operationId: "ListTransactionalMessages", effect: "omit_trigger_names" }]
399
+ },
400
+ webhook_duplicate: {
401
+ description: "The next reporting event is delivered twice (same event_id)",
402
+ webhook: { mode: "duplicate" }
403
+ },
404
+ webhook_drop: {
405
+ description: "The next reporting event is never delivered",
406
+ webhook: { mode: "drop" }
407
+ },
408
+ webhook_reorder: {
409
+ description: "The next reporting event is held until the one after it, then the two are swapped",
410
+ webhook: { mode: "reorder" }
411
+ }
412
+ };
413
+ var json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
414
+ var adminError = (status, message) => json(status, { error: { type: "mockingbird_admin", message } });
415
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
416
+ var adminRoutes = (runtime) => ({
417
+ ...(0, service_exports.outboxAdminRoutes)(
418
+ runtime,
419
+ (api) => api.state.deliveries,
420
+ (params) => {
421
+ const channel = params.get("channel");
422
+ const message = params.get("transactional_message_id");
423
+ const userId = params.get("userId");
424
+ const recipient = params.get("recipient");
425
+ const deliveryId = params.get("deliveryId");
426
+ if (channel === null && message === null && userId === null && recipient === null && deliveryId === null) {
427
+ return void 0;
428
+ }
429
+ return (item) => (channel === null || item.channel === channel) && (message === null || item.transactionalMessageId === message) && (userId === null || item.identifiers.id === userId) && (deliveryId === null || item.id === deliveryId) && (recipient === null || String(item.to).toLowerCase() === recipient.toLowerCase());
430
+ }
431
+ ),
432
+ "GET /cdp/events": ({ url, namespace }) => {
433
+ const userId = url.searchParams.get("userId");
434
+ const type = url.searchParams.get("type");
435
+ const event = url.searchParams.get("event");
436
+ return json(200, {
437
+ events: runtime.instance(namespace).state.cdp.list({
438
+ order: "oldest",
439
+ where: (e) => (userId === null || e.userId === userId) && (type === null || e.type === type) && (event === null || e.event === event)
440
+ }).map((row) => row.value)
441
+ });
442
+ },
443
+ "GET /profiles": ({ namespace }) => json(200, { profiles: runtime.instance(namespace).profiles() }),
444
+ "GET /profiles/:id": ({ params, namespace }) => {
445
+ const profile = runtime.instance(namespace).state.profile(params.id);
446
+ return profile ? json(200, profile) : adminError(404, `no profile ${params.id}`);
447
+ },
448
+ "GET /devices/:id": ({ params, namespace }) => json(200, {
449
+ userId: params.id,
450
+ devices: runtime.instance(namespace).state.devicesOf(params.id)
451
+ }),
452
+ "PUT /devices/:id": ({ params, body, namespace }) => {
453
+ const list = isRecord(body) ? body.devices : void 0;
454
+ const usage = `expected {"devices": [{token, platform, last_used?, attributes?}]} (at most ${MAX_DEVICES_PER_PERSON})`;
455
+ if (!Array.isArray(list) || list.length > MAX_DEVICES_PER_PERSON) return adminError(400, usage);
456
+ const api = runtime.instance(namespace);
457
+ const now = Math.floor(api.now() / 1e3);
458
+ const devices = [];
459
+ for (const raw of list) {
460
+ const token = isRecord(raw) ? raw.token ?? raw.id : void 0;
461
+ if (!isRecord(raw) || typeof token !== "string" || !token) return adminError(400, usage);
462
+ if (devices.some((device) => device.id === token))
463
+ return adminError(400, `duplicate token ${token}`);
464
+ devices.push({
465
+ id: token,
466
+ platform: typeof raw.platform === "string" ? raw.platform.toLowerCase() : "unknown",
467
+ last_used: typeof raw.last_used === "number" && Number.isFinite(raw.last_used) ? Math.floor(raw.last_used) : now,
468
+ attributes: isRecord(raw.attributes) ? raw.attributes : {}
469
+ });
470
+ }
471
+ const userId = params.id;
472
+ if (!api.state.profile(userId)) api.mergeProfile(userId, {});
473
+ api.state.releaseTokens(
474
+ userId,
475
+ devices.map((device) => device.id)
476
+ );
477
+ return json(200, { userId, devices: api.state.setDevices(userId, devices) });
478
+ },
479
+ "PUT /profiles/:id": ({ params, body, namespace }) => {
480
+ if (!isRecord(body)) return adminError(400, "expected a JSON object");
481
+ const patch = {};
482
+ if (isRecord(body.traits)) patch.traits = body.traits;
483
+ if (typeof body.email === "string" || body.email === null) patch.email = body.email;
484
+ if (typeof body.unsubscribed === "boolean") patch.unsubscribed = body.unsubscribed;
485
+ if (isRecord(body.preferences)) {
486
+ patch.preferences = body.preferences;
487
+ }
488
+ return json(200, runtime.instance(namespace).mergeProfile(params.id, patch));
489
+ },
490
+ "POST /optouts": ({ body, namespace }) => {
491
+ if (!isRecord(body) || typeof body.customerId !== "string" || typeof body.from !== "string" || !body.from.trim() || typeof body.optout !== "boolean" || body.channel !== void 0 && body.channel !== "sms" && body.channel !== "whatsapp") {
492
+ return adminError(400, "expected {customerId, from, optout: boolean, channel?: sms|whatsapp}");
493
+ }
494
+ const result = runtime.instance(namespace).state.setOptOut(
495
+ body.customerId,
496
+ body.from,
497
+ body.channel === "whatsapp" ? "whatsapp" : "sms",
498
+ body.optout
499
+ );
500
+ return result ? json(200, result) : adminError(404, "unknown customer");
501
+ },
502
+ "POST /deliveries/:id": ({ params, body, namespace }) => {
503
+ if (!isRecord(body) || typeof body.state !== "string") {
504
+ return adminError(400, `expected {"state": ${DELIVERY_STATES.join("|")}}`);
505
+ }
506
+ if (!DELIVERY_STATES.includes(body.state)) {
507
+ return adminError(400, `state must be one of ${DELIVERY_STATES.join(", ")}`);
508
+ }
509
+ const delivery = runtime.instance(namespace).transitionDelivery(params.id, body.state);
510
+ return delivery ? json(200, delivery) : adminError(404, `no delivery ${params.id}`);
511
+ },
512
+ "POST /namespace-clock": ({ body, namespace }) => {
513
+ if (!isRecord(body) || typeof body.advance !== "number" || !Number.isFinite(body.advance)) {
514
+ return adminError(400, 'expected {"advance": <milliseconds>}');
515
+ }
516
+ return json(200, runtime.instance(namespace).advanceClock(body.advance));
517
+ },
518
+ "POST /reporting-events": ({ body, namespace }) => {
519
+ if (!isRecord(body) || typeof body.metric !== "string") {
520
+ return adminError(
521
+ 400,
522
+ 'expected {"metric": "unsubscribed"|"subscribed"|"spammed"|"cio_subscription_preferences_changed"|\u2026, "userId"?, "email"?, "deliveryId"?, "objectType"?, "preferences"?}'
523
+ );
524
+ }
525
+ const text = (key) => typeof body[key] === "string" ? body[key] : void 0;
526
+ const input = { metric: body.metric };
527
+ for (const key of ["objectType", "userId", "email", "deliveryId", "href", "linkId"]) {
528
+ const value = text(key);
529
+ if (value !== void 0) input[key] = value;
530
+ }
531
+ if (isRecord(body.preferences))
532
+ input.preferences = body.preferences;
533
+ const event = runtime.instance(namespace).report(input);
534
+ return typeof event === "string" ? adminError(404, event) : json(201, event);
535
+ },
536
+ "GET /content": ({ namespace }) => json(200, runtime.instance(namespace).content()),
537
+ "PUT /content": ({ body, namespace }) => {
538
+ if (!isRecord(body)) {
539
+ return adminError(
540
+ 400,
541
+ "expected {reporting_webhooks?, topics?, snippets?, campaigns?, newsletters?, sender_identities?: [...]}"
542
+ );
543
+ }
544
+ const result = runtime.instance(namespace).setContent(body);
545
+ return typeof result === "string" ? adminError(400, result) : json(200, result);
546
+ },
547
+ "GET /exports/:id/file": ({ params, namespace }) => runtime.instance(namespace).exportFile(params.id) ?? adminError(404, `no export ${params.id}`),
548
+ "GET /transactional": ({ namespace }) => json(200, { messages: runtime.instance(namespace).state.catalog() }),
549
+ "PUT /transactional": ({ body, namespace }) => {
550
+ const list = Array.isArray(body) ? body : isRecord(body) ? body.messages : void 0;
551
+ if (!Array.isArray(list)) return adminError(400, "expected [{id, name, trigger_name, \u2026}]");
552
+ const state = runtime.instance(namespace).state;
553
+ for (const row of state.catalog()) state.messages.delete(String(row.id));
554
+ for (const [index, raw] of list.entries()) {
555
+ if (!isRecord(raw) || typeof raw.trigger_name !== "string") {
556
+ return adminError(400, `messages[${index}]: trigger_name is required`);
557
+ }
558
+ const id = typeof raw.id === "number" ? raw.id : index + 1;
559
+ state.messages.insert(String(id), {
560
+ id,
561
+ name: typeof raw.name === "string" ? raw.name : raw.trigger_name,
562
+ trigger_name: raw.trigger_name,
563
+ description: typeof raw.description === "string" ? raw.description : "",
564
+ send_to_unsubscribed: raw.send_to_unsubscribed !== false,
565
+ link_tracking: raw.link_tracking === true,
566
+ open_tracking: raw.open_tracking !== false,
567
+ hide_message_body: raw.hide_message_body === true,
568
+ queue_drafts: false,
569
+ created_at: 1735689600,
570
+ updated_at: 1735689600
571
+ });
572
+ }
573
+ return json(200, { messages: state.catalog() });
574
+ },
575
+ "GET /settings": ({ namespace }) => json(200, runtime.instance(namespace).state.current()),
576
+ "PUT /settings": ({ body, namespace }) => {
577
+ if (!isRecord(body)) return adminError(400, "expected a JSON object");
578
+ const patch = {};
579
+ if (typeof body.strictMessages === "boolean") patch.strictMessages = body.strictMessages;
580
+ if (typeof body.trackingBase === "string") patch.trackingBase = body.trackingBase;
581
+ if (Array.isArray(body.keys)) patch.keys = body.keys.map(String);
582
+ if (typeof body.statusVisibleAfterMs === "number" && Number.isFinite(body.statusVisibleAfterMs)) {
583
+ patch.statusVisibleAfterMs = body.statusVisibleAfterMs;
584
+ }
585
+ if (typeof body.clockOffsetMs === "number" && Number.isFinite(body.clockOffsetMs)) {
586
+ patch.clockOffsetMs = body.clockOffsetMs;
587
+ }
588
+ if (typeof body.retainMessageDataForTests === "boolean") {
589
+ patch.retainMessageDataForTests = body.retainMessageDataForTests;
590
+ }
591
+ if (body.transactionalListKey === "messages" || body.transactionalListKey === "transactional") {
592
+ patch.transactionalListKey = body.transactionalListKey;
593
+ }
594
+ if (body.pushUnknownTargets === "accept" || body.pushUnknownTargets === "reject") {
595
+ patch.pushUnknownTargets = body.pushUnknownTargets;
596
+ }
597
+ if (body.deviceTokenOwnership === "move" || body.deviceTokenOwnership === "share") {
598
+ patch.deviceTokenOwnership = body.deviceTokenOwnership;
599
+ }
600
+ return json(200, runtime.instance(namespace).state.update(patch));
601
+ }
602
+ });
603
+ var createRuntime2 = (options = {}) => {
604
+ const { retryDelaysMs, fetch: send, ...endpoint } = options.webhooks ?? { url: "" };
605
+ const hub = (0, service_exports.createWebhookHub)({
606
+ signer: service_exports.signers.custom(
607
+ async ({ body, timestampSeconds, secret }) => secret ? {
608
+ "x-cio-timestamp": String(timestampSeconds),
609
+ "x-cio-signature": await signReporting(secret, timestampSeconds, body)
610
+ } : {}
611
+ ),
612
+ ...retryDelaysMs ? { retryDelaysMs } : {},
613
+ ...send ? { fetch: send } : {},
614
+ ...options.wallClock ? { now: options.wallClock } : {},
615
+ endpoints: options.webhooks ? [endpoint] : []
616
+ });
617
+ const runtime = createRuntime({
618
+ name: CUSTOMERIO_NAMESPACE,
619
+ document,
620
+ ...options.sqlite ? { sqlite: options.sqlite } : {},
621
+ ...options.clock ? { clock: options.clock } : {},
622
+ ...options.seed !== void 0 ? { seed: options.seed } : {},
623
+ ...options.adminPrefix !== void 0 ? { adminPrefix: options.adminPrefix } : {},
624
+ ...options.adminKey !== void 0 ? { adminKey: options.adminKey } : {},
625
+ ...options.adminControls !== void 0 ? { adminControls: options.adminControls } : {},
626
+ ...options.onLog ? { onLog: options.onLog } : {},
627
+ credential: customerIoCredential,
628
+ presets: CUSTOMERIO_PRESETS,
629
+ webhooks: hub,
630
+ create: ({ sqlite, namespace, publicNamespace, adminPrefix, clock }) => new CustomerIoAPI({
631
+ sqlite,
632
+ namespace,
633
+ publicNamespace,
634
+ adminPrefix,
635
+ now: clock.now,
636
+ ...options.wallClock ? { wallClock: options.wallClock } : {},
637
+ ...options.messages ? { messages: options.messages } : {},
638
+ ...options.settings ? { settings: options.settings } : {},
639
+ onReport: (event) => hub.publish({
640
+ namespace: publicNamespace,
641
+ type: event.metric,
642
+ body: event,
643
+ id: event.event_id
644
+ })
645
+ }),
646
+ describe: () => ({ webhooks: hub.endpoints("default").length > 0 ? "on" : "off" }),
647
+ admin: adminRoutes
648
+ });
649
+ return Object.assign(runtime, { webhooks: hub });
650
+ };
651
+
652
+ // src/index.ts
653
+ var CUSTOMERIO_NAMESPACE = "customerio";
654
+ var customerIoCredential = (request) => (0, service_exports.basicAuth)(request)?.username || (0, service_exports.bearerToken)(request);
655
+ var CDP_OPERATIONS = /* @__PURE__ */ new Set(["CdpIdentify", "CdpTrack", "CdpBatch"]);
656
+ var APP_OPERATIONS = /* @__PURE__ */ new Set([
657
+ "SendEmail",
658
+ "SendSms",
659
+ "SendPush",
660
+ "SendInboxMessage",
661
+ "ListTransactionalMessages",
662
+ "GetTransactionalMessage",
663
+ "GetCustomerAttributes",
664
+ "ListOptOuts",
665
+ "GetCustomerOptOuts",
666
+ "GetMessage",
667
+ "ListReportingWebhooks",
668
+ "ListSubscriptionTopics",
669
+ "ExportCustomers",
670
+ "GetExport",
671
+ "DownloadExport",
672
+ "ListSnippets",
673
+ "ListCampaigns",
674
+ "ListNewsletters",
675
+ "ListSenderIdentities"
676
+ ]);
677
+ var DEVICE_UPSERT_EVENT = "Device Created or Updated";
678
+ var DEVICE_DELETE_EVENT = "Device Deleted";
679
+ var unixSeconds = (value) => {
680
+ if (typeof value !== "string") return void 0;
681
+ const ms = Date.parse(value);
682
+ return Number.isNaN(ms) ? void 0 : Math.floor(ms / 1e3);
683
+ };
684
+ var E164 = /^\+[1-9]\d{1,14}$/;
685
+ var clickNotFound = () => new Response("404 page not found", { status: 404, headers: { "content-type": "text/plain" } });
686
+ var cdpError = (status, error) => (0, service_exports.jsonRes)(status, { error });
687
+ var appError = (status, error) => (0, service_exports.jsonRes)(status, { meta: { error } });
688
+ var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
689
+ var URL_PATTERN = /https?:\/\/[^\s"'<>]+/g;
690
+ var boolRecord = (value) => {
691
+ if (!isRecord2(value)) return void 0;
692
+ const out = {};
693
+ for (const [key, item] of Object.entries(value)) {
694
+ if (typeof item === "boolean") out[key] = item;
695
+ }
696
+ return out;
697
+ };
698
+ var mergeBoolMap = (current, incoming) => {
699
+ const next = boolRecord(incoming);
700
+ return next ? { ...current, ...next } : { ...current };
701
+ };
702
+ var mergeTraits = (current, incoming) => {
703
+ const next = { ...current, ...incoming };
704
+ if (!("cio_subscription_preferences" in incoming)) return next;
705
+ if (!isRecord2(incoming.cio_subscription_preferences)) return next;
706
+ const currentPrefs = isRecord2(current.cio_subscription_preferences) ? current.cio_subscription_preferences : {};
707
+ const incomingPrefs = incoming.cio_subscription_preferences;
708
+ next.cio_subscription_preferences = {
709
+ ...currentPrefs,
710
+ ...incomingPrefs,
711
+ channels: mergeBoolMap(boolRecord(currentPrefs.channels) ?? {}, incomingPrefs.channels),
712
+ topics: mergeBoolMap(boolRecord(currentPrefs.topics) ?? {}, incomingPrefs.topics)
713
+ };
714
+ return next;
715
+ };
716
+ var preferencesOf = (traits) => {
717
+ const raw = traits.cio_subscription_preferences;
718
+ if (!isRecord2(raw)) return void 0;
719
+ return { channels: boolRecord(raw.channels) ?? {}, topics: boolRecord(raw.topics) ?? {} };
720
+ };
721
+ var channelsOffOf = (preferences) => {
722
+ const off = [];
723
+ if (preferences.channels.email === false) off.push("email");
724
+ if (preferences.channels.sms === false) off.push("sms");
725
+ return off;
726
+ };
727
+ var mergePreferences = (current, incoming) => ({
728
+ channels: mergeBoolMap(current?.channels ?? {}, incoming.channels),
729
+ topics: mergeBoolMap(current?.topics ?? {}, incoming.topics)
730
+ });
731
+ var profileAttributes = (profile) => ({
732
+ ...profile.traits,
733
+ id: profile.id,
734
+ cio_id: profile.cioId,
735
+ ...profile.email ? { email: profile.email } : {},
736
+ unsubscribed: profile.unsubscribed
737
+ });
738
+ var FILTER_KEYS = ["and", "or", "not", "segment", "attribute"];
739
+ var parseFilter = (node, path) => {
740
+ if (!isRecord2(node)) return `${path}: expected an object`;
741
+ const keys = Object.keys(node);
742
+ const key = keys[0];
743
+ if (keys.length !== 1 || key === void 0 || !FILTER_KEYS.includes(key)) {
744
+ return `${path}: expected exactly one of ${FILTER_KEYS.join(", ")}`;
745
+ }
746
+ const value = node[key];
747
+ if (key === "segment") return `${path}: segment filters are not supported by the emulator`;
748
+ if (key === "and" || key === "or") {
749
+ if (!Array.isArray(value) || value.length === 0)
750
+ return `${path}.${key}: expected a non-empty array`;
751
+ const parts = [];
752
+ for (const [index, child] of value.entries()) {
753
+ const part = parseFilter(child, `${path}.${key}[${index}]`);
754
+ if (typeof part === "string") return part;
755
+ parts.push(part);
756
+ }
757
+ return key === "and" ? (attributes) => parts.every((part) => part(attributes)) : (attributes) => parts.some((part) => part(attributes));
758
+ }
759
+ if (key === "not") {
760
+ const inner = parseFilter(value, `${path}.not`);
761
+ return typeof inner === "string" ? inner : (attributes) => !inner(attributes);
762
+ }
763
+ if (!isRecord2(value) || typeof value.field !== "string" || !value.field) {
764
+ return `${path}.attribute.field: is required`;
765
+ }
766
+ const { field, operator, inverse } = value;
767
+ if (operator !== "eq" && operator !== "exists") {
768
+ return `${path}.attribute.operator: must be eq or exists`;
769
+ }
770
+ if (inverse !== void 0 && typeof inverse !== "boolean") {
771
+ return `${path}.attribute.inverse: must be a boolean`;
772
+ }
773
+ if (operator === "eq" && !["string", "number", "boolean"].includes(typeof value.value)) {
774
+ return `${path}.attribute.value: is required for eq`;
775
+ }
776
+ const expected = String(value.value);
777
+ return (attributes) => {
778
+ const actual = attributes[field];
779
+ const present = actual !== void 0 && actual !== null;
780
+ const match = operator === "exists" ? present : present && String(actual) === expected;
781
+ return inverse === true ? !match : match;
782
+ };
783
+ };
784
+ var csvCell = (value) => {
785
+ const text = value === void 0 || value === null ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
786
+ return /[",\r\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
787
+ };
788
+ var publicExport = ({ csv: _csv, ...record }) => record;
789
+ var urlsIn = (value, out = []) => {
790
+ if (typeof value === "string") {
791
+ for (const url of [...(0, service_exports.extractLinks)(value), ...value.match(URL_PATTERN) ?? []]) {
792
+ if (/^https?:\/\//.test(url) && !out.includes(url)) out.push(url);
793
+ }
794
+ } else if (Array.isArray(value)) {
795
+ for (const item of value) urlsIn(item, out);
796
+ } else if (isRecord2(value)) {
797
+ for (const item of Object.values(value)) urlsIn(item, out);
798
+ }
799
+ return out;
800
+ };
801
+ var CustomerIoAPI = class {
802
+ app;
803
+ sqlite;
804
+ state;
805
+ service;
806
+ baseNow;
807
+ /** The namespace clock (shared clock plus this namespace's offset), epoch ms. */
808
+ now;
809
+ wallClock;
810
+ onReport;
811
+ adminPrefix;
812
+ publicNamespace;
813
+ /** Serializes handlers so concurrent identifies merge instead of dropping traits. */
814
+ tail = Promise.resolve();
815
+ constructor(options = {}) {
816
+ const sqlite = (0, service_exports.bootSqlite)(options.sqlite);
817
+ const namespace = options.namespace ?? CUSTOMERIO_NAMESPACE;
818
+ this.baseNow = options.now ?? (() => Date.now());
819
+ this.wallClock = options.wallClock ?? Date.now;
820
+ this.onReport = options.onReport;
821
+ this.adminPrefix = options.adminPrefix ?? "/__admin";
822
+ this.publicNamespace = options.publicNamespace ?? "default";
823
+ this.state = new CustomerIoState(sqlite, namespace, {
824
+ messages: options.messages ?? DEFAULT_TRANSACTIONAL_MESSAGES,
825
+ settings: options.settings ?? {}
826
+ });
827
+ this.now = () => this.baseNow() + this.state.current().clockOffsetMs;
828
+ const handlers = (0, service_exports.defineOperations)({
829
+ CdpIdentify: (context) => this.enqueue(() => this.cdp(context, "identify")),
830
+ CdpTrack: (context) => this.enqueue(() => this.cdp(context, "track")),
831
+ CdpBatch: (context) => this.enqueue(() => this.cdp(context, "batch")),
832
+ SendEmail: (context) => this.enqueue(() => this.send(context, "email")),
833
+ SendSms: (context) => this.enqueue(() => this.send(context, "sms")),
834
+ SendPush: (context) => this.enqueue(() => this.sendPush(context)),
835
+ SendInboxMessage: (context) => this.enqueue(() => this.send(context, "inbox")),
836
+ ListTransactionalMessages: (context) => this.enqueue(() => this.listMessages(context)),
837
+ GetTransactionalMessage: (context) => this.enqueue(() => this.oneMessage(context)),
838
+ ListOptOuts: (context) => this.enqueue(() => this.listOptOuts(context)),
839
+ GetCustomerOptOuts: (context) => this.enqueue(() => this.customerOptOuts(context)),
840
+ GetCustomerAttributes: (context) => this.enqueue(() => this.attributes(context)),
841
+ GetMessage: (context) => this.enqueue(() => this.deliveryMessage(context)),
842
+ ListReportingWebhooks: () => this.listContent("reporting_webhooks"),
843
+ ListSubscriptionTopics: () => this.listContent("topics"),
844
+ ListSnippets: () => this.listContent("snippets"),
845
+ ListCampaigns: () => this.listContent("campaigns"),
846
+ ListNewsletters: (context) => this.pageContent(context, "newsletters"),
847
+ ListSenderIdentities: (context) => this.pageContent(context, "sender_identities"),
848
+ ExportCustomers: (context) => this.enqueue(() => this.exportCustomers(context)),
849
+ GetExport: (context) => this.enqueue(() => this.getExport(context)),
850
+ DownloadExport: (context) => this.enqueue(() => this.downloadExport(context)),
851
+ ReportClick: (context) => this.enqueue(() => this.click(context, "post")),
852
+ FollowClick: (context) => this.enqueue(() => this.click(context, "get"))
853
+ });
854
+ this.service = (0, service_exports.createService)({
855
+ document,
856
+ handlers,
857
+ sqlite,
858
+ namespace,
859
+ now: this.now,
860
+ notFound: (request) => new URL(request.url).pathname.startsWith("/click") ? clickNotFound() : appError(404, "not found"),
861
+ onError: (error) => {
862
+ if (error instanceof service_exports.HttpError) return error.toResponse();
863
+ throw error;
864
+ },
865
+ before: (context) => {
866
+ const id = context.operation.operationId;
867
+ const keys = this.state.current().keys;
868
+ if (CDP_OPERATIONS.has(id)) {
869
+ const key = (0, service_exports.basicAuth)(context.request)?.username;
870
+ if (!key || keys.length > 0 && !keys.includes(key)) {
871
+ return cdpError(401, "Unauthorized");
872
+ }
873
+ }
874
+ if (APP_OPERATIONS.has(id)) {
875
+ const key = (0, service_exports.bearerToken)(context.request);
876
+ if (!key || keys.length > 0 && !keys.includes(key)) {
877
+ return appError(401, "Unauthorized request");
878
+ }
879
+ }
880
+ return void 0;
881
+ }
882
+ });
883
+ this.app = this.service.app;
884
+ this.sqlite = this.service.sqlite;
885
+ }
886
+ fetch(request) {
887
+ return this.service.fetch(request);
888
+ }
889
+ async reset() {
890
+ await this.service.reset();
891
+ this.state.ensureSeeded();
892
+ }
893
+ iso() {
894
+ return new Date(this.now()).toISOString();
895
+ }
896
+ /** Run `work` after every handler already queued. A rejection does not stall the next call. */
897
+ enqueue(work) {
898
+ const run = this.tail.then(work);
899
+ this.tail = run.then(
900
+ () => void 0,
901
+ () => void 0
902
+ );
903
+ return run;
904
+ }
905
+ // ---------------------------------------------------------------- CDP
906
+ cdp(context, kind) {
907
+ if (context.body.kind !== "json" || !isRecord2(context.body.value)) {
908
+ return cdpError(400, "Invalid JSON body");
909
+ }
910
+ const issue = (0, service_exports.bodyIssues)(context)[0];
911
+ if (issue) return cdpError(400, `${issue.path || "body"}: ${issue.message}`);
912
+ const body = context.body.value;
913
+ const items = kind === "batch" ? body.batch : [{ ...body, type: kind }];
914
+ for (const [index, item] of items.entries()) {
915
+ const type = item.type;
916
+ if (type !== "identify" && type !== "track") {
917
+ return cdpError(400, `batch.${index}.type: must be identify or track`);
918
+ }
919
+ if (typeof item.userId !== "string" && typeof item.anonymousId !== "string") {
920
+ return cdpError(400, "userId or anonymousId is required");
921
+ }
922
+ }
923
+ const ids = [];
924
+ for (const item of items) ids.push(this.ingest(item));
925
+ return (0, service_exports.annotateResponse)((0, service_exports.jsonRes)(200, { success: true }), {
926
+ ids: { messageIds: ids.join(",") }
927
+ });
928
+ }
929
+ /** Apply one CDP event; a repeated `messageId` is recorded as a duplicate and not re-applied. */
930
+ ingest(item) {
931
+ const at = this.iso();
932
+ const messageId = typeof item.messageId === "string" && item.messageId ? item.messageId : `mb-${this.state.ids.next("m", 20)}`;
933
+ const duplicate = this.state.cdp.has(messageId);
934
+ const event = {
935
+ messageId,
936
+ type: item.type,
937
+ userId: typeof item.userId === "string" ? item.userId : null,
938
+ anonymousId: typeof item.anonymousId === "string" ? item.anonymousId : null,
939
+ event: typeof item.event === "string" ? item.event : null,
940
+ traits: isRecord2(item.traits) ? item.traits : {},
941
+ properties: isRecord2(item.properties) ? item.properties : {},
942
+ timestamp: typeof item.timestamp === "string" ? item.timestamp : null,
943
+ receivedAt: at,
944
+ duplicate
945
+ };
946
+ this.state.cdp.insert(duplicate ? `${messageId}#${this.state.cdp.count()}` : messageId, event);
947
+ if (!duplicate && event.type === "track") this.applyDeviceEvent(item, event, at);
948
+ if (duplicate || event.type !== "identify") return messageId;
949
+ const id = event.userId ?? event.anonymousId ?? "";
950
+ const existing = this.state.profile(id);
951
+ const traits = mergeTraits(existing?.traits ?? {}, event.traits);
952
+ const preferences = preferencesOf(traits);
953
+ this.state.upsertProfile(
954
+ id,
955
+ {
956
+ traits,
957
+ ...typeof traits.email === "string" ? { email: traits.email } : {},
958
+ ...typeof event.traits.unsubscribed === "boolean" ? { unsubscribed: event.traits.unsubscribed } : {},
959
+ ...preferences ? { preferences, channelsOff: channelsOffOf(preferences) } : {}
960
+ },
961
+ at
962
+ );
963
+ return messageId;
964
+ }
965
+ /**
966
+ * `Device Created or Updated` upserts `context.device.token` on the event's `userId` (creating
967
+ * the person when needed) and refreshes `last_used`; `Device Deleted` removes it. Events
968
+ * without a `userId` or token change nothing.
969
+ */
970
+ applyDeviceEvent(item, event, at) {
971
+ if (event.event !== DEVICE_UPSERT_EVENT && event.event !== DEVICE_DELETE_EVENT) return;
972
+ const userId = event.userId;
973
+ const context = isRecord2(item.context) ? item.context : {};
974
+ const device = isRecord2(context.device) ? context.device : {};
975
+ const token = typeof device.token === "string" && device.token ? device.token : typeof event.properties.device_id === "string" && event.properties.device_id ? event.properties.device_id : void 0;
976
+ if (!userId || !token) return;
977
+ if (event.event === DEVICE_DELETE_EVENT) {
978
+ this.state.removeDevice(userId, token);
979
+ return;
980
+ }
981
+ const platform = typeof device.type === "string" && device.type ? device.type.toLowerCase() : typeof event.properties.device_platform === "string" ? event.properties.device_platform.toLowerCase() : "unknown";
982
+ const lastUsed = typeof event.properties.last_used === "number" && Number.isFinite(event.properties.last_used) ? Math.floor(event.properties.last_used) : unixSeconds(event.timestamp) ?? Math.floor(this.now() / 1e3);
983
+ if (!this.state.profile(userId)) this.state.upsertProfile(userId, {}, at);
984
+ this.state.upsertDevice(userId, {
985
+ id: token,
986
+ platform,
987
+ last_used: lastUsed,
988
+ attributes: { ...event.properties }
989
+ });
990
+ }
991
+ // ---------------------------------------------------------------- App API sends
992
+ /**
993
+ * `POST /v1/send/push`. Targets come from the person's device list: `to` absent or `all` is
994
+ * every device, `last_used` the newest, otherwise the one token. Unknown targets follow the
995
+ * `pushUnknownTargets` setting (or the `push_unknown_targets_rejected` preset).
996
+ */
997
+ sendPush(context) {
998
+ if (context.body.kind !== "json" || !isRecord2(context.body.value)) {
999
+ return appError(400, "invalid JSON body");
1000
+ }
1001
+ const issue = (0, service_exports.bodyIssues)(context)[0];
1002
+ if (issue) {
1003
+ const missing = /^missing required property (.+)$/.exec(issue.message);
1004
+ return appError(
1005
+ 400,
1006
+ missing ? `${[issue.path, missing[1]].filter(Boolean).join(".")}: is required` : `${issue.path || "body"}: ${issue.message}`
1007
+ );
1008
+ }
1009
+ const body = context.body.value;
1010
+ const identifiers = isRecord2(body.identifiers) ? body.identifiers : {};
1011
+ const named = ["id", "email", "cio_id"].filter(
1012
+ (key) => typeof identifiers[key] === "string" && identifiers[key] !== ""
1013
+ );
1014
+ if (named.length !== 1) {
1015
+ return appError(400, "identifiers: must contain exactly one of id, email or cio_id");
1016
+ }
1017
+ if (body.platform !== void 0 && body.platform !== "all") {
1018
+ return appError(400, "platform: values other than all require web push");
1019
+ }
1020
+ if (body.queue_draft === true) {
1021
+ return appError(400, "queue_draft: drafts are not modelled by the Mockingbird emulator");
1022
+ }
1023
+ const customData = isRecord2(body.custom_data) ? body.custom_data : null;
1024
+ for (const [key, value] of Object.entries(customData ?? {})) {
1025
+ if (typeof value !== "string") {
1026
+ return appError(
1027
+ 400,
1028
+ `custom_data.${key}: must be a string (Firebase only supports strings)`
1029
+ );
1030
+ }
1031
+ }
1032
+ const rawId = String(body.transactional_message_id);
1033
+ const message = this.state.message(rawId);
1034
+ if (!message && this.state.current().strictMessages) {
1035
+ return appError(400, "transactional_message_id not found");
1036
+ }
1037
+ const before = this.state.profileFor(identifiers);
1038
+ const reject = this.state.current().pushUnknownTargets === "reject" || (0, service_exports.faultEffect)(context.request, "push_unknown_targets_rejected") !== void 0;
1039
+ if (!before && reject) return appError(400, "identifiers: no person matches the identifiers");
1040
+ if (identifiers.id && !before) this.state.upsertProfile(identifiers.id, {}, this.iso());
1041
+ const profile = before ?? (identifiers.id ? this.state.profile(identifiers.id) : void 0);
1042
+ if (profile && isRecord2(body.custom_device) && typeof body.custom_device.token === "string") {
1043
+ const device = body.custom_device;
1044
+ this.state.upsertDevice(profile.id, {
1045
+ id: device.token,
1046
+ platform: typeof device.platform === "string" ? device.platform.toLowerCase() : "unknown",
1047
+ last_used: typeof device.last_used === "number" ? Math.floor(device.last_used) : Math.floor(this.now() / 1e3),
1048
+ attributes: isRecord2(device.attributes) ? { ...device.attributes } : {}
1049
+ });
1050
+ }
1051
+ const devices = profile ? this.state.devicesOf(profile.id) : [];
1052
+ const to = typeof body.to === "string" ? body.to : "all";
1053
+ let targets;
1054
+ let toOnProfile = null;
1055
+ if (to === "all") targets = devices.map((device) => device.id);
1056
+ else if (to === "last_used") {
1057
+ const newest = devices.reduce(
1058
+ (best, device) => !best || device.last_used >= best.last_used ? device : best,
1059
+ void 0
1060
+ );
1061
+ targets = newest ? [newest.id] : [];
1062
+ } else {
1063
+ toOnProfile = devices.some((device) => device.id === to);
1064
+ targets = [to];
1065
+ }
1066
+ if (reject && toOnProfile === false) return appError(400, "to: device not found on profile");
1067
+ if (reject && targets.length === 0) return appError(400, "to: the person has no devices");
1068
+ const sendToUnsubscribed = body.send_to_unsubscribed === true || body.send_to_unsubscribed === void 0 && !!message?.send_to_unsubscribed;
1069
+ const channelOff = profile?.preferences.channels.push === false;
1070
+ const suppressed = !sendToUnsubscribed && (!!profile?.unsubscribed || channelOff);
1071
+ const retain = body.disable_message_retention !== true;
1072
+ const keepBody = retain || this.state.current().retainMessageDataForTests;
1073
+ const text = (key) => typeof body[key] === "string" ? body[key] : null;
1074
+ const push = {
1075
+ to,
1076
+ devices: targets,
1077
+ to_on_profile: toOnProfile,
1078
+ profile_found: !!before,
1079
+ title: keepBody ? text("title") : null,
1080
+ message: keepBody ? text("message") : null,
1081
+ custom_data: keepBody ? customData : null,
1082
+ custom_payload: keepBody && isRecord2(body.custom_payload) ? body.custom_payload : null,
1083
+ sound: text("sound"),
1084
+ image_url: keepBody ? text("image_url") : null,
1085
+ link: keepBody ? text("link") : null
1086
+ };
1087
+ const deliveryId = this.state.deliveryId();
1088
+ const queuedAt = Math.floor(this.now() / 1e3);
1089
+ const reason = suppressed ? profile?.unsubscribed ? "unsubscribed" : "channel_off" : null;
1090
+ const delivery = {
1091
+ id: deliveryId,
1092
+ to: targets.length ? targets : to,
1093
+ createdAt: this.iso(),
1094
+ channel: "push",
1095
+ transactionalMessageId: rawId,
1096
+ messageId: message?.id ?? null,
1097
+ identifiers,
1098
+ from: null,
1099
+ subject: null,
1100
+ messageData: keepBody && isRecord2(body.message_data) ? body.message_data : keepBody ? {} : null,
1101
+ links: [],
1102
+ originalLinks: [],
1103
+ tracked: false,
1104
+ sendToUnsubscribed,
1105
+ disableMessageRetention: !retain,
1106
+ headers: {},
1107
+ attachments: [],
1108
+ state: suppressed ? "suppressed" : "pending",
1109
+ reason,
1110
+ failureMessage: reason,
1111
+ push,
1112
+ metrics: suppressed ? { suppressed: queuedAt } : {},
1113
+ visibleAt: this.now() + this.state.current().statusVisibleAfterMs,
1114
+ queuedAt,
1115
+ clicks: 0
1116
+ };
1117
+ this.state.deliveries.record(delivery);
1118
+ const ids = { deliveryId, transactionalMessageId: rawId };
1119
+ if ((0, service_exports.faultEffect)(context.request, "send_drop_after_accept") !== void 0) {
1120
+ throw new service_exports.DroppedConnectionError();
1121
+ }
1122
+ if ((0, service_exports.faultEffect)(context.request, "accepted_but_500") !== void 0) {
1123
+ return (0, service_exports.annotateResponse)(appError(500, "internal server error"), { ids });
1124
+ }
1125
+ return (0, service_exports.annotateResponse)((0, service_exports.jsonRes)(200, { delivery_id: deliveryId, queued_at: queuedAt }), {
1126
+ ids
1127
+ });
1128
+ }
1129
+ send(context, channel) {
1130
+ if (context.body.kind !== "json" || !isRecord2(context.body.value)) {
1131
+ return appError(400, "invalid JSON body");
1132
+ }
1133
+ const issue = (0, service_exports.bodyIssues)(context)[0];
1134
+ if (issue) {
1135
+ const missing = /^missing required property (.+)$/.exec(issue.message);
1136
+ return appError(
1137
+ 400,
1138
+ missing ? `${[issue.path, missing[1]].filter(Boolean).join(".")}: is required` : `${issue.path || "body"}: ${issue.message}`
1139
+ );
1140
+ }
1141
+ const body = context.body.value;
1142
+ const identifiers = isRecord2(body.identifiers) ? body.identifiers : {};
1143
+ const named = ["id", "email", "cio_id"].filter(
1144
+ (key) => typeof identifiers[key] === "string" && identifiers[key] !== ""
1145
+ );
1146
+ if (named.length !== 1) {
1147
+ return appError(400, "identifiers: must contain exactly one of id, email or cio_id");
1148
+ }
1149
+ const rawId = String(body.transactional_message_id);
1150
+ const message = this.state.message(rawId);
1151
+ if (!message && this.state.current().strictMessages) {
1152
+ return appError(400, "transactional_message_id not found");
1153
+ }
1154
+ if (channel === "sms" && typeof body.to === "string" && !E164.test(body.to)) {
1155
+ return appError(400, "to: must be an E.164 phone number");
1156
+ }
1157
+ const profile = this.state.profileFor(identifiers);
1158
+ let to = typeof body.to === "string" ? body.to : null;
1159
+ if (channel === "email") to ??= identifiers.email ?? profile?.email ?? null;
1160
+ if (channel === "sms") {
1161
+ const phone = profile?.traits.phone;
1162
+ to ??= typeof phone === "string" ? phone : null;
1163
+ }
1164
+ if (channel === "inbox") to = identifiers.id ?? identifiers.cio_id ?? identifiers.email ?? null;
1165
+ if (!to) {
1166
+ return appError(
1167
+ 400,
1168
+ channel === "email" ? "to: is required when the profile has no email attribute" : "to: is required when the profile has no phone attribute"
1169
+ );
1170
+ }
1171
+ if (identifiers.id && !this.state.profile(identifiers.id)) {
1172
+ this.state.upsertProfile(identifiers.id, {}, this.iso());
1173
+ }
1174
+ const tracked = body.tracked === true || body.tracked === void 0 && !!message?.link_tracking;
1175
+ const deliveryId = this.state.deliveryId();
1176
+ const messageData = isRecord2(body.message_data) ? body.message_data : {};
1177
+ const retain = body.disable_message_retention !== true;
1178
+ const keepBody = retain || this.state.current().retainMessageDataForTests;
1179
+ const originalLinks = urlsIn([messageData, body.body ?? ""]);
1180
+ const links = originalLinks.map((url) => {
1181
+ if (!tracked) return url;
1182
+ const linkId = this.state.linkId();
1183
+ this.state.links.insert(linkId, { linkId, deliveryId, url });
1184
+ return `${this.state.current().trackingBase.replace(/\/$/, "")}/click/${linkId}`;
1185
+ });
1186
+ const sendToUnsubscribed = body.send_to_unsubscribed === true || body.send_to_unsubscribed === void 0 && !!message?.send_to_unsubscribed;
1187
+ const channelOff = channel !== "inbox" && !!profile?.channelsOff.includes(channel === "sms" ? "sms" : "email");
1188
+ const suppressed = !sendToUnsubscribed && (!!profile?.unsubscribed || channelOff);
1189
+ const attachments = Array.isArray(body.attachments) ? body.attachments.map((a) => a.filename) : isRecord2(body.attachments) ? Object.keys(body.attachments) : [];
1190
+ const queuedAt = Math.floor(this.now() / 1e3);
1191
+ const delivery = {
1192
+ id: deliveryId,
1193
+ to,
1194
+ createdAt: this.iso(),
1195
+ channel,
1196
+ transactionalMessageId: rawId,
1197
+ messageId: message?.id ?? null,
1198
+ identifiers,
1199
+ from: typeof body.from === "string" ? body.from : null,
1200
+ subject: typeof body.subject === "string" ? body.subject : null,
1201
+ messageData: keepBody ? messageData : null,
1202
+ links: keepBody ? links : [],
1203
+ originalLinks: keepBody ? originalLinks : [],
1204
+ tracked,
1205
+ sendToUnsubscribed,
1206
+ disableMessageRetention: !retain,
1207
+ headers: isRecord2(body.headers) ? body.headers : {},
1208
+ attachments,
1209
+ state: suppressed ? "suppressed" : "pending",
1210
+ reason: suppressed ? profile?.unsubscribed ? "unsubscribed" : "channel_off" : null,
1211
+ failureMessage: suppressed ? profile?.unsubscribed ? "unsubscribed" : "channel_off" : null,
1212
+ metrics: suppressed ? { suppressed: queuedAt } : {},
1213
+ visibleAt: this.now() + this.state.current().statusVisibleAfterMs,
1214
+ queuedAt,
1215
+ clicks: 0
1216
+ };
1217
+ this.state.deliveries.record(delivery);
1218
+ const ids = { deliveryId, transactionalMessageId: rawId };
1219
+ if ((0, service_exports.faultEffect)(context.request, "send_drop_after_accept") !== void 0) {
1220
+ throw new service_exports.DroppedConnectionError();
1221
+ }
1222
+ if ((0, service_exports.faultEffect)(context.request, "accepted_but_500") !== void 0) {
1223
+ return (0, service_exports.annotateResponse)(appError(500, "internal server error"), { ids });
1224
+ }
1225
+ return (0, service_exports.annotateResponse)((0, service_exports.jsonRes)(200, { delivery_id: deliveryId, queued_at: queuedAt }), {
1226
+ ids
1227
+ });
1228
+ }
1229
+ listMessages(context) {
1230
+ const effect = (0, service_exports.faultEffect)(context.request, "omit_trigger_names");
1231
+ const selected = Array.isArray(effect?.ids) ? effect.ids.map(String) : null;
1232
+ const messages = this.state.catalog().map((message) => {
1233
+ const omit = effect !== void 0 && (selected === null || selected.includes(String(message.id)));
1234
+ if (!omit) return message;
1235
+ const { trigger_name: _trigger, ...rest } = message;
1236
+ return rest;
1237
+ });
1238
+ return (0, service_exports.jsonRes)(200, { [this.state.current().transactionalListKey]: messages });
1239
+ }
1240
+ oneMessage(context) {
1241
+ const message = this.state.message(context.params.transactional_id ?? "");
1242
+ return message ? (0, service_exports.jsonRes)(200, { message }) : appError(404, "not found");
1243
+ }
1244
+ listOptOuts(context) {
1245
+ const rawLimit = context.query.limit;
1246
+ const limit = rawLimit === void 0 ? 100 : Number(rawLimit);
1247
+ if (!Number.isInteger(limit) || limit < 1 || limit > 1e3)
1248
+ return appError(400, "limit must be between 1 and 1000");
1249
+ let after = 0;
1250
+ if (context.query.start !== void 0) {
1251
+ try {
1252
+ const decoded = atob(String(context.query.start));
1253
+ if (!/^optouts:[1-9]\d*$/.test(decoded)) return appError(400, "invalid start cursor");
1254
+ after = Number(decoded.slice(8));
1255
+ if (!Number.isSafeInteger(after)) return appError(400, "invalid start cursor");
1256
+ } catch {
1257
+ return appError(400, "invalid start cursor");
1258
+ }
1259
+ }
1260
+ const from = typeof context.query.from === "string" ? context.query.from.trim().toLowerCase() : void 0;
1261
+ const rows = this.state.optouts.list({ order: "oldest" }).flatMap((row) => {
1262
+ const profile = this.state.profile(row.value.customerId);
1263
+ const optouts = row.value.optouts.filter((item) => from === void 0 || item.from === from);
1264
+ return row.seq > after && profile && optouts.length ? [{ seq: row.seq, customer_id: profile.id, cio_id: profile.cioId, optouts }] : [];
1265
+ });
1266
+ const page = rows.slice(0, limit);
1267
+ const last = page.at(-1);
1268
+ return (0, service_exports.jsonRes)(200, {
1269
+ ...rows.length > limit && last ? { next: btoa(`optouts:${last.seq}`) } : {},
1270
+ optouts: page.map(({ seq: _seq, ...row }) => row)
1271
+ });
1272
+ }
1273
+ customerOptOuts(context) {
1274
+ const customerId = context.params.customer_id ?? "";
1275
+ const idType = context.query.id_type ?? "id";
1276
+ const profile = idType === "id" ? this.state.profile(customerId) : idType === "email" ? this.state.profileByEmail(customerId) : idType === "cio_id" ? this.state.profileByCioId(customerId) : void 0;
1277
+ if (!["id", "email", "cio_id"].includes(String(idType))) return appError(400, "invalid id_type");
1278
+ if (!profile) return appError(404, "not found");
1279
+ return (0, service_exports.jsonRes)(200, { optouts: this.state.optouts.get(profile.id)?.optouts ?? [] });
1280
+ }
1281
+ attributes(context) {
1282
+ const rawType = context.query.id_type;
1283
+ const idType = rawType === void 0 ? "id" : rawType;
1284
+ if (idType !== "id" && idType !== "email" && idType !== "cio_id") {
1285
+ return appError(400, "id_type: must be id, email, or cio_id");
1286
+ }
1287
+ const customerId = context.params.customer_id ?? "";
1288
+ const profile = idType === "email" ? this.state.profileByEmail(customerId) : idType === "cio_id" ? this.state.profileByCioId(customerId) : this.state.profile(customerId);
1289
+ if (!profile) return appError(404, "not found");
1290
+ const attributes = profileAttributes(profile);
1291
+ return (0, service_exports.annotateResponse)(
1292
+ (0, service_exports.jsonRes)(200, {
1293
+ customer: {
1294
+ identifiers: {
1295
+ id: profile.id,
1296
+ cio_id: profile.cioId,
1297
+ ...profile.email ? { email: profile.email } : {}
1298
+ },
1299
+ attributes,
1300
+ devices: this.state.devicesOf(profile.id).map(({ attributes: attributes2, ...device }) => ({
1301
+ ...device,
1302
+ ...Object.keys(attributes2).length ? { attributes: attributes2 } : {}
1303
+ }))
1304
+ }
1305
+ }),
1306
+ { ids: { userId: profile.id } }
1307
+ );
1308
+ }
1309
+ deliveryMessage(context) {
1310
+ const delivery = this.state.deliveries.get(context.params.message_id ?? "");
1311
+ if (!delivery || this.now() < delivery.visibleAt) return appError(404, "not found");
1312
+ const failed = FAILURE_STATES.has(delivery.state);
1313
+ const failure = delivery.failureMessage ?? delivery.reason ?? delivery.state;
1314
+ const recipient = delivery.channel === "inbox" ? null : typeof delivery.to === "string" ? delivery.to : delivery.to.join(",");
1315
+ return (0, service_exports.annotateResponse)(
1316
+ (0, service_exports.jsonRes)(200, {
1317
+ message: {
1318
+ id: delivery.id,
1319
+ type: delivery.channel === "inbox" ? "in_app" : delivery.channel,
1320
+ recipient,
1321
+ customer_id: delivery.identifiers.id ?? delivery.identifiers.cio_id ?? null,
1322
+ created: delivery.queuedAt,
1323
+ state: delivery.state,
1324
+ status: delivery.state,
1325
+ metrics: delivery.metrics,
1326
+ ...failed ? { failure_message: failure, rejection_reason: failure, error: failure } : {}
1327
+ }
1328
+ }),
1329
+ { ids: { deliveryId: delivery.id } }
1330
+ );
1331
+ }
1332
+ // ---------------------------------------------------------------- workspace content
1333
+ listContent(list) {
1334
+ return (0, service_exports.jsonRes)(200, { [list]: this.state.contentOf(list) });
1335
+ }
1336
+ /** `limit` / `sort` / opaque `start` paging (newsletters, sender identities). */
1337
+ pageContent(context, list) {
1338
+ const { limit: rawLimit, sort = "asc", start, hidden } = context.query;
1339
+ const limit = rawLimit === void 0 ? Number.POSITIVE_INFINITY : Number(rawLimit);
1340
+ if (rawLimit !== void 0 && (!Number.isInteger(limit) || limit < 1)) {
1341
+ return appError(400, "limit must be a positive integer");
1342
+ }
1343
+ if (sort !== "asc" && sort !== "desc") return appError(400, "sort must be asc or desc");
1344
+ let offset = 0;
1345
+ if (start !== void 0) {
1346
+ let decoded = "";
1347
+ try {
1348
+ decoded = atob(String(start));
1349
+ } catch {
1350
+ return appError(400, "invalid start cursor");
1351
+ }
1352
+ const match = new RegExp(`^${list}:(\\d+)$`).exec(decoded);
1353
+ if (!match) return appError(400, "invalid start cursor");
1354
+ offset = Number(match[1]);
1355
+ }
1356
+ let items = this.state.contentOf(list);
1357
+ if (list === "sender_identities" && String(hidden) !== "true") {
1358
+ items = items.filter((item) => item.hidden !== true);
1359
+ }
1360
+ if (sort === "desc") items = [...items].reverse();
1361
+ const page = items.slice(offset, offset + limit);
1362
+ const next = offset + page.length < items.length ? btoa(`${list}:${offset + page.length}`) : null;
1363
+ return (0, service_exports.jsonRes)(200, { ...next ? { next } : {}, [list]: page });
1364
+ }
1365
+ /**
1366
+ * Replace workspace content lists (admin). Each key of `body` that names a list replaces it;
1367
+ * items get the vendor defaults (`id` from 1, …). Everything is validated before any write.
1368
+ */
1369
+ setContent(body) {
1370
+ const next = /* @__PURE__ */ new Map();
1371
+ const at = Math.floor(this.now() / 1e3);
1372
+ for (const [key, raw] of Object.entries(body)) {
1373
+ if (!CONTENT_LISTS.includes(key)) {
1374
+ return `unknown list ${key}; expected ${CONTENT_LISTS.join(", ")}`;
1375
+ }
1376
+ const list = key;
1377
+ if (!Array.isArray(raw)) return `${list}: expected an array of objects`;
1378
+ const items = [];
1379
+ for (const [index, item] of raw.entries()) {
1380
+ if (!isRecord2(item)) return `${list}[${index}]: expected an object`;
1381
+ const id = typeof item.id === "number" ? item.id : index + 1;
1382
+ if (list === "reporting_webhooks") {
1383
+ if (typeof item.name !== "string" || typeof item.endpoint !== "string" || !Array.isArray(item.events) || !item.events.every((event) => typeof event === "string")) {
1384
+ return `${list}[${index}]: name, endpoint and events (strings) are required`;
1385
+ }
1386
+ items.push({
1387
+ type: "webhook",
1388
+ disabled: false,
1389
+ full_resolution: true,
1390
+ with_content: false,
1391
+ ...item,
1392
+ id
1393
+ });
1394
+ } else if (list === "snippets") {
1395
+ if (typeof item.name !== "string" || typeof item.value !== "string") {
1396
+ return `${list}[${index}]: name and value (strings) are required`;
1397
+ }
1398
+ items.push({ updated_at: at, ...item });
1399
+ } else if (list === "topics") {
1400
+ items.push({ identifier: `topic_${id}`, ...item, id });
1401
+ } else {
1402
+ items.push({ ...item, id });
1403
+ }
1404
+ }
1405
+ next.set(list, items);
1406
+ }
1407
+ for (const [list, items] of next) this.state.setContent(list, items);
1408
+ return this.content();
1409
+ }
1410
+ content() {
1411
+ return Object.fromEntries(
1412
+ CONTENT_LISTS.map((list) => [list, this.state.contentOf(list)])
1413
+ );
1414
+ }
1415
+ // ---------------------------------------------------------------- customer exports
1416
+ exportCustomers(context) {
1417
+ if (context.body.kind !== "json" || !isRecord2(context.body.value)) {
1418
+ return appError(400, "invalid JSON body");
1419
+ }
1420
+ const issue = (0, service_exports.bodyIssues)(context)[0];
1421
+ if (issue) return appError(400, `${issue.path || "body"}: ${issue.message}`);
1422
+ const body = context.body.value;
1423
+ const filter = parseFilter(body.filters, "filters");
1424
+ if (typeof filter === "string") return appError(400, filter);
1425
+ const extra = Array.isArray(body.attributes) ? body.attributes.map(String) : [];
1426
+ const columns = [.../* @__PURE__ */ new Set(["id", "cio_id", "email", ...extra])];
1427
+ const rows = this.profiles().map((profile) => profileAttributes(profile)).filter((attributes) => filter(attributes));
1428
+ const csv = `${[columns, ...rows.map((row) => columns.map((column) => row[column]))].map((cells) => cells.map(csvCell).join(",")).join("\n")}
1429
+ `;
1430
+ const id = this.state.exports.count() + 1;
1431
+ const at = Math.floor(this.now() / 1e3);
1432
+ const record = {
1433
+ id,
1434
+ type: "customers",
1435
+ status: "done",
1436
+ failed: false,
1437
+ total: rows.length,
1438
+ downloads: 0,
1439
+ created_at: at,
1440
+ updated_at: at,
1441
+ deduplicate_id: `${id}:${at}`,
1442
+ csv
1443
+ };
1444
+ this.state.exports.insert(String(id), record);
1445
+ return (0, service_exports.jsonRes)(200, { export: publicExport(record) });
1446
+ }
1447
+ exportOf(context) {
1448
+ const raw = String(context.params.export_id ?? "");
1449
+ return /^\d+$/.test(raw) ? this.state.exports.get(String(Number(raw))) : void 0;
1450
+ }
1451
+ getExport(context) {
1452
+ const record = this.exportOf(context);
1453
+ return record ? (0, service_exports.jsonRes)(200, { export: publicExport(record) }) : appError(404, "not found");
1454
+ }
1455
+ /** A link to the CSV the runtime serves under the admin prefix; each link counts a download. */
1456
+ downloadExport(context) {
1457
+ const record = this.exportOf(context);
1458
+ if (!record) return appError(404, "not found");
1459
+ this.state.exports.update(String(record.id), { ...record, downloads: record.downloads + 1 });
1460
+ const prefix = this.publicNamespace === "default" ? "" : `${this.adminPrefix}/ns/${encodeURIComponent(this.publicNamespace)}`;
1461
+ return (0, service_exports.jsonRes)(200, {
1462
+ url: `${context.url.origin}${prefix}${this.adminPrefix}/exports/${record.id}/file`
1463
+ });
1464
+ }
1465
+ /** The export's CSV file (the admin route the download link points at). */
1466
+ exportFile(id) {
1467
+ const record = this.state.exports.get(id);
1468
+ if (!record) return void 0;
1469
+ return new Response(record.csv, {
1470
+ status: 200,
1471
+ headers: {
1472
+ "content-type": "text/csv; charset=utf-8",
1473
+ "content-disposition": `attachment; filename="export-${record.id}.csv"`
1474
+ }
1475
+ });
1476
+ }
1477
+ // ---------------------------------------------------------------- link tracking
1478
+ click(context, mode) {
1479
+ const link = this.state.links.get(context.params.linkId ?? "");
1480
+ if (!link) return clickNotFound();
1481
+ const delivery = this.state.deliveries.get(link.deliveryId);
1482
+ if (delivery) {
1483
+ this.state.deliveries.update(delivery.id, { ...delivery, clicks: delivery.clicks + 1 });
1484
+ this.report({
1485
+ metric: "clicked",
1486
+ objectType: delivery.channel === "sms" ? "sms" : "email",
1487
+ deliveryId: delivery.id,
1488
+ href: link.url,
1489
+ linkId: link.linkId
1490
+ });
1491
+ }
1492
+ const ids = { linkId: link.linkId, deliveryId: link.deliveryId };
1493
+ if (mode === "get") {
1494
+ return (0, service_exports.annotateResponse)(
1495
+ new Response(null, { status: 302, headers: { location: link.url } }),
1496
+ {
1497
+ ids
1498
+ }
1499
+ );
1500
+ }
1501
+ return (0, service_exports.annotateResponse)(new Response(null, { status: 200 }), { ids });
1502
+ }
1503
+ // ---------------------------------------------------------------- reporting
1504
+ /**
1505
+ * Emit a reporting event and apply what it means to the profile (unsubscribed / subscribed /
1506
+ * spammed / subscription preferences). Returns the event, or a reason it could not be built.
1507
+ */
1508
+ report(input) {
1509
+ const delivery = input.deliveryId ? this.state.deliveries.get(input.deliveryId) : void 0;
1510
+ if (input.deliveryId && !delivery) return `no delivery ${input.deliveryId}`;
1511
+ const userId = input.userId ?? delivery?.identifiers.id ?? null;
1512
+ const profile = userId ? this.state.profile(userId) : input.email ? this.state.profileFor({ email: input.email }) : void 0;
1513
+ const email = input.email ?? delivery?.identifiers.email ?? (delivery?.channel === "email" && typeof delivery.to === "string" ? delivery.to : null) ?? profile?.email ?? null;
1514
+ const at = this.iso();
1515
+ const id = userId ?? profile?.id ?? null;
1516
+ let stored = profile;
1517
+ if (id) {
1518
+ if (input.metric === "unsubscribed") {
1519
+ stored = this.state.upsertProfile(
1520
+ id,
1521
+ { unsubscribed: true, traits: { ...profile?.traits ?? {}, unsubscribed: true } },
1522
+ at
1523
+ );
1524
+ }
1525
+ if (input.metric === "subscribed") {
1526
+ const preferences = mergePreferences(profile?.preferences, {
1527
+ channels: { email: true, sms: true }
1528
+ });
1529
+ stored = this.state.upsertProfile(
1530
+ id,
1531
+ {
1532
+ unsubscribed: false,
1533
+ channelsOff: [],
1534
+ preferences,
1535
+ traits: {
1536
+ ...profile?.traits ?? {},
1537
+ unsubscribed: false,
1538
+ cio_subscription_preferences: preferences
1539
+ }
1540
+ },
1541
+ at
1542
+ );
1543
+ }
1544
+ if (input.metric === "spammed") {
1545
+ const preferences = mergePreferences(profile?.preferences, { channels: { email: false } });
1546
+ const off = /* @__PURE__ */ new Set([...profile?.channelsOff ?? [], "email"]);
1547
+ stored = this.state.upsertProfile(
1548
+ id,
1549
+ {
1550
+ channelsOff: [...off],
1551
+ preferences,
1552
+ traits: { ...profile?.traits ?? {}, cio_subscription_preferences: preferences }
1553
+ },
1554
+ at
1555
+ );
1556
+ }
1557
+ if (input.metric === "cio_subscription_preferences_changed" && input.preferences) {
1558
+ const preferences = mergePreferences(profile?.preferences, input.preferences);
1559
+ stored = this.state.upsertProfile(
1560
+ id,
1561
+ {
1562
+ channelsOff: channelsOffOf(preferences),
1563
+ preferences,
1564
+ traits: { ...profile?.traits ?? {}, cio_subscription_preferences: preferences }
1565
+ },
1566
+ at
1567
+ );
1568
+ }
1569
+ }
1570
+ const event = {
1571
+ event_id: this.state.eventId(),
1572
+ object_type: input.objectType ?? (delivery ? delivery.channel : "customer"),
1573
+ metric: input.metric,
1574
+ // Signature and body timestamps follow the wall clock, not the mock clock.
1575
+ timestamp: Math.floor(this.wallClock() / 1e3),
1576
+ data: {
1577
+ identifiers: { id, email, cio_id: stored?.cioId ?? null },
1578
+ customer_id: id,
1579
+ email_address: email,
1580
+ ...delivery ? { delivery_id: delivery.id } : {},
1581
+ ...delivery?.messageId ? { transactional_message_id: delivery.messageId } : {},
1582
+ ...input.href ? { href: input.href } : {},
1583
+ ...input.linkId ? { link_id: input.linkId } : {},
1584
+ ...input.preferences ? { content: JSON.stringify(input.preferences) } : {}
1585
+ }
1586
+ };
1587
+ this.onReport?.(event);
1588
+ return event;
1589
+ }
1590
+ profiles() {
1591
+ return this.state.profiles.list({ order: "oldest" }).map((row) => row.value);
1592
+ }
1593
+ /** Merge traits onto a profile (admin). Omitted traits stay; preference `false` stays. */
1594
+ mergeProfile(id, patch) {
1595
+ const existing = this.state.profile(id);
1596
+ const traits = patch.traits ? mergeTraits(existing?.traits ?? {}, patch.traits) : { ...existing?.traits ?? {} };
1597
+ const preferences = patch.preferences ? mergePreferences(existing?.preferences, patch.preferences) : preferencesOf(traits);
1598
+ if (preferences && patch.preferences) traits.cio_subscription_preferences = preferences;
1599
+ return this.state.upsertProfile(
1600
+ id,
1601
+ {
1602
+ traits,
1603
+ ...patch.email !== void 0 ? { email: patch.email } : typeof traits.email === "string" ? { email: traits.email } : {},
1604
+ ...patch.unsubscribed !== void 0 ? { unsubscribed: patch.unsubscribed } : typeof patch.traits?.unsubscribed === "boolean" ? { unsubscribed: patch.traits.unsubscribed } : {},
1605
+ ...preferences ? { preferences, channelsOff: channelsOffOf(preferences) } : {}
1606
+ },
1607
+ this.iso()
1608
+ );
1609
+ }
1610
+ /** Move a delivery to `state` and stamp `metrics[state]` with the namespace clock. */
1611
+ transitionDelivery(id, state) {
1612
+ const delivery = this.state.deliveries.get(id);
1613
+ if (!delivery) return void 0;
1614
+ const at = Math.floor(this.now() / 1e3);
1615
+ const next = {
1616
+ ...delivery,
1617
+ state,
1618
+ metrics: { ...delivery.metrics, [state]: at },
1619
+ failureMessage: FAILURE_STATES.has(state) ? delivery.failureMessage ?? state : delivery.failureMessage
1620
+ };
1621
+ this.state.deliveries.update(id, next);
1622
+ return next;
1623
+ }
1624
+ /** Move this namespace's clock without touching the shared runtime clock. */
1625
+ advanceClock(ms) {
1626
+ return this.state.update({ clockOffsetMs: this.state.current().clockOffsetMs + ms });
1627
+ }
1628
+ };
1629
+
1630
+ export {
1631
+ document,
1632
+ operationIds,
1633
+ supportedOperationIds,
1634
+ DELIVERY_STATES,
1635
+ FAILURE_STATES,
1636
+ MAX_DEVICES_PER_PERSON,
1637
+ CONTENT_LISTS,
1638
+ DEFAULT_SETTINGS,
1639
+ TRANSACTIONAL_EMAIL_KEYS,
1640
+ DEFAULT_TRANSACTIONAL_MESSAGES,
1641
+ REPORTING_WEBHOOK_PATH,
1642
+ signReporting,
1643
+ CUSTOMERIO_PRESETS,
1644
+ createRuntime2 as createRuntime,
1645
+ CUSTOMERIO_NAMESPACE,
1646
+ customerIoCredential,
1647
+ DEVICE_UPSERT_EVENT,
1648
+ DEVICE_DELETE_EVENT,
1649
+ CustomerIoAPI
1650
+ };
1651
+ //# sourceMappingURL=chunk-UCKUIVGB.js.map