@fire-spark/analytics-server 0.0.0-stage → 0.25.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.
package/dist/index.js ADDED
@@ -0,0 +1,750 @@
1
+ import { a as stringifyJson, c as backoffDelay, d as resolveRetryPolicy, f as withProviderRetry, i as decimalText, l as postJson, o as AnalyticsServerConfigError, r as decimalNumber, s as DEFAULT_RETRY_POLICY, t as JsonNumber } from "./json-D5hsBi3M.js";
2
+ import { t as defineServerProvider } from "./provider-DIOneNqa.js";
3
+ import { HASHED_USER_WIRE_KEYS, MAX_ENVELOPE_EVENTS, SERVER_PROVIDER_IDS, SUPPORTED_CONTRACT_VERSIONS, SUPPORTED_CONTRACT_VERSIONS as SUPPORTED_CONTRACT_VERSIONS$1, buildTrackingEnvelope, hashUserData, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, sha256Hex, upgradeEnvelope, validateEnvelope, validateEnvelope as validateEnvelope$1 } from "@fire-spark/analytics";
4
+ //#region src/env.ts
5
+ const processEnv = () => {
6
+ return globalThis.process?.env ?? {};
7
+ };
8
+ /** `VERCEL_ENV` or `NODE_ENV` is `production`. */
9
+ const detectProduction = () => {
10
+ const env = processEnv();
11
+ return env.VERCEL_ENV === "production" || env.NODE_ENV === "production";
12
+ };
13
+ const defaultSleep = (ms, signal) => {
14
+ return new Promise((resolve) => {
15
+ if (signal.aborted || ms <= 0) {
16
+ resolve();
17
+ return;
18
+ }
19
+ const done = () => {
20
+ clearTimeout(timer);
21
+ signal.removeEventListener("abort", done);
22
+ resolve();
23
+ };
24
+ const timer = setTimeout(done, ms);
25
+ signal.addEventListener("abort", done, { once: true });
26
+ });
27
+ };
28
+ //#endregion
29
+ //#region src/redact.ts
30
+ const REDACTED = "[redacted]";
31
+ const EMAIL = /[^\s@"'<>]+@[^\s@"'<>]+/g;
32
+ const HEX_HASH = /\b[0-9a-fA-F]{32,}\b/g;
33
+ const META_TOKEN = /EAA[A-Za-z0-9]+/g;
34
+ const GOOGLE_TOKEN = /ya29\.[A-Za-z0-9._-]+/g;
35
+ const JWT = /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.?[A-Za-z0-9_-]*/g;
36
+ const PEM = /-----BEGIN [A-Z ]+-----[\s\S]*?(?:-----END [A-Z ]+-----|$)/g;
37
+ const QUERY = /\?[^\s"'<>]*/g;
38
+ const LONG_TOKEN = /\b[A-Za-z0-9_-]{40,}\b/g;
39
+ const IPV4$1 = /\b(?:\d{1,3}\.){3}\d{1,3}\b/g;
40
+ const MAX_MESSAGE = 300;
41
+ /**
42
+ * Last line of defense for issue text: strips emails, hashes, tokens,
43
+ * PEM keys, JWTs, IP addresses and query strings. Issue messages are
44
+ * fixed templates; this only catches what a template could not rule out.
45
+ */
46
+ const redactText = (text, secrets = []) => {
47
+ let next = text;
48
+ for (const secret of secrets) if (secret.length >= 4) next = next.split(secret).join(REDACTED);
49
+ next = next.replace(PEM, REDACTED).replace(JWT, REDACTED);
50
+ next = next.replace(GOOGLE_TOKEN, REDACTED);
51
+ next = next.replace(EMAIL, REDACTED).replace(META_TOKEN, REDACTED);
52
+ next = next.replace(HEX_HASH, REDACTED).replace(LONG_TOKEN, REDACTED);
53
+ next = next.replace(QUERY, "").replace(IPV4$1, REDACTED);
54
+ return next.slice(0, MAX_MESSAGE);
55
+ };
56
+ const SAFE_CODE = /^[A-Za-z0-9_.:-]{1,64}$/;
57
+ const safeCode = (code) => {
58
+ if (code === void 0 || typeof code === "number") return code;
59
+ return SAFE_CODE.test(code) ? code : void 0;
60
+ };
61
+ /** Issue safe to hand to `onIssue` (and from there to Sentry or logs). */
62
+ const redactIssue = (issue, secrets = []) => {
63
+ const message = redactText(issue.message, secrets);
64
+ const providerCode = safeCode(issue.providerCode);
65
+ const traceId = safeCode(issue.traceId);
66
+ const next = {
67
+ ...issue,
68
+ message,
69
+ providerCode,
70
+ traceId
71
+ };
72
+ if (next.providerCode === void 0) delete next.providerCode;
73
+ if (next.traceId === void 0) delete next.traceId;
74
+ return next;
75
+ };
76
+ //#endregion
77
+ //#region src/deliver.ts
78
+ /** Seconds an idempotency claim lasts: the ad platforms' 48 h dedup window. */
79
+ const IDEMPOTENCY_TTL_SECONDS = 172800;
80
+ const BUILTIN_IDS = new Set(SERVER_PROVIDER_IDS);
81
+ /** Thrown when `verifyEvent` itself fails: the request gets a `503`. */
82
+ var VerifyFailure = class extends Error {
83
+ constructor() {
84
+ super("verifyEvent failed");
85
+ this.name = "VerifyFailure";
86
+ }
87
+ };
88
+ const assertProviders = (providers) => {
89
+ if (!Array.isArray(providers) || providers.length === 0) throw new AnalyticsServerConfigError("PROVIDERS_REQUIRED", "analytics-server: providers needs at least one destination");
90
+ const ids = /* @__PURE__ */ new Set();
91
+ for (const provider of providers) {
92
+ if (ids.has(provider.id)) throw new AnalyticsServerConfigError("PROVIDER_DUPLICATED", `analytics-server: provider "${provider.id}" is listed twice`);
93
+ ids.add(provider.id);
94
+ }
95
+ return providers;
96
+ };
97
+ const createPipeline = (options) => {
98
+ const providers = assertProviders(options.providers);
99
+ const report = (issue) => {
100
+ try {
101
+ options.onIssue?.(redactIssue(issue));
102
+ } catch {}
103
+ };
104
+ const publish = (results) => {
105
+ try {
106
+ options.onResult?.(results);
107
+ } catch {}
108
+ };
109
+ const names = options.verifyEventNames ?? ["purchase"];
110
+ const fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
111
+ const p1 = {
112
+ providers,
113
+ verifyEvent: options.verifyEvent
114
+ };
115
+ const p2 = { allowUnverified: options.allowUnverifiedPurchases === true };
116
+ const p3 = {
117
+ verifyNames: new Set(names),
118
+ idempotency: options.idempotency
119
+ };
120
+ const p4 = { retry: resolveRetryPolicy(options.retry) };
121
+ const p5 = { isProduction: options.isProduction ?? detectProduction() };
122
+ const p6 = {
123
+ now: options.now ?? Date.now,
124
+ fetch: fetcher,
125
+ report,
126
+ publish
127
+ };
128
+ return {
129
+ ...p1,
130
+ ...p2,
131
+ ...p3,
132
+ ...p4,
133
+ ...p5,
134
+ ...p6
135
+ };
136
+ };
137
+ const isBuiltin = (id) => BUILTIN_IDS.has(id);
138
+ /** Built-ins get the events that list them; custom providers get all. */
139
+ const targets = (provider, event) => {
140
+ if (!isBuiltin(provider.id)) return true;
141
+ return event.providers.includes(provider.id);
142
+ };
143
+ const skippedFor = (pipeline, event, reason) => {
144
+ const b1 = {
145
+ eventIds: [event.event_id],
146
+ outcome: "skipped"
147
+ };
148
+ const b2 = {
149
+ reason,
150
+ retryable: false,
151
+ attempts: 0
152
+ };
153
+ return pipeline.providers.filter((provider) => targets(provider, event)).map((provider) => ({
154
+ provider: provider.id,
155
+ ...b1,
156
+ ...b2
157
+ }));
158
+ };
159
+ /** Event as the merchant's `verifyEvent` sees it: no request data. */
160
+ const contractEvent = (event) => {
161
+ const { ipAddress, userAgent, ...rest } = event;
162
+ return rest;
163
+ };
164
+ const warnUnconfigured = (pipeline, events) => {
165
+ const configured = new Set(pipeline.providers.map((provider) => provider.id));
166
+ const missing = /* @__PURE__ */ new Set();
167
+ for (const event of events) for (const id of event.providers) if (!configured.has(id)) missing.add(id);
168
+ for (const provider of missing) {
169
+ const p1 = `events list ${provider}, which this server does not send to`;
170
+ pipeline.report({
171
+ level: "warning",
172
+ source: "config",
173
+ provider,
174
+ message: p1
175
+ });
176
+ }
177
+ };
178
+ const verifyOne = async (pipeline, event, options) => {
179
+ const verifyEvent = pipeline.verifyEvent;
180
+ let result;
181
+ try {
182
+ result = await verifyEvent(contractEvent(event));
183
+ } catch {
184
+ throw new VerifyFailure();
185
+ }
186
+ const b1 = {
187
+ source: "verify",
188
+ eventIds: [event.event_id]
189
+ };
190
+ if (!result) {
191
+ const p1 = `verifyEvent rejected a ${event.name} event`;
192
+ pipeline.report({
193
+ ...b1,
194
+ level: "warning",
195
+ message: p1
196
+ });
197
+ return { reason: "verify_rejected" };
198
+ }
199
+ const clean = options.revalidate(result);
200
+ const same = clean?.event_id === event.event_id && clean.name === event.name;
201
+ if (!clean || !same) {
202
+ const p2 = `verifyEvent returned an invalid event or changed its event_id or name`;
203
+ pipeline.report({
204
+ ...b1,
205
+ level: "error",
206
+ message: p2
207
+ });
208
+ return { reason: "verify_rejected" };
209
+ }
210
+ const meta = {
211
+ ipAddress: event.ipAddress,
212
+ userAgent: event.userAgent
213
+ };
214
+ return { event: {
215
+ ...clean,
216
+ ...meta
217
+ } };
218
+ };
219
+ const claimOne = async (pipeline, event) => {
220
+ const store = pipeline.idempotency;
221
+ if (!store) return true;
222
+ try {
223
+ const key = `fs:${event.event_id}`;
224
+ return await store.claim(key, IDEMPOTENCY_TTL_SECONDS) !== false;
225
+ } catch {
226
+ pipeline.report({
227
+ level: "warning",
228
+ source: "idempotency",
229
+ message: "idempotency claim failed; the event is sent anyway",
230
+ eventIds: [event.event_id]
231
+ });
232
+ return true;
233
+ }
234
+ };
235
+ /**
236
+ * Consent, verification and idempotency, in that order. Throws
237
+ * `VerifyFailure` when `verifyEvent` throws, before anything is claimed.
238
+ */
239
+ const admitEvents = async (pipeline, events, options) => {
240
+ warnUnconfigured(pipeline, events);
241
+ const rejected = [];
242
+ const skipped = [];
243
+ const reject = (event, reason) => {
244
+ rejected.push({
245
+ event_id: event.event_id,
246
+ reason
247
+ });
248
+ const providerReason = reason;
249
+ skipped.push(...skippedFor(pipeline, event, providerReason));
250
+ };
251
+ const consented = events.filter((event) => {
252
+ if (event.consent.ads) return true;
253
+ reject(event, "consent_denied");
254
+ return false;
255
+ });
256
+ const needsVerify = (event) => {
257
+ return options.verify && pipeline.verifyNames.has(event.name);
258
+ };
259
+ const unverified = consented.filter((event) => {
260
+ if (!needsVerify(event) || pipeline.verifyEvent) return true;
261
+ if (pipeline.allowUnverified) return true;
262
+ reject(event, "verify_not_configured");
263
+ return false;
264
+ });
265
+ if (unverified.length < consented.length) pipeline.report({
266
+ level: "error",
267
+ source: "config",
268
+ message: `purchase events were rejected: configure verifyEvent or set allowUnverifiedPurchases`
269
+ });
270
+ const check = async (event) => {
271
+ return needsVerify(event) && !!pipeline.verifyEvent ? verifyOne(pipeline, event, options) : { event };
272
+ };
273
+ const checked = await Promise.all(unverified.map(check));
274
+ const verified = [];
275
+ unverified.forEach((event, index) => {
276
+ const outcome = checked[index] ?? { event };
277
+ if ("event" in outcome) verified.push(outcome.event);
278
+ else reject(event, outcome.reason);
279
+ });
280
+ const claims = await Promise.all(verified.map((e) => claimOne(pipeline, e)));
281
+ const deliverable = verified.filter((event, index) => {
282
+ if (claims[index]) return true;
283
+ skipped.push(...skippedFor(pipeline, event, "duplicate"));
284
+ return false;
285
+ });
286
+ return {
287
+ accepted: verified.map((event) => event.event_id),
288
+ rejected,
289
+ deliverable,
290
+ skipped
291
+ };
292
+ };
293
+ const chunk$1 = (items, size) => {
294
+ const step = Math.max(1, Math.floor(size));
295
+ const chunks = [];
296
+ for (let start = 0; start < items.length; start += step) chunks.push(items.slice(start, start + step));
297
+ return chunks;
298
+ };
299
+ const failedResult = (provider, events, reason) => {
300
+ const b1 = {
301
+ provider: provider.id,
302
+ eventIds: events.map((e) => e.event_id)
303
+ };
304
+ const b2 = {
305
+ outcome: "failed",
306
+ reason,
307
+ retryable: false
308
+ };
309
+ return {
310
+ ...b1,
311
+ ...b2,
312
+ attempts: 0
313
+ };
314
+ };
315
+ const reportFailure = (pipeline, result) => {
316
+ if (result.outcome !== "failed") return;
317
+ const auth = result.reason === "auth";
318
+ const p2 = `${`${result.provider} delivery failed: ${result.reason ?? "error"}`} after ${result.attempts} attempt(s)`;
319
+ const b1 = {
320
+ level: "error",
321
+ source: auth ? "auth" : "provider"
322
+ };
323
+ const b2 = {
324
+ provider: result.provider,
325
+ message: p2
326
+ };
327
+ const b3 = {
328
+ eventIds: result.eventIds,
329
+ providerCode: result.providerCode
330
+ };
331
+ const issue = {
332
+ ...b1,
333
+ ...b2,
334
+ ...b3,
335
+ traceId: result.traceId
336
+ };
337
+ pipeline.report(issue);
338
+ };
339
+ const runProvider = async (pipeline, provider, events) => {
340
+ const targeted = events.filter((event) => targets(provider, event));
341
+ if (targeted.length === 0) return [];
342
+ const signal = AbortSignal.timeout(pipeline.retry.totalBudgetMs);
343
+ const c1 = {
344
+ fetch: pipeline.fetch,
345
+ signal,
346
+ retry: pipeline.retry
347
+ };
348
+ const c2 = {
349
+ report: pipeline.report,
350
+ isProduction: pipeline.isProduction
351
+ };
352
+ const c3 = {
353
+ now: pipeline.now,
354
+ sleep: defaultSleep,
355
+ random: Math.random
356
+ };
357
+ const ctx = {
358
+ ...c1,
359
+ ...c2,
360
+ ...c3
361
+ };
362
+ let prepared;
363
+ try {
364
+ prepared = provider.prepare(targeted);
365
+ } catch {
366
+ const p1 = `${provider.id} prepare() threw; its events were not sent`;
367
+ pipeline.report({
368
+ level: "error",
369
+ source: "config",
370
+ provider: provider.id,
371
+ message: p1
372
+ });
373
+ return [failedResult(provider, targeted, "invalid_payload")];
374
+ }
375
+ const results = [...prepared.skipped];
376
+ for (const batch of chunk$1(prepared.ready, provider.maxBatchSize)) try {
377
+ results.push(await provider.send(batch, ctx));
378
+ } catch {
379
+ results.push(failedResult(provider, batch, "upstream_error"));
380
+ }
381
+ return results;
382
+ };
383
+ /**
384
+ * Sends to every provider in parallel. One provider failing never blocks
385
+ * another. Never throws; results go to `onResult`, failures to `onIssue`.
386
+ */
387
+ const deliverEvents = async (pipeline, events, skipped = []) => {
388
+ const runs = pipeline.providers.map((provider) => {
389
+ return runProvider(pipeline, provider, events);
390
+ });
391
+ const settled = await Promise.all(runs);
392
+ const results = [...skipped, ...settled.flat()];
393
+ results.forEach((result) => reportFailure(pipeline, result));
394
+ pipeline.publish(results);
395
+ return results;
396
+ };
397
+ //#endregion
398
+ //#region src/request.ts
399
+ const IPV4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
400
+ const IPV6 = /^[0-9A-Fa-f:.]{2,45}$/;
401
+ const PRINTABLE = /^[\x20-\x7E]+$/;
402
+ const MAX_USER_AGENT = 512;
403
+ const isIpv4 = (value) => {
404
+ const match = IPV4.exec(value);
405
+ if (!match) return false;
406
+ return match.slice(1).every((part) => part.length < 4 && +part <= 255);
407
+ };
408
+ /** IPv4 or IPv6 text, or `undefined`. */
409
+ const cleanIp = (value) => {
410
+ if (typeof value !== "string") return void 0;
411
+ const trimmed = value.trim();
412
+ if (isIpv4(trimmed)) return trimmed;
413
+ return IPV6.test(trimmed) && trimmed.includes(":") ? trimmed.toLowerCase() : void 0;
414
+ };
415
+ const cleanUserAgent = (value) => {
416
+ if (typeof value !== "string") return void 0;
417
+ const trimmed = value.trim().slice(0, MAX_USER_AGENT);
418
+ return PRINTABLE.test(trimmed) ? trimmed : void 0;
419
+ };
420
+ /** Only defined fields, each checked: a bad IP or UA is dropped. */
421
+ const cleanRequestMeta = (meta) => {
422
+ const clean = {};
423
+ const ipAddress = cleanIp(meta?.ipAddress);
424
+ const userAgent = cleanUserAgent(meta?.userAgent);
425
+ if (ipAddress) clean.ipAddress = ipAddress;
426
+ if (userAgent) clean.userAgent = userAgent;
427
+ return clean;
428
+ };
429
+ /**
430
+ * First `x-forwarded-for` entry, else `x-real-ip`, plus `user-agent`.
431
+ * On Vercel the platform sets `x-forwarded-for`; behind another proxy,
432
+ * pass `getRequestMeta` so a client-sent header is not trusted.
433
+ */
434
+ const defaultRequestMeta = (request) => {
435
+ return {
436
+ ipAddress: request.headers.get("x-forwarded-for")?.split(",")[0] ?? request.headers.get("x-real-ip") ?? void 0,
437
+ userAgent: request.headers.get("user-agent") ?? void 0
438
+ };
439
+ };
440
+ const safeUrl = (value) => {
441
+ try {
442
+ return new URL(value);
443
+ } catch {
444
+ return null;
445
+ }
446
+ };
447
+ /** `https://shop.example.com/` → `https://shop.example.com`. */
448
+ const parseAllowedOrigins = (origins) => {
449
+ if (!Array.isArray(origins) || origins.length === 0) throw new AnalyticsServerConfigError("ALLOWED_ORIGINS_REQUIRED", "createTrackingHandler: allowedOrigins needs at least one origin");
450
+ const parsed = /* @__PURE__ */ new Set();
451
+ for (const origin of origins) {
452
+ const url = typeof origin === "string" ? safeUrl(origin.trim()) : null;
453
+ const web = url?.protocol === "https:" || url?.protocol === "http:";
454
+ if (!url || !web) throw new AnalyticsServerConfigError("ALLOWED_ORIGIN_INVALID", `createTrackingHandler: every allowedOrigins entry must be an http(s) origin like https://shop.example.com`);
455
+ parsed.add(url.origin);
456
+ }
457
+ return parsed;
458
+ };
459
+ const normalizeOrigin = (value) => {
460
+ if (!value || value === "null") return void 0;
461
+ return safeUrl(value)?.origin;
462
+ };
463
+ /** `application/json`, with or without parameters. */
464
+ const isJsonContentType = (value) => {
465
+ return value?.split(";")[0]?.trim().toLowerCase() === "application/json";
466
+ };
467
+ /** The body as text, or `null` when it is larger than `maxBytes`. */
468
+ const readBodyLimited = async (request, maxBytes) => {
469
+ if (!request.body) return "";
470
+ const reader = request.body.getReader();
471
+ const chunks = [];
472
+ let size = 0;
473
+ for (;;) {
474
+ const { done, value } = await reader.read();
475
+ if (done) break;
476
+ size += value.byteLength;
477
+ if (size > maxBytes) {
478
+ await reader.cancel().catch(() => void 0);
479
+ return null;
480
+ }
481
+ chunks.push(value);
482
+ }
483
+ const bytes = new Uint8Array(size);
484
+ let offset = 0;
485
+ for (const chunk of chunks) {
486
+ bytes.set(chunk, offset);
487
+ offset += chunk.byteLength;
488
+ }
489
+ return new TextDecoder().decode(bytes);
490
+ };
491
+ //#endregion
492
+ //#region src/handler.ts
493
+ const DEFAULT_MAX_BODY_BYTES = 65536;
494
+ const CONTRACT_HEADER = "x-firespark-contract";
495
+ const SUPPORTED = [...SUPPORTED_CONTRACT_VERSIONS$1];
496
+ const CONTRACT_VERSION = /^\d{1,4}$/;
497
+ const json = (status, body, headers = {}) => {
498
+ const b1 = { "content-type": "application/json; charset=utf-8" };
499
+ const b2 = {
500
+ "cache-control": "no-store",
501
+ ...headers
502
+ };
503
+ return new Response(JSON.stringify(body), {
504
+ status,
505
+ headers: {
506
+ ...b1,
507
+ ...b2
508
+ }
509
+ });
510
+ };
511
+ const fail = (status, error) => {
512
+ return json(status, { error });
513
+ };
514
+ const unsupported = () => {
515
+ return json(422, {
516
+ error: "unsupported_contract_version",
517
+ supported: SUPPORTED
518
+ });
519
+ };
520
+ /** `X-FireSpark-Contract` is optional (`sendBeacon` cannot set it). */
521
+ const contractHeaderOk = (value) => {
522
+ if (value === null) return true;
523
+ const trimmed = value.trim();
524
+ if (!CONTRACT_VERSION.test(trimmed)) return false;
525
+ return SUPPORTED.includes(+trimmed);
526
+ };
527
+ const declaredTooLarge = (request, maxBytes) => {
528
+ const length = request.headers.get("content-length");
529
+ if (!length || !/^\d+$/.test(length.trim())) return false;
530
+ return +length.trim() > maxBytes;
531
+ };
532
+ /** `false` when there is no `waitUntil` or it threw: deliver inline. */
533
+ const keepAlive = (waitUntil, delivery) => {
534
+ if (!waitUntil) return false;
535
+ try {
536
+ waitUntil(delivery);
537
+ return true;
538
+ } catch {
539
+ return false;
540
+ }
541
+ };
542
+ /**
543
+ * `POST` handler for the relay endpoint (`serverSide.endpoint`), for any
544
+ * runtime with web `Request` / `Response` (Next.js route handlers, Hono,
545
+ * Workers). Answers `202` once the events are checked; provider delivery
546
+ * runs afterwards inside `waitUntil`, or before the response when there
547
+ * is no `waitUntil`.
548
+ */
549
+ const createTrackingHandler = (options) => {
550
+ const origins = parseAllowedOrigins(options.allowedOrigins);
551
+ const pipeline = createPipeline(options);
552
+ const maxBytes = options.maxBodyBytes ?? 65536;
553
+ const getMeta = options.getRequestMeta ?? defaultRequestMeta;
554
+ const local = options.allowLocalhost === true && !pipeline.isProduction;
555
+ const allowedOrigins = [...origins];
556
+ const providers = SERVER_PROVIDER_IDS;
557
+ const validation = () => {
558
+ return {
559
+ now: pipeline.now(),
560
+ allowedOrigins,
561
+ providers,
562
+ allowLocalhost: local
563
+ };
564
+ };
565
+ const revalidate = (event) => {
566
+ const b1 = {
567
+ v: 1,
568
+ sdk: {
569
+ name: "verifyEvent",
570
+ version: "1"
571
+ }
572
+ };
573
+ const b2 = {
574
+ sent_at: (/* @__PURE__ */ new Date()).toISOString(),
575
+ events: [event]
576
+ };
577
+ const result = validateEnvelope$1({
578
+ ...b1,
579
+ ...b2
580
+ }, validation());
581
+ return result.ok ? result.envelope.events[0] ?? null : null;
582
+ };
583
+ const handle = async (request) => {
584
+ if (request.method !== "POST") return json(405, { error: "method_not_allowed" }, { allow: "POST" });
585
+ if (!isJsonContentType(request.headers.get("content-type"))) return fail(415, "unsupported_media_type");
586
+ if (declaredTooLarge(request, maxBytes)) return fail(413, "payload_too_large");
587
+ const origin = normalizeOrigin(request.headers.get("origin"));
588
+ if (!origin || !origins.has(origin)) return fail(403, "origin_not_allowed");
589
+ if (!contractHeaderOk(request.headers.get("x-firespark-contract"))) return unsupported();
590
+ const body = await readBodyLimited(request, maxBytes);
591
+ if (body === null) return fail(413, "payload_too_large");
592
+ const result = validateEnvelope$1(body, validation());
593
+ if (!result.ok && result.error === "unsupported_contract_version") return unsupported();
594
+ if (!result.ok) return fail(400, result.error);
595
+ if (result.rejected.length > 0) {
596
+ const p1 = `${result.rejected.length} event(s) failed validation`;
597
+ const b1 = {
598
+ level: "warning",
599
+ source: "validation"
600
+ };
601
+ const ids = result.rejected.flatMap((item) => item.event_id ?? []);
602
+ pipeline.report({
603
+ ...b1,
604
+ message: p1,
605
+ eventIds: ids
606
+ });
607
+ }
608
+ const meta = cleanRequestMeta(getMeta(request));
609
+ const events = result.envelope.events.map((event) => ({
610
+ ...event,
611
+ ...meta
612
+ }));
613
+ const admission = await admitEvents(pipeline, events, {
614
+ verify: true,
615
+ revalidate
616
+ });
617
+ const b2 = [admission.deliverable, admission.skipped];
618
+ const delivery = deliverEvents(pipeline, ...b2);
619
+ if (!keepAlive(options.waitUntil, delivery)) await delivery;
620
+ const rejected = [...result.rejected, ...admission.rejected];
621
+ return json(202, {
622
+ accepted: admission.accepted,
623
+ rejected
624
+ });
625
+ };
626
+ return async (request) => {
627
+ try {
628
+ return await handle(request);
629
+ } catch (error) {
630
+ const verify = error instanceof VerifyFailure;
631
+ const source = verify ? "verify" : "config";
632
+ const message = `${verify ? "verifyEvent threw" : "tracking handler failed"}; answered 503 so the client retries`;
633
+ pipeline.report({
634
+ level: "error",
635
+ source,
636
+ message
637
+ });
638
+ return fail(503, "internal_error");
639
+ }
640
+ };
641
+ };
642
+ //#endregion
643
+ //#region src/tracker.ts
644
+ /** Raw `email`, `phone`, names and `externalId` → wire hashes. */
645
+ const hashedUserOf = async (input, defaultCountry) => {
646
+ const { email, phone, firstName, lastName, externalId, ...wire } = input.user;
647
+ const hashed = await hashUserData({
648
+ email,
649
+ phone,
650
+ firstName,
651
+ lastName,
652
+ externalId,
653
+ countryCode: wire.country_code
654
+ }, { defaultCountry });
655
+ const user = { ...wire };
656
+ for (const [key, wireKey] of Object.entries(HASHED_USER_WIRE_KEYS)) {
657
+ const value = hashed[key];
658
+ if (value) user[wireKey] = value;
659
+ }
660
+ if (hashed.countryCode) user.country_code = hashed.countryCode;
661
+ return user;
662
+ };
663
+ const chunk = (items, size) => {
664
+ const chunks = [];
665
+ for (let start = 0; start < items.length; start += size) chunks.push(items.slice(start, start + size));
666
+ return chunks;
667
+ };
668
+ /**
669
+ * Sends events built on your server (an order webhook, a back-office
670
+ * action) through the same providers. Raw personal data in `user` is
671
+ * hashed here and never sent. These events are trusted, so `verifyEvent`
672
+ * does not run; consent and idempotency still apply.
673
+ */
674
+ const createServerTracker = (options) => {
675
+ const pipeline = createPipeline(options);
676
+ const providers = SERVER_PROVIDER_IDS;
677
+ const allowLocalhost = !pipeline.isProduction;
678
+ const validate = (events) => {
679
+ const now = pipeline.now();
680
+ return validateEnvelope$1(buildTrackingEnvelope(events, { now }), {
681
+ now,
682
+ providers,
683
+ allowLocalhost
684
+ });
685
+ };
686
+ const revalidate = (event) => {
687
+ const result = validate([event]);
688
+ return result.ok ? result.envelope.events[0] ?? null : null;
689
+ };
690
+ const track = async (inputs, meta) => {
691
+ const country = options.defaultCountry;
692
+ const rejected = [];
693
+ const valid = [];
694
+ const hashOne = async (input) => {
695
+ const user = await hashedUserOf(input, country);
696
+ return {
697
+ ...input,
698
+ user
699
+ };
700
+ };
701
+ const hashed = await Promise.all(inputs.map(hashOne));
702
+ for (const group of chunk(hashed, MAX_ENVELOPE_EVENTS)) {
703
+ const result = validate(group);
704
+ if (!result.ok) {
705
+ const reason = "invalid_event";
706
+ group.map((event) => event.event_id).forEach((event_id) => rejected.push({
707
+ event_id,
708
+ reason
709
+ }));
710
+ continue;
711
+ }
712
+ valid.push(...result.envelope.events);
713
+ rejected.push(...result.rejected);
714
+ }
715
+ if (rejected.length > 0) {
716
+ const p1 = `${rejected.length} server event(s) failed validation`;
717
+ const b1 = {
718
+ level: "warning",
719
+ source: "validation"
720
+ };
721
+ const ids = rejected.flatMap((item) => item.event_id ?? []);
722
+ pipeline.report({
723
+ ...b1,
724
+ message: p1,
725
+ eventIds: ids
726
+ });
727
+ }
728
+ const clean = cleanRequestMeta(meta);
729
+ const withMeta = (event) => ({
730
+ ...event,
731
+ ...clean
732
+ });
733
+ const events = valid.map(withMeta);
734
+ const admission = await admitEvents(pipeline, events, {
735
+ verify: false,
736
+ revalidate
737
+ });
738
+ const b2 = [admission.deliverable, admission.skipped];
739
+ const results = await deliverEvents(pipeline, ...b2);
740
+ rejected.push(...admission.rejected);
741
+ return {
742
+ accepted: admission.accepted,
743
+ rejected,
744
+ results
745
+ };
746
+ };
747
+ return { track };
748
+ };
749
+ //#endregion
750
+ export { AnalyticsServerConfigError, CONTRACT_HEADER, DEFAULT_MAX_BODY_BYTES, DEFAULT_RETRY_POLICY, IDEMPOTENCY_TTL_SECONDS, JsonNumber, SUPPORTED_CONTRACT_VERSIONS, backoffDelay, cleanIp, cleanUserAgent, createServerTracker, createTrackingHandler, decimalNumber, decimalText, defaultRequestMeta, defineServerProvider, normalizeEmail, normalizeEmailForGoogle, normalizePhoneE164, phoneDigits, postJson, redactText, sha256Hex, stringifyJson, upgradeEnvelope, validateEnvelope, withProviderRetry };