@adhub-so/adhub-nextjs-sdk 0.3.0 → 0.4.1

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/nextjs.ts","../src/identity-cookie.ts","../src/server.ts"],"names":[],"mappings":";;;AAUA,IAAM,eAAA,GAAkB,sBAAA;AACxB,IAAM,eAAA,GAAkB,mBAAA;AACxB,IAAM,eAAA,GAAkB,GAAG,eAAe,CAAA,MAAA,CAAA;AAC1C,IAAM,SAAA,uBAAgB,GAAA,CAAI;AAAA,EACxB,GAAG,eAAe,CAAA,WAAA,CAAA;AAAA,EAClB,GAAG,eAAe,CAAA,QAAA,CAAA;AAAA,EAClB,GAAG,eAAe,CAAA,eAAA,CAAA;AAAA,EAClB,GAAG,eAAe,CAAA,gBAAA,CAAA;AAAA,EAClB,GAAG,eAAe,CAAA,MAAA,CAAA;AAAA,EAClB;AACF,CAAC,CAAA;AAED,SAAS,gBAAA,CAAiB,QAAgB,IAAA,EAAuB;AAC/D,EAAA,IAAI,IAAA,KAAS,eAAA,EAAiB,OAAO,MAAA,KAAW,KAAA;AAChD,EAAA,OAAO,MAAA,KAAW,MAAA;AACpB;AAEA,SAAS,iBAAiB,KAAA,EAAmC;AAC3D,EAAA,MAAM,MAAM,IAAI,GAAA,CAAI,KAAA,EAAO,IAAA,MAAU,eAAe,CAAA;AACpD,EAAA,IAAI,GAAA,CAAI,QAAA,KAAa,QAAA,IAAY,GAAA,CAAI,aAAa,OAAA,EAAS;AACzD,IAAA,MAAM,IAAI,UAAU,8CAA8C,CAAA;AAAA,EACpE;AACA,EAAA,OAAO,GAAA,CAAI,QAAA,EAAS,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AACzC;AAEA,SAAS,QAAQ,OAAA,EAAiC;AAChD,EAAA,MAAM,QAAA,GAAW,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA,CAAE,QAAA;AACtC,EA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AAM,IAAI,iBAAiB,kDAAA,EAAoD;AAAA,QAC7E,QAAQ,QAAA,CAAS,MAAA;AAAA,QACjB,SAAA,EAAW,SAAS,MAAA,IAAU;AAAA,OAC/B,CAAA;AAAA,IACH;AACA,IAAA,OAAO,MAAA;AAAA,EACT;AACF,CAAA;AAEO,SAAS,wBAAwB,OAAA,EAAsD;AAC5F,EAAA,OAAO,IAAI,yBAAyB,OAAO,CAAA;AAC7C;AAIO,SAAS,oBAAA,CACd,cACA,UAAA,EACe;AACf,EAAA,OAAO,8BAAA,CAA+B,cAAc,UAAU,CAAA;AAChE","file":"server.js","sourcesContent":["export interface AdHubNextRouteHandlerOptions {\n apiUrl?: string;\n}\n\ntype AdHubNextRouteHandler = ((request: Request) => Promise<Response>) & {\n GET: (request: Request) => Promise<Response>;\n POST: (request: Request) => Promise<Response>;\n OPTIONS: () => Promise<Response>;\n};\n\nconst DEFAULT_API_URL = \"https://api.adhub.so\";\nconst SDK_PATH_PREFIX = \"/api/v1/saas/sdk/\";\nconst SDK_CONFIG_PATH = `${SDK_PATH_PREFIX}config`;\nconst SDK_PATHS = new Set([\n `${SDK_PATH_PREFIX}touchpoints`,\n `${SDK_PATH_PREFIX}identify`,\n `${SDK_PATH_PREFIX}behavior-events`,\n `${SDK_PATH_PREFIX}page-engagements`,\n `${SDK_PATH_PREFIX}events`,\n SDK_CONFIG_PATH,\n]);\n\nfunction allowedSdkMethod(method: string, path: string): boolean {\n if (path === SDK_CONFIG_PATH) return method === \"GET\";\n return method === \"POST\";\n}\n\nfunction normalizedApiUrl(value: string | undefined): string {\n const url = new URL(value?.trim() || DEFAULT_API_URL);\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\"AdHub Next.js apiUrl must use HTTP or HTTPS.\");\n }\n return url.toString().replace(/\\/$/, \"\");\n}\n\nfunction sdkPath(request: Request): string | null {\n const pathname = new URL(request.url).pathname;\n const prefixIndex = pathname.indexOf(SDK_PATH_PREFIX);\n if (prefixIndex < 0) return null;\n const path = pathname.slice(prefixIndex);\n return SDK_PATHS.has(path) ? path : null;\n}\n\nfunction firstForwardedValue(value: string | null): string | null {\n return value?.split(\",\", 1)[0]?.trim() || null;\n}\n\nfunction firstHeader(request: Request, names: string[]): string | null {\n for (const name of names) {\n const value = request.headers.get(name)?.trim();\n if (value) return value;\n }\n return null;\n}\n\nfunction clientHeaders(request: Request): Headers {\n const headers = new Headers({ \"Content-Type\": \"application/json\" });\n const sourceUrl = new URL(request.url);\n const origin = request.headers.get(\"origin\") || `${sourceUrl.protocol}//${sourceUrl.host}`;\n const userAgent = request.headers.get(\"user-agent\");\n const clientIp =\n firstHeader(request, [\"cf-connecting-ip\", \"true-client-ip\"]) ||\n firstForwardedValue(request.headers.get(\"x-forwarded-for\")) ||\n firstForwardedValue(request.headers.get(\"x-vercel-forwarded-for\")) ||\n request.headers.get(\"x-real-ip\");\n const country = firstHeader(request, [\n \"cf-ipcountry\",\n \"x-vercel-ip-country\",\n \"cloudfront-viewer-country\",\n ]);\n const region = firstHeader(request, [\"x-vercel-ip-country-region\"]);\n const city = firstHeader(request, [\"x-vercel-ip-city\"]);\n\n headers.set(\"Origin\", origin);\n if (userAgent) headers.set(\"User-Agent\", userAgent);\n if (clientIp) headers.set(\"X-AdHub-Client-IP\", clientIp);\n if (country) headers.set(\"X-AdHub-Client-Country\", country);\n if (region) headers.set(\"X-AdHub-Client-Region\", region);\n if (city) headers.set(\"X-AdHub-Client-City\", city);\n\n for (const name of [\n \"Idempotency-Key\",\n \"X-AdHub-Project-Key\",\n \"X-AdHub-SDK\",\n \"X-AdHub-SDK-Version\",\n ]) {\n const value = request.headers.get(name);\n if (value) headers.set(name, value);\n }\n return headers;\n}\n\nexport function createRouteHandler(\n options: AdHubNextRouteHandlerOptions = {},\n): AdHubNextRouteHandler {\n const apiUrl = normalizedApiUrl(options.apiUrl);\n const handler = (async (request: Request): Promise<Response> => {\n const path = sdkPath(request);\n if (!path || !allowedSdkMethod(request.method, path)) {\n return Response.json({ error: \"Not found\" }, { status: 404 });\n }\n\n const isGet = request.method === \"GET\";\n try {\n const headers = clientHeaders(request);\n if (isGet) headers.delete(\"content-type\");\n const response = await fetch(`${apiUrl}${path}`, {\n method: request.method,\n headers,\n ...(isGet ? {} : { body: await request.text() }),\n });\n const responseHeaders = new Headers();\n const contentType = response.headers.get(\"content-type\");\n const retryAfter = response.headers.get(\"retry-after\");\n if (contentType) responseHeaders.set(\"Content-Type\", contentType);\n if (retryAfter) responseHeaders.set(\"Retry-After\", retryAfter);\n return new Response(await response.arrayBuffer(), {\n status: response.status,\n headers: responseHeaders,\n });\n } catch (error) {\n return Response.json(\n {\n error: \"Failed to proxy AdHub SDK request\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n }) as AdHubNextRouteHandler;\n\n handler.GET = handler;\n handler.POST = handler;\n handler.OPTIONS = async () =>\n new Response(null, {\n status: 204,\n headers: { Allow: \"GET, POST, OPTIONS\" },\n });\n return handler;\n}\n","const COOKIE_PREFIX = \"adhub_project_anonymous_id_\";\n\nfunction hashKey(input: string): string {\n let hash = 2_166_136_261;\n for (let index = 0; index < input.length; index += 1) {\n hash ^= input.charCodeAt(index);\n hash = Math.imul(hash, 16_777_619);\n }\n return (hash >>> 0).toString(36);\n}\n\nfunction validAnonymousId(value: string | null): value is string {\n return value !== null && value.length >= 8 && value.length <= 255 && !/\\s/.test(value);\n}\n\nexport function getAdHubAnonymousIdCookieName(projectKey: string): string {\n return `${COOKIE_PREFIX}${hashKey(projectKey.trim())}`;\n}\n\nexport function readAdHubAnonymousIdFromCookie(\n cookieHeader: string | null | undefined,\n projectKey: string,\n): string | null {\n if (!cookieHeader) return null;\n const cookieName = getAdHubAnonymousIdCookieName(projectKey);\n for (const part of cookieHeader.split(\";\")) {\n const [rawName, ...rawValue] = part.trim().split(\"=\");\n if (rawName !== cookieName) continue;\n try {\n const value = decodeURIComponent(rawValue.join(\"=\"));\n return validAnonymousId(value) ? value : null;\n } catch {\n return null;\n }\n }\n return null;\n}\n","import type { JsonObject, JsonValue } from \"./types\";\nimport { readAdHubAnonymousIdFromCookie } from \"./identity-cookie\";\nimport { isUuid, normalizeEventFields, normalizeProfileId } from \"./utils\";\n\nconst DEFAULT_ENDPOINT = \"https://api.adhub.so\";\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\nexport interface AdHubServerClientOptions {\n projectKey: string;\n ingestionKey: string;\n endpoint?: string;\n timeoutMs?: number;\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface ServerEventInput {\n eventType: string;\n profileId: string;\n anonymousId?: string;\n eventId: string;\n occurredAt?: string;\n value?: number;\n currency?: string;\n properties?: Record<string, unknown>;\n}\n\nexport interface ServerEventPayload {\n project: string;\n profileId: string;\n anonymousId?: string;\n eventDefinitionId?: string;\n eventKey?: string;\n eventId: string;\n occurredAt: string;\n value?: number;\n currency?: string;\n properties?: JsonObject;\n}\n\nexport interface ServerEventDeliveryResult {\n bindingId: string;\n advertisingAccountId: string;\n conversionActionId: string;\n status: string;\n googleRequestId?: string | null;\n errorCode?: string | null;\n errorMessage?: string | null;\n retryable?: boolean;\n outcomeUnknown?: boolean;\n}\n\nexport interface ServerEventTrackResult {\n eventId: string;\n externalEventId: string;\n attributionStatus: string;\n attributionReason?: string | null;\n deliveryStatus?: string | null;\n googleRequestId?: string | null;\n duplicate?: boolean;\n deliveries?: ServerEventDeliveryResult[];\n}\n\nexport interface AdHubServerClient {\n track(event: ServerEventInput): Promise<ServerEventTrackResult>;\n}\n\ninterface ServerErrorEnvelope {\n error?: {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n outcome_unknown?: unknown;\n outcomeUnknown?: unknown;\n };\n}\n\nexport class AdHubServerError extends Error {\n readonly status: number;\n readonly code: string | null;\n readonly retryable: boolean;\n readonly outcomeUnknown: boolean;\n\n constructor(\n message: string,\n options: {\n status: number;\n code?: string | null;\n retryable?: boolean;\n outcomeUnknown?: boolean;\n },\n ) {\n super(message);\n this.name = \"AdHubServerError\";\n this.status = options.status;\n this.code = options.code ?? null;\n this.retryable = options.retryable ?? false;\n this.outcomeUnknown = options.outcomeUnknown ?? false;\n }\n}\n\nfunction normalizeEndpoint(endpoint: string | undefined): string {\n let parsed: URL;\n try {\n parsed = new URL(endpoint?.trim() || DEFAULT_ENDPOINT);\n } catch {\n throw new Error(\"AdHub server endpoint must be a valid HTTP(S) URL.\");\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new Error(\"AdHub server endpoint must be a valid HTTP(S) URL.\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n\nexport function createServerEventPayload(\n projectKey: string,\n input: ServerEventInput,\n): ServerEventPayload {\n const normalizedProjectKey = projectKey.trim();\n const profileId = normalizeProfileId(input.profileId);\n if (!isUuid(normalizedProjectKey)) {\n throw new Error(\"AdHub server projectKey must be a UUID.\");\n }\n if (!profileId) {\n throw new Error(\n \"AdHub server profileId must be 1-255 characters without control characters.\",\n );\n }\n\n const normalized = normalizeEventFields(input);\n if (!normalized.eventId) {\n throw new Error(\"AdHub server eventId is required.\");\n }\n\n const payload: ServerEventPayload = {\n project: normalizedProjectKey,\n profileId,\n eventId: normalized.eventId,\n occurredAt: normalized.occurredAt,\n };\n if (input.anonymousId !== undefined) payload.anonymousId = input.anonymousId;\n if (isUuid(normalized.eventType)) payload.eventDefinitionId = normalized.eventType;\n else payload.eventKey = normalized.eventType;\n if (normalized.value !== undefined) payload.value = normalized.value;\n if (normalized.currency !== undefined) payload.currency = normalized.currency;\n if (normalized.properties !== undefined) payload.properties = normalized.properties;\n return payload;\n}\n\nfunction errorDetails(value: unknown, status: number): AdHubServerError {\n const envelope = value && typeof value === \"object\" ? value as ServerErrorEnvelope : {};\n const error = envelope.error;\n const message = typeof error?.message === \"string\"\n ? error.message\n : `AdHub server endpoint returned HTTP ${status}.`;\n return new AdHubServerError(message, {\n status,\n code: typeof error?.code === \"string\" ? error.code : null,\n retryable: error?.retryable === true,\n outcomeUnknown: error?.outcome_unknown === true || error?.outcomeUnknown === true,\n });\n}\n\nasync function readJson(response: Response): Promise<JsonValue | undefined> {\n try {\n return await response.json() as JsonValue;\n } catch {\n return undefined;\n }\n}\n\nclass DefaultAdHubServerClient implements AdHubServerClient {\n private readonly projectKey: string;\n private readonly ingestionKey: string;\n private readonly endpoint: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n constructor(options: AdHubServerClientOptions) {\n this.projectKey = options.projectKey.trim();\n if (!isUuid(this.projectKey)) {\n throw new Error(\"AdHub server projectKey must be a UUID.\");\n }\n this.ingestionKey = options.ingestionKey.trim();\n if (!this.ingestionKey || this.ingestionKey.length > 4_096) {\n throw new Error(\"AdHub server ingestionKey is required.\");\n }\n this.endpoint = normalizeEndpoint(options.endpoint);\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (!Number.isFinite(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 300_000) {\n throw new Error(\"AdHub server timeoutMs must be between 1 and 300000.\");\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\"AdHub server client requires a Fetch API implementation.\");\n }\n this.fetchImpl = fetchImpl;\n }\n\n async track(event: ServerEventInput): Promise<ServerEventTrackResult> {\n const payload = createServerEventPayload(this.projectKey, event);\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.endpoint}/api/v1/saas/events/track`, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${this.ingestionKey}`,\n \"Content-Type\": \"application/json\",\n \"Idempotency-Key\": payload.eventId,\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n } catch (error) {\n if (error instanceof AdHubServerError) throw error;\n const message = error instanceof Error ? error.message : \"AdHub server request failed.\";\n throw new AdHubServerError(message, { status: 0, retryable: true });\n } finally {\n clearTimeout(timeout);\n }\n\n const result = await readJson(response);\n if (!response.ok) throw errorDetails(result, response.status);\n if (!result || typeof result !== \"object\" || Array.isArray(result)) {\n throw new AdHubServerError(\"AdHub server returned an invalid event response.\", {\n status: response.status,\n retryable: response.status >= 500,\n });\n }\n return result as unknown as ServerEventTrackResult;\n }\n}\n\nexport function createAdHubServerClient(options: AdHubServerClientOptions): AdHubServerClient {\n return new DefaultAdHubServerClient(options);\n}\n\nexport { getAdHubAnonymousIdCookieName } from \"./identity-cookie\";\n\nexport function readAdHubAnonymousId(\n cookieHeader: string | null | undefined,\n projectKey: string,\n): string | null {\n return readAdHubAnonymousIdFromCookie(cookieHeader, projectKey);\n}\n"]}
1
+ {"version":3,"sources":["../src/identity-cookie.ts","../src/nextjs.ts","../src/server.ts"],"names":[],"mappings":";;;AAAA,IAAM,aAAA,GAAgB,6BAAA;AAEtB,SAAS,QAAQ,KAAA,EAAuB;AACtC,EAAA,IAAI,IAAA,GAAO,UAAA;AACX,EAAA,KAAA,IAAS,QAAQ,CAAA,EAAG,KAAA,GAAQ,KAAA,CAAM,MAAA,EAAQ,SAAS,CAAA,EAAG;AACpD,IAAA,IAAA,IAAQ,KAAA,CAAM,WAAW,KAAK,CAAA;AAC9B,IAAA,IAAA,GAAO,IAAA,CAAK,IAAA,CAAK,IAAA,EAAM,QAAU,CAAA;AAAA,EACnC;AACA,EAAA,OAAA,CAAQ,IAAA,KAAS,CAAA,EAAG,QAAA,CAAS,EAAE,CAAA;AACjC;AAEO,IAAM,mCAAA,GAAsC,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK,GAAA;AAE3D,SAAS,iBAAiB,KAAA,EAAuC;AACtE,EAAA,OAAO,KAAA,KAAU,IAAA,IAAQ,KAAA,CAAM,MAAA,IAAU,CAAA,IAAK,KAAA,CAAM,MAAA,IAAU,GAAA,IAAO,CAAC,IAAA,CAAK,IAAA,CAAK,KAAK,CAAA;AACvF;AAEO,SAAS,8BAA8B,UAAA,EAA4B;AACxE,EAAA,OAAO,GAAG,aAAa,CAAA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C5F,EAAA,OAAO,IAAI,yBAAyB,OAAO,CAAA;AAC7C;AAIO,SAAS,oBAAA,CACd,cACA,UAAA,EACe;AACf,EAAA,OAAO,8BAAA,CAA+B,cAAc,UAAU,CAAA;AAChE","file":"server.js","sourcesContent":["const COOKIE_PREFIX = \"adhub_project_anonymous_id_\";\n\nfunction hashKey(input: string): string {\n let hash = 2_166_136_261;\n for (let index = 0; index < input.length; index += 1) {\n hash ^= input.charCodeAt(index);\n hash = Math.imul(hash, 16_777_619);\n }\n return (hash >>> 0).toString(36);\n}\n\nexport const ANONYMOUS_ID_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 395;\n\nexport function validAnonymousId(value: string | null): value is string {\n return value !== null && value.length >= 8 && value.length <= 255 && !/\\s/.test(value);\n}\n\nexport function getAdHubAnonymousIdCookieName(projectKey: string): string {\n return `${COOKIE_PREFIX}${hashKey(projectKey.trim())}`;\n}\n\nexport function readAdHubAnonymousIdFromCookie(\n cookieHeader: string | null | undefined,\n projectKey: string,\n): string | null {\n if (!cookieHeader) return null;\n const cookieName = getAdHubAnonymousIdCookieName(projectKey);\n for (const part of cookieHeader.split(\";\")) {\n const [rawName, ...rawValue] = part.trim().split(\"=\");\n if (rawName !== cookieName) continue;\n try {\n const value = decodeURIComponent(rawValue.join(\"=\"));\n return validAnonymousId(value) ? value : null;\n } catch {\n return null;\n }\n }\n return null;\n}\n\n/**\n * Normalizes a cookie `Domain` and checks that `hostname` belongs to it.\n * Returns null for anything a browser would refuse for this host, so callers\n * never trade a working host-only cookie for one that cannot be stored.\n */\nexport function cookieDomainForHost(\n domain: string | null | undefined,\n hostname: string | null | undefined,\n): string | null {\n const candidate = domain?.trim().toLowerCase().replace(/^\\./, \"\").replace(/\\.$/, \"\");\n const host = hostname?.trim().toLowerCase().replace(/\\.$/, \"\");\n if (!candidate || !host) return null;\n if (!/^[a-z0-9-]+(\\.[a-z0-9-]+)+$/.test(candidate)) return null;\n if (/^[\\d.]+$/.test(candidate)) return null;\n return host === candidate || host.endsWith(`.${candidate}`) ? candidate : null;\n}\n\nexport function serializeAdHubAnonymousIdCookie(input: {\n projectKey: string;\n anonymousId: string;\n domain?: string | null;\n secure: boolean;\n maxAgeSeconds?: number;\n}): string {\n const parts = [\n `${getAdHubAnonymousIdCookieName(input.projectKey)}=${encodeURIComponent(input.anonymousId)}`,\n ];\n if (input.domain) parts.push(`Domain=${input.domain}`);\n parts.push(\n \"Path=/\",\n `Max-Age=${input.maxAgeSeconds ?? ANONYMOUS_ID_COOKIE_MAX_AGE_SECONDS}`,\n \"SameSite=Lax\",\n );\n if (input.secure) parts.push(\"Secure\");\n return parts.join(\"; \");\n}\n","import {\n cookieDomainForHost,\n serializeAdHubAnonymousIdCookie,\n validAnonymousId,\n} from \"./identity-cookie\";\n\nexport interface AdHubNextRouteHandlerOptions {\n apiUrl?: string;\n /**\n * Share the anonymous visitor ID cookie with every subdomain of this domain,\n * for example `example.com`. Defaults to the site's own hostname only.\n */\n cookieDomain?: string;\n}\n\ntype AdHubNextRouteHandler = ((request: Request) => Promise<Response>) & {\n GET: (request: Request) => Promise<Response>;\n POST: (request: Request) => Promise<Response>;\n OPTIONS: () => Promise<Response>;\n};\n\nconst DEFAULT_API_URL = \"https://api.adhub.so\";\nconst SDK_PATH_PREFIX = \"/api/v1/saas/sdk/\";\nconst SDK_CONFIG_PATH = `${SDK_PATH_PREFIX}config`;\nconst SDK_PATHS = new Set([\n `${SDK_PATH_PREFIX}touchpoints`,\n `${SDK_PATH_PREFIX}identify`,\n `${SDK_PATH_PREFIX}behavior-events`,\n `${SDK_PATH_PREFIX}page-engagements`,\n `${SDK_PATH_PREFIX}events`,\n SDK_CONFIG_PATH,\n]);\n\nfunction allowedSdkMethod(method: string, path: string): boolean {\n if (path === SDK_CONFIG_PATH) return method === \"GET\";\n return method === \"POST\";\n}\n\nfunction normalizedApiUrl(value: string | undefined): string {\n const url = new URL(value?.trim() || DEFAULT_API_URL);\n if (url.protocol !== \"https:\" && url.protocol !== \"http:\") {\n throw new TypeError(\"AdHub Next.js apiUrl must use HTTP or HTTPS.\");\n }\n return url.toString().replace(/\\/$/, \"\");\n}\n\nfunction sdkPath(request: Request): string | null {\n const pathname = new URL(request.url).pathname;\n const prefixIndex = pathname.indexOf(SDK_PATH_PREFIX);\n if (prefixIndex < 0) return null;\n const path = pathname.slice(prefixIndex);\n return SDK_PATHS.has(path) ? path : null;\n}\n\nfunction firstForwardedValue(value: string | null): string | null {\n return value?.split(\",\", 1)[0]?.trim() || null;\n}\n\nfunction firstHeader(request: Request, names: string[]): string | null {\n for (const name of names) {\n const value = request.headers.get(name)?.trim();\n if (value) return value;\n }\n return null;\n}\n\n/**\n * The site origin the browser used. Browsers omit Origin on same-origin GET\n * requests, and `request.url` in a Next.js server carries the address the\n * server listens on rather than the site's domain, so fall back to the\n * forwarded or Host header the browser actually addressed.\n */\nfunction requestOrigin(request: Request): string {\n const origin = request.headers.get(\"origin\");\n if (origin) return origin;\n const sourceUrl = new URL(request.url);\n const protocol =\n firstForwardedValue(request.headers.get(\"x-forwarded-proto\")) ??\n sourceUrl.protocol.replace(/:$/, \"\");\n const host =\n firstForwardedValue(request.headers.get(\"x-forwarded-host\")) ??\n request.headers.get(\"host\") ??\n sourceUrl.host;\n return `${protocol}://${host}`;\n}\n\nfunction clientHeaders(request: Request): Headers {\n const headers = new Headers({ \"Content-Type\": \"application/json\" });\n const origin = requestOrigin(request);\n const userAgent = request.headers.get(\"user-agent\");\n const clientIp =\n firstHeader(request, [\"cf-connecting-ip\", \"true-client-ip\"]) ||\n firstForwardedValue(request.headers.get(\"x-forwarded-for\")) ||\n firstForwardedValue(request.headers.get(\"x-vercel-forwarded-for\")) ||\n request.headers.get(\"x-real-ip\");\n const country = firstHeader(request, [\n \"cf-ipcountry\",\n \"x-vercel-ip-country\",\n \"cloudfront-viewer-country\",\n ]);\n const region = firstHeader(request, [\"x-vercel-ip-country-region\"]);\n const city = firstHeader(request, [\"x-vercel-ip-city\"]);\n\n headers.set(\"Origin\", origin);\n if (userAgent) headers.set(\"User-Agent\", userAgent);\n if (clientIp) headers.set(\"X-AdHub-Client-IP\", clientIp);\n if (country) headers.set(\"X-AdHub-Client-Country\", country);\n if (region) headers.set(\"X-AdHub-Client-Region\", region);\n if (city) headers.set(\"X-AdHub-Client-City\", city);\n\n for (const name of [\n \"Idempotency-Key\",\n \"X-AdHub-Project-Key\",\n \"X-AdHub-SDK\",\n \"X-AdHub-SDK-Version\",\n ]) {\n const value = request.headers.get(name);\n if (value) headers.set(name, value);\n }\n return headers;\n}\n\nfunction requestIsSecure(request: Request): boolean {\n const forwarded = firstForwardedValue(request.headers.get(\"x-forwarded-proto\"));\n return (forwarded ?? new URL(request.url).protocol.replace(/:$/, \"\")) === \"https\";\n}\n\nfunction requestHostname(request: Request): string {\n const forwarded = firstForwardedValue(request.headers.get(\"x-forwarded-host\"));\n const host = forwarded ?? request.headers.get(\"host\") ?? new URL(request.url).host;\n try {\n return new URL(`http://${host}`).hostname;\n } catch {\n return new URL(request.url).hostname;\n }\n}\n\n/**\n * The visitor's anonymous ID as a cookie set by the site's own server.\n * Browsers that expire script-written cookies after a few days keep a\n * server-set first-party cookie for its full lifetime.\n */\nfunction anonymousIdCookie(\n request: Request,\n body: string,\n cookieDomain: string | null,\n): string | null {\n let envelope: unknown;\n try {\n envelope = JSON.parse(body);\n } catch {\n return null;\n }\n if (!envelope || typeof envelope !== \"object\") return null;\n const record = envelope as Record<string, unknown>;\n const anonymousId = typeof record.anonymousId === \"string\" ? record.anonymousId : null;\n const projectKey =\n request.headers.get(\"X-AdHub-Project-Key\")?.trim() ||\n (typeof record.projectKey === \"string\" ? record.projectKey.trim() : \"\");\n if (!validAnonymousId(anonymousId) || /[\\u0000-\\u001f\\u007f]/.test(anonymousId) || !projectKey) {\n return null;\n }\n return serializeAdHubAnonymousIdCookie({\n projectKey,\n anonymousId,\n domain: cookieDomain,\n secure: requestIsSecure(request),\n });\n}\n\nfunction withIdentityCookieDomain(body: ArrayBuffer, cookieDomain: string): BodyInit {\n try {\n const config: unknown = JSON.parse(new TextDecoder().decode(body));\n if (!config || typeof config !== \"object\" || Array.isArray(config)) return body;\n return JSON.stringify({ ...config, identityCookieDomain: cookieDomain });\n } catch {\n return body;\n }\n}\n\nexport function createRouteHandler(\n options: AdHubNextRouteHandlerOptions = {},\n): AdHubNextRouteHandler {\n const apiUrl = normalizedApiUrl(options.apiUrl);\n const handler = (async (request: Request): Promise<Response> => {\n const path = sdkPath(request);\n if (!path || !allowedSdkMethod(request.method, path)) {\n return Response.json({ error: \"Not found\" }, { status: 404 });\n }\n\n const isGet = request.method === \"GET\";\n try {\n const headers = clientHeaders(request);\n if (isGet) headers.delete(\"content-type\");\n const requestBody = isGet ? null : await request.text();\n const response = await fetch(`${apiUrl}${path}`, {\n method: request.method,\n headers,\n ...(requestBody === null ? {} : { body: requestBody }),\n });\n const responseHeaders = new Headers();\n const contentType = response.headers.get(\"content-type\");\n const retryAfter = response.headers.get(\"retry-after\");\n if (contentType) responseHeaders.set(\"Content-Type\", contentType);\n if (retryAfter) responseHeaders.set(\"Retry-After\", retryAfter);\n const cookieDomain = cookieDomainForHost(options.cookieDomain, requestHostname(request));\n let responseBody: BodyInit = await response.arrayBuffer();\n if (response.ok && requestBody !== null) {\n const cookie = anonymousIdCookie(request, requestBody, cookieDomain);\n if (cookie) responseHeaders.append(\"Set-Cookie\", cookie);\n } else if (response.ok && cookieDomain) {\n // Tell the browser SDK which domain its own cookie writes must use.\n responseBody = withIdentityCookieDomain(responseBody as ArrayBuffer, cookieDomain);\n }\n return new Response(responseBody, {\n status: response.status,\n headers: responseHeaders,\n });\n } catch (error) {\n return Response.json(\n {\n error: \"Failed to proxy AdHub SDK request\",\n message: error instanceof Error ? error.message : String(error),\n },\n { status: 502 },\n );\n }\n }) as AdHubNextRouteHandler;\n\n handler.GET = handler;\n handler.POST = handler;\n handler.OPTIONS = async () =>\n new Response(null, {\n status: 204,\n headers: { Allow: \"GET, POST, OPTIONS\" },\n });\n return handler;\n}\n","import type { JsonObject, JsonValue } from \"./types\";\nimport { readAdHubAnonymousIdFromCookie } from \"./identity-cookie\";\nimport { isUuid, normalizeEventFields, normalizeProfileId } from \"./utils\";\n\nconst DEFAULT_ENDPOINT = \"https://api.adhub.so\";\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\nexport interface AdHubServerClientOptions {\n projectKey: string;\n ingestionKey: string;\n endpoint?: string;\n timeoutMs?: number;\n fetch?: typeof globalThis.fetch;\n}\n\nexport interface ServerEventInput {\n eventType: string;\n profileId: string;\n anonymousId?: string;\n eventId: string;\n occurredAt?: string;\n value?: number;\n currency?: string;\n properties?: Record<string, unknown>;\n}\n\nexport interface ServerEventPayload {\n project: string;\n profileId: string;\n anonymousId?: string;\n eventDefinitionId?: string;\n eventKey?: string;\n eventId: string;\n occurredAt: string;\n value?: number;\n currency?: string;\n properties?: JsonObject;\n}\n\nexport interface ServerEventDeliveryResult {\n bindingId: string;\n advertisingAccountId: string;\n conversionActionId: string;\n status: string;\n googleRequestId?: string | null;\n errorCode?: string | null;\n errorMessage?: string | null;\n retryable?: boolean;\n outcomeUnknown?: boolean;\n}\n\nexport interface ServerEventTrackResult {\n eventId: string;\n externalEventId: string;\n attributionStatus: string;\n attributionReason?: string | null;\n deliveryStatus?: string | null;\n googleRequestId?: string | null;\n duplicate?: boolean;\n deliveries?: ServerEventDeliveryResult[];\n}\n\nexport interface AdHubServerClient {\n track(event: ServerEventInput): Promise<ServerEventTrackResult>;\n}\n\ninterface ServerErrorEnvelope {\n error?: {\n code?: unknown;\n message?: unknown;\n retryable?: unknown;\n outcome_unknown?: unknown;\n outcomeUnknown?: unknown;\n };\n}\n\nexport class AdHubServerError extends Error {\n readonly status: number;\n readonly code: string | null;\n readonly retryable: boolean;\n readonly outcomeUnknown: boolean;\n\n constructor(\n message: string,\n options: {\n status: number;\n code?: string | null;\n retryable?: boolean;\n outcomeUnknown?: boolean;\n },\n ) {\n super(message);\n this.name = \"AdHubServerError\";\n this.status = options.status;\n this.code = options.code ?? null;\n this.retryable = options.retryable ?? false;\n this.outcomeUnknown = options.outcomeUnknown ?? false;\n }\n}\n\nfunction normalizeEndpoint(endpoint: string | undefined): string {\n let parsed: URL;\n try {\n parsed = new URL(endpoint?.trim() || DEFAULT_ENDPOINT);\n } catch {\n throw new Error(\"AdHub server endpoint must be a valid HTTP(S) URL.\");\n }\n if (parsed.protocol !== \"https:\" && parsed.protocol !== \"http:\") {\n throw new Error(\"AdHub server endpoint must be a valid HTTP(S) URL.\");\n }\n return parsed.toString().replace(/\\/$/, \"\");\n}\n\nexport function createServerEventPayload(\n projectKey: string,\n input: ServerEventInput,\n): ServerEventPayload {\n const normalizedProjectKey = projectKey.trim();\n const profileId = normalizeProfileId(input.profileId);\n if (!isUuid(normalizedProjectKey)) {\n throw new Error(\"AdHub server projectKey must be a UUID.\");\n }\n if (!profileId) {\n throw new Error(\n \"AdHub server profileId must be 1-255 characters without control characters.\",\n );\n }\n\n const normalized = normalizeEventFields(input);\n if (!normalized.eventId) {\n throw new Error(\"AdHub server eventId is required.\");\n }\n\n const payload: ServerEventPayload = {\n project: normalizedProjectKey,\n profileId,\n eventId: normalized.eventId,\n occurredAt: normalized.occurredAt,\n };\n if (input.anonymousId !== undefined) payload.anonymousId = input.anonymousId;\n if (isUuid(normalized.eventType)) payload.eventDefinitionId = normalized.eventType;\n else payload.eventKey = normalized.eventType;\n if (normalized.value !== undefined) payload.value = normalized.value;\n if (normalized.currency !== undefined) payload.currency = normalized.currency;\n if (normalized.properties !== undefined) payload.properties = normalized.properties;\n return payload;\n}\n\nfunction errorDetails(value: unknown, status: number): AdHubServerError {\n const envelope = value && typeof value === \"object\" ? value as ServerErrorEnvelope : {};\n const error = envelope.error;\n const message = typeof error?.message === \"string\"\n ? error.message\n : `AdHub server endpoint returned HTTP ${status}.`;\n return new AdHubServerError(message, {\n status,\n code: typeof error?.code === \"string\" ? error.code : null,\n retryable: error?.retryable === true,\n outcomeUnknown: error?.outcome_unknown === true || error?.outcomeUnknown === true,\n });\n}\n\nasync function readJson(response: Response): Promise<JsonValue | undefined> {\n try {\n return await response.json() as JsonValue;\n } catch {\n return undefined;\n }\n}\n\nclass DefaultAdHubServerClient implements AdHubServerClient {\n private readonly projectKey: string;\n private readonly ingestionKey: string;\n private readonly endpoint: string;\n private readonly timeoutMs: number;\n private readonly fetchImpl: typeof globalThis.fetch;\n\n constructor(options: AdHubServerClientOptions) {\n this.projectKey = options.projectKey.trim();\n if (!isUuid(this.projectKey)) {\n throw new Error(\"AdHub server projectKey must be a UUID.\");\n }\n this.ingestionKey = options.ingestionKey.trim();\n if (!this.ingestionKey || this.ingestionKey.length > 4_096) {\n throw new Error(\"AdHub server ingestionKey is required.\");\n }\n this.endpoint = normalizeEndpoint(options.endpoint);\n this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n if (!Number.isFinite(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 300_000) {\n throw new Error(\"AdHub server timeoutMs must be between 1 and 300000.\");\n }\n const fetchImpl = options.fetch ?? globalThis.fetch;\n if (typeof fetchImpl !== \"function\") {\n throw new Error(\"AdHub server client requires a Fetch API implementation.\");\n }\n this.fetchImpl = fetchImpl;\n }\n\n async track(event: ServerEventInput): Promise<ServerEventTrackResult> {\n const payload = createServerEventPayload(this.projectKey, event);\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.timeoutMs);\n let response: Response;\n try {\n response = await this.fetchImpl(`${this.endpoint}/api/v1/saas/events/track`, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${this.ingestionKey}`,\n \"Content-Type\": \"application/json\",\n \"Idempotency-Key\": payload.eventId,\n },\n body: JSON.stringify(payload),\n signal: controller.signal,\n });\n } catch (error) {\n if (error instanceof AdHubServerError) throw error;\n const message = error instanceof Error ? error.message : \"AdHub server request failed.\";\n throw new AdHubServerError(message, { status: 0, retryable: true });\n } finally {\n clearTimeout(timeout);\n }\n\n const result = await readJson(response);\n if (!response.ok) throw errorDetails(result, response.status);\n if (!result || typeof result !== \"object\" || Array.isArray(result)) {\n throw new AdHubServerError(\"AdHub server returned an invalid event response.\", {\n status: response.status,\n retryable: response.status >= 500,\n });\n }\n return result as unknown as ServerEventTrackResult;\n }\n}\n\nexport function createAdHubServerClient(options: AdHubServerClientOptions): AdHubServerClient {\n return new DefaultAdHubServerClient(options);\n}\n\nexport { getAdHubAnonymousIdCookieName } from \"./identity-cookie\";\n\nexport function readAdHubAnonymousId(\n cookieHeader: string | null | undefined,\n projectKey: string,\n): string | null {\n return readAdHubAnonymousIdFromCookie(cookieHeader, projectKey);\n}\n"]}
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+
3
+ // src/utils.ts
4
+ var MAX_PARAM_LENGTH = 2048;
5
+ var MAX_ROUTE_LENGTH = 255;
6
+ var MAX_URL_LENGTH = 8192;
7
+ var MAX_UTM_KEYS = 50;
8
+ var MAX_VALUES_PER_PARAM = 10;
9
+ var UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
10
+ var MAX_PROFILE_ID_LENGTH = 255;
11
+ var PROFILE_ID_CONTROL_PATTERN = /[\p{Cc}\p{Cf}]/u;
12
+ function nowIso() {
13
+ return (/* @__PURE__ */ new Date()).toISOString();
14
+ }
15
+ function randomId(prefix) {
16
+ const uuid = globalThis.crypto?.randomUUID?.();
17
+ if (uuid) return `${prefix}_${uuid}`;
18
+ const random = Math.random().toString(36).slice(2);
19
+ return `${prefix}_${Date.now().toString(36)}${random}`;
20
+ }
21
+ function truncate(value) {
22
+ return value.slice(0, MAX_PARAM_LENGTH);
23
+ }
24
+ function unique(values) {
25
+ return [...new Set(values.filter(Boolean).map(truncate))];
26
+ }
27
+ function valuesFor(searchParams, wantedKey) {
28
+ const values = [];
29
+ for (const [key, value] of searchParams.entries()) {
30
+ if (key.toLowerCase() === wantedKey) values.push(value);
31
+ }
32
+ return unique(values).slice(0, MAX_VALUES_PER_PARAM);
33
+ }
34
+ function isUuid(value) {
35
+ return UUID_PATTERN.test(value);
36
+ }
37
+ function normalizeProfileId(value) {
38
+ const normalized = value.trim();
39
+ if (!normalized || [...normalized].length > MAX_PROFILE_ID_LENGTH || PROFILE_ID_CONTROL_PATTERN.test(normalized)) {
40
+ return null;
41
+ }
42
+ return normalized;
43
+ }
44
+ function safePageUrl(input) {
45
+ try {
46
+ const url = new URL(input);
47
+ return `${url.origin}${url.pathname}`.slice(0, MAX_URL_LENGTH);
48
+ } catch {
49
+ return "";
50
+ }
51
+ }
52
+ function safeReferrer(input) {
53
+ if (!input) return null;
54
+ const safe = safePageUrl(input);
55
+ return safe || null;
56
+ }
57
+ function captureTouchpoint(location, referrer, capturedAt = nowIso()) {
58
+ const url = new URL(location.href);
59
+ const clickIds = {
60
+ gclid: valuesFor(url.searchParams, "gclid"),
61
+ gbraid: valuesFor(url.searchParams, "gbraid"),
62
+ wbraid: valuesFor(url.searchParams, "wbraid")
63
+ };
64
+ const utm = {};
65
+ for (const key of [...new Set([...url.searchParams.keys()].map((key2) => key2.toLowerCase()))].filter((candidate) => candidate.startsWith("utm_")).slice(0, MAX_UTM_KEYS)) {
66
+ utm[key] = valuesFor(url.searchParams, key);
67
+ }
68
+ return {
69
+ ahRoute: valuesFor(url.searchParams, "ah_route")[0]?.slice(0, MAX_ROUTE_LENGTH) ?? null,
70
+ clickIds,
71
+ utm,
72
+ landingUrl: safePageUrl(url.href),
73
+ referrer: safeReferrer(referrer),
74
+ // Browsers do not know Google's server-side click timestamp. This is the
75
+ // first-party observation time and is the upper bound available to the SDK.
76
+ clickTime: capturedAt
77
+ };
78
+ }
79
+
80
+ // src/testing.ts
81
+ var CLICK_ID_TYPES = /* @__PURE__ */ new Set(["gclid", "gbraid", "wbraid"]);
82
+ function envelope(projectKey, anonymousId, type, data, sentAt) {
83
+ return {
84
+ schemaVersion: "1.0",
85
+ type,
86
+ requestId: randomId("req_test"),
87
+ sentAt,
88
+ projectKey,
89
+ anonymousId,
90
+ data
91
+ };
92
+ }
93
+ function createAttributionTestEnvelopes(input) {
94
+ const projectKey = input.projectKey.trim();
95
+ const attributionRouteKey = input.attributionRouteKey.trim();
96
+ const clickId = input.clickId.trim();
97
+ const profileId = normalizeProfileId(input.profileId);
98
+ if (!isUuid(projectKey)) {
99
+ throw new Error("Attribution test requires a UUID project identifier.");
100
+ }
101
+ if (!isUuid(attributionRouteKey)) {
102
+ throw new Error("Attribution test requires a UUID attribution route identifier.");
103
+ }
104
+ if (!profileId) {
105
+ throw new Error(
106
+ "Attribution test profileId must be 1-255 characters without control characters."
107
+ );
108
+ }
109
+ if (!CLICK_ID_TYPES.has(input.clickIdType) || !clickId || clickId.length > 2048 || /\s/.test(clickId)) {
110
+ throw new Error("Attribution test requires one valid Google click ID.");
111
+ }
112
+ const capturedAt = input.capturedAt ?? nowIso();
113
+ const testUrl = new URL(input.pageUrl);
114
+ const trackingKeys = /* @__PURE__ */ new Set(["ah_route", "gclid", "gbraid", "wbraid"]);
115
+ for (const key of [...testUrl.searchParams.keys()]) {
116
+ if (trackingKeys.has(key.toLowerCase())) testUrl.searchParams.delete(key);
117
+ }
118
+ testUrl.searchParams.set("ah_route", attributionRouteKey);
119
+ testUrl.searchParams.set(input.clickIdType, clickId);
120
+ const captured = captureTouchpoint(
121
+ { href: testUrl.toString() },
122
+ input.referrer ?? "",
123
+ capturedAt
124
+ );
125
+ const anonymousId = randomId("anon_test");
126
+ const sessionId = randomId("sess_test");
127
+ const touchpointData = {
128
+ ...captured,
129
+ sessionId,
130
+ locale: input.locale ?? null,
131
+ timezone: input.timezone ?? null
132
+ };
133
+ const identityData = {
134
+ profile: {
135
+ profileId,
136
+ properties: { source: "adhub_attribution_test" }
137
+ },
138
+ identifiedAt: capturedAt,
139
+ pageUrl: safePageUrl(input.pageUrl)
140
+ };
141
+ return {
142
+ touchpoint: envelope(projectKey, anonymousId, "touchpoint.capture", touchpointData, capturedAt),
143
+ identity: envelope(projectKey, anonymousId, "profile.identify", identityData, capturedAt)
144
+ };
145
+ }
146
+
147
+ exports.createAttributionTestEnvelopes = createAttributionTestEnvelopes;
148
+ //# sourceMappingURL=testing.cjs.map
149
+ //# sourceMappingURL=testing.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/utils.ts","../src/testing.ts"],"names":["key"],"mappings":";;;AAUA,IAAM,gBAAA,GAAmB,IAAA;AACzB,IAAM,gBAAA,GAAmB,GAAA;AACzB,IAAM,cAAA,GAAiB,IAAA;AACvB,IAAM,YAAA,GAAe,EAAA;AACrB,IAAM,oBAAA,GAAuB,EAAA;AAC7B,IAAM,YAAA,GAAe,4EAAA;AAKrB,IAAM,qBAAA,GAAwB,GAAA;AAC9B,IAAM,0BAAA,GAA6B,iBAAA;AA2B5B,SAAS,MAAA,GAAiB;AAC/B,EAAA,OAAA,iBAAO,IAAI,IAAA,EAAK,EAAE,WAAA,EAAY;AAChC;AAEO,SAAS,SAAS,MAAA,EAAwB;AAC/C,EAAA,MAAM,IAAA,GAAO,UAAA,CAAW,MAAA,EAAQ,UAAA,IAAa;AAC7C,EAAA,IAAI,IAAA,EAAM,OAAO,CAAA,EAAG,MAAM,IAAI,IAAI,CAAA,CAAA;AAElC,EAAA,MAAM,MAAA,GAAS,KAAK,MAAA,EAAO,CAAE,SAAS,EAAE,CAAA,CAAE,MAAM,CAAC,CAAA;AACjD,EAAA,OAAO,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,IAAA,CAAK,GAAA,GAAM,QAAA,CAAS,EAAE,CAAC,CAAA,EAAG,MAAM,CAAA,CAAA;AACtD;AAEA,SAAS,SAAS,KAAA,EAAuB;AACvC,EAAA,OAAO,KAAA,CAAM,KAAA,CAAM,CAAA,EAAG,gBAAgB,CAAA;AACxC;AAEA,SAAS,OAAO,MAAA,EAA4B;AAC1C,EAAA,OAAO,CAAC,GAAG,IAAI,GAAA,CAAI,MAAA,CAAO,MAAA,CAAO,OAAO,CAAA,CAAE,G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O;AAAA,IACL,YAAY,QAAA,CAAS,UAAA,EAAY,WAAA,EAAa,oBAAA,EAAsB,gBAAgB,UAAU,CAAA;AAAA,IAC9F,UAAU,QAAA,CAAS,UAAA,EAAY,WAAA,EAAa,kBAAA,EAAoB,cAAc,UAAU;AAAA,GAC1F;AACF","file":"testing.cjs","sourcesContent":["import type {\n BrowserBehaviorEventInput,\n BrowserPageviewInput,\n CapturedTouchpoint,\n ClickIdentifiers,\n IdentifyProfile,\n JsonObject,\n JsonValue,\n} from \"./types\";\n\nconst MAX_PARAM_LENGTH = 2_048;\nconst MAX_ROUTE_LENGTH = 255;\nconst MAX_URL_LENGTH = 8_192;\nconst MAX_UTM_KEYS = 50;\nconst MAX_VALUES_PER_PARAM = 10;\nconst UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst EVENT_TYPE_PATTERN = /^[a-z][a-z0-9_.-]{0,127}$/;\nconst TIMEZONE_SUFFIX_PATTERN = /(?:z|[+-]\\d{2}:\\d{2})$/i;\nconst MAX_EVENT_ID_LENGTH = 255;\nconst MAX_EVENT_PROPERTIES_LENGTH = 32_768;\nconst MAX_PROFILE_ID_LENGTH = 255;\nconst PROFILE_ID_CONTROL_PATTERN = /[\\p{Cc}\\p{Cf}]/u;\n\nexport interface NormalizedEventFields {\n eventType: string;\n occurredAt: string;\n eventId?: string;\n value?: number;\n currency?: string;\n properties?: JsonObject;\n}\n\nexport interface NormalizedBehaviorEventFields {\n eventName: string;\n occurredAt: string;\n eventId?: string;\n pageUrl?: string;\n path?: string;\n title?: string;\n referrer?: string | null;\n properties?: JsonObject;\n}\n\nexport interface NormalizedPageviewFields\n extends Omit<NormalizedBehaviorEventFields, \"eventName\"> {\n eventName: \"pageview\";\n}\n\nexport function nowIso(): string {\n return new Date().toISOString();\n}\n\nexport function randomId(prefix: string): string {\n const uuid = globalThis.crypto?.randomUUID?.();\n if (uuid) return `${prefix}_${uuid}`;\n\n const random = Math.random().toString(36).slice(2);\n return `${prefix}_${Date.now().toString(36)}${random}`;\n}\n\nfunction truncate(value: string): string {\n return value.slice(0, MAX_PARAM_LENGTH);\n}\n\nfunction unique(values: string[]): string[] {\n return [...new Set(values.filter(Boolean).map(truncate))];\n}\n\nfunction valuesFor(searchParams: URLSearchParams, wantedKey: string): string[] {\n const values: string[] = [];\n for (const [key, value] of searchParams.entries()) {\n if (key.toLowerCase() === wantedKey) values.push(value);\n }\n return unique(values).slice(0, MAX_VALUES_PER_PARAM);\n}\n\nexport function isUuid(value: string): boolean {\n return UUID_PATTERN.test(value);\n}\n\nexport function normalizeProfileId(value: string): string | null {\n const normalized = value.trim();\n if (\n !normalized ||\n [...normalized].length > MAX_PROFILE_ID_LENGTH ||\n PROFILE_ID_CONTROL_PATTERN.test(normalized)\n ) {\n return null;\n }\n return normalized;\n}\n\nexport function safePageUrl(input: string): string {\n try {\n const url = new URL(input);\n return `${url.origin}${url.pathname}`.slice(0, MAX_URL_LENGTH);\n } catch {\n return \"\";\n }\n}\n\nexport function safeReferrer(input: string): string | null {\n if (!input) return null;\n const safe = safePageUrl(input);\n return safe || null;\n}\n\nexport function captureTouchpoint(\n location: Pick<Location, \"href\">,\n referrer: string,\n capturedAt = nowIso(),\n): CapturedTouchpoint {\n const url = new URL(location.href);\n const clickIds: ClickIdentifiers = {\n gclid: valuesFor(url.searchParams, \"gclid\"),\n gbraid: valuesFor(url.searchParams, \"gbraid\"),\n wbraid: valuesFor(url.searchParams, \"wbraid\"),\n };\n const utm: Record<string, string[]> = {};\n\n for (const key of [...new Set([...url.searchParams.keys()].map((key) => key.toLowerCase()))]\n .filter((candidate) => candidate.startsWith(\"utm_\"))\n .slice(0, MAX_UTM_KEYS)) {\n utm[key] = valuesFor(url.searchParams, key);\n }\n\n return {\n ahRoute: valuesFor(url.searchParams, \"ah_route\")[0]?.slice(0, MAX_ROUTE_LENGTH) ?? null,\n clickIds,\n utm,\n landingUrl: safePageUrl(url.href),\n referrer: safeReferrer(referrer),\n // Browsers do not know Google's server-side click timestamp. This is the\n // first-party observation time and is the upper bound available to the SDK.\n clickTime: capturedAt,\n };\n}\n\nexport function toJsonValue(value: unknown): JsonValue | undefined {\n if (value === undefined) return undefined;\n try {\n return JSON.parse(JSON.stringify(value)) as JsonValue;\n } catch {\n return undefined;\n }\n}\n\ninterface EventFieldsInput {\n eventType: string;\n eventId?: string;\n occurredAt?: string;\n value?: number;\n currency?: string;\n properties?: Record<string, unknown>;\n}\n\nexport function normalizeEventFields(input: EventFieldsInput): NormalizedEventFields {\n const eventType = input.eventType?.trim().toLowerCase();\n if (!eventType || (!EVENT_TYPE_PATTERN.test(eventType) && !isUuid(eventType))) {\n throw new Error(\n \"AdHub eventType must be an Event Definition UUID or event key.\",\n );\n }\n\n const occurredAtInput = input.occurredAt?.trim() || nowIso();\n if (!TIMEZONE_SUFFIX_PATTERN.test(occurredAtInput)) {\n throw new Error(\"AdHub occurredAt must include a timezone offset.\");\n }\n const occurredAtDate = new Date(occurredAtInput);\n if (Number.isNaN(occurredAtDate.getTime())) {\n throw new Error(\"AdHub occurredAt must be a valid ISO-8601 timestamp.\");\n }\n\n const result: NormalizedEventFields = {\n eventType,\n occurredAt: occurredAtDate.toISOString(),\n };\n\n if (input.eventId !== undefined) {\n const eventId = input.eventId.trim();\n if (\n !eventId ||\n eventId.length > MAX_EVENT_ID_LENGTH ||\n [...eventId].some((character) => character.charCodeAt(0) < 32 || character === \"\\u007f\")\n ) {\n throw new Error(\"AdHub eventId must be 1-255 characters without control characters.\");\n }\n result.eventId = eventId;\n }\n\n if (input.value !== undefined) {\n if (!Number.isFinite(input.value) || input.value < 0) {\n throw new Error(\"AdHub event value must be a finite non-negative number.\");\n }\n result.value = input.value;\n }\n\n if (input.currency !== undefined) {\n const currency = input.currency.trim().toUpperCase();\n if (!/^[A-Z]{3}$/.test(currency)) {\n throw new Error(\"AdHub event currency must be a three-letter ISO 4217 code.\");\n }\n result.currency = currency;\n }\n\n if (input.properties !== undefined) {\n const properties = toJsonValue(input.properties);\n if (\n !properties ||\n typeof properties !== \"object\" ||\n Array.isArray(properties) ||\n JSON.stringify(properties).length > MAX_EVENT_PROPERTIES_LENGTH\n ) {\n throw new Error(\"AdHub event properties must be a JSON object no larger than 32 KiB.\");\n }\n result.properties = properties;\n }\n\n return result;\n}\n\nexport function normalizeBehaviorEventFields(\n input: BrowserBehaviorEventInput,\n): NormalizedBehaviorEventFields {\n const eventName = input.eventName?.trim().toLowerCase();\n if (!eventName || !EVENT_TYPE_PATTERN.test(eventName)) {\n throw new Error(\n \"AdHub behavior eventName must start with a letter and use letters, digits, _, . or -.\",\n );\n }\n\n const occurredAtInput = input.occurredAt?.trim() || nowIso();\n if (!TIMEZONE_SUFFIX_PATTERN.test(occurredAtInput)) {\n throw new Error(\"AdHub behavior occurredAt must include a timezone offset.\");\n }\n const occurredAtDate = new Date(occurredAtInput);\n if (Number.isNaN(occurredAtDate.getTime())) {\n throw new Error(\"AdHub behavior occurredAt must be a valid ISO-8601 timestamp.\");\n }\n\n const result: NormalizedBehaviorEventFields = {\n eventName,\n occurredAt: occurredAtDate.toISOString(),\n };\n\n if (input.eventId !== undefined) {\n const eventId = input.eventId.trim();\n if (\n !eventId ||\n eventId.length > MAX_EVENT_ID_LENGTH ||\n [...eventId].some((character) => character.charCodeAt(0) < 32 || character === \"\\u007f\")\n ) {\n throw new Error(\"AdHub behavior eventId must be 1-255 characters without control characters.\");\n }\n result.eventId = eventId;\n }\n\n if (input.pageUrl !== undefined) {\n const pageUrl = safePageUrl(input.pageUrl);\n if (pageUrl) result.pageUrl = pageUrl;\n }\n if (input.path !== undefined) {\n const path = input.path.trim().slice(0, 2_048);\n if (path) result.path = path;\n }\n if (input.title !== undefined) {\n result.title = input.title.trim().slice(0, 512);\n }\n if (input.referrer !== undefined) {\n result.referrer = input.referrer === null ? null : safeReferrer(input.referrer);\n }\n\n if (input.properties !== undefined) {\n const properties = toJsonValue(input.properties);\n if (\n !properties ||\n typeof properties !== \"object\" ||\n Array.isArray(properties) ||\n JSON.stringify(properties).length > MAX_EVENT_PROPERTIES_LENGTH\n ) {\n throw new Error(\"AdHub behavior properties must be a JSON object no larger than 32 KiB.\");\n }\n result.properties = properties;\n }\n\n return result;\n}\n\nexport function normalizePageviewFields(input: BrowserPageviewInput = {}): NormalizedPageviewFields {\n return {\n ...normalizeBehaviorEventFields({ eventName: \"pageview\", ...input }),\n eventName: \"pageview\",\n };\n}\n\nexport function sanitizeProfile(profile: IdentifyProfile): IdentifyProfile | null {\n const profileId = normalizeProfileId(profile.profileId);\n if (!profileId) return null;\n\n const result: IdentifyProfile = { profileId };\n if (profile.email?.trim()) result.email = profile.email.trim().slice(0, 320);\n if (profile.firstName?.trim()) result.firstName = profile.firstName.trim().slice(0, 200);\n if (profile.lastName?.trim()) result.lastName = profile.lastName.trim().slice(0, 200);\n if (profile.properties) {\n const properties = toJsonValue(profile.properties);\n if (\n properties &&\n typeof properties === \"object\" &&\n !Array.isArray(properties) &&\n JSON.stringify(properties).length <= 32_768\n ) {\n result.properties = properties;\n }\n }\n return result;\n}\n","import type {\n AttributionTestEnvelopeInput,\n AttributionTestEnvelopes,\n IdentifyData,\n SdkEnvelope,\n TouchpointData,\n} from \"./types\";\n\nexport type {\n AttributionTestClickIdType,\n AttributionTestEnvelopeInput,\n AttributionTestEnvelopes,\n} from \"./types\";\nimport {\n captureTouchpoint,\n isUuid,\n normalizeProfileId,\n nowIso,\n randomId,\n safePageUrl,\n} from \"./utils\";\n\nconst CLICK_ID_TYPES = new Set([\"gclid\", \"gbraid\", \"wbraid\"]);\n\nfunction envelope<TType extends string, TData>(\n projectKey: string,\n anonymousId: string,\n type: TType,\n data: TData,\n sentAt: string,\n): SdkEnvelope<TType, TData> {\n return {\n schemaVersion: \"1.0\",\n type,\n requestId: randomId(\"req_test\"),\n sentAt,\n projectKey,\n anonymousId,\n data,\n };\n}\n\nexport function createAttributionTestEnvelopes(\n input: AttributionTestEnvelopeInput,\n): AttributionTestEnvelopes {\n const projectKey = input.projectKey.trim();\n const attributionRouteKey = input.attributionRouteKey.trim();\n const clickId = input.clickId.trim();\n const profileId = normalizeProfileId(input.profileId);\n if (!isUuid(projectKey)) {\n throw new Error(\"Attribution test requires a UUID project identifier.\");\n }\n if (!isUuid(attributionRouteKey)) {\n throw new Error(\"Attribution test requires a UUID attribution route identifier.\");\n }\n if (!profileId) {\n throw new Error(\n \"Attribution test profileId must be 1-255 characters without control characters.\",\n );\n }\n if (!CLICK_ID_TYPES.has(input.clickIdType) || !clickId || clickId.length > 2_048 || /\\s/.test(clickId)) {\n throw new Error(\"Attribution test requires one valid Google click ID.\");\n }\n\n const capturedAt = input.capturedAt ?? nowIso();\n const testUrl = new URL(input.pageUrl);\n const trackingKeys = new Set([\"ah_route\", \"gclid\", \"gbraid\", \"wbraid\"]);\n for (const key of [...testUrl.searchParams.keys()]) {\n if (trackingKeys.has(key.toLowerCase())) testUrl.searchParams.delete(key);\n }\n testUrl.searchParams.set(\"ah_route\", attributionRouteKey);\n testUrl.searchParams.set(input.clickIdType, clickId);\n const captured = captureTouchpoint(\n { href: testUrl.toString() } as Location,\n input.referrer ?? \"\",\n capturedAt,\n );\n const anonymousId = randomId(\"anon_test\");\n const sessionId = randomId(\"sess_test\");\n const touchpointData: TouchpointData = {\n ...captured,\n sessionId,\n locale: input.locale ?? null,\n timezone: input.timezone ?? null,\n };\n const identityData: IdentifyData = {\n profile: {\n profileId,\n properties: { source: \"adhub_attribution_test\" },\n },\n identifiedAt: capturedAt,\n pageUrl: safePageUrl(input.pageUrl),\n };\n\n return {\n touchpoint: envelope(projectKey, anonymousId, \"touchpoint.capture\", touchpointData, capturedAt),\n identity: envelope(projectKey, anonymousId, \"profile.identify\", identityData, capturedAt),\n };\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import { A as AttributionTestEnvelopeInput, a as AttributionTestEnvelopes } from './types-DMUJO8Kj.cjs';
2
+ export { b as AttributionTestClickIdType } from './types-DMUJO8Kj.cjs';
3
+
4
+ declare function createAttributionTestEnvelopes(input: AttributionTestEnvelopeInput): AttributionTestEnvelopes;
5
+
6
+ export { AttributionTestEnvelopeInput, AttributionTestEnvelopes, createAttributionTestEnvelopes };
@@ -0,0 +1,6 @@
1
+ import { A as AttributionTestEnvelopeInput, a as AttributionTestEnvelopes } from './types-DMUJO8Kj.js';
2
+ export { b as AttributionTestClickIdType } from './types-DMUJO8Kj.js';
3
+
4
+ declare function createAttributionTestEnvelopes(input: AttributionTestEnvelopeInput): AttributionTestEnvelopes;
5
+
6
+ export { AttributionTestEnvelopeInput, AttributionTestEnvelopes, createAttributionTestEnvelopes };
@@ -0,0 +1,72 @@
1
+ import { normalizeProfileId, isUuid, nowIso, captureTouchpoint, randomId, safePageUrl } from './chunk-NF56G46G.js';
2
+
3
+ // src/testing.ts
4
+ var CLICK_ID_TYPES = /* @__PURE__ */ new Set(["gclid", "gbraid", "wbraid"]);
5
+ function envelope(projectKey, anonymousId, type, data, sentAt) {
6
+ return {
7
+ schemaVersion: "1.0",
8
+ type,
9
+ requestId: randomId("req_test"),
10
+ sentAt,
11
+ projectKey,
12
+ anonymousId,
13
+ data
14
+ };
15
+ }
16
+ function createAttributionTestEnvelopes(input) {
17
+ const projectKey = input.projectKey.trim();
18
+ const attributionRouteKey = input.attributionRouteKey.trim();
19
+ const clickId = input.clickId.trim();
20
+ const profileId = normalizeProfileId(input.profileId);
21
+ if (!isUuid(projectKey)) {
22
+ throw new Error("Attribution test requires a UUID project identifier.");
23
+ }
24
+ if (!isUuid(attributionRouteKey)) {
25
+ throw new Error("Attribution test requires a UUID attribution route identifier.");
26
+ }
27
+ if (!profileId) {
28
+ throw new Error(
29
+ "Attribution test profileId must be 1-255 characters without control characters."
30
+ );
31
+ }
32
+ if (!CLICK_ID_TYPES.has(input.clickIdType) || !clickId || clickId.length > 2048 || /\s/.test(clickId)) {
33
+ throw new Error("Attribution test requires one valid Google click ID.");
34
+ }
35
+ const capturedAt = input.capturedAt ?? nowIso();
36
+ const testUrl = new URL(input.pageUrl);
37
+ const trackingKeys = /* @__PURE__ */ new Set(["ah_route", "gclid", "gbraid", "wbraid"]);
38
+ for (const key of [...testUrl.searchParams.keys()]) {
39
+ if (trackingKeys.has(key.toLowerCase())) testUrl.searchParams.delete(key);
40
+ }
41
+ testUrl.searchParams.set("ah_route", attributionRouteKey);
42
+ testUrl.searchParams.set(input.clickIdType, clickId);
43
+ const captured = captureTouchpoint(
44
+ { href: testUrl.toString() },
45
+ input.referrer ?? "",
46
+ capturedAt
47
+ );
48
+ const anonymousId = randomId("anon_test");
49
+ const sessionId = randomId("sess_test");
50
+ const touchpointData = {
51
+ ...captured,
52
+ sessionId,
53
+ locale: input.locale ?? null,
54
+ timezone: input.timezone ?? null
55
+ };
56
+ const identityData = {
57
+ profile: {
58
+ profileId,
59
+ properties: { source: "adhub_attribution_test" }
60
+ },
61
+ identifiedAt: capturedAt,
62
+ pageUrl: safePageUrl(input.pageUrl)
63
+ };
64
+ return {
65
+ touchpoint: envelope(projectKey, anonymousId, "touchpoint.capture", touchpointData, capturedAt),
66
+ identity: envelope(projectKey, anonymousId, "profile.identify", identityData, capturedAt)
67
+ };
68
+ }
69
+
70
+ export { createAttributionTestEnvelopes };
71
+ //# sourceMappingURL=testing.js.map
72
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/testing.ts"],"names":[],"mappings":";;;AAsBA,IAAM,iCAAiB,IAAI,GAAA,CAAI,CAAC,OAAA,EAAS,QAAA,EAAU,QAAQ,CAAC,CAAA;AAE5D,SAAS,QAAA,CACP,UAAA,EACA,WAAA,EACA,IAAA,EACA,MACA,MAAA,EAC2B;AAC3B,EAAA,OAAO;AAAA,IACL,aAAA,EAAe,KAAA;AAAA,IACf,IAAA;AAAA,IACA,SAAA,EAAW,SAAS,UAAU,CAAA;AAAA,IAC9B,MAAA;AAAA,IACA,UAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF;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I,WAAA,EAAa,CAAA,EAAG,OAAA,CAAQ,YAAA,CAAa,MAAA,CAAO,GAAG,CAAA;AAAA,EAC1E;AACA,EAAA,OAAA,CAAQ,YAAA,CAAa,GAAA,CAAI,UAAA,EAAY,mBAAmB,CAAA;AACxD,EAAA,OAAA,CAAQ,YAAA,CAAa,GAAA,CAAI,KAAA,CAAM,WAAA,EAAa,OAAO,CAAA;AACnD,EAAA,MAAM,QAAA,GAAW,iBAAA;AAAA,IACf,EAAE,IAAA,EAAM,OAAA,CAAQ,QAAA,EAAS,EAAE;AAAA,IAC3B,MAAM,QAAA,IAAY,EAAA;AAAA,IAClB;AAAA,GACF;AACA,EAAA,MAAM,WAAA,GAAc,SAAS,WAAW,CAAA;AACxC,EAAA,MAAM,SAAA,GAAY,SAAS,WAAW,CAAA;AACtC,EAAA,MAAM,cAAA,GAAiC;AAAA,IACrC,GAAG,QAAA;AAAA,IACH,SAAA;AAAA,IACA,MAAA,EAAQ,MAAM,MAAA,IAAU,IAAA;AAAA,IACxB,QAAA,EAAU,MAAM,QAAA,IAAY;AAAA,GAC9B;AACA,EAAA,MAAM,YAAA,GAA6B;AAAA,IACjC,OAAA,EAAS;AAAA,MACP,SAAA;AAAA,MACA,UAAA,EAAY,EAAE,MAAA,EAAQ,wBAAA;AAAyB,KACjD;AAAA,IACA,YAAA,EAAc,UAAA;AAAA,IACd,OAAA,EAAS,WAAA,CAAY,KAAA,CAAM,OAAO;AAAA,GACpC;AAEA,EAAA,OAAO;AAAA,IACL,YAAY,QAAA,CAAS,UAAA,EAAY,WAAA,EAAa,oBAAA,EAAsB,gBAAgB,UAAU,CAAA;AAAA,IAC9F,UAAU,QAAA,CAAS,UAAA,EAAY,WAAA,EAAa,kBAAA,EAAoB,cAAc,UAAU;AAAA,GAC1F;AACF","file":"testing.js","sourcesContent":["import type {\n AttributionTestEnvelopeInput,\n AttributionTestEnvelopes,\n IdentifyData,\n SdkEnvelope,\n TouchpointData,\n} from \"./types\";\n\nexport type {\n AttributionTestClickIdType,\n AttributionTestEnvelopeInput,\n AttributionTestEnvelopes,\n} from \"./types\";\nimport {\n captureTouchpoint,\n isUuid,\n normalizeProfileId,\n nowIso,\n randomId,\n safePageUrl,\n} from \"./utils\";\n\nconst CLICK_ID_TYPES = new Set([\"gclid\", \"gbraid\", \"wbraid\"]);\n\nfunction envelope<TType extends string, TData>(\n projectKey: string,\n anonymousId: string,\n type: TType,\n data: TData,\n sentAt: string,\n): SdkEnvelope<TType, TData> {\n return {\n schemaVersion: \"1.0\",\n type,\n requestId: randomId(\"req_test\"),\n sentAt,\n projectKey,\n anonymousId,\n data,\n };\n}\n\nexport function createAttributionTestEnvelopes(\n input: AttributionTestEnvelopeInput,\n): AttributionTestEnvelopes {\n const projectKey = input.projectKey.trim();\n const attributionRouteKey = input.attributionRouteKey.trim();\n const clickId = input.clickId.trim();\n const profileId = normalizeProfileId(input.profileId);\n if (!isUuid(projectKey)) {\n throw new Error(\"Attribution test requires a UUID project identifier.\");\n }\n if (!isUuid(attributionRouteKey)) {\n throw new Error(\"Attribution test requires a UUID attribution route identifier.\");\n }\n if (!profileId) {\n throw new Error(\n \"Attribution test profileId must be 1-255 characters without control characters.\",\n );\n }\n if (!CLICK_ID_TYPES.has(input.clickIdType) || !clickId || clickId.length > 2_048 || /\\s/.test(clickId)) {\n throw new Error(\"Attribution test requires one valid Google click ID.\");\n }\n\n const capturedAt = input.capturedAt ?? nowIso();\n const testUrl = new URL(input.pageUrl);\n const trackingKeys = new Set([\"ah_route\", \"gclid\", \"gbraid\", \"wbraid\"]);\n for (const key of [...testUrl.searchParams.keys()]) {\n if (trackingKeys.has(key.toLowerCase())) testUrl.searchParams.delete(key);\n }\n testUrl.searchParams.set(\"ah_route\", attributionRouteKey);\n testUrl.searchParams.set(input.clickIdType, clickId);\n const captured = captureTouchpoint(\n { href: testUrl.toString() } as Location,\n input.referrer ?? \"\",\n capturedAt,\n );\n const anonymousId = randomId(\"anon_test\");\n const sessionId = randomId(\"sess_test\");\n const touchpointData: TouchpointData = {\n ...captured,\n sessionId,\n locale: input.locale ?? null,\n timezone: input.timezone ?? null,\n };\n const identityData: IdentifyData = {\n profile: {\n profileId,\n properties: { source: \"adhub_attribution_test\" },\n },\n identifiedAt: capturedAt,\n pageUrl: safePageUrl(input.pageUrl),\n };\n\n return {\n touchpoint: envelope(projectKey, anonymousId, \"touchpoint.capture\", touchpointData, capturedAt),\n identity: envelope(projectKey, anonymousId, \"profile.identify\", identityData, capturedAt),\n };\n}\n"]}
@@ -0,0 +1,62 @@
1
+ type JsonPrimitive = string | number | boolean | null;
2
+ type JsonObject = {
3
+ [key: string]: JsonValue;
4
+ };
5
+ type JsonValue = JsonPrimitive | JsonValue[] | JsonObject;
6
+ interface ClickIdentifiers {
7
+ gclid: string[];
8
+ gbraid: string[];
9
+ wbraid: string[];
10
+ }
11
+ interface CapturedTouchpoint {
12
+ ahRoute: string | null;
13
+ clickIds: ClickIdentifiers;
14
+ utm: Record<string, string[]>;
15
+ landingUrl: string;
16
+ referrer: string | null;
17
+ clickTime: string;
18
+ }
19
+ interface SdkEnvelope<TType extends string, TData> {
20
+ schemaVersion: "1.0";
21
+ type: TType;
22
+ requestId: string;
23
+ sentAt: string;
24
+ projectKey: string;
25
+ anonymousId: string;
26
+ data: TData;
27
+ }
28
+ interface TouchpointData extends CapturedTouchpoint {
29
+ sessionId: string;
30
+ locale: string | null;
31
+ timezone: string | null;
32
+ }
33
+ interface IdentifyData {
34
+ profile: {
35
+ profileId: string;
36
+ email?: string;
37
+ firstName?: string;
38
+ lastName?: string;
39
+ properties?: JsonValue;
40
+ };
41
+ identifiedAt: string;
42
+ pageUrl: string;
43
+ }
44
+ type AttributionTestClickIdType = keyof ClickIdentifiers;
45
+ interface AttributionTestEnvelopeInput {
46
+ projectKey: string;
47
+ attributionRouteKey: string;
48
+ clickIdType: AttributionTestClickIdType;
49
+ clickId: string;
50
+ profileId: string;
51
+ pageUrl: string;
52
+ referrer?: string | null;
53
+ capturedAt?: string;
54
+ locale?: string | null;
55
+ timezone?: string | null;
56
+ }
57
+ interface AttributionTestEnvelopes {
58
+ touchpoint: SdkEnvelope<"touchpoint.capture", TouchpointData>;
59
+ identity: SdkEnvelope<"profile.identify", IdentifyData>;
60
+ }
61
+
62
+ export type { AttributionTestEnvelopeInput as A, JsonObject as J, AttributionTestEnvelopes as a, AttributionTestClickIdType as b };
@@ -0,0 +1,62 @@
1
+ type JsonPrimitive = string | number | boolean | null;
2
+ type JsonObject = {
3
+ [key: string]: JsonValue;
4
+ };
5
+ type JsonValue = JsonPrimitive | JsonValue[] | JsonObject;
6
+ interface ClickIdentifiers {
7
+ gclid: string[];
8
+ gbraid: string[];
9
+ wbraid: string[];
10
+ }
11
+ interface CapturedTouchpoint {
12
+ ahRoute: string | null;
13
+ clickIds: ClickIdentifiers;
14
+ utm: Record<string, string[]>;
15
+ landingUrl: string;
16
+ referrer: string | null;
17
+ clickTime: string;
18
+ }
19
+ interface SdkEnvelope<TType extends string, TData> {
20
+ schemaVersion: "1.0";
21
+ type: TType;
22
+ requestId: string;
23
+ sentAt: string;
24
+ projectKey: string;
25
+ anonymousId: string;
26
+ data: TData;
27
+ }
28
+ interface TouchpointData extends CapturedTouchpoint {
29
+ sessionId: string;
30
+ locale: string | null;
31
+ timezone: string | null;
32
+ }
33
+ interface IdentifyData {
34
+ profile: {
35
+ profileId: string;
36
+ email?: string;
37
+ firstName?: string;
38
+ lastName?: string;
39
+ properties?: JsonValue;
40
+ };
41
+ identifiedAt: string;
42
+ pageUrl: string;
43
+ }
44
+ type AttributionTestClickIdType = keyof ClickIdentifiers;
45
+ interface AttributionTestEnvelopeInput {
46
+ projectKey: string;
47
+ attributionRouteKey: string;
48
+ clickIdType: AttributionTestClickIdType;
49
+ clickId: string;
50
+ profileId: string;
51
+ pageUrl: string;
52
+ referrer?: string | null;
53
+ capturedAt?: string;
54
+ locale?: string | null;
55
+ timezone?: string | null;
56
+ }
57
+ interface AttributionTestEnvelopes {
58
+ touchpoint: SdkEnvelope<"touchpoint.capture", TouchpointData>;
59
+ identity: SdkEnvelope<"profile.identify", IdentifyData>;
60
+ }
61
+
62
+ export type { AttributionTestEnvelopeInput as A, JsonObject as J, AttributionTestEnvelopes as a, AttributionTestClickIdType as b };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adhub-so/adhub-nextjs-sdk",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "First-party attribution, identity, and event SDK for Next.js",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",