@pingaura/telemetry 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 PingAura AI
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,124 @@
1
+ # @pingaura/telemetry
2
+
3
+ First-party, privacy-respecting analytics SDK for server and edge runtimes. It
4
+ sends page views and custom events to the PingAura collector from your own
5
+ infrastructure — no client-side script, no third-party cookies.
6
+
7
+ - **Zero runtime dependencies.**
8
+ - **Fire-and-forget** — tracking never blocks, alters, or fails a request.
9
+ - **First-class entry points** for Next.js, Node/Express, and Cloudflare
10
+ Workers, plus a generic client for any other JavaScript or TypeScript server.
11
+ - **ESM and CommonJS**, with bundled TypeScript types.
12
+
13
+ ## Install
14
+
15
+ ```bash
16
+ npm install @pingaura/telemetry
17
+ # or: pnpm add @pingaura/telemetry / yarn add @pingaura/telemetry
18
+ ```
19
+
20
+ Requires Node.js 24+ (or any runtime with a global `fetch`).
21
+
22
+ ## Configuration
23
+
24
+ Every entry point takes the same two required fields:
25
+
26
+ | Field | Description |
27
+ | ---------- | ------------------------------------------------------------- |
28
+ | `writeKey` | Your ingest key, e.g. from `process.env.PINGAURA_INGEST_KEY`. |
29
+ | `domain` | The site domain registered in PingAura, e.g. `"example.com"`. |
30
+
31
+ If either is missing or empty, the SDK becomes a no-op and warns once — it never
32
+ throws. Optional fields: `endpoint`, `timeoutMs`, `debug`, `keepalive`,
33
+ `fetchImpl`, `onWarn`.
34
+
35
+ ## Usage
36
+
37
+ ### Next.js middleware
38
+
39
+ ```ts
40
+ // middleware.ts
41
+ import { createAnalyticsMiddleware } from '@pingaura/telemetry/next';
42
+ import { NextResponse } from 'next/server';
43
+
44
+ const track = createAnalyticsMiddleware({
45
+ writeKey: process.env.PINGAURA_INGEST_KEY,
46
+ domain: 'example.com',
47
+ });
48
+
49
+ export function middleware(req, event) {
50
+ track(req, event);
51
+ return NextResponse.next();
52
+ }
53
+ ```
54
+
55
+ ### Node / Express
56
+
57
+ ```ts
58
+ import { analyticsMiddleware } from '@pingaura/telemetry/node';
59
+
60
+ app.use(
61
+ analyticsMiddleware({
62
+ writeKey: process.env.PINGAURA_INGEST_KEY,
63
+ domain: 'example.com',
64
+ }),
65
+ );
66
+ ```
67
+
68
+ ### Cloudflare Worker
69
+
70
+ ```ts
71
+ import { trackEdge } from '@pingaura/telemetry/cloudflare';
72
+
73
+ export default {
74
+ async fetch(request, env, ctx) {
75
+ const response = await fetch(request);
76
+ trackEdge(request, response, ctx, {
77
+ writeKey: env.PINGAURA_INGEST_KEY,
78
+ domain: env.PINGAURA_DOMAIN,
79
+ });
80
+ return response;
81
+ },
82
+ };
83
+ ```
84
+
85
+ See [`examples/cloudflare-worker`](./examples/cloudflare-worker) for a complete,
86
+ deployable worker.
87
+
88
+ ### Generic client
89
+
90
+ ```ts
91
+ import { createClient } from '@pingaura/telemetry';
92
+
93
+ const client = createClient({
94
+ writeKey: process.env.PINGAURA_INGEST_KEY,
95
+ domain: 'example.com',
96
+ });
97
+
98
+ await client.pageView({ url: 'https://example.com/pricing', path: '/pricing' });
99
+ await client.track(
100
+ 'signup_completed',
101
+ { plan: 'pro' },
102
+ { url: 'https://example.com/welcome' },
103
+ );
104
+ ```
105
+
106
+ ## Event properties and PII
107
+
108
+ Custom `properties` are archived verbatim. **Never put PII in them** — no emails,
109
+ names, user IDs, or raw query strings. The collector rejects events whose values
110
+ look like PII. Use opaque or aggregate values only.
111
+
112
+ ## Development
113
+
114
+ ```bash
115
+ pnpm install
116
+ pnpm test # vitest
117
+ pnpm typecheck # tsc --noEmit
118
+ pnpm lint # eslint
119
+ pnpm build # tsup → dist/
120
+ ```
121
+
122
+ ## License
123
+
124
+ [Apache-2.0](./LICENSE) © PingAura AI
@@ -0,0 +1,60 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_core = require("./core-KgLaVgR4.cjs");
3
+ const require_matchers = require("./matchers-CMwG37qc.cjs");
4
+ //#region src/cloudflare.ts
5
+ /** Map a Cloudflare `cf-cache-status` header to our coarse vocab. */
6
+ function mapCacheStatus(header) {
7
+ if (!header) return void 0;
8
+ switch (header.toUpperCase()) {
9
+ case "HIT":
10
+ case "REVALIDATED": return "hit";
11
+ case "MISS":
12
+ case "EXPIRED":
13
+ case "STALE":
14
+ case "UPDATING": return "miss";
15
+ case "BYPASS":
16
+ case "DYNAMIC": return "bypass";
17
+ default: return;
18
+ }
19
+ }
20
+ /** True when the response is an HTML document (worth a page_view). */
21
+ function isHtmlResponse(response) {
22
+ return (response.headers.get("content-type") ?? "").toLowerCase().includes("text/html");
23
+ }
24
+ /**
25
+ * Fire-and-forget edge page_view. Reads only headers; never consumes the body;
26
+ * never throws. Call from a Cloudflare Worker:
27
+ * const res = await fetch(request);
28
+ * trackEdge(request, res, ctx, { writeKey: env.PINGAURA_INGEST_KEY, domain: env.PINGAURA_DOMAIN });
29
+ * return res;
30
+ */
31
+ function trackEdge(request, response, ctx, config) {
32
+ try {
33
+ let pathname;
34
+ try {
35
+ pathname = new URL(request.url).pathname;
36
+ } catch {
37
+ return;
38
+ }
39
+ if (!(config.shouldTrack ?? require_matchers.shouldTrackPath)(pathname) || !isHtmlResponse(response)) return;
40
+ const client = require_core.createClient({
41
+ ...config,
42
+ keepalive: false
43
+ });
44
+ const cacheStatus = mapCacheStatus(response.headers.get("cf-cache-status"));
45
+ ctx.waitUntil(client.pageView({
46
+ url: request.url,
47
+ path: pathname,
48
+ referrer: request.headers.get("referer") ?? void 0,
49
+ userAgent: request.headers.get("user-agent") ?? void 0,
50
+ ip: request.headers.get("cf-connecting-ip") ?? void 0,
51
+ properties: cacheStatus ? { cache_status: cacheStatus } : void 0
52
+ }));
53
+ } catch {}
54
+ }
55
+ //#endregion
56
+ exports.isHtmlResponse = isHtmlResponse;
57
+ exports.mapCacheStatus = mapCacheStatus;
58
+ exports.trackEdge = trackEdge;
59
+
60
+ //# sourceMappingURL=cloudflare.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare.cjs","names":["shouldTrackPath","createClient"],"sources":["../src/cloudflare.ts"],"sourcesContent":["import { type ClientConfig, createClient } from './core';\nimport { shouldTrackPath } from './matchers';\n\n// Structural Cloudflare types — no @cloudflare/workers-types runtime dependency.\ninterface CfRequestLike {\n url: string;\n headers: { get(name: string): string | null };\n}\ninterface CfResponseLike {\n headers: { get(name: string): string | null };\n}\ninterface CfCtxLike {\n waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type CacheStatus = 'hit' | 'miss' | 'bypass';\n\n/** Map a Cloudflare `cf-cache-status` header to our coarse vocab. */\nexport function mapCacheStatus(header: string | null): CacheStatus | undefined {\n if (!header) return undefined;\n switch (header.toUpperCase()) {\n case 'HIT':\n case 'REVALIDATED':\n return 'hit';\n case 'MISS':\n case 'EXPIRED':\n case 'STALE':\n case 'UPDATING':\n return 'miss';\n case 'BYPASS':\n case 'DYNAMIC':\n return 'bypass';\n default:\n return undefined;\n }\n}\n\n/** True when the response is an HTML document (worth a page_view). */\nexport function isHtmlResponse(response: CfResponseLike): boolean {\n return (response.headers.get('content-type') ?? '')\n .toLowerCase()\n .includes('text/html');\n}\n\nexport interface EdgeConfig extends ClientConfig {\n /** Override the default path matcher. */\n shouldTrack?: (pathname: string) => boolean;\n}\n\n/**\n * Fire-and-forget edge page_view. Reads only headers; never consumes the body;\n * never throws. Call from a Cloudflare Worker:\n * const res = await fetch(request);\n * trackEdge(request, res, ctx, { writeKey: env.PINGAURA_INGEST_KEY, domain: env.PINGAURA_DOMAIN });\n * return res;\n */\nexport function trackEdge(\n request: CfRequestLike,\n response: CfResponseLike,\n ctx: CfCtxLike,\n config: EdgeConfig,\n): void {\n try {\n let pathname: string;\n try {\n pathname = new URL(request.url).pathname;\n } catch {\n return; // malformed url — skip\n }\n\n const matcher = config.shouldTrack ?? shouldTrackPath;\n if (!matcher(pathname) || !isHtmlResponse(response)) return;\n\n // Workers use ctx.waitUntil for fire-and-forget — keepalive off.\n const client = createClient({ ...config, keepalive: false });\n const cacheStatus = mapCacheStatus(response.headers.get('cf-cache-status'));\n\n ctx.waitUntil(\n client.pageView({\n url: request.url,\n path: pathname,\n referrer: request.headers.get('referer') ?? undefined,\n userAgent: request.headers.get('user-agent') ?? undefined,\n ip: request.headers.get('cf-connecting-ip') ?? undefined,\n properties: cacheStatus ? { cache_status: cacheStatus } : undefined,\n }),\n );\n } catch {\n // never throw into the request path\n }\n}\n"],"mappings":";;;;;AAkBA,SAAgB,eAAe,QAAgD;CAC7E,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,QAAQ,OAAO,YAAY,GAA3B;EACE,KAAK;EACL,KAAK,eACH,OAAO;EACT,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,YACH,OAAO;EACT,KAAK;EACL,KAAK,WACH,OAAO;EACT,SACE;CACJ;AACF;;AAGA,SAAgB,eAAe,UAAmC;CAChE,QAAQ,SAAS,QAAQ,IAAI,cAAc,KAAK,GAAA,CAC7C,YAAY,CAAC,CACb,SAAS,WAAW;AACzB;;;;;;;;AAcA,SAAgB,UACd,SACA,UACA,KACA,QACM;CACN,IAAI;EACF,IAAI;EACJ,IAAI;GACF,WAAW,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC;EAClC,QAAQ;GACN;EACF;EAGA,IAAI,EADY,OAAO,eAAeA,iBAAAA,gBAAAA,CACzB,QAAQ,KAAK,CAAC,eAAe,QAAQ,GAAG;EAGrD,MAAM,SAASC,aAAAA,aAAa;GAAE,GAAG;GAAQ,WAAW;EAAM,CAAC;EAC3D,MAAM,cAAc,eAAe,SAAS,QAAQ,IAAI,iBAAiB,CAAC;EAE1E,IAAI,UACF,OAAO,SAAS;GACd,KAAK,QAAQ;GACb,MAAM;GACN,UAAU,QAAQ,QAAQ,IAAI,SAAS,KAAK,KAAA;GAC5C,WAAW,QAAQ,QAAQ,IAAI,YAAY,KAAK,KAAA;GAChD,IAAI,QAAQ,QAAQ,IAAI,kBAAkB,KAAK,KAAA;GAC/C,YAAY,cAAc,EAAE,cAAc,YAAY,IAAI,KAAA;EAC5D,CAAC,CACH;CACF,QAAQ,CAER;AACF"}
@@ -0,0 +1,37 @@
1
+ import { n as ClientConfig } from "./core-DVilpn_i.cjs";
2
+
3
+ //#region src/cloudflare.d.ts
4
+ interface CfRequestLike {
5
+ url: string;
6
+ headers: {
7
+ get(name: string): string | null;
8
+ };
9
+ }
10
+ interface CfResponseLike {
11
+ headers: {
12
+ get(name: string): string | null;
13
+ };
14
+ }
15
+ interface CfCtxLike {
16
+ waitUntil(promise: Promise<unknown>): void;
17
+ }
18
+ type CacheStatus = 'hit' | 'miss' | 'bypass';
19
+ /** Map a Cloudflare `cf-cache-status` header to our coarse vocab. */
20
+ declare function mapCacheStatus(header: string | null): CacheStatus | undefined;
21
+ /** True when the response is an HTML document (worth a page_view). */
22
+ declare function isHtmlResponse(response: CfResponseLike): boolean;
23
+ interface EdgeConfig extends ClientConfig {
24
+ /** Override the default path matcher. */
25
+ shouldTrack?: (pathname: string) => boolean;
26
+ }
27
+ /**
28
+ * Fire-and-forget edge page_view. Reads only headers; never consumes the body;
29
+ * never throws. Call from a Cloudflare Worker:
30
+ * const res = await fetch(request);
31
+ * trackEdge(request, res, ctx, { writeKey: env.PINGAURA_INGEST_KEY, domain: env.PINGAURA_DOMAIN });
32
+ * return res;
33
+ */
34
+ declare function trackEdge(request: CfRequestLike, response: CfResponseLike, ctx: CfCtxLike, config: EdgeConfig): void;
35
+ //#endregion
36
+ export { CacheStatus, EdgeConfig, isHtmlResponse, mapCacheStatus, trackEdge };
37
+ //# sourceMappingURL=cloudflare.d.cts.map
@@ -0,0 +1,37 @@
1
+ import { n as ClientConfig } from "./core-DVilpn_i.mjs";
2
+
3
+ //#region src/cloudflare.d.ts
4
+ interface CfRequestLike {
5
+ url: string;
6
+ headers: {
7
+ get(name: string): string | null;
8
+ };
9
+ }
10
+ interface CfResponseLike {
11
+ headers: {
12
+ get(name: string): string | null;
13
+ };
14
+ }
15
+ interface CfCtxLike {
16
+ waitUntil(promise: Promise<unknown>): void;
17
+ }
18
+ type CacheStatus = 'hit' | 'miss' | 'bypass';
19
+ /** Map a Cloudflare `cf-cache-status` header to our coarse vocab. */
20
+ declare function mapCacheStatus(header: string | null): CacheStatus | undefined;
21
+ /** True when the response is an HTML document (worth a page_view). */
22
+ declare function isHtmlResponse(response: CfResponseLike): boolean;
23
+ interface EdgeConfig extends ClientConfig {
24
+ /** Override the default path matcher. */
25
+ shouldTrack?: (pathname: string) => boolean;
26
+ }
27
+ /**
28
+ * Fire-and-forget edge page_view. Reads only headers; never consumes the body;
29
+ * never throws. Call from a Cloudflare Worker:
30
+ * const res = await fetch(request);
31
+ * trackEdge(request, res, ctx, { writeKey: env.PINGAURA_INGEST_KEY, domain: env.PINGAURA_DOMAIN });
32
+ * return res;
33
+ */
34
+ declare function trackEdge(request: CfRequestLike, response: CfResponseLike, ctx: CfCtxLike, config: EdgeConfig): void;
35
+ //#endregion
36
+ export { CacheStatus, EdgeConfig, isHtmlResponse, mapCacheStatus, trackEdge };
37
+ //# sourceMappingURL=cloudflare.d.mts.map
@@ -0,0 +1,57 @@
1
+ import { t as createClient } from "./core-Cvg8zn6Q.mjs";
2
+ import { t as shouldTrackPath } from "./matchers-CUD5NL5K.mjs";
3
+ //#region src/cloudflare.ts
4
+ /** Map a Cloudflare `cf-cache-status` header to our coarse vocab. */
5
+ function mapCacheStatus(header) {
6
+ if (!header) return void 0;
7
+ switch (header.toUpperCase()) {
8
+ case "HIT":
9
+ case "REVALIDATED": return "hit";
10
+ case "MISS":
11
+ case "EXPIRED":
12
+ case "STALE":
13
+ case "UPDATING": return "miss";
14
+ case "BYPASS":
15
+ case "DYNAMIC": return "bypass";
16
+ default: return;
17
+ }
18
+ }
19
+ /** True when the response is an HTML document (worth a page_view). */
20
+ function isHtmlResponse(response) {
21
+ return (response.headers.get("content-type") ?? "").toLowerCase().includes("text/html");
22
+ }
23
+ /**
24
+ * Fire-and-forget edge page_view. Reads only headers; never consumes the body;
25
+ * never throws. Call from a Cloudflare Worker:
26
+ * const res = await fetch(request);
27
+ * trackEdge(request, res, ctx, { writeKey: env.PINGAURA_INGEST_KEY, domain: env.PINGAURA_DOMAIN });
28
+ * return res;
29
+ */
30
+ function trackEdge(request, response, ctx, config) {
31
+ try {
32
+ let pathname;
33
+ try {
34
+ pathname = new URL(request.url).pathname;
35
+ } catch {
36
+ return;
37
+ }
38
+ if (!(config.shouldTrack ?? shouldTrackPath)(pathname) || !isHtmlResponse(response)) return;
39
+ const client = createClient({
40
+ ...config,
41
+ keepalive: false
42
+ });
43
+ const cacheStatus = mapCacheStatus(response.headers.get("cf-cache-status"));
44
+ ctx.waitUntil(client.pageView({
45
+ url: request.url,
46
+ path: pathname,
47
+ referrer: request.headers.get("referer") ?? void 0,
48
+ userAgent: request.headers.get("user-agent") ?? void 0,
49
+ ip: request.headers.get("cf-connecting-ip") ?? void 0,
50
+ properties: cacheStatus ? { cache_status: cacheStatus } : void 0
51
+ }));
52
+ } catch {}
53
+ }
54
+ //#endregion
55
+ export { isHtmlResponse, mapCacheStatus, trackEdge };
56
+
57
+ //# sourceMappingURL=cloudflare.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare.mjs","names":[],"sources":["../src/cloudflare.ts"],"sourcesContent":["import { type ClientConfig, createClient } from './core';\nimport { shouldTrackPath } from './matchers';\n\n// Structural Cloudflare types — no @cloudflare/workers-types runtime dependency.\ninterface CfRequestLike {\n url: string;\n headers: { get(name: string): string | null };\n}\ninterface CfResponseLike {\n headers: { get(name: string): string | null };\n}\ninterface CfCtxLike {\n waitUntil(promise: Promise<unknown>): void;\n}\n\nexport type CacheStatus = 'hit' | 'miss' | 'bypass';\n\n/** Map a Cloudflare `cf-cache-status` header to our coarse vocab. */\nexport function mapCacheStatus(header: string | null): CacheStatus | undefined {\n if (!header) return undefined;\n switch (header.toUpperCase()) {\n case 'HIT':\n case 'REVALIDATED':\n return 'hit';\n case 'MISS':\n case 'EXPIRED':\n case 'STALE':\n case 'UPDATING':\n return 'miss';\n case 'BYPASS':\n case 'DYNAMIC':\n return 'bypass';\n default:\n return undefined;\n }\n}\n\n/** True when the response is an HTML document (worth a page_view). */\nexport function isHtmlResponse(response: CfResponseLike): boolean {\n return (response.headers.get('content-type') ?? '')\n .toLowerCase()\n .includes('text/html');\n}\n\nexport interface EdgeConfig extends ClientConfig {\n /** Override the default path matcher. */\n shouldTrack?: (pathname: string) => boolean;\n}\n\n/**\n * Fire-and-forget edge page_view. Reads only headers; never consumes the body;\n * never throws. Call from a Cloudflare Worker:\n * const res = await fetch(request);\n * trackEdge(request, res, ctx, { writeKey: env.PINGAURA_INGEST_KEY, domain: env.PINGAURA_DOMAIN });\n * return res;\n */\nexport function trackEdge(\n request: CfRequestLike,\n response: CfResponseLike,\n ctx: CfCtxLike,\n config: EdgeConfig,\n): void {\n try {\n let pathname: string;\n try {\n pathname = new URL(request.url).pathname;\n } catch {\n return; // malformed url — skip\n }\n\n const matcher = config.shouldTrack ?? shouldTrackPath;\n if (!matcher(pathname) || !isHtmlResponse(response)) return;\n\n // Workers use ctx.waitUntil for fire-and-forget — keepalive off.\n const client = createClient({ ...config, keepalive: false });\n const cacheStatus = mapCacheStatus(response.headers.get('cf-cache-status'));\n\n ctx.waitUntil(\n client.pageView({\n url: request.url,\n path: pathname,\n referrer: request.headers.get('referer') ?? undefined,\n userAgent: request.headers.get('user-agent') ?? undefined,\n ip: request.headers.get('cf-connecting-ip') ?? undefined,\n properties: cacheStatus ? { cache_status: cacheStatus } : undefined,\n }),\n );\n } catch {\n // never throw into the request path\n }\n}\n"],"mappings":";;;;AAkBA,SAAgB,eAAe,QAAgD;CAC7E,IAAI,CAAC,QAAQ,OAAO,KAAA;CACpB,QAAQ,OAAO,YAAY,GAA3B;EACE,KAAK;EACL,KAAK,eACH,OAAO;EACT,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK,YACH,OAAO;EACT,KAAK;EACL,KAAK,WACH,OAAO;EACT,SACE;CACJ;AACF;;AAGA,SAAgB,eAAe,UAAmC;CAChE,QAAQ,SAAS,QAAQ,IAAI,cAAc,KAAK,GAAA,CAC7C,YAAY,CAAC,CACb,SAAS,WAAW;AACzB;;;;;;;;AAcA,SAAgB,UACd,SACA,UACA,KACA,QACM;CACN,IAAI;EACF,IAAI;EACJ,IAAI;GACF,WAAW,IAAI,IAAI,QAAQ,GAAG,CAAC,CAAC;EAClC,QAAQ;GACN;EACF;EAGA,IAAI,EADY,OAAO,eAAe,gBAAA,CACzB,QAAQ,KAAK,CAAC,eAAe,QAAQ,GAAG;EAGrD,MAAM,SAAS,aAAa;GAAE,GAAG;GAAQ,WAAW;EAAM,CAAC;EAC3D,MAAM,cAAc,eAAe,SAAS,QAAQ,IAAI,iBAAiB,CAAC;EAE1E,IAAI,UACF,OAAO,SAAS;GACd,KAAK,QAAQ;GACb,MAAM;GACN,UAAU,QAAQ,QAAQ,IAAI,SAAS,KAAK,KAAA;GAC5C,WAAW,QAAQ,QAAQ,IAAI,YAAY,KAAK,KAAA;GAChD,IAAI,QAAQ,QAAQ,IAAI,kBAAkB,KAAK,KAAA;GAC/C,YAAY,cAAc,EAAE,cAAc,YAAY,IAAI,KAAA;EAC5D,CAAC,CACH;CACF,QAAQ,CAER;AACF"}
@@ -0,0 +1,139 @@
1
+ //#region src/contract.ts
2
+ const ANALYTICS_SCHEMA_VERSION = 1;
3
+ const EVENT_TYPES = [
4
+ "page_view",
5
+ "page_leave",
6
+ "web_vitals",
7
+ "track"
8
+ ];
9
+ /** Build a contract-valid event envelope. `now` is injectable for tests. */
10
+ function buildEvent(input, now = () => (/* @__PURE__ */ new Date()).toISOString()) {
11
+ const ts = input.timestamp ?? now();
12
+ return {
13
+ event_id: globalThis.crypto.randomUUID(),
14
+ schema_version: 1,
15
+ type: input.type,
16
+ view_id: input.view_id,
17
+ timestamp: ts,
18
+ sent_at: now(),
19
+ context: input.context,
20
+ properties: input.properties ?? {},
21
+ library: input.library
22
+ };
23
+ }
24
+ //#endregion
25
+ //#region src/core.ts
26
+ const DEFAULT_TIMEOUT_MS = 2e3;
27
+ const DEFAULT_ENDPOINT = "https://telemetry.pingaura.ai/v1/events";
28
+ async function drainAndCountRejected(res) {
29
+ try {
30
+ if (typeof res.json === "function") {
31
+ const rejected = (await res.json())?.rejected;
32
+ if (Array.isArray(rejected)) return rejected.length;
33
+ if (typeof rejected === "number") return rejected;
34
+ return 0;
35
+ }
36
+ } catch {}
37
+ await res.body?.cancel?.().catch(() => {});
38
+ return 0;
39
+ }
40
+ function createClient(config) {
41
+ const fetchImpl = config.fetchImpl ?? globalThis.fetch;
42
+ const warn = config.onWarn ?? ((m) => console.warn(m));
43
+ const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
44
+ const endpoint = config.endpoint ?? DEFAULT_ENDPOINT;
45
+ const warnedStatuses = /* @__PURE__ */ new Set();
46
+ if (!config.writeKey) warn("[pingaura] writeKey missing — analytics disabled");
47
+ if (!config.domain) warn("[pingaura] domain missing — analytics disabled");
48
+ async function send(event, options = {}) {
49
+ if (!config.writeKey || !config.domain) return;
50
+ const headers = {
51
+ "content-type": "application/json",
52
+ authorization: `Bearer ${config.writeKey}`
53
+ };
54
+ if (options.ip) headers["x-pa-client-ip"] = options.ip;
55
+ let body;
56
+ try {
57
+ body = JSON.stringify({
58
+ domain: config.domain,
59
+ events: [event]
60
+ });
61
+ } catch (err) {
62
+ if (config.debug) warn(`[pingaura] failed to serialize event: ${String(err)}`);
63
+ return;
64
+ }
65
+ const controller = new AbortController();
66
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
67
+ try {
68
+ const res = await fetchImpl(endpoint, {
69
+ method: "POST",
70
+ headers,
71
+ body,
72
+ signal: controller.signal,
73
+ keepalive: config.keepalive ?? true
74
+ });
75
+ if (res.status < 200 || res.status >= 300) {
76
+ let detail = "";
77
+ try {
78
+ detail = (await res.text?.() ?? "").slice(0, 200);
79
+ } catch {}
80
+ const message = `[pingaura] ingest rejected (${res.status})${detail ? `: ${detail}` : ""}`;
81
+ if (res.status === 429 || res.status >= 500) {
82
+ if (config.debug) warn(message);
83
+ } else if (!warnedStatuses.has(res.status)) {
84
+ warnedStatuses.add(res.status);
85
+ warn(message);
86
+ }
87
+ return;
88
+ }
89
+ const rejected = await drainAndCountRejected(res);
90
+ if (rejected > 0) warn(`[pingaura] ${rejected} event(s) rejected by collector`);
91
+ } catch (err) {
92
+ if (config.debug) warn(`[pingaura] send failed: ${String(err)}`);
93
+ } finally {
94
+ clearTimeout(timer);
95
+ }
96
+ }
97
+ function safeSend(input, options) {
98
+ let event;
99
+ try {
100
+ event = buildEvent(input);
101
+ } catch (err) {
102
+ if (config.debug) warn(`[pingaura] failed to build event: ${String(err)}`);
103
+ return Promise.resolve();
104
+ }
105
+ return send(event, options);
106
+ }
107
+ return {
108
+ send,
109
+ sendRaw: (input, options) => safeSend(input, options),
110
+ pageView: (input) => safeSend({
111
+ type: "page_view",
112
+ context: {
113
+ url: input.url,
114
+ path: input.path,
115
+ referrer: input.referrer,
116
+ title: input.title,
117
+ locale: input.locale,
118
+ user_agent: input.userAgent
119
+ },
120
+ properties: input.properties
121
+ }, { ip: input.ip }),
122
+ track: (name, properties = {}, context) => safeSend({
123
+ type: "track",
124
+ context: {
125
+ url: context.url,
126
+ path: context.path,
127
+ referrer: context.referrer
128
+ },
129
+ properties: {
130
+ ...properties,
131
+ name
132
+ }
133
+ })
134
+ };
135
+ }
136
+ //#endregion
137
+ export { buildEvent as i, ANALYTICS_SCHEMA_VERSION as n, EVENT_TYPES as r, createClient as t };
138
+
139
+ //# sourceMappingURL=core-Cvg8zn6Q.mjs.map