@fire-spark/analytics-server 0.0.0-stage → 0.26.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/google.js ADDED
@@ -0,0 +1,653 @@
1
+ import { a as stringifyJson, f as withProviderRetry, l as postJson, n as compact, o as AnalyticsServerConfigError, r as decimalNumber, t as JsonNumber, u as readBody } from "./json-D5hsBi3M.js";
2
+ import { Big } from "big.js";
3
+ //#region src/google-auth.ts
4
+ const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token";
5
+ /** The only scope requested: Data Manager, nothing else in the account. */
6
+ const DATA_MANAGER_SCOPE = "https://www.googleapis.com/auth/datamanager";
7
+ /** A cached token is refreshed this long before Google says it expires. */
8
+ const TOKEN_REFRESH_MARGIN_MS = 3e5;
9
+ const PROVIDER$1 = "google-ads";
10
+ const JWT_GRANT = "urn:ietf:params:oauth:grant-type:jwt-bearer";
11
+ const ASSERTION_SECONDS = 3600;
12
+ const PEM_BODY = /-----BEGIN PRIVATE KEY-----([A-Za-z0-9+/=\s]+)-----END/;
13
+ const SAFE_ERROR = /^[a-z_]{1,64}$/;
14
+ const RSA = {
15
+ name: "RSASSA-PKCS1-v1_5",
16
+ hash: "SHA-256"
17
+ };
18
+ const HEADER = {
19
+ alg: "RS256",
20
+ typ: "JWT"
21
+ };
22
+ /** Escaped `\n` from an environment variable become real newlines. */
23
+ const normalizePrivateKey = (value) => {
24
+ return value.replace(/\\n/g, "\n").trim();
25
+ };
26
+ /** DER bytes of a PEM PKCS#8 key, or `null` when it is not one. */
27
+ const pkcs8Der = (pem) => {
28
+ const match = PEM_BODY.exec(pem);
29
+ if (!match) return null;
30
+ const base64 = (match[1] ?? "").replace(/\s+/g, "");
31
+ try {
32
+ const binary = atob(base64);
33
+ if (binary.length === 0) return null;
34
+ const bytes = new Uint8Array(new ArrayBuffer(binary.length));
35
+ for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
36
+ return bytes;
37
+ } catch {
38
+ return null;
39
+ }
40
+ };
41
+ const base64Url = (bytes) => {
42
+ let binary = "";
43
+ for (const byte of bytes) binary += String.fromCharCode(byte);
44
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
45
+ };
46
+ const encoder = new TextEncoder();
47
+ const encodeJson = (value) => {
48
+ return base64Url(encoder.encode(JSON.stringify(value)));
49
+ };
50
+ const failed = (reason, retryable) => {
51
+ return {
52
+ outcome: "failed",
53
+ reason,
54
+ retryable
55
+ };
56
+ };
57
+ const recordOf$1 = (value) => {
58
+ return !!value && typeof value === "object" && !Array.isArray(value) ? value : {};
59
+ };
60
+ /** OAuth `error` (`invalid_grant`) as a code; never its description. */
61
+ const errorCodeOf = (body) => {
62
+ const code = body.error;
63
+ return typeof code === "string" && SAFE_ERROR.test(code) ? code : void 0;
64
+ };
65
+ /** Token endpoint reply → token and lifetime, or an attempt outcome. */
66
+ const classifyTokenReply = (reply) => {
67
+ const body = recordOf$1(reply.body);
68
+ const token = body.access_token;
69
+ const seconds = body.expires_in;
70
+ if (reply.status === 200) {
71
+ if (typeof token === "string" && token.length > 0 && typeof seconds === "number" && seconds > 0) return {
72
+ token,
73
+ expiresInMs: seconds * 1e3
74
+ };
75
+ return { outcome: failed("upstream_error", true) };
76
+ }
77
+ const b1 = {
78
+ httpStatus: reply.status,
79
+ providerCode: errorCodeOf(body)
80
+ };
81
+ if (reply.status === 429) return { outcome: {
82
+ ...failed("rate_limited", true),
83
+ ...b1
84
+ } };
85
+ if (reply.status >= 500) return { outcome: {
86
+ ...failed("upstream_error", true),
87
+ ...b1
88
+ } };
89
+ return { outcome: {
90
+ ...failed("auth", false),
91
+ ...b1
92
+ } };
93
+ };
94
+ const importKey = async (privateKey) => {
95
+ const der = pkcs8Der(privateKey);
96
+ if (!der) return null;
97
+ try {
98
+ const p1 = [
99
+ "pkcs8",
100
+ der,
101
+ RSA,
102
+ false,
103
+ ["sign"]
104
+ ];
105
+ return await crypto.subtle.importKey(...p1);
106
+ } catch {
107
+ return null;
108
+ }
109
+ };
110
+ /**
111
+ * OAuth 2.0 service account flow: a signed RS256 JWT is exchanged for an
112
+ * access token with the Data Manager scope only. The token is cached
113
+ * until five minutes before it expires, and concurrent callers share one
114
+ * request. The key, the assertion and the token are never logged.
115
+ */
116
+ const googleTokenSource = (credentials) => {
117
+ let keyPromise;
118
+ let cached;
119
+ let pending;
120
+ const assertionOf = async (key, nowMs) => {
121
+ const iat = Math.floor(nowMs / 1e3);
122
+ const c1 = {
123
+ iss: credentials.clientEmail,
124
+ scope: DATA_MANAGER_SCOPE
125
+ };
126
+ const c2 = {
127
+ aud: GOOGLE_TOKEN_URL,
128
+ iat,
129
+ exp: iat + ASSERTION_SECONDS
130
+ };
131
+ const unsigned = `${encodeJson(HEADER)}.${encodeJson({
132
+ ...c1,
133
+ ...c2
134
+ })}`;
135
+ const data = encoder.encode(unsigned);
136
+ const signature = await crypto.subtle.sign(RSA.name, key, data);
137
+ return `${unsigned}.${base64Url(new Uint8Array(signature))}`;
138
+ };
139
+ const request = async (ctx, signal) => {
140
+ keyPromise ??= importKey(credentials.privateKey);
141
+ const key = await keyPromise;
142
+ if (!key) {
143
+ const p1 = "googleDataManager: privateKey could not be imported";
144
+ const b1 = {
145
+ level: "error",
146
+ source: "config"
147
+ };
148
+ const b2 = { providerCode: "GOOGLE_PRIVATE_KEY_INVALID" };
149
+ ctx.report({
150
+ ...b1,
151
+ provider: PROVIDER$1,
152
+ message: p1,
153
+ ...b2
154
+ });
155
+ return { outcome: failed("auth", false) };
156
+ }
157
+ const startedAt = ctx.now();
158
+ const assertion = await assertionOf(key, startedAt);
159
+ const init = {
160
+ method: "POST",
161
+ headers: { "content-type": "application/x-www-form-urlencoded" },
162
+ body: new URLSearchParams({
163
+ grant_type: JWT_GRANT,
164
+ assertion
165
+ }).toString(),
166
+ signal
167
+ };
168
+ const response = await ctx.fetch(GOOGLE_TOKEN_URL, init);
169
+ const reply = {
170
+ status: response.status,
171
+ body: await readBody(response)
172
+ };
173
+ const result = classifyTokenReply(reply);
174
+ if ("outcome" in result) return result;
175
+ const expiresAt = startedAt + result.expiresInMs;
176
+ cached = {
177
+ token: result.token,
178
+ expiresAt
179
+ };
180
+ return { token: result.token };
181
+ };
182
+ const cachedToken = (nowMs) => {
183
+ if (!cached || nowMs >= cached.expiresAt - 3e5) return;
184
+ return cached.token;
185
+ };
186
+ const get = (ctx, signal) => {
187
+ const token = cachedToken(ctx.now());
188
+ if (token) return Promise.resolve({ token });
189
+ pending ??= request(ctx, signal).finally(() => {
190
+ pending = void 0;
191
+ });
192
+ return pending;
193
+ };
194
+ const invalidate = () => {
195
+ cached = void 0;
196
+ };
197
+ return {
198
+ get,
199
+ invalidate
200
+ };
201
+ };
202
+ //#endregion
203
+ //#region src/google.ts
204
+ const PROVIDER = "google-ads";
205
+ const INGEST_URL = "https://datamanager.googleapis.com/v1/events:ingest";
206
+ /** Data Manager limits: 2000 events and 10 destinations per request. */
207
+ const MAX_BATCH = 2e3;
208
+ const MAX_DESTINATIONS = 10;
209
+ const CUSTOMER_ID = /^\d{10}$/;
210
+ const ACTION_ID = /^\d{1,20}$/;
211
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
212
+ const SAFE_STATUS = /^[A-Z_]{1,64}$/;
213
+ const TRUE_VALUES = /* @__PURE__ */ new Set([
214
+ "1",
215
+ "true",
216
+ "yes"
217
+ ]);
218
+ /** Server-only variables `googleDataManagerFromEnv` reads. */
219
+ const GOOGLE_DATA_MANAGER_ENV_VARS = {
220
+ serviceAccountJson: "FIRESPARK_GOOGLE_DATA_MANAGER_SERVICE_ACCOUNT_JSON",
221
+ clientEmail: "FIRESPARK_GOOGLE_DATA_MANAGER_CLIENT_EMAIL",
222
+ privateKey: "FIRESPARK_GOOGLE_DATA_MANAGER_PRIVATE_KEY",
223
+ customerId: "FIRESPARK_GOOGLE_ADS_CUSTOMER_ID",
224
+ loginCustomerId: "FIRESPARK_GOOGLE_ADS_LOGIN_CUSTOMER_ID",
225
+ conversionActions: "FIRESPARK_GOOGLE_ADS_CONVERSION_ACTIONS",
226
+ validateOnly: "FIRESPARK_GOOGLE_DATA_MANAGER_VALIDATE_ONLY"
227
+ };
228
+ const configError = (code, text) => {
229
+ return new AnalyticsServerConfigError(code, `googleDataManager: ${text}`);
230
+ };
231
+ const consentOf = (granted) => {
232
+ return granted ? "CONSENT_GRANTED" : "CONSENT_DENIED";
233
+ };
234
+ const consentFor = (event) => {
235
+ const { ads, ad_user_data: userData } = event.consent;
236
+ const personalization = event.consent.ad_personalization ?? ads;
237
+ return {
238
+ ad_user_data: consentOf(userData ?? ads),
239
+ ad_personalization: consentOf(personalization)
240
+ };
241
+ };
242
+ /** Hashed e-mail and E.164 phone, only with `ad_user_data` consent. */
243
+ const userIdentifiersOf = (event) => {
244
+ if ((event.consent.ad_user_data ?? event.consent.ads) === false) return [];
245
+ const { user } = event;
246
+ const email = user.email_google_sha256 ?? user.email_sha256;
247
+ const b1 = email ? [{ email_address: email }] : [];
248
+ const phone = user.phone_e164_sha256;
249
+ const b2 = phone ? [{ phone_number: phone }] : [];
250
+ return [...b1, ...b2];
251
+ };
252
+ const adIdentifiersOf = (event) => {
253
+ const { gclid, gbraid, wbraid } = event.click_ids;
254
+ const session = event.click_ids.google_session_attributes;
255
+ return compact({
256
+ gclid,
257
+ gbraid,
258
+ wbraid,
259
+ session_attributes: session
260
+ });
261
+ };
262
+ const deviceOf = (event) => {
263
+ return compact({
264
+ user_agent: event.userAgent,
265
+ ip_address: event.ipAddress
266
+ });
267
+ };
268
+ /** Whole-unit quantity as written; `null` when it has a fraction. */
269
+ const quantityOf = (quantity) => {
270
+ try {
271
+ const amount = new Big(quantity);
272
+ return amount.mod(1).eq(0) ? new JsonNumber(amount.toFixed()) : null;
273
+ } catch {
274
+ return null;
275
+ }
276
+ };
277
+ /**
278
+ * `cart_data.items`. Google's `quantity` is an integer, so a fractional
279
+ * quantity (for example `"1.5"` kg) drops the whole cart rather than
280
+ * rounding it; `conversion_value` still carries the exact total.
281
+ */
282
+ const cartDataOf = (event) => {
283
+ const items = event.items ?? [];
284
+ const mapped = [];
285
+ for (const item of items) {
286
+ const quantity = item.quantity ? quantityOf(item.quantity) : void 0;
287
+ if (quantity === null) return void 0;
288
+ const b1 = {
289
+ merchant_product_id: item.id,
290
+ quantity
291
+ };
292
+ mapped.push(compact({
293
+ ...b1,
294
+ unit_price: decimalNumber(item.price)
295
+ }));
296
+ }
297
+ return mapped.length > 0 ? { items: mapped } : void 0;
298
+ };
299
+ /**
300
+ * One Data Manager event for a conversion action. `transaction_id` is the
301
+ * order id (what the Google tag sends, so Google deduplicates), else the
302
+ * Fire Spark event id.
303
+ */
304
+ const googleEventOf = (event, actionId) => {
305
+ const identifiers = userIdentifiersOf(event);
306
+ const e1 = { destination_references: [actionId] };
307
+ const e2 = { transaction_id: event.order_id ?? event.event_id };
308
+ const e3 = { event_timestamp: new Date(event.timestamp).toISOString() };
309
+ const e4 = {
310
+ event_source: "WEB",
311
+ currency: event.currency
312
+ };
313
+ const e5 = { conversion_value: decimalNumber(event.value) };
314
+ const e6 = { user_data: compact({ user_identifiers: identifiers }) };
315
+ const e7 = { ad_identifiers: adIdentifiersOf(event) };
316
+ const e8 = { event_device_info: deviceOf(event) };
317
+ const e9 = {
318
+ consent: consentFor(event),
319
+ cart_data: cartDataOf(event)
320
+ };
321
+ return compact({
322
+ ...e1,
323
+ ...e2,
324
+ ...e3,
325
+ ...e4,
326
+ ...e5,
327
+ ...e6,
328
+ ...e7,
329
+ ...e8,
330
+ ...e9
331
+ });
332
+ };
333
+ const accountOf = (accountId) => {
334
+ return {
335
+ account_type: "GOOGLE_ADS",
336
+ account_id: accountId
337
+ };
338
+ };
339
+ const destinationOf = (config, actionId) => {
340
+ const login = config.loginCustomerId;
341
+ const d1 = { reference: actionId };
342
+ const d2 = { operating_account: accountOf(config.customerId) };
343
+ const d3 = { login_account: login ? accountOf(login) : void 0 };
344
+ const d4 = { product_destination_id: actionId };
345
+ return compact({
346
+ ...d1,
347
+ ...d2,
348
+ ...d3,
349
+ ...d4
350
+ });
351
+ };
352
+ const recordOf = (value) => {
353
+ return !!value && typeof value === "object" && !Array.isArray(value) ? value : {};
354
+ };
355
+ const textOf = (value) => {
356
+ return typeof value === "string" && value ? value : void 0;
357
+ };
358
+ const statusRule = (httpStatus, status) => {
359
+ const retry = (reason) => ({
360
+ reason,
361
+ retry: true
362
+ });
363
+ const stop = (reason) => ({
364
+ reason,
365
+ retry: false
366
+ });
367
+ if (httpStatus === 429 || status === "RESOURCE_EXHAUSTED") return retry("rate_limited");
368
+ if (httpStatus === 401 || status === "UNAUTHENTICATED") return stop("auth");
369
+ if (httpStatus === 403 || status === "PERMISSION_DENIED") return stop("auth");
370
+ if (httpStatus === 408 || httpStatus === 409 || httpStatus >= 500) return retry("upstream_error");
371
+ return stop("invalid_payload");
372
+ };
373
+ /** Data Manager response → outcome. Google's error text is never kept. */
374
+ const classifyGoogleReply = (reply) => {
375
+ const body = recordOf(reply.body);
376
+ const error = recordOf(body.error);
377
+ const traceId = textOf(body.requestId) ?? textOf(body.request_id);
378
+ const base = {
379
+ httpStatus: reply.status,
380
+ traceId
381
+ };
382
+ if (reply.status >= 200 && reply.status < 300 && Object.keys(error).length === 0) return {
383
+ ...base,
384
+ outcome: "sent",
385
+ retryable: false
386
+ };
387
+ const status = textOf(error.status);
388
+ const providerCode = status && SAFE_STATUS.test(status) ? status : void 0;
389
+ const { reason, retry } = statusRule(reply.status, providerCode);
390
+ const b1 = {
391
+ outcome: "failed",
392
+ reason,
393
+ retryable: retry
394
+ };
395
+ return {
396
+ ...base,
397
+ ...b1,
398
+ providerCode
399
+ };
400
+ };
401
+ const digitsOf = (value) => {
402
+ return String(value ?? "").replace(/-/g, "").trim();
403
+ };
404
+ const actionsOf = (value) => {
405
+ const bad = () => {
406
+ return configError("GOOGLE_CONVERSION_ACTIONS_INVALID", `conversionActions must map event names to numeric conversion action ids (at most ${MAX_DESTINATIONS})`);
407
+ };
408
+ const record = recordOf(value);
409
+ const actions = /* @__PURE__ */ new Map();
410
+ for (const [name, id] of Object.entries(record)) {
411
+ const actionId = typeof id === "number" ? String(id) : id;
412
+ const valid = typeof actionId === "string" && ACTION_ID.test(actionId);
413
+ if (!name.trim() || !valid) throw bad();
414
+ actions.set(name.trim(), actionId);
415
+ }
416
+ const distinct = new Set(actions.values()).size;
417
+ if (actions.size === 0 || distinct > MAX_DESTINATIONS) throw bad();
418
+ return actions;
419
+ };
420
+ /** Checks the options; throws an `AnalyticsServerConfigError`. */
421
+ const resolveConfig = (options) => {
422
+ const clientEmail = String(options?.clientEmail ?? "").trim();
423
+ const rawKey = String(options?.privateKey ?? "");
424
+ if (!clientEmail || !rawKey.trim()) throw configError("GOOGLE_CREDENTIALS_REQUIRED", "clientEmail and privateKey are required");
425
+ if (!EMAIL.test(clientEmail)) throw configError("GOOGLE_SERVICE_ACCOUNT_INVALID", "clientEmail must be the service account e-mail");
426
+ const privateKey = normalizePrivateKey(rawKey);
427
+ if (!pkcs8Der(privateKey)) throw configError("GOOGLE_PRIVATE_KEY_INVALID", "privateKey must be the PEM PKCS#8 key of the JSON key file");
428
+ const customerId = digitsOf(options.customerId);
429
+ if (!CUSTOMER_ID.test(customerId)) throw configError("GOOGLE_CUSTOMER_ID_INVALID", "customerId must be the 10-digit Google Ads customer id");
430
+ const login = options.loginCustomerId;
431
+ const loginCustomerId = login ? digitsOf(login) : void 0;
432
+ if (loginCustomerId !== void 0 && !CUSTOMER_ID.test(loginCustomerId)) throw configError("GOOGLE_LOGIN_CUSTOMER_ID_INVALID", "loginCustomerId must be the 10-digit manager account id");
433
+ return {
434
+ clientEmail,
435
+ privateKey,
436
+ customerId,
437
+ loginCustomerId,
438
+ actions: actionsOf(options.conversionActions)
439
+ };
440
+ };
441
+ const hasIdentifier = (event) => {
442
+ const ads = adIdentifiersOf(event);
443
+ return Object.keys(ads).length > 0 || userIdentifiersOf(event).length > 0;
444
+ };
445
+ const validateOnlyFor = (options, ctx) => {
446
+ if (!options.validateOnly) return false;
447
+ if (!ctx.isProduction || options.allowTestInProduction) return true;
448
+ const p1 = `${PROVIDER} validate_only ignored in production`;
449
+ ctx.report({
450
+ level: "warning",
451
+ source: "config",
452
+ provider: PROVIDER,
453
+ message: p1
454
+ });
455
+ return false;
456
+ };
457
+ /**
458
+ * Fail closed: nothing reaches Google, every event fails with
459
+ * `not_configured`, and a `config` error with the code is reported.
460
+ * Other providers in the same handler keep working.
461
+ */
462
+ const disabledProvider = (error) => {
463
+ const send = async (events, ctx) => {
464
+ const eventIds = events.map((event) => event.event_id);
465
+ const b1 = {
466
+ level: "error",
467
+ source: "config"
468
+ };
469
+ const b2 = {
470
+ message: error.message,
471
+ providerCode: error.code,
472
+ eventIds
473
+ };
474
+ ctx.report({
475
+ ...b1,
476
+ provider: PROVIDER,
477
+ ...b2
478
+ });
479
+ return {
480
+ provider: PROVIDER,
481
+ eventIds,
482
+ outcome: "failed",
483
+ reason: "not_configured",
484
+ retryable: false,
485
+ attempts: 0
486
+ };
487
+ };
488
+ const prepare = (events) => ({
489
+ ready: events,
490
+ skipped: []
491
+ });
492
+ return {
493
+ id: PROVIDER,
494
+ maxBatchSize: MAX_BATCH,
495
+ runtimes: ["web"],
496
+ prepare,
497
+ send
498
+ };
499
+ };
500
+ /**
501
+ * Google Data Manager destination (`events:ingest`) for Google Ads
502
+ * conversions. Authenticates as a service account with the Data Manager
503
+ * scope only. Invalid options never throw: the provider fails closed (see
504
+ * `disabledProvider`). The key and tokens are never logged.
505
+ */
506
+ const googleDataManager = (options) => {
507
+ let config;
508
+ try {
509
+ config = resolveConfig(options);
510
+ } catch (error) {
511
+ if (error instanceof AnalyticsServerConfigError) return disabledProvider(error);
512
+ return disabledProvider(configError("GOOGLE_CREDENTIALS_REQUIRED", "options could not be read"));
513
+ }
514
+ const { actions, clientEmail, privateKey } = config;
515
+ const tokens = googleTokenSource({
516
+ clientEmail,
517
+ privateKey
518
+ });
519
+ const prepare = (events) => {
520
+ const ready = [];
521
+ const skipped = [];
522
+ const skip = (event, reason) => {
523
+ const b1 = {
524
+ provider: PROVIDER,
525
+ eventIds: [event.event_id]
526
+ };
527
+ const b2 = {
528
+ outcome: "skipped",
529
+ reason,
530
+ retryable: false
531
+ };
532
+ skipped.push({
533
+ ...b1,
534
+ ...b2,
535
+ attempts: 0
536
+ });
537
+ };
538
+ for (const event of events) if (!actions.has(event.name)) skip(event, "not_mapped");
539
+ else if (!hasIdentifier(event)) skip(event, "no_identifier");
540
+ else ready.push(event);
541
+ return {
542
+ ready,
543
+ skipped
544
+ };
545
+ };
546
+ const send = async (events, ctx) => {
547
+ const actionOf = (event) => actions.get(event.name) ?? "";
548
+ const body = stringifyJson(compact({
549
+ destinations: [...new Set(events.map(actionOf))].map((id) => destinationOf(config, id)),
550
+ events: events.map((event) => googleEventOf(event, actionOf(event))),
551
+ encoding: "HEX",
552
+ validate_only: validateOnlyFor(options, ctx) || void 0
553
+ }));
554
+ let refreshed = false;
555
+ const final = await withProviderRetry(ctx, async (signal) => {
556
+ const auth = await tokens.get(ctx, signal);
557
+ if ("outcome" in auth) return auth.outcome;
558
+ const headers = { authorization: `Bearer ${auth.token}` };
559
+ const reply = await postJson(ctx, {
560
+ url: INGEST_URL,
561
+ body,
562
+ headers
563
+ }, signal);
564
+ const outcome = classifyGoogleReply(reply);
565
+ if (reply.status !== 401 || refreshed) return outcome;
566
+ refreshed = true;
567
+ tokens.invalidate();
568
+ return {
569
+ ...outcome,
570
+ retryable: true
571
+ };
572
+ });
573
+ const eventIds = events.map((event) => event.event_id);
574
+ return {
575
+ provider: PROVIDER,
576
+ eventIds,
577
+ ...final
578
+ };
579
+ };
580
+ return {
581
+ id: PROVIDER,
582
+ maxBatchSize: MAX_BATCH,
583
+ runtimes: ["web"],
584
+ prepare,
585
+ send
586
+ };
587
+ };
588
+ const parseJson = (text) => {
589
+ try {
590
+ return JSON.parse(text);
591
+ } catch {
592
+ return;
593
+ }
594
+ };
595
+ const credentialsFromEnv = (env) => {
596
+ const vars = GOOGLE_DATA_MANAGER_ENV_VARS;
597
+ const json = env[vars.serviceAccountJson]?.trim();
598
+ if (!json) return {
599
+ clientEmail: env[vars.clientEmail] ?? "",
600
+ privateKey: env[vars.privateKey] ?? ""
601
+ };
602
+ const key = recordOf(parseJson(json));
603
+ const clientEmail = key.client_email;
604
+ const privateKey = key.private_key;
605
+ if (!(typeof clientEmail === "string" && !!clientEmail) || typeof privateKey !== "string" || !privateKey) throw configError("GOOGLE_SERVICE_ACCOUNT_INVALID", `the service account JSON must have client_email and private_key`);
606
+ return {
607
+ clientEmail,
608
+ privateKey
609
+ };
610
+ };
611
+ const actionsFromEnv = (env) => {
612
+ const name = GOOGLE_DATA_MANAGER_ENV_VARS.conversionActions;
613
+ const text = env[name]?.trim();
614
+ if (!text) return {};
615
+ const parsed = parseJson(text);
616
+ if (Object.keys(recordOf(parsed)).length > 0) return recordOf(parsed);
617
+ const p1 = `${name} must be a JSON object like {"purchase":"987654321"}`;
618
+ throw configError("GOOGLE_CONVERSION_ACTIONS_INVALID", p1);
619
+ };
620
+ /** Options from the server-only variables in `GOOGLE_DATA_MANAGER_ENV_VARS`. */
621
+ const googleDataManagerOptionsFromEnv = (env) => {
622
+ const vars = GOOGLE_DATA_MANAGER_ENV_VARS;
623
+ const credentials = credentialsFromEnv(env);
624
+ const conversionActions = actionsFromEnv(env);
625
+ const customerId = env[vars.customerId] ?? "";
626
+ const loginCustomerId = env[vars.loginCustomerId]?.trim() || void 0;
627
+ const flag = env[vars.validateOnly]?.trim().toLowerCase() ?? "";
628
+ const o1 = {
629
+ customerId,
630
+ loginCustomerId,
631
+ conversionActions
632
+ };
633
+ return {
634
+ ...credentials,
635
+ ...o1,
636
+ validateOnly: TRUE_VALUES.has(flag)
637
+ };
638
+ };
639
+ /**
640
+ * `googleDataManager` configured from server-only environment variables
641
+ * (pass `process.env`, or the Worker `env`). Never throws: a missing or
642
+ * invalid variable makes the provider fail closed.
643
+ */
644
+ const googleDataManagerFromEnv = (env) => {
645
+ try {
646
+ return googleDataManager(googleDataManagerOptionsFromEnv(env));
647
+ } catch (error) {
648
+ if (error instanceof AnalyticsServerConfigError) return disabledProvider(error);
649
+ return disabledProvider(configError("GOOGLE_CREDENTIALS_REQUIRED", "environment variables could not be read"));
650
+ }
651
+ };
652
+ //#endregion
653
+ export { DATA_MANAGER_SCOPE, GOOGLE_DATA_MANAGER_ENV_VARS, GOOGLE_TOKEN_URL, TOKEN_REFRESH_MARGIN_MS, classifyGoogleReply, classifyTokenReply, googleDataManager, googleDataManagerFromEnv, googleDataManagerOptionsFromEnv, googleEventOf };