@growthgenie/ai-traffic 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Growth Genie
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,280 @@
1
- # Temporary Holding Version
1
+ # @growthgenie/ai-traffic (N1)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Server-only ESM client for Growth Genie's v1 AI traffic ingest. Node 24; no
4
+ browser export or frontend credential. Create a **Next.js or Node** (or Vercel
5
+ **Middleware**) connection in Growth Genie to get its key.
6
+
7
+ MIT licensed (see `LICENSE`). `THIRD_PARTY_NOTICES` holds the full MIT notices for
8
+ the bundled Zod and ipaddr.js.
9
+
10
+ **Coverage:** Static and CDN hits that bypass Node are invisible. Use an edge
11
+ method for full coverage. Proxy observes requests, not downstream responses:
12
+ status and content type are null and response coverage is unavailable. Referrals
13
+ are observed AI referrers, not confirmed people; referrers can be missing/forged.
14
+ Node `finish` means writes completed at the server, not that the client received
15
+ the response. Aborted responses have unknown status. No sampling is performed.
16
+
17
+ ## Setup
18
+
19
+ `npm install @growthgenie/ai-traffic`. In Growth Genie, open AI traffic → Connect your
20
+ site and choose **Next.js or Node** (or Vercel → **Middleware**); that creates the
21
+ connection with your site's hosts and shows its key once. Keep the full issued
22
+ `gg_ai_<uuid>.<tag>_<secret>` key in server secret configuration. The server still
23
+ owns classification, tenant binding, verification, policy and accounting.
24
+
25
+ Only API keys and endpoint URLs below come from environment variables. Runtime,
26
+ proxy trust and output choices are explicit integration configuration; there are
27
+ no environment-variable feature flags.
28
+
29
+ ## Next.js 16 Proxy
30
+
31
+ **For Next.js, initialize through `createTrafficClientFromEnv` from
32
+ `@growthgenie/ai-traffic/next/server`.** This module is marked `import 'server-only'`
33
+ and reads `process.env.GROWTHGENIE_AI_TRAFFIC_KEY` at runtime when called. Set that
34
+ private server secret in the host's secret configuration. It accepts the optional
35
+ `endpoint`, `fetch` and `onDelivery` client options, never an `apiKey` option.
36
+ Keep the client in server modules; reuse it across requests where the host permits.
37
+ The direct `createTrafficClient({ apiKey })` API remains for Node/Express without
38
+ a client bundle; it is not the Next.js initialization pattern.
39
+
40
+ Never put credential literals in source, use `NEXT_PUBLIC_*` for credentials,
41
+ configure them in `next.config` `env` or any build-time substitution, or pass them
42
+ into client props. Import rejection alone cannot protect source literals:
43
+ **Turbopack may write literals into `.next/static` chunks before rejecting a build.**
44
+ Failed-build artifacts can therefore expose literals during CI artifact upload.
45
+ Use the private-env server-only initializer even when imports are guarded; never
46
+ publish a failed build's output.
47
+
48
+ Reject static export at config evaluation time, because an exported site's Proxy
49
+ will never execute. Use the same config in the adapter:
50
+
51
+ ```js
52
+ // next.config.mjs
53
+ import { withAiTrafficConfig } from '@growthgenie/ai-traffic/next';
54
+ export default withAiTrafficConfig({}); // output: 'export' throws
55
+ ```
56
+
57
+ ```ts
58
+ // proxy.ts (Next 16)
59
+ import { createTrafficClientFromEnv } from '@growthgenie/ai-traffic/next/server';
60
+ import { createNextProxy } from '@growthgenie/ai-traffic/next';
61
+ import type { NextRequest, NextFetchEvent } from 'next/server';
62
+ import config from './next.config.mjs';
63
+
64
+ const client = createTrafficClientFromEnv();
65
+ const capture = createNextProxy({
66
+ client, allowedHosts: ['example.com', 'www.example.com'], output: config.output,
67
+ });
68
+ export function proxy(request: NextRequest, event: NextFetchEvent) {
69
+ capture(request, event); // schedules with event.waitUntil, continues routing
70
+ }
71
+ ```
72
+
73
+ Compose capture with an existing Proxy; don't export a second Proxy or wrap
74
+ `NextResponse.next()` as though it were a final page response. Choose a matcher
75
+ that includes the pages and crawler files you want to measure. Local test fixture
76
+ uses no matcher and exercises a real Next **16.4.5** development server, Node 24,
77
+ with `NextFetchEvent.waitUntil`, plus production server-initializer success and client-import rejection builds
78
+ with webpack and Turbopack. The optional `next` peer dependency is **16.x** (optional
79
+ so plain Node/Express consumers do not install Next). Only 16.4.5 is locally tested;
80
+ broader compatibility is unproven until the live Hobby/Pro checks. Next 15,
81
+ Hobby/Pro entitlement and execution limits are unproven; this is not production
82
+ Vercel evidence. See [Next's Proxy documentation](https://nextjs.org/docs/app/api-reference/file-conventions/proxy).
83
+
84
+ A Web Request has no trustworthy socket IP. Default `client_ip` is null. Optional
85
+ `clientIp(request)` must read host-attested metadata under a documented trust
86
+ boundary; never take arbitrary X-Forwarded-For or X-Real-IP. Null IP yields only
87
+ unverified fetches. No country is inferred.
88
+
89
+ Request-only referral candidates require GET, a recognized AI referrer,
90
+ `Sec-Fetch-Mode: navigate` **and** `Sec-Fetch-Dest: document`, an eligible path,
91
+ and no prefetch/preview purpose. API/framework/static asset/private/account paths
92
+ are excluded (including encoded forms). No navigation evidence means no referral
93
+ candidate. **A1b v1 does not transmit navigation headers, and its referral rule
94
+ requires a successful final status and document evidence. Consequently Proxy-only
95
+ referral candidates are dropped centrally, not counted. Referral measurement is
96
+ unavailable with request-only Proxy.** Null status is never replaced with 200.
97
+ `proxyCoverage` exposes this limitation in code.
98
+
99
+ Where the runtime exposes a **final** Web Response and a supported lifetime hook,
100
+ use `createResponseWrapper`. It preserves the response body/stream and reports
101
+ its actual status/content type. It covers only the routes it wraps, not all Next
102
+ page rendering. For a Next route handler with `after` support:
103
+
104
+ ```ts
105
+ import { after } from 'next/server';
106
+ import { createResponseWrapper } from '@growthgenie/ai-traffic/next';
107
+ // Reuse server-side client, config and host policy from above in a server module.
108
+ const wrapped = createResponseWrapper({ client, allowedHosts: ['example.com'], output: config.output })(
109
+ async (request: Request) => new Response('<html>Example</html>', {
110
+ headers: { 'Content-Type': 'text/html' },
111
+ }),
112
+ );
113
+ export function GET(request: Request) {
114
+ return wrapped(request, { waitUntil: work => after(() => work) });
115
+ }
116
+ ```
117
+
118
+ Supply the host's documented supported lifetime hook; it must keep work alive
119
+ until settled. Do not count the same request through both Proxy and a wrapper:
120
+ choose one capture point per request (for example exclude wrapped routes in the
121
+ Proxy matcher). The package doesn't dedupe two separate capture points.
122
+
123
+ ## Long-lived Node / Express
124
+
125
+ ```ts
126
+ import express from 'express';
127
+ import { createTrafficClient } from '@growthgenie/ai-traffic';
128
+ import { createNodeMiddleware } from '@growthgenie/ai-traffic/node';
129
+
130
+ const app = express();
131
+ const client = createTrafficClient({ apiKey: process.env.AI_TRAFFIC_API_KEY! });
132
+ app.use(createNodeMiddleware({
133
+ client, runtime: 'long-lived', allowedHosts: ['example.com'],
134
+ trustedProxyCidrs: ['10.20.0.0/16'], // replace with YOUR actual ingress ranges
135
+ }));
136
+ // Register routes after capture. Bare Node: capture(req, res, () => route(req, res)).
137
+ const server = app.listen(3000);
138
+ process.once('SIGTERM', () => {
139
+ server.close(() => { // stop accepting and drain responses before closing capture
140
+ void client.shutdown(5000).then(() => process.exit(0));
141
+ });
142
+ });
143
+ ```
144
+
145
+ Configure a host response-drain deadline as well; `server.close` itself is not a
146
+ bounded shutdown policy.
147
+
148
+ Headers and remote address come from IncomingMessage, not Express's `req.ip` or
149
+ `trust proxy`. A forwarded chain is used only if the socket peer is trusted. Walk
150
+ right to left, stopping at the nearest untrusted hop. Malformed chains behind a
151
+ trusted peer yield null; IPv4-mapped sockets and CIDRs are normalized to IPv4
152
+ (mapped CIDR prefixes subtract 96). Mapped prefixes below /96 and scoped CIDRs
153
+ throw a configuration error rather than broadening proxy trust. Never trust all
154
+ proxies merely to recover a desired IP. CIDRs must match your ingress topology.
155
+ Host must match the exact configured allowlist; forwarded host is ignored.
156
+
157
+ Capture occurs once, at response finish or close; close without finish sends null
158
+ status/type, never Node's default 200. Request time/headers/path are captured
159
+ before routing, and query/fragment/referrer details are stripped. No request
160
+ bodies, cookies, authorization headers or arbitrary header objects are forwarded.
161
+ Private/admin/account/password-reset routes are excluded before delivery.
162
+
163
+ Serverless Node requires `runtime: 'serverless'` and
164
+ `waitUntil(work, request)`, supplied by the host. Missing hook throws during setup.
165
+ The hook is registered **before** response completion, waits for finish/close and
166
+ then waits for bounded delivery. Never label serverless as long-lived to bypass
167
+ this requirement; detached fetch is not a delivery guarantee. The package cannot
168
+ detect every hosting topology. A terminating runtime without a supported lifetime
169
+ hook is unsupported.
170
+
171
+ ## Delivery and privacy
172
+
173
+ `createTrafficClient({ apiKey, endpoint?, fetch?, onDelivery? })` returns `send`, `flush` and
174
+ `shutdown`. Integrations construct generic v1 observations; `send` also validates
175
+ the strict A0 schema and rejects extra category/verification/identity fields.
176
+ Root exports include `deliveryLimits` and `catalogVersion`; `/node` exports
177
+ `createNodeMiddleware` and `nodeCoverage`; `/next` exports `createNextProxy`,
178
+ `createResponseWrapper`, `assertNextOutput`, `withAiTrafficConfig`, `proxyCoverage`.
179
+ The fetch injection must honor AbortSignal. All exported modules reject browser
180
+ execution; the root, `/node` and `/next` use ordered `types`, `react-server`, `browser`,
181
+ `module`, and `default` export conditions. `react-server` and plain Node's `default` use the
182
+ server implementation. `browser` selects a module whose preserved `import
183
+ "server-only"` makes Next reject static **and lazy** Client Component imports at
184
+ build time; its runtime throw is only a fallback. The bundler-only `module` condition
185
+ selects marked server re-exports too: Next's Client Component SSR pass must reject
186
+ imports during SSR compilation. Native Node ignores `module`, uses `default`,
187
+ and can load those entry points without React conditions. `/next/server` always
188
+ loads its marked server-only initializer; it is intended for Next server modules.
189
+ Real Next 16.4.5 production tests cover static/lazy client imports of all entries
190
+ and legitimate server initialization on webpack and Turbopack, with keys supplied
191
+ only through the private server environment. Rejected builds are scanned across
192
+ all `.next`; successful builds are scanned across public `.next/static`.
193
+ One literal-credential test asserts rejection only, documenting the failed-build
194
+ residue limitation rather than claiming literal absence.
195
+ Private subpath imports are blocked by the exports map. The build keeps `server-only` external (a public
196
+ runtime dependency), so Next can recognize the marker.
197
+
198
+ This follows [Next's environment-poisoning guidance](https://nextjs.org/docs/app/getting-started/server-and-client-components#preventing-environment-poisoning),
199
+ [Node's ordered conditional exports](https://nodejs.org/api/packages.html#conditional-exports),
200
+ and [React's server module conventions](https://github.com/reactjs/rfcs/blob/main/text/0227-server-module-conventions.md#react-server-conditional-exports).
201
+
202
+ Each post is a one-record v1 JSON **array**, at most 8,192 bytes per event (hence
203
+ below 1,000 records / 4,000,000 bytes per batch). No compression or redirects.
204
+ Authentication uses X-API-Key. Only 200 acknowledges delivery; permanent per-event
205
+ drops inside a 200 are never retried. Results report acknowledgement rather than
206
+ claiming newly accepted counts. Installation validation uses A1b's separate
207
+ `/v1/ai-traffic/test` with the same schema/key, not fabricated production events.
208
+
209
+ Shipped fixed bounds: 2 active posts, 256 queued events, 3 seconds per attempt,
210
+ 3 retries (4 attempts), 30 seconds total per active delivery, and the event's
211
+ 72-hour age ceiling. Retry network errors, 429 and 5xx only, with full jitter over
212
+ `min(60s, 1s * 2**attempt)`. Honor Retry-After seconds or dates as a minimum; if
213
+ it exceeds the remaining delivery deadline, fail instead of retrying early.
214
+ Retries reuse identical serialized bytes and event UUID. Queue overflow and
215
+ exhausted retries lose observations; the in-memory queue is not durable.
216
+
217
+ `flush(ms = 5000)` returns false at the deadline without closing the client;
218
+ `shutdown(ms = 5000)` rejects new events, flushes, discards queued work and aborts
219
+ active delivery at the deadline. Both accept 0–30,000 ms. Shutdown is bounded and
220
+ best-effort, including on long-lived hosts; allow process exit only after the
221
+ host's response drain policy and this hook complete. No signal handlers are
222
+ installed by the package. `send` resolves `{ outcome, attempts, status }`, with
223
+ `outcome` acknowledged/failed/overflow/closed and no payload or receiver body.
224
+ The optional `onDelivery(result)` callback surfaces every terminal outcome, including
225
+ overflow and exhausted retries, without event metadata. Callback errors are
226
+ contained; avoid logging request DTOs from application wrappers.
227
+
228
+ **There is no persisted spool, filesystem/database/queue storage, or package
229
+ logging. Raw IP/UA exist only in bounded request/delivery memory and are discarded
230
+ after acknowledgement/failure/shutdown.** Never persist failed send events in
231
+ logs, error trackers, retry spools or deadletters. The central receiver strips
232
+ IP/UA before storage. Paths can still contain personal information; configure
233
+ additional server-side path redaction in site policy. This is not a claim that
234
+ all stored data is nonpersonal.
235
+
236
+ ## Catalog updates, gates and live owner steps
237
+
238
+ Build bundles A0's reviewed candidate catalog/rules and schema from
239
+ `@growthwand/contracts` (no private workspace runtime dependency in the artifact).
240
+ `catalogVersion` identifies its classifier catalog. Runtime prefilter does no IP
241
+ lookup or authoritative verification. A stale package can miss newly added
242
+ agents/referrers; central classification may reject old candidates and remains
243
+ authoritative. Deliver catalog/rule updates as new package patch versions, run the
244
+ A0 parity tests, update the consumer lockfile and redeploy. There is no remote
245
+ catalog fetch or silent automatic runtime update. Review catalog version changes
246
+ and stale package installations in operational diagnostics.
247
+
248
+ Local: `corepack pnpm --filter @growthgenie/ai-traffic test` builds the distributable
249
+ and runs real Express/Node, real local Next 16 Proxy, delivery bounds, aborts,
250
+ static export, spoofing and A1b public-route/accounting tests. Docker is required
251
+ for the latter; it creates a disposable `postgres:17.11-bookworm` on a free
252
+ 127.0.0.1 port, uses a chmod-600 JSON config, and removes container/config in
253
+ finally. No MCP implementation is copied or changed. Root gates are lint,
254
+ typecheck, build and test, using `TMPDIR="$HOME/.t3/tmp" TURBO_ENV_MODE=loose
255
+ VITEST_MAX_WORKERS=2`. Detailed results are in `N1-REPORT.md`.
256
+
257
+ Owner's unexecuted live G-node gate:
258
+
259
+ 1. Install the built package into separate staging apps for each proposed Next
260
+ version (start with locally tested 16.4.5; expand the peer range only after testing).
261
+ Deploy on actual Vercel Hobby **and** Pro. Record Next/Node/package versions,
262
+ plan, host limits, region, timestamp and sanitized request captures.
263
+ 2. Create separate generic staging connections. Run `/v1/ai-traffic/test`; confirm
264
+ test health changes without analytics/allowance. Rotate/revoke keys and check
265
+ failures without recording keys or payloads in logs.
266
+ 3. Send a known-UA fetch to a dynamic page through Proxy; reconcile one accepted
267
+ unverified observation, null status/type, no duplicate charges on ambiguous
268
+ replay. Do not claim a spoofed UA/IP is verified. Verify waitUntil after the
269
+ page response, cold starts, host timeouts, bursts, queue overflow and retries.
270
+ 4. Prove request-only referral non-counting, navigation-header/path exclusions,
271
+ redirects, prefetches, assets, aborted requests and no-IP behavior. In a
272
+ response-aware route prove successful HTML AI referrals can be accepted;
273
+ record coverage as unavailable for unwrapped rendering routes.
274
+ 5. Compare dynamic, static, CDN-cached, robots/sitemap, rewrites and redirects;
275
+ measure which requests execute Proxy/Node and disclose every bypass. Test
276
+ static export build rejection with `withAiTrafficConfig`.
277
+ 6. Measure delivery success, loss, overhead and shutdown at host execution limits
278
+ and reconcile recent rows, daily aggregates and workspace allowance. Save
279
+ sanitized captures/negative cases plus source/version/date notes. Do not claim
280
+ full G-node or universal plan/version support until these steps pass.
@@ -0,0 +1,47 @@
1
+ Third-party software bundled in @growthgenie/ai-traffic
2
+
3
+ ===== zod 4.5.4 (MIT) =====
4
+
5
+ MIT License
6
+
7
+ Copyright (c) 2025 Colin McDonnell
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+
27
+ ===== ipaddr.js 2.3.0 (MIT) =====
28
+
29
+ Copyright (C) 2011-2017 whitequark <whitequark@whitequark.org>
30
+
31
+ Permission is hereby granted, free of charge, to any person obtaining a copy
32
+ of this software and associated documentation files (the "Software"), to deal
33
+ in the Software without restriction, including without limitation the rights
34
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
35
+ copies of the Software, and to permit persons to whom the Software is
36
+ furnished to do so, subject to the following conditions:
37
+
38
+ The above copyright notice and this permission notice shall be included in
39
+ all copies or substantial portions of the Software.
40
+
41
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
42
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
43
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
44
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
45
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
46
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
47
+ THE SOFTWARE.
@@ -0,0 +1,59 @@
1
+ import {
2
+ makeEvent,
3
+ validatePolicy
4
+ } from "./chunk-HAXY7PYH.js";
5
+
6
+ // src/next.ts
7
+ function assertNextOutput(output) {
8
+ if (output === "export") throw new Error("Static export has no Proxy execution. Use an edge connector for coverage.");
9
+ if (output !== void 0 && output !== "standalone") throw new Error("Unsupported Next.js output");
10
+ }
11
+ var proxyCoverage = Object.freeze({ response: "unavailable", referrals: "candidates-only; v1 receiver requires final status", staticAndCdnBypass: "unavailable" });
12
+ function createNextProxy(options) {
13
+ assertNextOutput(options.output);
14
+ const hosts = validatePolicy(options);
15
+ return (request, event) => {
16
+ if (typeof event?.waitUntil !== "function") throw new Error("NextFetchEvent.waitUntil is required");
17
+ const candidate = makeEvent({
18
+ url: request.url,
19
+ headers: request.headers,
20
+ method: request.method,
21
+ clientIp: options.clientIp?.(request) ?? null,
22
+ status: null,
23
+ contentType: null
24
+ }, hosts);
25
+ if (candidate) event.waitUntil(options.client.send(candidate));
26
+ };
27
+ }
28
+ function createResponseWrapper(options) {
29
+ assertNextOutput(options.output);
30
+ const hosts = validatePolicy(options);
31
+ return (handler) => async (request, event, ...args) => {
32
+ if (typeof event?.waitUntil !== "function") throw new Error("A supported runtime lifetime hook is required");
33
+ const occurredAt = (/* @__PURE__ */ new Date()).toISOString();
34
+ const response = await handler(request, ...args);
35
+ const candidate = makeEvent({
36
+ occurredAt,
37
+ url: request.url,
38
+ headers: request.headers,
39
+ method: request.method,
40
+ clientIp: options.clientIp?.(request) ?? null,
41
+ status: response.status,
42
+ contentType: response.headers.get("content-type")
43
+ }, hosts);
44
+ if (candidate) event.waitUntil(options.client.send(candidate));
45
+ return response;
46
+ };
47
+ }
48
+ function withAiTrafficConfig(config) {
49
+ assertNextOutput(config.output);
50
+ return config;
51
+ }
52
+
53
+ export {
54
+ assertNextOutput,
55
+ proxyCoverage,
56
+ createNextProxy,
57
+ createResponseWrapper,
58
+ withAiTrafficConfig
59
+ };
@@ -0,0 +1,130 @@
1
+ import {
2
+ AiTrafficRequestEvent
3
+ } from "./chunk-RYXHXHXU.js";
4
+
5
+ // src/delivery.ts
6
+ var deliveryLimits = Object.freeze({ concurrency: 2, queueEvents: 256, timeoutMs: 3e3, retries: 3, baseDelayMs: 1e3, maxDelayMs: 6e4, maxDeliveryMs: 3e4, shutdownMs: 5e3 });
7
+ function createTrafficClient(options) {
8
+ const endpoint = new URL(options.endpoint ?? "https://auth.growthgenie.so/v1/ai-traffic/events");
9
+ if (endpoint.username || endpoint.password || endpoint.search || endpoint.hash || endpoint.pathname !== "/v1/ai-traffic/events" || !(endpoint.protocol === "https:" || endpoint.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(endpoint.hostname))) throw new Error("Use the HTTPS generic events endpoint (or loopback HTTP)");
10
+ if (!/^gg_ai_[a-f0-9-]{36}\.[A-Za-z0-9_-]+_[A-Za-z0-9_-]+$/.test(options.apiKey)) throw new Error("Use the complete issued gg_ai key");
11
+ const transport = options.fetch ?? fetch;
12
+ const queue = [], idle = /* @__PURE__ */ new Set(), controllers = /* @__PURE__ */ new Set();
13
+ let active = 0, closed = false;
14
+ const signalIdle = () => {
15
+ if (!active && !queue.length) for (const done of idle) done();
16
+ };
17
+ async function deliver(job) {
18
+ const controller = new AbortController();
19
+ controllers.add(controller);
20
+ const deadline = Math.min(Date.now() + deliveryLimits.maxDeliveryMs, job.expiresAt);
21
+ let status = null, attempts = 0;
22
+ try {
23
+ for (let attempt = 0; attempt <= deliveryLimits.retries; attempt++) {
24
+ if (controller.signal.aborted || Date.now() >= deadline) break;
25
+ attempts++;
26
+ const timeout = AbortSignal.timeout(Math.max(1, Math.min(deliveryLimits.timeoutMs, deadline - Date.now())));
27
+ let retryAfter = 0;
28
+ try {
29
+ const response = await transport(endpoint.href, {
30
+ method: "POST",
31
+ headers: { "Content-Type": "application/json", "X-API-Key": options.apiKey },
32
+ body: job.body,
33
+ redirect: "manual",
34
+ signal: AbortSignal.any([controller.signal, timeout])
35
+ });
36
+ status = response.status;
37
+ const header = response.headers.get("retry-after");
38
+ if (header) retryAfter = /^\d+(?:\.\d+)?$/.test(header) ? Number(header) * 1e3 : Math.max(0, Date.parse(header) - Date.now());
39
+ await response.body?.cancel();
40
+ if (status === 200) return { outcome: "acknowledged", attempts, status };
41
+ if (status !== 429 && status < 500 || status >= 600) break;
42
+ } catch {
43
+ status = null;
44
+ }
45
+ if (attempt === deliveryLimits.retries || controller.signal.aborted) break;
46
+ const delay = Math.max(
47
+ Number.isFinite(retryAfter) ? retryAfter : 0,
48
+ Math.random() * Math.min(deliveryLimits.maxDelayMs, deliveryLimits.baseDelayMs * 2 ** attempt)
49
+ );
50
+ if (Date.now() + delay >= deadline) break;
51
+ await new Promise((resolve) => {
52
+ const done = () => {
53
+ clearTimeout(timer);
54
+ controller.signal.removeEventListener("abort", done);
55
+ resolve();
56
+ };
57
+ const timer = setTimeout(done, delay);
58
+ controller.signal.addEventListener("abort", done, { once: true });
59
+ if (controller.signal.aborted) done();
60
+ });
61
+ }
62
+ return { outcome: "failed", attempts, status };
63
+ } finally {
64
+ controllers.delete(controller);
65
+ }
66
+ }
67
+ function pump() {
68
+ while (active < deliveryLimits.concurrency && queue.length) {
69
+ const job = queue.shift();
70
+ active++;
71
+ void deliver(job).then(job.resolve).finally(() => {
72
+ active--;
73
+ pump();
74
+ signalIdle();
75
+ });
76
+ }
77
+ }
78
+ async function flush(timeoutMs = deliveryLimits.shutdownMs) {
79
+ if (!Number.isFinite(timeoutMs) || timeoutMs < 0 || timeoutMs > deliveryLimits.maxDeliveryMs) throw new Error("flush timeout must be 0\u201330000 ms");
80
+ if (!active && !queue.length) return true;
81
+ return new Promise((resolve) => {
82
+ const done = () => {
83
+ clearTimeout(timer);
84
+ idle.delete(done);
85
+ resolve(true);
86
+ };
87
+ const timer = setTimeout(() => {
88
+ idle.delete(done);
89
+ resolve(false);
90
+ }, timeoutMs);
91
+ idle.add(done);
92
+ });
93
+ }
94
+ function report(result) {
95
+ try {
96
+ options.onDelivery?.(result);
97
+ } catch {
98
+ }
99
+ return result;
100
+ }
101
+ return {
102
+ send(event) {
103
+ if (closed) return Promise.resolve(report({ outcome: "closed", attempts: 0, status: null }));
104
+ if (queue.length >= deliveryLimits.queueEvents) return Promise.resolve(report({ outcome: "overflow", attempts: 0, status: null }));
105
+ const parsed = AiTrafficRequestEvent.safeParse(event);
106
+ if (!parsed.success || Date.now() - Date.parse(parsed.data.occurred_at) > 72 * 60 * 60 * 1e3) return Promise.resolve(report({ outcome: "failed", attempts: 0, status: null }));
107
+ const body = JSON.stringify([parsed.data]);
108
+ if (new TextEncoder().encode(body).byteLength > 8194) return Promise.resolve(report({ outcome: "failed", attempts: 0, status: null }));
109
+ return new Promise((resolve) => {
110
+ queue.push({ body, expiresAt: Date.parse(parsed.data.occurred_at) + 72 * 60 * 60 * 1e3, resolve: (result) => resolve(report(result)) });
111
+ pump();
112
+ });
113
+ },
114
+ flush,
115
+ async shutdown(timeoutMs = deliveryLimits.shutdownMs) {
116
+ closed = true;
117
+ const drained = await flush(timeoutMs);
118
+ if (!drained) {
119
+ for (const job of queue.splice(0)) job.resolve({ outcome: "closed", attempts: 0, status: null });
120
+ for (const controller of controllers) controller.abort();
121
+ }
122
+ return drained;
123
+ }
124
+ };
125
+ }
126
+
127
+ export {
128
+ deliveryLimits,
129
+ createTrafficClient
130
+ };