import {z} from 'zod' export type MatchType = 'unknown' | 'screen_view' | 'custom_event' | 'user_attributes' | 'user_identities' | 'product_action' | 'promotion_action' | 'product_impression'; export type ScreenViewEventCriteria = {screen_name: string}; export type CustomEventCriteria = {event_name: string, custom_event_type: 'unknown' | 'navigation' | 'location' | 'search' | 'transaction' | 'user_content' | 'user_preference' | 'social' | 'other' | 'media'}; export type UserAttributeCriteria = Record; export type ProductAction = 'add_to_cart' | 'remove_from_cart' | 'checkout' | 'checkout_option' | 'click' | 'view_detail' | 'purchase' | 'refund' | 'add_to_wishlist' | 'remove_from_wish_list'; export type PromotionAction = 'view' | 'click'; export type CommerceActionEventCriteria = {action?: (ProductAction | PromotionAction) | undefined}; export type Criteria = ScreenViewEventCriteria | CustomEventCriteria | UserAttributeCriteria | CommerceActionEventCriteria; export type DataPointMatch = {type: MatchType, criteria: Criteria}; export type DataPointValidator = {type: 'json_schema', definition: Record}; export type DataPoint = {description?: string | undefined, match: DataPointMatch, validator: DataPointValidator}; export type SchemaKeyword = 'none' | 'additionalItems' | 'additionalProperties' | 'allOf' | 'anyOf' | 'const' | 'contains' | 'contentEncoding' | 'contentMediaType' | 'default' | 'definitions' | 'dependencies' | 'dependentRequired' | 'dependentSchemas' | 'else' | 'enum' | 'exclusiveMaximum' | 'exclusiveMinimum' | 'format' | 'id' | 'if' | 'items' | 'maxContains' | 'maximum' | 'maximum' | 'maxLength' | 'maxProperties' | 'minContains' | 'minimum' | 'minItems' | 'minLength' | 'minProperties' | 'multipleOf' | 'not' | 'oneOf' | 'pattern' | 'patternProperties' | 'properties' | 'propertyNames' | 'readOnly' | 'required' | 'then' | 'type' | 'unevaluatedItems' | 'unevaluatedProperties' | 'uniqueItems' | 'writeOnly' | '$anchor' | '$defs' | '$id' | '$recursiveAnchor' | '$recursiveRef' | '$ref' | '$schema' | '$vocabulary' | 'timeLimit' | '$comment' | 'description' | 'examples' | 'title'; export type DataPlanPatch = {op?: ('unknown' | 'add' | 'remove' | 'replace' | 'copy' | 'move' | 'test') | undefined, from?: string | undefined, path?: string | undefined, value?: string | undefined}; export type DataPlanTransformation = {transformation_id?: number | undefined, transformation_name?: string | undefined, error_pointer?: string | undefined, validation_error_types?: (Array<'unknown' | 'unplanned' | 'missing_required' | 'invalid_value'>) | undefined, schema_keywords?: Array | undefined, json_patch?: Array | undefined, description?: string | undefined}; export type VersionDocument = {data_points?: Array | undefined, active_transformation_ids?: Array | undefined, transformations?: DataPlanTransformation | undefined}; export type MparticleS2sEventsOasDataPlanContext = {plan_id: string, plan_version?: number | undefined}; export type MparticleS2sEventsOasBatchContext = {data_plan?: MparticleS2sEventsOasDataPlanContext | undefined}; export type MparticleS2sEventsOasGeoLocation = {latitude: number, longitude: number, accuracy?: number | undefined}; export type MparticleS2sEventsOasDeviceCurrentState = {time_since_start_ms?: number | undefined, battery_level?: number | undefined, data_connection_type?: string | undefined, data_connection_type_detail?: string | undefined, gps_state?: boolean | undefined, total_system_memory_usage_bytes?: number | undefined, disk_space_free_bytes?: number | undefined, external_disk_space_free_bytes?: number | undefined, cpu?: string | undefined, system_memory_available_bytes?: number | undefined, system_memory_low?: boolean | undefined, system_memory_threshold_bytes?: number | undefined, application_memory_available_bytes?: number | undefined, application_memory_max_bytes?: number | undefined, application_memory_total_bytes?: number | undefined, device_orientation?: ('portrait' | 'portrait_upside_down' | 'landscape' | 'LandscapeLeft' | 'LandscapeRight' | 'FaceUp' | 'FaceDown' | 'Square') | undefined, status_bar_orientation?: ('portrait' | 'portrait_upside_down' | 'landscape' | 'LandscapeLeft' | 'LandscapeRight' | 'FaceUp' | 'FaceDown' | 'Square') | undefined}; export type MparticleS2sEventsOasEventSystemNotificationInfo = {type: 'gdpr_change'}; export type MparticleS2sEventsOasCommonEventData = {timestamp_unixtime_ms?: number | undefined, event_id?: number | undefined, source_message_id?: string | undefined, session_id?: number | undefined, session_uuid?: string | undefined, session_start_unixtime_ms?: number | undefined, event_start_unixtime_ms?: number | undefined, custom_attributes?: {[key: string]: string} | undefined, location?: MparticleS2sEventsOasGeoLocation | undefined, device_current_state?: MparticleS2sEventsOasDeviceCurrentState | undefined, is_goal_defined?: boolean | undefined, lifetime_value_change?: boolean | undefined, lifetime_value_attribute_name?: string | undefined, data_connection_type?: string | undefined, event_num?: number | undefined, view_controller?: string | undefined, is_main_thread?: boolean | undefined, canonical_name?: string | undefined, event_system_notification_info?: MparticleS2sEventsOasEventSystemNotificationInfo | undefined}; export type MparticleS2sEventsOasEventType = 'session_start' | 'session_end' | 'screen_view' | 'custom_event' | 'crash_report' | 'opt_out' | 'first_run' | 'pre_attribution' | 'push_registration' | 'application_state_transition' | 'push_message' | 'network_performance' | 'breadcrumb' | 'profile' | 'push_reaction' | 'commerce_event' | 'user_attribute_change' | 'user_identity_change' | 'uninstall'; export type MparticleS2sEventsOasBaseEvent = {data?: MparticleS2sEventsOasCommonEventData | undefined, event_type?: MparticleS2sEventsOasEventType | undefined}; export type MparticleS2sEventsOasDeviceInformation = {brand?: string | undefined, product?: string | undefined, device?: string | undefined, android_uuid?: string | undefined, device_manufacturer?: string | undefined, platform?: ('iOS' | 'Android' | 'web' | 'desktop' | 'tvOS' | 'roku' | 'out_of_band' | 'smart_tv' | 'samsung_tv' | 'xbox') | undefined, os_version?: string | undefined, device_model?: string | undefined, screen_height?: number | undefined, screen_width?: number | undefined, screen_dpi?: number | undefined, device_country?: string | undefined, locale_language?: string | undefined, locale_country?: string | undefined, network_country?: string | undefined, network_carrier?: string | undefined, network_code?: string | undefined, network_mobile_country_code?: string | undefined, timezone_offset?: number | undefined, build_identifier?: string | undefined, http_header_user_agent?: string | undefined, ios_advertising_id?: string | undefined, att_authorization_status?: ('authorized' | 'denied' | 'not_determined' | 'restricted') | undefined, att_timestamp_unixtime_ms?: number | undefined, push_token?: string | undefined, cpu_architecture?: string | undefined, is_tablet?: boolean | undefined, push_notification_sound_enabled?: boolean | undefined, push_notification_vibrate_enabled?: boolean | undefined, radio_access_technology?: string | undefined, supports_telephony?: boolean | undefined, has_nfc?: boolean | undefined, bluetooth_enabled?: boolean | undefined, bluetooth_version?: string | undefined, ios_idfv?: string | undefined, android_advertising_id?: string | undefined, build_version_release?: string | undefined, limit_ad_tracking?: boolean | undefined, amp_id?: string | undefined, is_dst?: boolean | undefined, roku_advertising_id?: string | undefined, roku_publisher_id?: string | undefined, microsoft_advertising_id?: string | undefined, microsoft_publisher_id?: string | undefined, fire_advertising_id?: string | undefined, tizen_advertising_id?: string | undefined}; export type MparticleS2sEventsOasApplicationInformation = {application_name?: string | undefined, application_version?: string | undefined, application_build_number?: string | undefined, install_referrer?: string | undefined, package?: string | undefined, os?: ('Unknown' | 'IOS' | 'Android' | 'WindowsPhone' | 'MobileWeb' | 'UnityIOS' | 'UnityAndroid' | 'Desktop' | 'TVOS' | 'Roku' | 'OutOfBand' | 'Alexa' | 'SmartTV' | 'FireTV' | 'Xbox') | undefined, apple_search_ads_attributes?: {[key: string]: {[key: string]: string}} | undefined}; export type MparticleS2sEventsOasSourceInformation = {channel?: ('native' | 'javascript' | 'pixel' | 'desktop' | 'partner' | 'server_to_server') | undefined, partner?: string | undefined, replay_request_id?: string | undefined, replay_job_id?: string | undefined, is_historical?: boolean | undefined}; export type MparticleS2sEventsOasAttributionInfo = {service_provider: string, publisher: string, campaign: string}; export type MparticleS2sEventsOasGDPRConsentState = {regulation: string, document: string, consented: boolean, timestamp_unixtime_ms: number, location: string, hardware_id: string}; export type MparticleS2sEventsOasConsentState = {gdpr: MparticleS2sEventsOasGDPRConsentState}; export type MparticleS2sEventsOasBatch = {source_request_id?: string | undefined, context?: MparticleS2sEventsOasBatchContext | undefined, events?: Array | undefined, device_info?: MparticleS2sEventsOasDeviceInformation | undefined, application_info?: MparticleS2sEventsOasApplicationInformation | undefined, user_attributes?: {[key: string]: Record} | undefined, deleted_user_attributes?: Array | undefined, user_identities?: ({other?: string | undefined, customer_id?: string | undefined, facebook?: string | undefined, twitter?: string | undefined, google?: string | undefined, microsoft?: string | undefined, yahoo?: string | undefined, email?: string | undefined, alias?: string | undefined, facebook_custom_audience_id?: string | undefined, other_id_2?: string | undefined, other_id_3?: string | undefined, other_id_4?: string | undefined, other_id_5?: string | undefined, other_id_6?: string | undefined, other_id_7?: string | undefined, other_id_8?: string | undefined, other_id_9?: string | undefined, other_id_10?: string | undefined, mobile_number?: string | undefined, phone_number_2?: string | undefined, phone_number_3?: string | undefined}) | undefined, environment: 'unknown' | 'development' | 'production', api_key?: string | undefined, api_keys?: Array | undefined, ip?: string | undefined, integration_attributes?: {[key: string]: {[key: string]: string}} | undefined, partner_identity?: string | undefined, source_info?: MparticleS2sEventsOasSourceInformation | undefined, mp_deviceid?: string | undefined, attribution_info?: MparticleS2sEventsOasAttributionInfo | undefined, timestamp_unixtime_ms?: number | undefined, batch_id?: number | undefined, mpid?: number | undefined, sdk_version?: string | undefined, consent_state?: MparticleS2sEventsOasConsentState | undefined, job_id?: string | undefined}; export type CreateApiValidateArgs = {body: {document?: VersionDocument | undefined, batch?: MparticleS2sEventsOasBatch | undefined}}; export type CreateApiValidateOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const matchType = z.enum(["unknown", "screen_view", "custom_event", "user_attributes", "user_identities", "product_action", "promotion_action", "product_impression"]); export const screenViewEventCriteria = z.object({screen_name: z.string()}); export const customEventCriteria = z.object({event_name: z.string(), custom_event_type: z.enum(["unknown", "navigation", "location", "search", "transaction", "user_content", "user_preference", "social", "other", "media"])}); export const userAttributeCriteria = z.object({}); export const productAction = z.enum(["add_to_cart", "remove_from_cart", "checkout", "checkout_option", "click", "view_detail", "purchase", "refund", "add_to_wishlist", "remove_from_wish_list"]); export const promotionAction = z.enum(["view", "click"]); export const commerceActionEventCriteria = z.object({action: z.union([productAction, promotionAction]).optional()}); export const criteria = z.union([screenViewEventCriteria, customEventCriteria, userAttributeCriteria, commerceActionEventCriteria]); export const dataPointMatch = z.object({type: matchType, criteria: criteria}); export const schemaKeyword = z.enum(["none", "additionalItems", "additionalProperties", "allOf", "anyOf", "const", "contains", "contentEncoding", "contentMediaType", "default", "definitions", "dependencies", "dependentRequired", "dependentSchemas", "else", "enum", "exclusiveMaximum", "exclusiveMinimum", "format", "id", "if", "items", "maxContains", "maximum", "maximum", "maxLength", "maxProperties", "minContains", "minimum", "minItems", "minLength", "minProperties", "multipleOf", "not", "oneOf", "pattern", "patternProperties", "properties", "propertyNames", "readOnly", "required", "then", "type", "unevaluatedItems", "unevaluatedProperties", "uniqueItems", "writeOnly", "$anchor", "$defs", "$id", "$recursiveAnchor", "$recursiveRef", "$ref", "$schema", "$vocabulary", "timeLimit", "$comment", "description", "examples", "title"]); export const mparticleS2sEventsOasGeoLocation = z.object({latitude: z.number(), longitude: z.number(), accuracy: z.number().optional()}); export const mparticleS2sEventsOasDeviceCurrentState = z.object({time_since_start_ms: z.number().int().optional(), battery_level: z.number().optional(), data_connection_type: z.string().optional(), data_connection_type_detail: z.string().optional(), gps_state: z.boolean().optional(), total_system_memory_usage_bytes: z.number().int().optional(), disk_space_free_bytes: z.number().int().optional(), external_disk_space_free_bytes: z.number().int().optional(), cpu: z.string().optional(), system_memory_available_bytes: z.number().optional(), system_memory_low: z.boolean().optional(), system_memory_threshold_bytes: z.number().optional(), application_memory_available_bytes: z.number().optional(), application_memory_max_bytes: z.number().optional(), application_memory_total_bytes: z.number().optional(), device_orientation: z.enum(["portrait", "portrait_upside_down", "landscape", "LandscapeLeft", "LandscapeRight", "FaceUp", "FaceDown", "Square"]).optional(), status_bar_orientation: z.enum(["portrait", "portrait_upside_down", "landscape", "LandscapeLeft", "LandscapeRight", "FaceUp", "FaceDown", "Square"]).optional()}); export const mparticleS2sEventsOasEventSystemNotificationInfo = z.object({type: z.literal("gdpr_change")}); export const createApiValidateResponse = z.object({results: z.array(z.object({data: z.object({match: dataPointMatch.optional(), validation_errors: z.array(z.object({validation_error_type: z.enum(["unknown", "unplanned", "missing_required", "invalid_value"]).optional(), key: z.string().optional(), error_pointer: z.string().optional(), expected: z.string().optional(), actual: z.string().optional(), action_expected: z.enum(["unknown", "allow", "drop_event", "drop_attribute", "drop_batch"]).optional(), schema_keyword: schemaKeyword.optional()})).optional(), validated_event_id: z.number().optional(), validated_source_message_id: z.string().optional(), executed_transformations: z.object({transformation_id: z.number().optional(), transformation_status: z.enum(["success", "failure", "unchanged", "quarantined"]).optional(), transformation_error_type: z.enum(["valid", "invalid", "unrecognized_data_point", "events_schema_violated"]).optional(), transformation_error_message: z.string().optional(), transformation_error_pointer: z.string().optional()}).optional(), timestamp_unixtime_ms: z.number().int().optional(), event_id: z.number().int().optional(), source_message_id: z.string().optional(), session_id: z.number().int().optional(), session_uuid: z.string().optional(), session_start_unixtime_ms: z.number().int().optional(), event_start_unixtime_ms: z.number().int().optional(), custom_attributes: z.record(z.string(), z.string()).optional(), location: mparticleS2sEventsOasGeoLocation.optional(), device_current_state: mparticleS2sEventsOasDeviceCurrentState.optional(), is_goal_defined: z.boolean().optional(), lifetime_value_change: z.boolean().optional(), lifetime_value_attribute_name: z.string().optional(), data_connection_type: z.string().optional(), event_num: z.number().int().optional(), view_controller: z.string().optional(), is_main_thread: z.boolean().optional(), canonical_name: z.string().optional(), event_system_notification_info: mparticleS2sEventsOasEventSystemNotificationInfo.optional()}).optional()})).optional(), batch: z.object({}).optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Validate Event Batch * * POST /validate */ export const createApiValidate = async (args: CreateApiValidateArgs, options?: CreateApiValidateOptions) => { const {baseUrl = "https://api.mparticle.com/platform/v2/workspaces/0/plans", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/validate${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(createApiValidateResponse, await res.json()) };