@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.
@@ -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,143 @@
1
+ import { A as ServerProvider, R as JsonNumber, T as ResolvedEvent, i as HttpReply, t as AttemptOutcome } from "./retry-BRNUy4Of.js";
2
+ import "@fire-spark/analytics";
3
+ //#region src/meta.types.d.ts
4
+ interface MetaDataProcessingOptions {
5
+ /** For example `["LDU"]` (Limited Data Use). */
6
+ options: string[];
7
+ /** `1` = United States; `0` lets Meta geolocate. */
8
+ country?: number;
9
+ /** For example `1000` = California; `0` lets Meta geolocate. */
10
+ state?: number;
11
+ }
12
+ interface MetaConversionsApiOptions {
13
+ /** Numeric pixel (dataset) id. */
14
+ pixelId: string;
15
+ /** System user token from Events Manager. Server only, never logged. */
16
+ accessToken: string;
17
+ /** Default `v27.0`. */
18
+ graphVersion?: `v${number}.0`;
19
+ /** Events Manager → Test Events. Dropped in production. */
20
+ testEventCode?: string;
21
+ /** Keeps `testEventCode` in production. */
22
+ allowTestInProduction?: boolean;
23
+ dataProcessingOptions?: MetaDataProcessingOptions;
24
+ }
25
+ interface MetaAppConversionsApiOptions {
26
+ /** Numeric id of the dataset linked to the app in Events Manager. */
27
+ datasetId: string;
28
+ /** Conversions API token. Server only, never logged. */
29
+ accessToken: string;
30
+ /** Default `v27.0`. */
31
+ graphVersion?: `v${number}.0`;
32
+ /** Events Manager → Test Events. Dropped in production. */
33
+ testEventCode?: string;
34
+ /** Keeps `testEventCode` in production. */
35
+ allowTestInProduction?: boolean;
36
+ /** Limited Data Use. Not set by default. */
37
+ dataProcessingOptions?: MetaDataProcessingOptions;
38
+ /**
39
+ * Contract name → Meta `event_name`, merged over the default
40
+ * `{ purchase: "fb_mobile_purchase" }`. Use it for the Test Events check
41
+ * of `Purchase` against `fb_mobile_purchase`.
42
+ */
43
+ eventNames?: Readonly<Record<string, string>>;
44
+ }
45
+ //#endregion
46
+ //#region src/meta.shared.d.ts
47
+ /** Meta response → outcome, per the retry matrix. */
48
+ declare const classifyMetaReply: (reply: HttpReply, expected: number) => AttemptOutcome;
49
+ //#endregion
50
+ //#region src/meta.app.d.ts
51
+ /** One Conversions API app event (`action_source: "app"`). */
52
+ declare const metaAppEventOf: (event: ResolvedEvent, options: MetaAppConversionsApiOptions) => Promise<Partial<{
53
+ data_processing_options?: string[] | undefined;
54
+ data_processing_options_country?: number | undefined;
55
+ data_processing_options_state?: number | undefined;
56
+ event_name: string | undefined;
57
+ event_time: number;
58
+ event_id: string;
59
+ action_source: string;
60
+ app_data: Partial<{
61
+ advertiser_tracking_enabled: number;
62
+ application_tracking_enabled: number;
63
+ vendor_id: string | undefined;
64
+ install_referrer: string | undefined;
65
+ extinfo: string[];
66
+ }>;
67
+ user_data: Partial<{
68
+ anon_id: string;
69
+ madid: string | undefined;
70
+ client_ip_address: string | undefined;
71
+ em: string[] | undefined;
72
+ ph: string[] | undefined;
73
+ external_id: string[] | undefined;
74
+ fn: string[] | undefined;
75
+ ln: string[] | undefined;
76
+ country: string[] | undefined;
77
+ }>;
78
+ custom_data: Partial<{
79
+ currency: string | undefined;
80
+ value: JsonNumber | undefined;
81
+ order_id: string | undefined;
82
+ content_type: string | undefined;
83
+ contents: Partial<{
84
+ id: string;
85
+ quantity: JsonNumber | undefined;
86
+ item_price: JsonNumber | undefined;
87
+ }>[] | undefined;
88
+ num_items: JsonNumber | undefined;
89
+ }>;
90
+ }> | undefined>;
91
+ /**
92
+ * Meta Conversions API destination for app events (React Native), sent
93
+ * to the dataset linked to the app. Use it with `createAppTrackingHandler`.
94
+ * The token travels in the JSON body, never in the URL, and is never
95
+ * logged.
96
+ */
97
+ declare const metaAppConversionsApi: (options: MetaAppConversionsApiOptions) => ServerProvider;
98
+ //#endregion
99
+ //#region src/meta.d.ts
100
+ /** One Conversions API server event. `event_name` is the pixel's name. */
101
+ declare const metaEventOf: (event: ResolvedEvent, options: MetaConversionsApiOptions) => Promise<Partial<{
102
+ data_processing_options?: string[] | undefined;
103
+ data_processing_options_country?: number | undefined;
104
+ data_processing_options_state?: number | undefined;
105
+ event_name: string | null;
106
+ event_time: number;
107
+ event_id: string;
108
+ action_source: string;
109
+ event_source_url: string | undefined;
110
+ referrer_url: string | undefined;
111
+ user_data: Partial<{
112
+ em: string[] | undefined;
113
+ ph: string[] | undefined;
114
+ fn: string[] | undefined;
115
+ ln: string[] | undefined;
116
+ external_id: string[] | undefined;
117
+ country: string[] | undefined;
118
+ client_ip_address: string | undefined;
119
+ client_user_agent: string | undefined;
120
+ fbp: string | undefined;
121
+ fbc: string | undefined;
122
+ }>;
123
+ custom_data: Partial<{
124
+ currency: string | undefined;
125
+ value: string | undefined;
126
+ order_id: string | undefined;
127
+ content_type: string | undefined;
128
+ content_ids: string[];
129
+ contents: Partial<{
130
+ id: string;
131
+ quantity: JsonNumber | undefined;
132
+ item_price: JsonNumber | undefined;
133
+ }>[];
134
+ num_items: JsonNumber | undefined;
135
+ }>;
136
+ }>>;
137
+ /**
138
+ * Meta Conversions API destination for web events. The token travels in
139
+ * the JSON body, never in the URL, and is never logged.
140
+ */
141
+ declare const metaConversionsApi: (options: MetaConversionsApiOptions) => ServerProvider;
142
+ //#endregion
143
+ export { type MetaAppConversionsApiOptions, type MetaConversionsApiOptions, type MetaDataProcessingOptions, classifyMetaReply, metaAppConversionsApi, metaAppEventOf, metaConversionsApi, metaEventOf };