@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.
@@ -0,0 +1,183 @@
1
+ import { isDecimalString } from "@fire-spark/analytics";
2
+ //#region src/retry.ts
3
+ const DEFAULT_RETRY_POLICY = {
4
+ maxAttempts: 3,
5
+ baseDelayMs: 250,
6
+ maxDelayMs: 2e3,
7
+ totalBudgetMs: 8e3
8
+ };
9
+ const MAX_RESPONSE_CHARS = 65536;
10
+ const positive = (value, fallback) => {
11
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback;
12
+ };
13
+ const resolveRetryPolicy = (policy = {}) => {
14
+ const d = DEFAULT_RETRY_POLICY;
15
+ const attempts = positive(policy.maxAttempts, d.maxAttempts);
16
+ const r1 = { maxAttempts: Math.max(1, Math.floor(attempts)) };
17
+ const r2 = { baseDelayMs: positive(policy.baseDelayMs, d.baseDelayMs) };
18
+ const r3 = { maxDelayMs: positive(policy.maxDelayMs, d.maxDelayMs) };
19
+ const budget = positive(policy.totalBudgetMs, d.totalBudgetMs);
20
+ return {
21
+ ...r1,
22
+ ...r2,
23
+ ...r3,
24
+ totalBudgetMs: budget
25
+ };
26
+ };
27
+ /** Full jitter: random in [0, min(maxDelayMs, baseDelayMs · 2^attempt)). */
28
+ const backoffDelay = (policy, attempt, random) => {
29
+ const exponential = policy.baseDelayMs * 2 ** attempt;
30
+ const cap = Math.min(policy.maxDelayMs, exponential);
31
+ return Math.floor(random() * cap);
32
+ };
33
+ const timeoutOutcome = () => {
34
+ return {
35
+ outcome: "failed",
36
+ reason: "timeout",
37
+ retryable: true
38
+ };
39
+ };
40
+ const networkOutcome = () => {
41
+ return {
42
+ outcome: "failed",
43
+ reason: "upstream_error",
44
+ retryable: true
45
+ };
46
+ };
47
+ /**
48
+ * Runs `attempt` until it succeeds, fails for good, runs out of attempts,
49
+ * or the next wait would pass `totalBudgetMs`. A thrown error (network
50
+ * failure) counts as a retryable `upstream_error`; an abort as `timeout`.
51
+ */
52
+ const withProviderRetry = async (ctx, attempt) => {
53
+ const policy = ctx.retry;
54
+ const startedAt = ctx.now();
55
+ let last = timeoutOutcome();
56
+ for (let count = 1; count <= policy.maxAttempts; count += 1) {
57
+ if (ctx.signal.aborted) return {
58
+ ...timeoutOutcome(),
59
+ attempts: count - 1
60
+ };
61
+ const remaining = policy.totalBudgetMs - (ctx.now() - startedAt);
62
+ const b1 = [ctx.signal, AbortSignal.timeout(Math.max(1, remaining))];
63
+ const signal = AbortSignal.any(b1);
64
+ try {
65
+ last = await attempt(signal);
66
+ } catch {
67
+ last = signal.aborted ? timeoutOutcome() : networkOutcome();
68
+ }
69
+ if (last.outcome !== "failed" || !last.retryable || count === policy.maxAttempts) return {
70
+ ...last,
71
+ attempts: count
72
+ };
73
+ const delay = backoffDelay(policy, count - 1, ctx.random);
74
+ if (ctx.now() - startedAt + delay >= policy.totalBudgetMs) return {
75
+ ...last,
76
+ attempts: count
77
+ };
78
+ await ctx.sleep(delay, ctx.signal);
79
+ }
80
+ return {
81
+ ...last,
82
+ attempts: policy.maxAttempts
83
+ };
84
+ };
85
+ /** Parsed JSON body, or `null` when it is empty, too large or not JSON. */
86
+ const readBody = async (response) => {
87
+ const text = await response.text();
88
+ if (!text || text.length > MAX_RESPONSE_CHARS) return null;
89
+ try {
90
+ return JSON.parse(text);
91
+ } catch {
92
+ return null;
93
+ }
94
+ };
95
+ /** POSTs a JSON body. The body (and any token in it) is never logged. */
96
+ const postJson = async (ctx, request, signal) => {
97
+ const init = {
98
+ method: "POST",
99
+ headers: {
100
+ "content-type": "application/json",
101
+ ...request.headers
102
+ },
103
+ body: request.body,
104
+ signal
105
+ };
106
+ const response = await ctx.fetch(request.url, init);
107
+ return {
108
+ status: response.status,
109
+ body: await readBody(response)
110
+ };
111
+ };
112
+ //#endregion
113
+ //#region src/types.ts
114
+ /** Invalid setup, thrown when the handler or a provider is created. */
115
+ var AnalyticsServerConfigError = class extends Error {
116
+ code;
117
+ constructor(code, message) {
118
+ super(message);
119
+ this.name = "AnalyticsServerConfigError";
120
+ this.code = code;
121
+ }
122
+ };
123
+ //#endregion
124
+ //#region src/json.ts
125
+ /** A JSON number written exactly as its decimal string. */
126
+ var JsonNumber = class {
127
+ token;
128
+ constructor(token) {
129
+ this.token = token;
130
+ }
131
+ };
132
+ /** `"0012.50"` → `"12.50"`. Trailing zeros stay: they are not rounding. */
133
+ const canonical = (decimal) => {
134
+ const negative = decimal.startsWith("-");
135
+ const [whole, fraction] = (negative ? decimal.slice(1) : decimal).split(".");
136
+ const digits = (whole ?? "").replace(/^0+(?=\d)/, "");
137
+ const body = fraction === void 0 ? digits : `${digits}.${fraction}`;
138
+ const zero = /^0(\.0+)?$/.test(body);
139
+ return negative && !zero ? `-${body}` : body;
140
+ };
141
+ /**
142
+ * Money for a JSON number field: `"25.90"` is written as `25.90`, never
143
+ * `25.9`. Returns `undefined` for anything that is not a decimal string.
144
+ */
145
+ const decimalNumber = (value) => {
146
+ if (!isDecimalString(value)) return void 0;
147
+ return new JsonNumber(canonical(value));
148
+ };
149
+ /** Money for a JSON string field, with the same digits. */
150
+ const decimalText = (value) => {
151
+ return isDecimalString(value) ? canonical(value) : void 0;
152
+ };
153
+ const write = (value) => {
154
+ if (value instanceof JsonNumber) return value.token;
155
+ if (value === null) return "null";
156
+ if (Array.isArray(value)) return `[${value.map((item) => write(item) ?? "null").join(",")}]`;
157
+ if (typeof value === "object") {
158
+ const parts = [];
159
+ for (const [key, item] of Object.entries(value)) {
160
+ const encoded = write(item);
161
+ if (encoded !== void 0) parts.push(`${JSON.stringify(key)}:${encoded}`);
162
+ }
163
+ return `{${parts.join(",")}}`;
164
+ }
165
+ return JSON.stringify(value);
166
+ };
167
+ /** `JSON.stringify` that writes `JsonNumber` tokens as they are. */
168
+ const stringifyJson = (value) => write(value) ?? "null";
169
+ const isEmpty = (value) => {
170
+ if (value === void 0) return true;
171
+ if (Array.isArray(value)) return value.length === 0;
172
+ if (!value || typeof value !== "object") return false;
173
+ if (value instanceof JsonNumber) return false;
174
+ return Object.keys(value).length === 0;
175
+ };
176
+ /** Drops `undefined` fields and empty objects or arrays (one level). */
177
+ const compact = (record) => {
178
+ const next = {};
179
+ for (const [key, value] of Object.entries(record)) if (!isEmpty(value)) next[key] = value;
180
+ return next;
181
+ };
182
+ //#endregion
183
+ export { stringifyJson as a, backoffDelay as c, resolveRetryPolicy as d, withProviderRetry as f, decimalText as i, postJson as l, compact as n, AnalyticsServerConfigError as o, decimalNumber as r, DEFAULT_RETRY_POLICY as s, JsonNumber as t, readBody as u };
package/dist/meta.d.ts ADDED
@@ -0,0 +1,71 @@
1
+ import { C as ResolvedEvent, F as JsonNumber, O as ServerProvider, i as HttpReply, t as AttemptOutcome } from "./retry-CKgkb0DS.js";
2
+ //#region src/meta.types.d.ts
3
+ interface MetaDataProcessingOptions {
4
+ /** For example `["LDU"]` (Limited Data Use). */
5
+ options: string[];
6
+ /** `1` = United States; `0` lets Meta geolocate. */
7
+ country?: number;
8
+ /** For example `1000` = California; `0` lets Meta geolocate. */
9
+ state?: number;
10
+ }
11
+ interface MetaConversionsApiOptions {
12
+ /** Numeric pixel (dataset) id. */
13
+ pixelId: string;
14
+ /** System user token from Events Manager. Server only, never logged. */
15
+ accessToken: string;
16
+ /** Default `v27.0`. */
17
+ graphVersion?: `v${number}.0`;
18
+ /** Events Manager → Test Events. Dropped in production. */
19
+ testEventCode?: string;
20
+ /** Keeps `testEventCode` in production. */
21
+ allowTestInProduction?: boolean;
22
+ dataProcessingOptions?: MetaDataProcessingOptions;
23
+ }
24
+ //#endregion
25
+ //#region src/meta.d.ts
26
+ /** One Conversions API server event. `event_name` is the pixel's name. */
27
+ declare const metaEventOf: (event: ResolvedEvent, options: MetaConversionsApiOptions) => Promise<Partial<{
28
+ data_processing_options?: string[] | undefined;
29
+ data_processing_options_country?: number | undefined;
30
+ data_processing_options_state?: number | undefined;
31
+ event_name: string | null;
32
+ event_time: number;
33
+ event_id: string;
34
+ action_source: string;
35
+ event_source_url: string;
36
+ referrer_url: string | undefined;
37
+ user_data: Partial<{
38
+ em: string[] | undefined;
39
+ ph: string[] | undefined;
40
+ fn: string[] | undefined;
41
+ ln: string[] | undefined;
42
+ external_id: string[] | undefined;
43
+ country: string[] | undefined;
44
+ client_ip_address: string | undefined;
45
+ client_user_agent: string | undefined;
46
+ fbp: string | undefined;
47
+ fbc: string | undefined;
48
+ }>;
49
+ custom_data: Partial<{
50
+ currency: string | undefined;
51
+ value: string | undefined;
52
+ order_id: string | undefined;
53
+ content_type: string | undefined;
54
+ content_ids: string[];
55
+ contents: Partial<{
56
+ id: string;
57
+ quantity: JsonNumber | undefined;
58
+ item_price: JsonNumber | undefined;
59
+ }>[];
60
+ num_items: JsonNumber | undefined;
61
+ }>;
62
+ }>>;
63
+ /** Meta response → outcome, per the retry matrix. */
64
+ declare const classifyMetaReply: (reply: HttpReply, expected: number) => AttemptOutcome;
65
+ /**
66
+ * Meta Conversions API destination. The token travels in the JSON body,
67
+ * never in the URL, and is never logged.
68
+ */
69
+ declare const metaConversionsApi: (options: MetaConversionsApiOptions) => ServerProvider;
70
+ //#endregion
71
+ export { type MetaConversionsApiOptions, classifyMetaReply, metaConversionsApi, metaEventOf };
package/dist/meta.js ADDED
@@ -0,0 +1,252 @@
1
+ import { a as stringifyJson, f as withProviderRetry, i as decimalText, l as postJson, n as compact, o as AnalyticsServerConfigError, r as decimalNumber } from "./json-D5hsBi3M.js";
2
+ import { n as testCodeFor } from "./provider-DIOneNqa.js";
3
+ import { providerEventName, sha256Hex } from "@fire-spark/analytics";
4
+ import { Big } from "big.js";
5
+ //#region src/meta.ts
6
+ const PROVIDER = "meta";
7
+ const DEFAULT_GRAPH_VERSION = "v27.0";
8
+ const MAX_BATCH = 1e3;
9
+ const PIXEL_ID = /^\d{1,32}$/;
10
+ const GRAPH_VERSION = /^v\d{1,3}\.0$/;
11
+ /** Graph errors worth retrying: 1, 2 unknown/service; 4, 17, 32, 613 limits. */
12
+ const RATE_LIMIT_CODES = /* @__PURE__ */ new Set([
13
+ 4,
14
+ 17,
15
+ 32,
16
+ 613
17
+ ]);
18
+ const TRANSIENT_CODES = /* @__PURE__ */ new Set([1, 2]);
19
+ const ZERO = new Big(0);
20
+ const list = (value) => value ? [value] : void 0;
21
+ const contentsOf = (event) => {
22
+ return (event.items ?? []).map((item) => {
23
+ return compact({
24
+ id: item.id,
25
+ quantity: decimalNumber(item.quantity),
26
+ item_price: decimalNumber(item.price)
27
+ });
28
+ });
29
+ };
30
+ /** Sum of item quantities (an item without one counts as 1), unrounded. */
31
+ const numItemsOf = (event) => {
32
+ const items = event.items ?? [];
33
+ if (items.length === 0) return void 0;
34
+ const add = (sum, quantity) => sum.plus(quantity ?? "1");
35
+ return decimalNumber(items.reduce((sum, item) => add(sum, item.quantity), ZERO).toFixed());
36
+ };
37
+ const customDataOf = (event) => {
38
+ const items = event.items ?? [];
39
+ const priced = items.length > 0;
40
+ const c1 = {
41
+ currency: event.currency,
42
+ value: decimalText(event.value)
43
+ };
44
+ const c2 = { order_id: event.order_id };
45
+ const c3 = { content_type: priced ? "product" : void 0 };
46
+ const c4 = { content_ids: items.map((item) => item.id) };
47
+ const c5 = {
48
+ contents: contentsOf(event),
49
+ num_items: numItemsOf(event)
50
+ };
51
+ return compact({
52
+ ...c1,
53
+ ...c2,
54
+ ...c3,
55
+ ...c4,
56
+ ...c5
57
+ });
58
+ };
59
+ const userDataOf = async (event) => {
60
+ const { user, click_ids: clickIds } = event;
61
+ const country = user.country_code?.toLowerCase();
62
+ const hashedCountry = country ? await sha256Hex(country) : void 0;
63
+ const u1 = { em: list(user.email_sha256) };
64
+ const u2 = { ph: list(user.phone_digits_sha256) };
65
+ const u3 = { fn: list(user.first_name_sha256) };
66
+ const u4 = { ln: list(user.last_name_sha256) };
67
+ const u5 = { external_id: list(user.external_id_sha256) };
68
+ const u6 = { country: list(hashedCountry) };
69
+ const u7 = { client_ip_address: event.ipAddress };
70
+ const u8 = { client_user_agent: event.userAgent };
71
+ const u9 = {
72
+ fbp: clickIds.fbp,
73
+ fbc: clickIds.fbc
74
+ };
75
+ return compact({
76
+ ...u1,
77
+ ...u2,
78
+ ...u3,
79
+ ...u4,
80
+ ...u5,
81
+ ...u6,
82
+ ...u7,
83
+ ...u8,
84
+ ...u9
85
+ });
86
+ };
87
+ const processingOptionsOf = (options) => {
88
+ const dpo = options.dataProcessingOptions;
89
+ if (!dpo) return {};
90
+ const d1 = { data_processing_options: [...dpo.options] };
91
+ const d2 = { data_processing_options_country: dpo.country };
92
+ const d3 = { data_processing_options_state: dpo.state };
93
+ return compact({
94
+ ...d1,
95
+ ...d2,
96
+ ...d3
97
+ });
98
+ };
99
+ /** One Conversions API server event. `event_name` is the pixel's name. */
100
+ const metaEventOf = async (event, options) => {
101
+ const e1 = {
102
+ event_name: providerEventName(PROVIDER, event.name),
103
+ event_time: Math.floor(event.timestamp / 1e3)
104
+ };
105
+ const e2 = {
106
+ event_id: event.event_id,
107
+ action_source: "website"
108
+ };
109
+ const e3 = { event_source_url: event.source_url };
110
+ const e4 = { referrer_url: event.referrer_url };
111
+ const e5 = { user_data: await userDataOf(event) };
112
+ const e6 = { custom_data: customDataOf(event) };
113
+ const e7 = processingOptionsOf(options);
114
+ return compact({
115
+ ...e1,
116
+ ...e2,
117
+ ...e3,
118
+ ...e4,
119
+ ...e5,
120
+ ...e6,
121
+ ...e7
122
+ });
123
+ };
124
+ const recordOf = (value) => {
125
+ return !!value && typeof value === "object" && !Array.isArray(value) ? value : {};
126
+ };
127
+ const textOf = (value) => {
128
+ return typeof value === "string" && value ? value : void 0;
129
+ };
130
+ const failed = (reason, retryable) => {
131
+ return {
132
+ outcome: "failed",
133
+ reason,
134
+ retryable
135
+ };
136
+ };
137
+ const classifyError = (status, error) => {
138
+ const code = typeof error.code === "number" ? error.code : void 0;
139
+ if (code === 190) return failed("auth", false);
140
+ if (code !== void 0 && code >= 200 && code <= 299) return failed("auth", false);
141
+ if (code === 100) return failed("invalid_payload", false);
142
+ if (code !== void 0 && RATE_LIMIT_CODES.has(code)) return failed("rate_limited", true);
143
+ if (code !== void 0 && TRANSIENT_CODES.has(code)) return failed("upstream_error", true);
144
+ if (error.is_transient === true) return failed("upstream_error", true);
145
+ if (status >= 500) return failed("upstream_error", true);
146
+ if (status === 429) return failed("rate_limited", true);
147
+ if (status === 401 || status === 403) return failed("auth", false);
148
+ return failed("invalid_payload", false);
149
+ };
150
+ /** Meta response → outcome, per the retry matrix. */
151
+ const classifyMetaReply = (reply, expected) => {
152
+ const body = recordOf(reply.body);
153
+ const error = recordOf(body.error);
154
+ const hasError = Object.keys(error).length > 0;
155
+ const traceId = textOf(error.fbtrace_id) ?? textOf(body.fbtrace_id);
156
+ const base = {
157
+ httpStatus: reply.status,
158
+ traceId
159
+ };
160
+ if (reply.status === 200 && !hasError) {
161
+ if (body.events_received === expected) return {
162
+ ...base,
163
+ outcome: "sent",
164
+ retryable: false
165
+ };
166
+ return {
167
+ ...base,
168
+ ...failed("upstream_error", false)
169
+ };
170
+ }
171
+ const code = typeof error.code === "number" ? error.code : void 0;
172
+ const outcome = classifyError(reply.status, error);
173
+ return {
174
+ ...base,
175
+ ...outcome,
176
+ providerCode: code
177
+ };
178
+ };
179
+ const assertOptions = (options) => {
180
+ if (!PIXEL_ID.test(String(options.pixelId ?? ""))) throw new AnalyticsServerConfigError("META_PIXEL_ID_INVALID", "metaConversionsApi: pixelId must be the numeric pixel id");
181
+ if (typeof options.accessToken !== "string" || !options.accessToken.trim()) throw new AnalyticsServerConfigError("META_ACCESS_TOKEN_REQUIRED", "metaConversionsApi: accessToken is required");
182
+ const version = options.graphVersion ?? DEFAULT_GRAPH_VERSION;
183
+ if (!GRAPH_VERSION.test(version)) throw new AnalyticsServerConfigError("META_GRAPH_VERSION_INVALID", "metaConversionsApi: graphVersion must look like v27.0");
184
+ return version;
185
+ };
186
+ const prepare = (events) => {
187
+ const ready = [];
188
+ const skipped = [];
189
+ const skip = (event, reason) => {
190
+ const b1 = {
191
+ provider: PROVIDER,
192
+ eventIds: [event.event_id]
193
+ };
194
+ const b2 = {
195
+ outcome: "skipped",
196
+ reason,
197
+ retryable: false
198
+ };
199
+ skipped.push({
200
+ ...b1,
201
+ ...b2,
202
+ attempts: 0
203
+ });
204
+ };
205
+ for (const event of events) if (!providerEventName(PROVIDER, event.name)) skip(event, "not_mapped");
206
+ else if (!event.userAgent) skip(event, "no_identifier");
207
+ else ready.push(event);
208
+ return {
209
+ ready,
210
+ skipped
211
+ };
212
+ };
213
+ /**
214
+ * Meta Conversions API destination. The token travels in the JSON body,
215
+ * never in the URL, and is never logged.
216
+ */
217
+ const metaConversionsApi = (options) => {
218
+ const version = assertOptions(options);
219
+ const pixelId = String(options.pixelId);
220
+ const accessToken = options.accessToken.trim();
221
+ const url = `https://graph.facebook.com/${version}/${pixelId}/events`;
222
+ const send = async (events, ctx) => {
223
+ const body = stringifyJson({
224
+ ...compact({
225
+ data: await Promise.all(events.map((e) => metaEventOf(e, options))),
226
+ test_event_code: testCodeFor(PROVIDER, options, ctx)
227
+ }),
228
+ access_token: accessToken
229
+ });
230
+ const final = await withProviderRetry(ctx, async (signal) => {
231
+ const reply = await postJson(ctx, {
232
+ url,
233
+ body
234
+ }, signal);
235
+ return classifyMetaReply(reply, events.length);
236
+ });
237
+ const eventIds = events.map((event) => event.event_id);
238
+ return {
239
+ provider: PROVIDER,
240
+ eventIds,
241
+ ...final
242
+ };
243
+ };
244
+ return {
245
+ id: PROVIDER,
246
+ maxBatchSize: MAX_BATCH,
247
+ prepare,
248
+ send
249
+ };
250
+ };
251
+ //#endregion
252
+ export { classifyMetaReply, metaConversionsApi, metaEventOf };
@@ -0,0 +1,22 @@
1
+ //#region src/provider.ts
2
+ /**
3
+ * The test event code to send. In production it is dropped (with a
4
+ * warning) unless `allowTestInProduction` is set, so a code left in the
5
+ * production env cannot hide real conversions in Test Events.
6
+ */
7
+ const testCodeFor = (provider, options, ctx) => {
8
+ const code = options.testEventCode?.trim();
9
+ if (!code) return void 0;
10
+ if (!ctx.isProduction || options.allowTestInProduction) return code;
11
+ const p1 = `${provider} test event code ignored in production`;
12
+ ctx.report({
13
+ level: "warning",
14
+ source: "config",
15
+ provider,
16
+ message: p1
17
+ });
18
+ };
19
+ /** Typed identity helper for a custom destination. */
20
+ const defineServerProvider = (provider) => provider;
21
+ //#endregion
22
+ export { testCodeFor as n, defineServerProvider as t };