@prism-analytics/browser 0.0.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/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # @prism-analytics/browser
2
+
3
+ Browser SDK for [Prism](https://prism-analytics.vercel.app) — page views, custom events, error tracking, and privacy-first collection. Built on `@prism-analytics/core`.
4
+
5
+ [![npm](https://img.shields.io/npm/v/@prism-analytics/browser)](https://www.npmjs.com/package/@prism-analytics/browser)
6
+ [![license: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](../../LICENSE)
7
+
8
+ ## Install
9
+
10
+ ```sh
11
+ npm install @prism-analytics/browser
12
+ # yarn add @prism-analytics/browser
13
+ # pnpm add @prism-analytics/browser
14
+ ```
15
+
16
+ ## Quick start
17
+
18
+ ```ts
19
+ import { createBrowserClient } from "@prism-analytics/browser";
20
+
21
+ export const prism = await createBrowserClient({
22
+ sourceKey: "psk_…", // from Prism dashboard -> Sources -> Web
23
+ endpoint: "https://prism-api.orekud.workers.dev",
24
+ collection: { initialState: "granted" }, // or "denied" for consent gate
25
+ pageViews: { mode: "history" }, // or "manual" with usePrismPageView
26
+ });
27
+
28
+ prism.track("checkout_started", { value: 42 });
29
+ ```
30
+
31
+ ## Docs
32
+
33
+ - [Quickstart](https://prism-analytics.vercel.app/docs/start/javascript-sdk)
34
+ - [Capturing events](https://prism-analytics.vercel.app/docs/features/capturing-events)
35
+ - [Page analytics](https://prism-analytics.vercel.app/docs/features/page-analytics)
36
+ - [Error tracking](https://prism-analytics.vercel.app/docs/features/error-tracking)
37
+
38
+ ## License
39
+
40
+ MIT — see [LICENSE](../../LICENSE).
@@ -0,0 +1,170 @@
1
+ import { CaptureResult, ErrorCaptureResult, PrismErrorReporter, ErrorReportInput, PrismDiagnostic, PrismDiagnosticHandle, ErrorReporterShare, ErrorBeforeSend, ErrorReporterOptions, CollectionState, AnonymousPersistence, PrismQueueOptions, SanitizeOptions, BrowserPageViewOptions, PrismClient } from '@prism-analytics/core';
2
+ export { BrowserPageViewOptions, ErrorBeforeSend, ErrorReporterShare, framesFromStack } from '@prism-analytics/core';
3
+
4
+ /**
5
+ * Sanitized page identity for explicit tracking (§11): the PATH ONLY —
6
+ * query strings and hashes are excluded — and the referrer ORIGIN only
7
+ * (never a full URL with query parameters). Returned as plain data so
8
+ * callers decide where to attach it; automatic route tracking is a later
9
+ * task.
10
+ */
11
+ declare function capturePageContext(): {
12
+ path: string;
13
+ referrer: string | null;
14
+ };
15
+
16
+ interface BrowserPageViewController {
17
+ readonly mode: "history" | "manual";
18
+ /** Manual-mode capture; history mode rejects manual calls. Synchronous,
19
+ * track()-style result semantics. */
20
+ capture(input?: {
21
+ path?: string;
22
+ title?: string;
23
+ }): CaptureResult;
24
+ /** Test/diagnostic surface: forces a fresh Web session on next capture. */
25
+ resetForTests(): void;
26
+ }
27
+
28
+ /**
29
+ * Browser error adapter (task-15 slice 3b) — `createBrowserErrorReporter`.
30
+ *
31
+ * Translates browser failure primitives (Error, ErrorEvent,
32
+ * PromiseRejectionEvent, strings, arbitrary rejection reasons) into the
33
+ * core's `ErrorReportInput` shape and drives the runtime-neutral
34
+ * `createPrismErrorReporter` lane from `@prism-analytics/core`.
35
+ *
36
+ * Global error handlers are OPT-IN (never installed by the factory
37
+ * unless `captureGlobalErrors` is set), idempotently installable/
38
+ * uninstallable, and always `handled: false`. A bounded dedupe window
39
+ * coalesces same-fingerprint bursts. "Script error." (the opaque
40
+ * cross-origin message) is captured HONESTLY — its own fingerprintable
41
+ * type, no fabricated frames — so it groups separately instead of being
42
+ * thrown away or faked.
43
+ *
44
+ * Like its analytics sibling, this package only translates browser
45
+ * primitives; the core owns queueing, batching, retries, consent, and
46
+ * sanitization, and unload flushes are the runtime's authenticated
47
+ * keepalive.
48
+ */
49
+ /** Result of `captureException` — core's plus a coarsened `deduped` state. */
50
+ type BrowserCaptureResult = ErrorCaptureResult | {
51
+ readonly status: "deduped";
52
+ readonly id: string;
53
+ };
54
+ interface ErrorCaptureOptions {
55
+ /** Default `false` for global-handler captures; direct calls default `true`. */
56
+ handled?: boolean;
57
+ level?: ErrorReportInput["level"];
58
+ release?: string;
59
+ environment?: string;
60
+ context?: ErrorReportInput["context"];
61
+ breadcrumbs?: ErrorReportInput["breadcrumbs"];
62
+ }
63
+ interface BrowserErrorReporterOptions {
64
+ /** Project source key (ingestion auth; server derives project/source). */
65
+ sourceKey: string;
66
+ /** Ingestion origin chosen at runtime — REQUIRED, never compiled in. */
67
+ endpoint: string;
68
+ /** Safe identity/consent sharing source (wire the analytics client's). */
69
+ share: ErrorReporterShare;
70
+ /** Optional dev-side boundary (immutable in; drop/redact/throw-safe). */
71
+ beforeSend?: ErrorBeforeSend;
72
+ /** Queue/delivery tuning passthrough to the core reporter. */
73
+ queue?: ErrorReporterOptions["queue"];
74
+ /** Optional release + environment stamped on every report. */
75
+ release?: string;
76
+ environment?: string;
77
+ /** Opt-in: install window onerror + unhandledrejection handlers. */
78
+ captureGlobalErrors?: boolean;
79
+ /** Coalescing window in ms for same-fingerprint bursts. Default 1000. */
80
+ dedupeMs?: number;
81
+ /** Diagnostic subscription made BEFORE the reporter starts. */
82
+ onDiagnostic?: (diagnostic: PrismDiagnostic) => void;
83
+ }
84
+ interface BrowserErrorReporter {
85
+ /** The underlying runtime-neutral reporter (flush/shutdown/diagnostics). */
86
+ readonly reporter: PrismErrorReporter;
87
+ readonly installed: boolean;
88
+ /** Number of queued, undelivered error reports. */
89
+ readonly pendingCount: number;
90
+ /**
91
+ * Normalize ANY thrown/collected value into an error report and enqueue
92
+ * it. Invalid callers passing a malformed ErrorReportInput still THROW
93
+ * (same contract as core). Consent/shutdown/queue-capacity return
94
+ * `dropped`; a same-fingerprint duplicate within the dedupe window
95
+ * returns `deduped`.
96
+ */
97
+ captureException(value: unknown, options?: ErrorCaptureOptions): BrowserCaptureResult;
98
+ /** Idempotent: install window error handlers (no-op when installed). */
99
+ install(): void;
100
+ /** Idempotent: remove window error handlers (no-op when not installed). */
101
+ uninstall(): void;
102
+ /** Attempt delivery of all queued batches. */
103
+ flush(): Promise<void>;
104
+ /** Idempotent shutdown: stop handlers, timers, bounded final flush. */
105
+ shutdown(options?: {
106
+ timeoutMs?: number;
107
+ }): Promise<void>;
108
+ /** Subscribe to diagnostics; returns an idempotent remove handle. */
109
+ onDiagnostic(listener: (d: PrismDiagnostic) => void): PrismDiagnosticHandle;
110
+ }
111
+ /**
112
+ * Normalize ANY collected value into an ErrorReportInput: Error instances
113
+ * (frames from stack), ErrorEvent, PromiseRejectionEvent, strings, plain
114
+ * objects that already match the report shape (passthrough), and opaque
115
+ * rejection reasons (summarized, never thrown).
116
+ */
117
+ declare function normalizeErrorValue(value: unknown): ErrorReportInput;
118
+ declare function createBrowserErrorReporter(options: BrowserErrorReporterOptions): Promise<BrowserErrorReporter>;
119
+
120
+ interface BrowserClientOptions {
121
+ /** Source ingestion key (publishable, write-only). */
122
+ sourceKey: string;
123
+ /**
124
+ * Ingestion origin chosen at runtime (hosted or self-hosted) — REQUIRED,
125
+ * never compiled into the package (task-9 §11).
126
+ */
127
+ endpoint: string;
128
+ /** Privacy/collection configuration (explicit consent, like the core). */
129
+ collection: {
130
+ initialState: CollectionState;
131
+ anonymousPersistence?: AnonymousPersistence;
132
+ };
133
+ queue?: PrismQueueOptions;
134
+ sanitize?: SanitizeOptions;
135
+ /**
136
+ * Task 17: explicit Web page-view tracking. Omitted (or undefined) means
137
+ * the client captures NO page views and exposes `pageViews: null`.
138
+ */
139
+ pageViews?: BrowserPageViewOptions;
140
+ }
141
+ /**
142
+ * The Browser client surface: everything PrismClient promises plus a
143
+ * stable page controller when (and only when) pageViews is configured.
144
+ */
145
+ type BrowserPrismClient = PrismClient & {
146
+ readonly pageViews: {
147
+ readonly mode: "history" | "manual";
148
+ capture(input?: {
149
+ path?: string;
150
+ title?: string;
151
+ }): CaptureResult;
152
+ } | null;
153
+ };
154
+ /**
155
+ * Create the minimal browser client (task-9 §11): a thin runtime adapter
156
+ * over the @prism-analytics/core engine. The core owns ALL queueing, consent,
157
+ * sanitization, session, authentication, and retry semantics — this
158
+ * package only translates browser primitives (fetch transport, local
159
+ * storage, timers, lifecycle events) into the runtime seam.
160
+ *
161
+ * - Fails loudly outside a browser (no half-working Node import).
162
+ * - Requires an explicit runtime `endpoint`.
163
+ * - Storage denial (privacy modes) degrades to the core's in-memory
164
+ * queue — never a crash.
165
+ * - Unload flushes use an AUTHENTICATED fetch keepalive — never an
166
+ * unauthenticated sendBeacon fallback.
167
+ */
168
+ declare function createBrowserClient(options: BrowserClientOptions): Promise<BrowserPrismClient>;
169
+
170
+ export { type BrowserCaptureResult, type BrowserClientOptions, type BrowserErrorReporter, type BrowserErrorReporterOptions, type BrowserPageViewController, type BrowserPrismClient, type ErrorCaptureOptions, capturePageContext, createBrowserClient, createBrowserErrorReporter, normalizeErrorValue };
@@ -0,0 +1,170 @@
1
+ import { CaptureResult, ErrorCaptureResult, PrismErrorReporter, ErrorReportInput, PrismDiagnostic, PrismDiagnosticHandle, ErrorReporterShare, ErrorBeforeSend, ErrorReporterOptions, CollectionState, AnonymousPersistence, PrismQueueOptions, SanitizeOptions, BrowserPageViewOptions, PrismClient } from '@prism-analytics/core';
2
+ export { BrowserPageViewOptions, ErrorBeforeSend, ErrorReporterShare, framesFromStack } from '@prism-analytics/core';
3
+
4
+ /**
5
+ * Sanitized page identity for explicit tracking (§11): the PATH ONLY —
6
+ * query strings and hashes are excluded — and the referrer ORIGIN only
7
+ * (never a full URL with query parameters). Returned as plain data so
8
+ * callers decide where to attach it; automatic route tracking is a later
9
+ * task.
10
+ */
11
+ declare function capturePageContext(): {
12
+ path: string;
13
+ referrer: string | null;
14
+ };
15
+
16
+ interface BrowserPageViewController {
17
+ readonly mode: "history" | "manual";
18
+ /** Manual-mode capture; history mode rejects manual calls. Synchronous,
19
+ * track()-style result semantics. */
20
+ capture(input?: {
21
+ path?: string;
22
+ title?: string;
23
+ }): CaptureResult;
24
+ /** Test/diagnostic surface: forces a fresh Web session on next capture. */
25
+ resetForTests(): void;
26
+ }
27
+
28
+ /**
29
+ * Browser error adapter (task-15 slice 3b) — `createBrowserErrorReporter`.
30
+ *
31
+ * Translates browser failure primitives (Error, ErrorEvent,
32
+ * PromiseRejectionEvent, strings, arbitrary rejection reasons) into the
33
+ * core's `ErrorReportInput` shape and drives the runtime-neutral
34
+ * `createPrismErrorReporter` lane from `@prism-analytics/core`.
35
+ *
36
+ * Global error handlers are OPT-IN (never installed by the factory
37
+ * unless `captureGlobalErrors` is set), idempotently installable/
38
+ * uninstallable, and always `handled: false`. A bounded dedupe window
39
+ * coalesces same-fingerprint bursts. "Script error." (the opaque
40
+ * cross-origin message) is captured HONESTLY — its own fingerprintable
41
+ * type, no fabricated frames — so it groups separately instead of being
42
+ * thrown away or faked.
43
+ *
44
+ * Like its analytics sibling, this package only translates browser
45
+ * primitives; the core owns queueing, batching, retries, consent, and
46
+ * sanitization, and unload flushes are the runtime's authenticated
47
+ * keepalive.
48
+ */
49
+ /** Result of `captureException` — core's plus a coarsened `deduped` state. */
50
+ type BrowserCaptureResult = ErrorCaptureResult | {
51
+ readonly status: "deduped";
52
+ readonly id: string;
53
+ };
54
+ interface ErrorCaptureOptions {
55
+ /** Default `false` for global-handler captures; direct calls default `true`. */
56
+ handled?: boolean;
57
+ level?: ErrorReportInput["level"];
58
+ release?: string;
59
+ environment?: string;
60
+ context?: ErrorReportInput["context"];
61
+ breadcrumbs?: ErrorReportInput["breadcrumbs"];
62
+ }
63
+ interface BrowserErrorReporterOptions {
64
+ /** Project source key (ingestion auth; server derives project/source). */
65
+ sourceKey: string;
66
+ /** Ingestion origin chosen at runtime — REQUIRED, never compiled in. */
67
+ endpoint: string;
68
+ /** Safe identity/consent sharing source (wire the analytics client's). */
69
+ share: ErrorReporterShare;
70
+ /** Optional dev-side boundary (immutable in; drop/redact/throw-safe). */
71
+ beforeSend?: ErrorBeforeSend;
72
+ /** Queue/delivery tuning passthrough to the core reporter. */
73
+ queue?: ErrorReporterOptions["queue"];
74
+ /** Optional release + environment stamped on every report. */
75
+ release?: string;
76
+ environment?: string;
77
+ /** Opt-in: install window onerror + unhandledrejection handlers. */
78
+ captureGlobalErrors?: boolean;
79
+ /** Coalescing window in ms for same-fingerprint bursts. Default 1000. */
80
+ dedupeMs?: number;
81
+ /** Diagnostic subscription made BEFORE the reporter starts. */
82
+ onDiagnostic?: (diagnostic: PrismDiagnostic) => void;
83
+ }
84
+ interface BrowserErrorReporter {
85
+ /** The underlying runtime-neutral reporter (flush/shutdown/diagnostics). */
86
+ readonly reporter: PrismErrorReporter;
87
+ readonly installed: boolean;
88
+ /** Number of queued, undelivered error reports. */
89
+ readonly pendingCount: number;
90
+ /**
91
+ * Normalize ANY thrown/collected value into an error report and enqueue
92
+ * it. Invalid callers passing a malformed ErrorReportInput still THROW
93
+ * (same contract as core). Consent/shutdown/queue-capacity return
94
+ * `dropped`; a same-fingerprint duplicate within the dedupe window
95
+ * returns `deduped`.
96
+ */
97
+ captureException(value: unknown, options?: ErrorCaptureOptions): BrowserCaptureResult;
98
+ /** Idempotent: install window error handlers (no-op when installed). */
99
+ install(): void;
100
+ /** Idempotent: remove window error handlers (no-op when not installed). */
101
+ uninstall(): void;
102
+ /** Attempt delivery of all queued batches. */
103
+ flush(): Promise<void>;
104
+ /** Idempotent shutdown: stop handlers, timers, bounded final flush. */
105
+ shutdown(options?: {
106
+ timeoutMs?: number;
107
+ }): Promise<void>;
108
+ /** Subscribe to diagnostics; returns an idempotent remove handle. */
109
+ onDiagnostic(listener: (d: PrismDiagnostic) => void): PrismDiagnosticHandle;
110
+ }
111
+ /**
112
+ * Normalize ANY collected value into an ErrorReportInput: Error instances
113
+ * (frames from stack), ErrorEvent, PromiseRejectionEvent, strings, plain
114
+ * objects that already match the report shape (passthrough), and opaque
115
+ * rejection reasons (summarized, never thrown).
116
+ */
117
+ declare function normalizeErrorValue(value: unknown): ErrorReportInput;
118
+ declare function createBrowserErrorReporter(options: BrowserErrorReporterOptions): Promise<BrowserErrorReporter>;
119
+
120
+ interface BrowserClientOptions {
121
+ /** Source ingestion key (publishable, write-only). */
122
+ sourceKey: string;
123
+ /**
124
+ * Ingestion origin chosen at runtime (hosted or self-hosted) — REQUIRED,
125
+ * never compiled into the package (task-9 §11).
126
+ */
127
+ endpoint: string;
128
+ /** Privacy/collection configuration (explicit consent, like the core). */
129
+ collection: {
130
+ initialState: CollectionState;
131
+ anonymousPersistence?: AnonymousPersistence;
132
+ };
133
+ queue?: PrismQueueOptions;
134
+ sanitize?: SanitizeOptions;
135
+ /**
136
+ * Task 17: explicit Web page-view tracking. Omitted (or undefined) means
137
+ * the client captures NO page views and exposes `pageViews: null`.
138
+ */
139
+ pageViews?: BrowserPageViewOptions;
140
+ }
141
+ /**
142
+ * The Browser client surface: everything PrismClient promises plus a
143
+ * stable page controller when (and only when) pageViews is configured.
144
+ */
145
+ type BrowserPrismClient = PrismClient & {
146
+ readonly pageViews: {
147
+ readonly mode: "history" | "manual";
148
+ capture(input?: {
149
+ path?: string;
150
+ title?: string;
151
+ }): CaptureResult;
152
+ } | null;
153
+ };
154
+ /**
155
+ * Create the minimal browser client (task-9 §11): a thin runtime adapter
156
+ * over the @prism-analytics/core engine. The core owns ALL queueing, consent,
157
+ * sanitization, session, authentication, and retry semantics — this
158
+ * package only translates browser primitives (fetch transport, local
159
+ * storage, timers, lifecycle events) into the runtime seam.
160
+ *
161
+ * - Fails loudly outside a browser (no half-working Node import).
162
+ * - Requires an explicit runtime `endpoint`.
163
+ * - Storage denial (privacy modes) degrades to the core's in-memory
164
+ * queue — never a crash.
165
+ * - Unload flushes use an AUTHENTICATED fetch keepalive — never an
166
+ * unauthenticated sendBeacon fallback.
167
+ */
168
+ declare function createBrowserClient(options: BrowserClientOptions): Promise<BrowserPrismClient>;
169
+
170
+ export { type BrowserCaptureResult, type BrowserClientOptions, type BrowserErrorReporter, type BrowserErrorReporterOptions, type BrowserPageViewController, type BrowserPrismClient, type ErrorCaptureOptions, capturePageContext, createBrowserClient, createBrowserErrorReporter, normalizeErrorValue };