@libo11y/webext 0.4.0 → 0.6.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/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @libo11y/webext
2
2
 
3
3
  The libo11y Manifest V3 extension platform for TypeScript. It builds on
4
- [`@libo11y/web`](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/web).
4
+ [`@libo11y/web`](https://github.com/libo11y/libo11y/tree/main/ts/packages/web).
5
5
  `setupWorker()` runs in the extension's service worker. The browser can
6
6
  stop the worker at any time, so the worker stores every batch in IndexedDB
7
7
  before it sends it, and it drains the queue on every wake.
@@ -17,6 +17,10 @@ It has no RUM features. Those belong to `@libo11y/rum`, whose
17
17
  npm install @libo11y/webext
18
18
  ```
19
19
 
20
+ `@opentelemetry/api` is a peer dependency. npm 7 and later and Bun install
21
+ it automatically. If your application already depends on it, use a version
22
+ that satisfies `>=1.10.0 <1.11.0`.
23
+
20
24
  ## Quick start
21
25
 
22
26
  `manifest.json`:
@@ -84,9 +88,12 @@ the message that woke the worker reaches it. Batches that arrive before the
84
88
  telemetry is ready are answered once it is.
85
89
 
86
90
  `setupWorker` takes core's `TelemetryOptions` and the
87
- [`@libo11y/web` export options](https://github.com/jamesainslie/libo11y/tree/main/ts/packages/web#endpoints-and-cors):
91
+ [`@libo11y/web` export options](https://github.com/libo11y/libo11y/tree/main/ts/packages/web#endpoints-and-cors):
88
92
  `endpoint`, the per-signal endpoints, `headers`, `env`, `transport` and
89
- `userAgent`. It differs from the page `setup` in these ways:
93
+ `userAgent`. The worker uses the same endpoint order as the page.
94
+ Per-signal options come first, followed by `endpoint`, per-signal
95
+ environment values, and the common environment value. The worker
96
+ differs from the page `setup` in these ways:
90
97
 
91
98
  - Every batch is put in the IndexedDB queue, leased, before its first
92
99
  attempt. It is removed after a success or a fatal error and rescheduled
@@ -97,9 +104,16 @@ telemetry is ready are answered once it is.
97
104
  interval to 15000 ms, because the worker can stop at any time.
98
105
  `OTEL_BSP_SCHEDULE_DELAY`, `OTEL_BLRP_SCHEDULE_DELAY` and
99
106
  `OTEL_METRIC_EXPORT_INTERVAL` in `env` override them.
100
- - `serviceVersion` defaults to the manifest's `version`.
107
+ - The manifest's `version` is the detected `service.version`. A
108
+ `service.version` in `OTEL_RESOURCE_ATTRIBUTES` beats it, and the
109
+ `serviceVersion` option beats both, as resource layers merge in core.
101
110
  - The console sink defaults to off.
102
111
  - `setupWorker` rejects when there is no `chrome.runtime`.
112
+ - `telemetry.shutdown({ timeoutMillis })` keeps one deadline for the
113
+ providers and the delivery, as on a page. A batch still on the wire when
114
+ it passes is aborted and stays in the queue for the next wake. Shutdown
115
+ also removes every listener the handle added, the traced ones from
116
+ `onMessage` included.
103
117
 
104
118
  | Worker option | Default | Effect |
105
119
  | ----------------- | ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------- |
@@ -165,9 +179,11 @@ content scripts to read. A content script starts from the stored state, or
165
179
 
166
180
  Every context writes its changes to storage and applies changes from other
167
181
  contexts. `grant()` and `revoke()` in any context change consent for the
168
- whole extension. A revoke anywhere clears the worker's IndexedDB queue and
169
- each context's buffers, as `revoke()` does on a page. A stored state never
170
- moves back to `pending`.
182
+ whole extension. Each saved revocation advances a generation in storage.
183
+ The worker and other contexts use it to clear data from the previous
184
+ grant, even when they first observe the change after consent was granted
185
+ again. The worker also clears its queue when it starts denied. A stored
186
+ state never moves back to `pending`.
171
187
 
172
188
  The worker's `consent` options decide the privacy signals for the whole
173
189
  extension. When a respected DNT or GPC signal refuses a stored grant, from
@@ -182,7 +198,8 @@ with the listener's result. It rejects with the listener's error message,
182
198
  or when no traced listener answered. `onMessage` runs the listener inside
183
199
  the sender's context, so spans it starts are children of the sender's
184
200
  active span. A returned promise is awaited, and its value is the reply.
185
- `onMessage` returns a function that removes the listener.
201
+ `onMessage` returns a function that removes the listener. Shutting down
202
+ either handle removes its remaining traced listeners.
186
203
 
187
204
  Payloads cross `chrome.runtime.sendMessage`, so they must survive the
188
205
  browser's JSON serialization of runtime messages.
@@ -194,12 +211,17 @@ Every libo11y message is a plain JSON object with `libo11y: 1`
194
211
  other listeners in the extension keep working. Do not send messages with a
195
212
  `libo11y` field of your own.
196
213
 
197
- | `type` | From | Fields | Meaning |
198
- | -------------- | ---------------------- | ------------------------------------------------ | -------------------------------------------------------------------------------------- |
199
- | `export` | content script or page | `signal` (`traces`, `metrics` or `logs`), `body` | one OTLP/HTTP JSON request body for the worker to queue and send |
200
- | `export-reply` | worker | `ok`, `reason` when refused | the batch is queued, or the reason it was refused |
201
- | `traced` | any context | `carrier`, `payload` | an application message with `traceparent`, and `tracestate` and `baggage` when present |
202
- | `traced-reply` | the listener's context | `ok`, `result` or `error` | the listener's result, or its error message |
214
+ | `type` | From | Fields | Meaning |
215
+ | -------------- | ---------------------- | --------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
216
+ | `export` | content script or page | `signal` (`traces`, `metrics` or `logs`), `body`, optional `revocation` (integer) | one OTLP/HTTP JSON request body for the worker to queue and send |
217
+ | `export-reply` | worker | `ok`, `reason` when refused | the batch is queued, or the reason it was refused |
218
+ | `traced` | any context | `carrier`, `payload` | an application message with `traceparent`, and `tracestate` and `baggage` when present |
219
+ | `traced-reply` | the listener's context | `ok`, `result` or `error` | the listener's result, or its error message |
220
+
221
+ On an `export` frame, `revocation` is the nonnegative safe integer consent
222
+ revocation generation observed by the sender (omitted is treated as `0`).
223
+ The worker refuses any frame whose generation differs from the stored
224
+ revocation generation.
203
225
 
204
226
  ## Known limitations
205
227
 
package/dist/chrome.d.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  /**
2
- * Contract, frozen by the L4 scaffold. Owned by WP5.
3
- *
4
2
  * The slice of the extension API libo11y uses, typed by hand so the package needs no @types/chrome
5
3
  * and tests can pass a fake. Chrome and Firefox both expose it as `chrome` in Manifest V3, with
6
4
  * promise-returning methods.
@@ -47,7 +45,7 @@ export interface ChromeLike {
47
45
  /** Needs the "storage" permission. */
48
46
  readonly storage?: {
49
47
  readonly local: {
50
- get(key: string): Promise<Record<string, unknown>>;
48
+ get(key: string | string[]): Promise<Record<string, unknown>>;
51
49
  set(items: Record<string, unknown>): Promise<void>;
52
50
  };
53
51
  readonly onChanged: ExtensionEvent<(changes: Record<string, StorageChangeLike>, areaName: string) => void>;
package/dist/chrome.js CHANGED
@@ -1,6 +1,4 @@
1
1
  /**
2
- * Contract, frozen by the L4 scaffold. Owned by WP5.
3
- *
4
2
  * The slice of the extension API libo11y uses, typed by hand so the package needs no @types/chrome
5
3
  * and tests can pass a fake. Chrome and Firefox both expose it as `chrome` in Manifest V3, with
6
4
  * promise-returning methods.
@@ -1,37 +1,30 @@
1
1
  /**
2
- * WP5 (webext). One consent state for the whole extension, in chrome.storage.local.
2
+ * One consent state and revocation generation for the whole extension.
3
3
  */
4
4
  import type { ConsentController, ConsentState } from "@libo11y/web/internal";
5
- import type { ChromeLike } from "./chrome.ts";
6
- /** The chrome.storage.local key. */
5
+ import type { ChromeLike, RuntimeMessageListener } from "./chrome.ts";
7
6
  export declare const CONSENT_STORAGE_KEY = "libo11y.consent";
8
- /** The stored state, or undefined when none is stored, storage is unavailable or the value is malformed. */
9
- export declare function readStoredConsent(chrome: ChromeLike): Promise<ConsentState | undefined>;
7
+ export declare const CONSENT_REVOCATION_KEY = "libo11y.consent.revocation";
8
+ export declare const QUEUE_REVOCATION_KEY = "libo11y.queue.revocation";
9
+ interface ConsentSnapshot {
10
+ readonly state: ConsentState | undefined;
11
+ readonly revocation: number;
12
+ readonly queueRevocation: number;
13
+ }
14
+ export declare function readConsentSnapshot(chrome: ChromeLike): Promise<ConsentSnapshot>;
15
+ type LocalStorage = NonNullable<ChromeLike["storage"]>["local"];
16
+ export declare function writeRevocation(storage: LocalStorage, seen: number): Promise<number>;
17
+ export declare function consentWriteListener(chrome: ChromeLike): RuntimeMessageListener;
10
18
  /** A running sync between a controller and storage. */
11
19
  export interface ConsentSync {
12
- /** Stops syncing both ways. Idempotent. */
13
20
  readonly stop: () => void;
14
- /**
15
- * Re-reads the stored state and applies it now, resolving once applied. For a decision that
16
- * must not wait for storage.onChanged, such as accepting a batch just after a grant elsewhere.
17
- */
18
- readonly refresh: () => Promise<void>;
21
+ /** Reports whether the latest stored state and any revocation cleanup were applied. */
22
+ readonly refresh: () => Promise<boolean>;
23
+ /** True once the latest refresh read stored consent without error. */
24
+ readonly verified: () => boolean;
25
+ readonly observedRevocation: () => number;
26
+ /** The observed generation, including local revocation writes already queued. */
27
+ readonly revocation: () => Promise<number>;
19
28
  }
20
- /**
21
- * Keeps controller and storage in step: every controller change is written, and a storage change
22
- * from another context is applied with grant() or revoke() when it differs (so a revoke anywhere
23
- * clears this context's queues). Returns the running sync.
24
- *
25
- * A storage change is a signal to re-read the stored state rather than a value to apply, because
26
- * storage operations run in order: the echo of an earlier write of this context can arrive after a
27
- * later change here, and the re-read then returns the later state. "pending" is never applied,
28
- * because consent has no way back to it. The stored state is also read once at the start, to
29
- * catch a change between readStoredConsent and this call.
30
- *
31
- * Privacy signals deny everywhere: when a stored "granted" cannot be applied because this
32
- * controller respects a privacy signal (DNT or GPC) that is set, "denied" is written back, and
33
- * every other context then revokes. So a grant in a content script, whose controller reads no
34
- * signals, is undone extension-wide when the worker's signals refuse it, as is a stored grant the
35
- * worker finds when it wakes.
36
- */
37
- export declare function syncConsent(controller: ConsentController, chrome: ChromeLike): ConsentSync;
29
+ export declare function syncConsent(controller: ConsentController, chrome: ChromeLike, seenRevocation?: number, worker?: boolean): ConsentSync;
30
+ export {};
@@ -1,97 +1,150 @@
1
1
  import { diag } from "@opentelemetry/api";
2
- /** The chrome.storage.local key. */
3
2
  export const CONSENT_STORAGE_KEY = "libo11y.consent";
4
- function isConsentState(v) {
5
- return v === "pending" || v === "granted" || v === "denied";
3
+ export const CONSENT_REVOCATION_KEY = "libo11y.consent.revocation";
4
+ export const QUEUE_REVOCATION_KEY = "libo11y.queue.revocation";
5
+ function generation(value) {
6
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : 0;
6
7
  }
7
- /** The stored state, or undefined when none is stored, storage is unavailable or the value is malformed. */
8
- export async function readStoredConsent(chrome) {
9
- if (chrome.storage === undefined)
10
- return undefined;
11
- try {
12
- const items = await chrome.storage.local.get(CONSENT_STORAGE_KEY);
13
- const value = items[CONSENT_STORAGE_KEY];
14
- return isConsentState(value) ? value : undefined;
15
- }
16
- catch (err) {
17
- diag.warn("o11y: reading the stored consent", err);
18
- return undefined;
19
- }
8
+ export async function readConsentSnapshot(chrome) {
9
+ const items = await chrome.storage?.local.get([
10
+ CONSENT_STORAGE_KEY,
11
+ CONSENT_REVOCATION_KEY,
12
+ QUEUE_REVOCATION_KEY,
13
+ ]);
14
+ const state = items?.[CONSENT_STORAGE_KEY];
15
+ return {
16
+ state: state === "pending" || state === "granted" || state === "denied" ? state : undefined,
17
+ revocation: generation(items?.[CONSENT_REVOCATION_KEY]),
18
+ queueRevocation: generation(items?.[QUEUE_REVOCATION_KEY]),
19
+ };
20
+ }
21
+ let writeTail = Promise.resolve();
22
+ export function writeRevocation(storage, seen) {
23
+ const write = writeTail.then(async () => {
24
+ const stored = await storage.get(CONSENT_REVOCATION_KEY);
25
+ const next = Math.max(seen, generation(stored[CONSENT_REVOCATION_KEY])) + 1;
26
+ await storage.set({ [CONSENT_STORAGE_KEY]: "denied", [CONSENT_REVOCATION_KEY]: next });
27
+ return next;
28
+ });
29
+ // A failed write must not prevent a later revocation from being stored.
30
+ writeTail = write.catch(() => { });
31
+ return write;
32
+ }
33
+ // The worker serializes the read-modify-write across tabs, whose content scripts run on
34
+ // different origins. Its listener is active while setup is still opening the queue.
35
+ export function consentWriteListener(chrome) {
36
+ return (message, sender, reply) => {
37
+ const storage = chrome.storage?.local;
38
+ if (sender.id !== chrome.runtime.id || typeof message !== "object" || message === null || !storage) {
39
+ return undefined;
40
+ }
41
+ if (!Object.hasOwn(message, CONSENT_REVOCATION_KEY))
42
+ return undefined;
43
+ const seen = generation(message[CONSENT_REVOCATION_KEY]);
44
+ void writeRevocation(storage, seen)
45
+ .then(reply, () => reply(undefined))
46
+ .catch((err) => diag.debug("o11y: answering a consent write", err));
47
+ return true;
48
+ };
20
49
  }
21
- /**
22
- * Keeps controller and storage in step: every controller change is written, and a storage change
23
- * from another context is applied with grant() or revoke() when it differs (so a revoke anywhere
24
- * clears this context's queues). Returns the running sync.
25
- *
26
- * A storage change is a signal to re-read the stored state rather than a value to apply, because
27
- * storage operations run in order: the echo of an earlier write of this context can arrive after a
28
- * later change here, and the re-read then returns the later state. "pending" is never applied,
29
- * because consent has no way back to it. The stored state is also read once at the start, to
30
- * catch a change between readStoredConsent and this call.
31
- *
32
- * Privacy signals deny everywhere: when a stored "granted" cannot be applied because this
33
- * controller respects a privacy signal (DNT or GPC) that is set, "denied" is written back, and
34
- * every other context then revokes. So a grant in a content script, whose controller reads no
35
- * signals, is undone extension-wide when the worker's signals refuse it, as is a stored grant the
36
- * worker finds when it wakes.
37
- */
38
- export function syncConsent(controller, chrome) {
50
+ export function syncConsent(controller, chrome, seenRevocation = 0, worker = false) {
39
51
  const storage = chrome.storage;
40
- if (storage === undefined)
41
- return { stop: () => { }, refresh: async () => { } };
52
+ if (storage === undefined) {
53
+ return {
54
+ stop: () => { },
55
+ refresh: async () => true,
56
+ verified: () => true,
57
+ observedRevocation: () => 0,
58
+ revocation: async () => 0,
59
+ };
60
+ }
61
+ const { consent } = controller;
42
62
  let stopped = false;
43
63
  let applying = false;
64
+ let verified = false;
65
+ let writing = Promise.resolve();
66
+ let refreshing = Promise.resolve(true);
44
67
  const write = (state) => {
45
- storage.local.set({ [CONSENT_STORAGE_KEY]: state }).catch((err) => {
46
- diag.warn("o11y: storing the consent state", err);
47
- });
68
+ writing = writing
69
+ .then(async () => {
70
+ if (state === "denied") {
71
+ // A standalone content setup can still persist consent without a libo11y worker.
72
+ const saved = worker
73
+ ? undefined
74
+ : await chrome.runtime
75
+ .sendMessage({ [CONSENT_REVOCATION_KEY]: seenRevocation })
76
+ .catch(() => undefined);
77
+ seenRevocation = generation(saved) || (await writeRevocation(storage.local, seenRevocation));
78
+ }
79
+ else {
80
+ await storage.local.set({ [CONSENT_STORAGE_KEY]: state });
81
+ }
82
+ })
83
+ .catch((err) => diag.warn("o11y: storing the consent state", err));
84
+ return writing;
48
85
  };
49
- const apply = (stored) => {
50
- if (stopped || stored === undefined || stored === "pending")
51
- return;
52
- const consent = controller.consent;
53
- if (stored === consent.state())
54
- return;
55
- applying = true;
56
- try {
57
- if (stored === "granted")
58
- consent.grant();
59
- else
60
- void consent.revoke();
61
- }
62
- finally {
63
- applying = false;
86
+ const apply = async () => {
87
+ while (!stopped) {
88
+ const pending = writing;
89
+ await pending;
90
+ const { state, revocation } = await readConsentSnapshot(chrome);
91
+ if (stopped)
92
+ break;
93
+ if (pending !== writing)
94
+ continue;
95
+ if (revocation > seenRevocation || (state === "denied" && consent.state() !== state)) {
96
+ seenRevocation = Math.max(seenRevocation, revocation);
97
+ applying = true;
98
+ const cleanup = consent.revoke();
99
+ applying = false;
100
+ await cleanup;
101
+ // The stored state can change during asynchronous cleanup.
102
+ continue;
103
+ }
104
+ if (state === "granted" && consent.state() !== state) {
105
+ applying = true;
106
+ const granted = consent.grant();
107
+ applying = false;
108
+ if (granted !== state)
109
+ await write("denied");
110
+ }
111
+ verified = true;
112
+ return true;
64
113
  }
65
- // A respected privacy signal refused the grant: store the refusal, so every context denies.
66
- if (stored === "granted" && consent.state() !== "granted")
67
- write(consent.state());
114
+ return false;
68
115
  };
69
- const refresh = () => readStoredConsent(chrome)
70
- .then(apply)
71
- .catch((err) => {
72
- diag.warn("o11y: applying the stored consent", err);
73
- });
74
- const reconcile = () => {
75
- void refresh();
116
+ const refresh = () => {
117
+ refreshing = refreshing.then(apply).catch((err) => {
118
+ applying = false;
119
+ verified = false;
120
+ diag.warn("o11y: applying the stored consent", err);
121
+ return false;
122
+ });
123
+ return refreshing;
76
124
  };
77
- const unsubscribe = controller.consent.subscribe((state) => {
78
- if (stopped || applying)
79
- return;
80
- write(state);
125
+ const unsubscribe = consent.subscribe((state) => {
126
+ if (!stopped && !applying)
127
+ void write(state);
81
128
  });
82
- const onChanged = (changes, areaName) => {
83
- if (areaName !== "local" || !Object.hasOwn(changes, CONSENT_STORAGE_KEY))
84
- return;
85
- reconcile();
129
+ const onChanged = (changes, area) => {
130
+ if (area === "local" && (CONSENT_STORAGE_KEY in changes || CONSENT_REVOCATION_KEY in changes)) {
131
+ void refresh();
132
+ }
86
133
  };
87
134
  storage.onChanged.addListener(onChanged);
88
- reconcile();
89
- const stop = () => {
90
- if (stopped)
91
- return;
92
- stopped = true;
93
- unsubscribe();
94
- storage.onChanged.removeListener(onChanged);
135
+ void refresh();
136
+ return {
137
+ stop() {
138
+ stopped = true;
139
+ unsubscribe();
140
+ storage.onChanged.removeListener(onChanged);
141
+ },
142
+ refresh,
143
+ verified: () => verified,
144
+ observedRevocation: () => seenRevocation,
145
+ revocation: async () => {
146
+ await writing;
147
+ return seenRevocation;
148
+ },
95
149
  };
96
- return { stop, refresh };
97
150
  }
package/dist/content.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * WP5 (webext). setupContentScript for content scripts and extension pages.
2
+ * setupContentScript for content scripts and extension pages.
3
3
  */
4
4
  import { type Platform } from "@libo11y/core";
5
5
  import { type DocumentLoadOptions, type HttpInstrumentationOptions } from "@libo11y/web";
@@ -38,7 +38,7 @@ export interface ContentDeps {
38
38
  export declare function defaultContentDeps(): ContentDeps;
39
39
  /**
40
40
  * Builds and installs telemetry whose exporters forward to the worker. In order: the consent
41
- * controller from readStoredConsent (default "pending") and syncConsent; a memory queue; the
41
+ * controller from readConsentSnapshot (default "pending") and syncConsent; a memory queue; the
42
42
  * messaging transport; a delivery (mode "normal", always online, because messaging the worker
43
43
  * needs no network and the worker handles being offline); webPlatform with name "webext" and endpoints
44
44
  * set for all three signals to the marker "libo11y-webext:worker" (the batches never leave by
@@ -52,7 +52,7 @@ export declare function defaultContentDeps(): ContentDeps;
52
52
  */
53
53
  export declare function setupContentScript(options?: ContentScriptSetupOptions): Promise<ContentScriptTelemetry>;
54
54
  /**
55
- * setupContentScript over deps. Internal: the seam the unit tests and @libo11y/rum use. With install
55
+ * setupContentScript over deps. Internal: the seam the unit tests and `@libo11y/rum` use. With install
56
56
  * false it builds the telemetry as web's createTelemetry does: no globals, no instrumentation and
57
57
  * no active consent, still flushing on hide (tests that run two contexts in one process).
58
58
  */
package/dist/content.js CHANGED
@@ -1,13 +1,13 @@
1
1
  /**
2
- * WP5 (webext). setupContentScript for content scripts and extension pages.
2
+ * setupContentScript for content scripts and extension pages.
3
3
  */
4
4
  import { createTelemetryWith, setupWith, } from "@libo11y/core";
5
5
  import { installXhrInstrumentation, recordDocumentLoad, } from "@libo11y/web";
6
- import { activeConsent, createConsentController, createDelivery, createMemoryQueue, installFetchInstrumentation, installFlushOnHide, setActiveConsent, webPlatform, } from "@libo11y/web/internal";
6
+ import { activeConsent, createConsentController, createDelivery, createMemoryQueue, installFetchInstrumentation, installFlushOnHide, setActiveConsent, shutdownWithin, webPlatform, } from "@libo11y/web/internal";
7
7
  import { flushInBackground } from "@libo11y/web/portable";
8
8
  import { diag } from "@opentelemetry/api";
9
9
  import { getChrome } from "./chrome.js";
10
- import { readStoredConsent, syncConsent } from "./consent-sync.js";
10
+ import { readConsentSnapshot, syncConsent } from "./consent-sync.js";
11
11
  import { createTracedMessaging } from "./messaging.js";
12
12
  import { createMessagingTransport } from "./messaging-transport.js";
13
13
  /**
@@ -41,7 +41,7 @@ export function defaultContentDeps() {
41
41
  }
42
42
  /**
43
43
  * Builds and installs telemetry whose exporters forward to the worker. In order: the consent
44
- * controller from readStoredConsent (default "pending") and syncConsent; a memory queue; the
44
+ * controller from readConsentSnapshot (default "pending") and syncConsent; a memory queue; the
45
45
  * messaging transport; a delivery (mode "normal", always online, because messaging the worker
46
46
  * needs no network and the worker handles being offline); webPlatform with name "webext" and endpoints
47
47
  * set for all three signals to the marker "libo11y-webext:worker" (the batches never leave by
@@ -67,7 +67,7 @@ async function cleanup(steps) {
67
67
  }
68
68
  }
69
69
  /**
70
- * setupContentScript over deps. Internal: the seam the unit tests and @libo11y/rum use. With install
70
+ * setupContentScript over deps. Internal: the seam the unit tests and `@libo11y/rum` use. With install
71
71
  * false it builds the telemetry as web's createTelemetry does: no globals, no instrumentation and
72
72
  * no active consent, still flushing on hide (tests that run two contexts in one process).
73
73
  */
@@ -76,20 +76,22 @@ export async function setupContentScriptWith(options, deps, install = true) {
76
76
  if (chrome === undefined) {
77
77
  throw new Error("o11y: setupContentScript needs the extension API (chrome.runtime)");
78
78
  }
79
- const stored = await readStoredConsent(chrome);
79
+ const { state: stored, revocation } = await readConsentSnapshot(chrome);
80
80
  const controller = deps.createConsentController(stored === undefined ? {} : { initial: stored });
81
- const steps = [syncConsent(controller, chrome).stop];
81
+ const sync = syncConsent(controller, chrome, revocation);
82
+ const steps = [sync.stop];
82
83
  const queue = deps.createMemoryQueue({});
83
84
  steps.push(() => queue.close());
84
85
  const delivery = deps.createDelivery({
85
- transport: createMessagingTransport(chrome),
86
+ transport: createMessagingTransport(chrome, undefined, sync.observedRevocation),
86
87
  queue,
87
88
  gate: controller,
88
89
  mode: () => "normal",
89
90
  // Messaging the worker needs no network; the worker queues while the browser is offline.
90
91
  isOnline: () => true,
91
92
  });
92
- steps.unshift(() => delivery.shutdown());
93
+ // Kept apart from steps: a working handle shuts the delivery down under its deadline itself.
94
+ const stopDelivery = () => delivery.shutdown();
93
95
  const endpoints = {
94
96
  traces: WORKER_ENDPOINT,
95
97
  metrics: WORKER_ENDPOINT,
@@ -100,6 +102,17 @@ export async function setupContentScriptWith(options, deps, install = true) {
100
102
  ...(options.userAgent === undefined ? {} : { userAgent: options.userAgent }),
101
103
  };
102
104
  let telemetry;
105
+ // Erase retries even if consent changes while core is still starting. Another grant can send
106
+ // only after erasure and consent writes, so retries keep their original generation.
107
+ steps.unshift(controller.onRevoke(async () => {
108
+ const cleared = Promise.all([delivery.clear(), sync.revocation()]);
109
+ try {
110
+ await telemetry?.forceFlush();
111
+ }
112
+ finally {
113
+ await cleared;
114
+ }
115
+ }));
103
116
  try {
104
117
  const platform = deps.webPlatform({
105
118
  name: "webext",
@@ -116,24 +129,13 @@ export async function setupContentScriptWith(options, deps, install = true) {
116
129
  : await createTelemetryWith(coreOptions, platform);
117
130
  }
118
131
  catch (err) {
119
- await cleanup(steps);
132
+ await cleanup([stopDelivery, ...steps]);
120
133
  throw err;
121
134
  }
122
135
  const core = telemetry;
123
136
  const doc = deps.document;
124
137
  if (doc !== undefined)
125
138
  steps.unshift(deps.installFlushOnHide(doc, deps.window, () => flushInBackground(core, "flush on hide")));
126
- steps.unshift(
127
- // The queue is emptied first, whatever the flush does, as on a page.
128
- controller.onRevoke(async () => {
129
- const cleared = delivery.clear();
130
- try {
131
- await core.forceFlush();
132
- }
133
- finally {
134
- await cleared;
135
- }
136
- }));
137
139
  const messaging = createTracedMessaging(chrome, core.propagator);
138
140
  const uninstalls = [];
139
141
  // Core's handle extended in place, so identity-keyed lookups such as exemplarStoreOf still work.
@@ -144,9 +146,11 @@ export async function setupContentScriptWith(options, deps, install = true) {
144
146
  let shutdownPromise;
145
147
  handle.shutdown = (opts) => {
146
148
  shutdownPromise ??= (async () => {
147
- const report = await coreShutdown(opts);
149
+ // One deadline: core's providers, then the delivery's drain in what is left of it.
150
+ const report = await shutdownWithin(coreShutdown, delivery, opts);
148
151
  await cleanup([
149
152
  ...uninstalls,
153
+ messaging.dispose,
150
154
  () => {
151
155
  if (activeConsent() === controller.consent)
152
156
  setActiveConsent(undefined);
package/dist/index.d.ts CHANGED
@@ -3,8 +3,6 @@
3
3
  * every batch to IndexedDB before sending because the worker can stop at any time, and
4
4
  * setupContentScript for content scripts and extension pages, which forward their records to the
5
5
  * worker by runtime messaging. Trace context crosses with every traced message. No RUM features.
6
- *
7
- * Scaffold, frozen: the public API. Changing it needs the architect's sign-off.
8
6
  */
9
7
  export type { Consent, ConsentOptions, ConsentState, WebTelemetry } from "@libo11y/web";
10
8
  export type { ChromeLike, ExtensionEvent, MessageSenderLike, RuntimeMessageListener, StorageChangeLike, } from "./chrome.ts";
package/dist/index.js CHANGED
@@ -3,8 +3,6 @@
3
3
  * every batch to IndexedDB before sending because the worker can stop at any time, and
4
4
  * setupContentScript for content scripts and extension pages, which forward their records to the
5
5
  * worker by runtime messaging. Trace context crosses with every traced message. No RUM features.
6
- *
7
- * Scaffold, frozen: the public API. Changing it needs the architect's sign-off.
8
6
  */
9
7
  export { setupContentScript } from "./content.js";
10
8
  export { PROTOCOL_VERSION, } from "./protocol.js";
@@ -1,7 +1,8 @@
1
1
  /**
2
- * @libo11y/webext/internal: the seams @libo11y/rum composes. For libo11y packages only; it follows
3
- * the package version but carries no compatibility promise and has no API report.
2
+ * @libo11y/webext/internal: the seams @libo11y/rum composes. For libo11y packages only.
3
+ * It follows the package version and carries no compatibility promise.
4
4
  */
5
- export type { ChromeLike } from "./chrome.ts";
5
+ export type { ChromeLike, ExtensionEvent, MessageSenderLike, RuntimeMessageListener, StorageChangeLike, } from "./chrome.ts";
6
6
  export { type ContentDeps, defaultContentDeps, setupContentScriptWith, WORKER_ENDPOINT } from "./content.ts";
7
+ export type { ContentScriptSetupOptions, ContentScriptTelemetry, TracedMessageListener, TracedMessaging, WorkerSetupOptions, WorkerTelemetry, } from "./options.ts";
7
8
  export { defaultWorkerDeps, setupWorkerWith, type WorkerDeps } from "./worker.ts";
package/dist/internal.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @libo11y/webext/internal: the seams @libo11y/rum composes. For libo11y packages only; it follows
3
- * the package version but carries no compatibility promise and has no API report.
2
+ * @libo11y/webext/internal: the seams @libo11y/rum composes. For libo11y packages only.
3
+ * It follows the package version and carries no compatibility promise.
4
4
  */
5
5
  export { defaultContentDeps, setupContentScriptWith, WORKER_ENDPOINT } from "./content.js";
6
6
  export { defaultWorkerDeps, setupWorkerWith } from "./worker.js";
@@ -1,5 +1,5 @@
1
1
  /**
2
- * WP5 (webext). The Transport a content script or extension page uses: each batch goes to the
2
+ * The Transport a content script or extension page uses: each batch goes to the
3
3
  * worker as an ExportMessage.
4
4
  */
5
5
  import type { Transport } from "@libo11y/web/internal";
@@ -10,4 +10,4 @@ import type { ChromeLike } from "./chrome.ts";
10
10
  * extension reloaded) or a timeout of timeoutMillis (default 10000) is "retry". The mode is
11
11
  * ignored: messaging has no unload budget.
12
12
  */
13
- export declare function createMessagingTransport(chrome: ChromeLike, timeoutMillis?: number): Transport;
13
+ export declare function createMessagingTransport(chrome: ChromeLike, timeoutMillis?: number, revocation?: () => number): Transport;
@@ -10,7 +10,7 @@ function errorText(err) {
10
10
  * extension reloaded) or a timeout of timeoutMillis (default 10000) is "retry". The mode is
11
11
  * ignored: messaging has no unload budget.
12
12
  */
13
- export function createMessagingTransport(chrome, timeoutMillis = DEFAULT_TIMEOUT_MILLIS) {
13
+ export function createMessagingTransport(chrome, timeoutMillis = DEFAULT_TIMEOUT_MILLIS, revocation) {
14
14
  return {
15
15
  async send(req) {
16
16
  const message = {
@@ -18,6 +18,7 @@ export function createMessagingTransport(chrome, timeoutMillis = DEFAULT_TIMEOUT
18
18
  type: "export",
19
19
  signal: req.signal,
20
20
  body: req.body,
21
+ ...(revocation === undefined ? {} : { revocation: revocation() }),
21
22
  };
22
23
  let timer;
23
24
  const expired = new Promise((resolve) => {
@@ -1,20 +1,17 @@
1
1
  /**
2
- * WP5 (webext). Trace context across runtime messages.
2
+ * Trace context across runtime messages.
3
3
  */
4
4
  import { type TextMapPropagator } from "@opentelemetry/api";
5
5
  import type { ChromeLike, RuntimeMessageListener } from "./chrome.ts";
6
- import type { TracedMessageListener, TracedMessaging } from "./options.ts";
7
- /**
8
- * The runtime.onMessage listener behind TracedMessaging.onMessage: it extracts the carrier, runs
9
- * listener under context.with(extracted), answers with a TracedReply (awaiting a promise result,
10
- * returning true), and ignores any message that is not a TracedMessage.
11
- */
12
- export declare function tracedListener(propagator: TextMapPropagator, listener: TracedMessageListener): RuntimeMessageListener;
6
+ import type { TracedMessaging } from "./options.ts";
13
7
  /**
14
8
  * Traced messaging over chrome with propagator (the telemetry's, so the baggage egress filter
15
9
  * applies). sendMessage injects the active context into a TracedMessage and unwraps the
16
- * TracedReply. onMessage adds a tracedListener.
10
+ * TracedReply. dispose removes the listeners registered through onMessage.
11
+ * The worker also reads the listener set to replay messages received during startup.
17
12
  */
18
- export declare function createTracedMessaging(chrome: ChromeLike, propagator: TextMapPropagator): TracedMessaging;
13
+ export declare function createTracedMessaging(chrome: ChromeLike, propagator: TextMapPropagator, listeners?: Set<RuntimeMessageListener>): TracedMessaging & {
14
+ dispose(): void;
15
+ };
19
16
  /** tabs.sendMessage counterpart of TracedMessaging.sendMessage. */
20
17
  export declare function sendTracedTabMessage<R>(chrome: ChromeLike, propagator: TextMapPropagator, tabId: number, payload: unknown): Promise<R>;
package/dist/messaging.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * WP5 (webext). Trace context across runtime messages.
2
+ * Trace context across runtime messages.
3
3
  */
4
4
  import { context, defaultTextMapGetter, defaultTextMapSetter, ROOT_CONTEXT, } from "@opentelemetry/api";
5
5
  import { isReply, isTracedMessage, PROTOCOL_VERSION, } from "./protocol.js";
@@ -41,7 +41,7 @@ function failed(err) {
41
41
  * listener under context.with(extracted), answers with a TracedReply (awaiting a promise result,
42
42
  * returning true), and ignores any message that is not a TracedMessage.
43
43
  */
44
- export function tracedListener(propagator, listener) {
44
+ function tracedListener(propagator, listener) {
45
45
  return (message, sender, sendResponse) => {
46
46
  if (!isTracedMessage(message))
47
47
  return undefined;
@@ -65,14 +65,29 @@ export function tracedListener(propagator, listener) {
65
65
  /**
66
66
  * Traced messaging over chrome with propagator (the telemetry's, so the baggage egress filter
67
67
  * applies). sendMessage injects the active context into a TracedMessage and unwraps the
68
- * TracedReply. onMessage adds a tracedListener.
68
+ * TracedReply. dispose removes the listeners registered through onMessage.
69
+ * The worker also reads the listener set to replay messages received during startup.
69
70
  */
70
- export function createTracedMessaging(chrome, propagator) {
71
+ export function createTracedMessaging(chrome, propagator, listeners = new Set()) {
72
+ const runtimeMessages = chrome.runtime.onMessage;
71
73
  return {
72
74
  onMessage(listener) {
73
75
  const onRuntimeMessage = tracedListener(propagator, listener);
74
- chrome.runtime.onMessage.addListener(onRuntimeMessage);
75
- return () => chrome.runtime.onMessage.removeListener(onRuntimeMessage);
76
+ runtimeMessages.addListener(onRuntimeMessage);
77
+ listeners.add(onRuntimeMessage);
78
+ return () => {
79
+ if (listeners.delete(onRuntimeMessage))
80
+ runtimeMessages.removeListener(onRuntimeMessage);
81
+ };
82
+ },
83
+ dispose() {
84
+ try {
85
+ for (const listener of listeners)
86
+ runtimeMessages.removeListener(listener);
87
+ }
88
+ finally {
89
+ listeners.clear();
90
+ }
76
91
  },
77
92
  sendMessage(payload) {
78
93
  const message = tracedMessage(propagator, payload);
package/dist/options.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Contract, frozen by the L4 scaffold. The public options and handles of @libo11y/webext.
2
+ * The public options and handles of @libo11y/webext.
3
3
  */
4
4
  import type { BrowserExportOptions, ConsentOptions, HttpInstrumentationOptions, TelemetryOptions, WebInstrumentationOptions, WebTelemetry } from "@libo11y/web";
5
5
  import type { ContextManager } from "@opentelemetry/api";
@@ -1,11 +1,11 @@
1
1
  /**
2
- * WP5 (webext). The runtime messaging protocol between content scripts or extension pages and the
3
- * service worker. The types are a contract frozen by the L4 scaffold; the guards are WP5's.
2
+ * The runtime messaging protocol between content scripts or extension pages and the service
3
+ * worker.
4
4
  *
5
5
  * Every libo11y message is a plain JSON object with `libo11y: 1`, so it survives Chrome's JSON
6
6
  * serialization of runtime messages and other listeners can tell it apart.
7
7
  */
8
- import { type OtlpSignal } from "@libo11y/web/internal";
8
+ import type { OtlpSignal } from "@libo11y/web";
9
9
  /** The protocol version every message carries. A listener ignores any other value. */
10
10
  export declare const PROTOCOL_VERSION = 1;
11
11
  /** A content script's or page's export batch, for the worker to persist and deliver. */
@@ -15,6 +15,8 @@ export interface ExportMessage {
15
15
  readonly signal: OtlpSignal;
16
16
  /** The OTLP/HTTP JSON request body, exactly as the worker will post it. */
17
17
  readonly body: string;
18
+ /** The consent revocation generation observed by the sender. */
19
+ readonly revocation?: number;
18
20
  }
19
21
  /**
20
22
  * The worker's answer to an ExportMessage, sent once the batch is in the worker's IndexedDB queue
package/dist/protocol.js CHANGED
@@ -1,10 +1,3 @@
1
- /**
2
- * WP5 (webext). The runtime messaging protocol between content scripts or extension pages and the
3
- * service worker. The types are a contract frozen by the L4 scaffold; the guards are WP5's.
4
- *
5
- * Every libo11y message is a plain JSON object with `libo11y: 1`, so it survives Chrome's JSON
6
- * serialization of runtime messages and other listeners can tell it apart.
7
- */
8
1
  import { OTLP_SIGNALS } from "@libo11y/web/internal";
9
2
  /** The protocol version every message carries. A listener ignores any other value. */
10
3
  export const PROTOCOL_VERSION = 1;
@@ -26,7 +19,9 @@ function isCarrier(c) {
26
19
  export function isExportMessage(m) {
27
20
  return (framed(m, "export") &&
28
21
  OTLP_SIGNALS.includes(m.signal) &&
29
- typeof m.body === "string");
22
+ typeof m.body === "string" &&
23
+ (m.revocation === undefined ||
24
+ (typeof m.revocation === "number" && Number.isSafeInteger(m.revocation) && m.revocation >= 0)));
30
25
  }
31
26
  /** True for a well-formed TracedMessage: libo11y 1 and a carrier of string values. */
32
27
  export function isTracedMessage(m) {
package/dist/version.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The @libo11y/webext package version. scripts/release.ts keeps it equal to package.json. */
2
- export declare const VERSION = "0.4.0";
2
+ export declare const VERSION = "0.6.0";
package/dist/version.js CHANGED
@@ -1,2 +1,2 @@
1
1
  /** The @libo11y/webext package version. scripts/release.ts keeps it equal to package.json. */
2
- export const VERSION = "0.4.0";
2
+ export const VERSION = "0.6.0";
package/dist/worker.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * WP5 (webext). setupWorker for a Manifest V3 service worker.
2
+ * setupWorker for a Manifest V3 service worker.
3
3
  */
4
4
  import { type Platform } from "@libo11y/core";
5
5
  import type { BrowserExportOptions, HttpInstrumentationOptions } from "@libo11y/web";
@@ -27,15 +27,16 @@ export declare function defaultWorkerDeps(): WorkerDeps;
27
27
  /**
28
28
  * Builds and installs the worker's telemetry. Call it at the top level of the worker script on
29
29
  * every wake. In order: the consent controller with the stored state beating options.consent
30
- * (readStoredConsent) and syncConsent; openQueue (IndexedDB at the extension origin), releasing
30
+ * and syncConsent; openQueue (IndexedDB at the extension origin), releasing
31
31
  * every lease an earlier wake left (it is the queue's only user, so none of those sends is still in
32
32
  * flight); the HTTP
33
33
  * transport with sendBeacon undefined; a delivery with persistFirst true, mode always "normal" and a
34
34
  * lease of three times transport.timeoutMillis when that is longer than the default;
35
- * webPlatform with name "webext" and WORKER_ENV_DEFAULTS; setupWith; serviceVersion defaulting to
36
- * the manifest version. Then: the runtime.onMessage listener for ExportMessages from this
37
- * extension's own contexts (sender.id === runtime.id), which puts each accepted batch in the queue,
38
- * replies, and drains; the worker's fetch instrumentation; and a drain of whatever the last wake
35
+ * webPlatform with name "webext" and WORKER_ENV_DEFAULTS, with the manifest version as a detected
36
+ * service.version (below OTEL_RESOURCE_ATTRIBUTES and the serviceVersion option); setupWith. A wake
37
+ * to a denied consent clears the queue before the delivery is built. Then: the runtime.onMessage
38
+ * listener for ExportMessages from this extension's own contexts (sender.id === runtime.id),
39
+ * which puts each accepted batch in the queue, replies, and drains; the worker's fetch instrumentation; and a drain of whatever the last wake
39
40
  * left. Rejects like setup on a bad configuration.
40
41
  *
41
42
  * The export listener is registered before the first await, so the message that woke the worker
package/dist/worker.js CHANGED
@@ -1,12 +1,12 @@
1
1
  /**
2
- * WP5 (webext). setupWorker for a Manifest V3 service worker.
2
+ * setupWorker for a Manifest V3 service worker.
3
3
  */
4
- import { setupWith } from "@libo11y/core";
5
- import { activeConsent, createConsentController, createDelivery, createHttpTransport, installFetchInstrumentation, OTLP_SIGNALS, openQueue, resolveEndpoints, setActiveConsent, webPlatform, } from "@libo11y/web/internal";
4
+ import { setupWith, } from "@libo11y/core";
5
+ import { activeConsent, createConsentController, createDelivery, createHttpTransport, installFetchInstrumentation, OTLP_SIGNALS, openQueue, resolveEndpoints, setActiveConsent, shutdownWithin, webPlatform, } from "@libo11y/web/internal";
6
6
  import { diag } from "@opentelemetry/api";
7
7
  import { getChrome } from "./chrome.js";
8
- import { CONSENT_STORAGE_KEY, readStoredConsent, syncConsent } from "./consent-sync.js";
9
- import { createTracedMessaging, sendTracedTabMessage, tracedListener } from "./messaging.js";
8
+ import { CONSENT_STORAGE_KEY, consentWriteListener, QUEUE_REVOCATION_KEY, readConsentSnapshot, syncConsent, writeRevocation, } from "./consent-sync.js";
9
+ import { createTracedMessaging, sendTracedTabMessage } from "./messaging.js";
10
10
  import { isExportMessage, isTracedMessage, PROTOCOL_VERSION } from "./protocol.js";
11
11
  /** OTEL_* defaults for the worker, under the caller's env: short delays, because the worker can stop at any time. */
12
12
  export const WORKER_ENV_DEFAULTS = {
@@ -30,15 +30,16 @@ export function defaultWorkerDeps() {
30
30
  /**
31
31
  * Builds and installs the worker's telemetry. Call it at the top level of the worker script on
32
32
  * every wake. In order: the consent controller with the stored state beating options.consent
33
- * (readStoredConsent) and syncConsent; openQueue (IndexedDB at the extension origin), releasing
33
+ * and syncConsent; openQueue (IndexedDB at the extension origin), releasing
34
34
  * every lease an earlier wake left (it is the queue's only user, so none of those sends is still in
35
35
  * flight); the HTTP
36
36
  * transport with sendBeacon undefined; a delivery with persistFirst true, mode always "normal" and a
37
37
  * lease of three times transport.timeoutMillis when that is longer than the default;
38
- * webPlatform with name "webext" and WORKER_ENV_DEFAULTS; setupWith; serviceVersion defaulting to
39
- * the manifest version. Then: the runtime.onMessage listener for ExportMessages from this
40
- * extension's own contexts (sender.id === runtime.id), which puts each accepted batch in the queue,
41
- * replies, and drains; the worker's fetch instrumentation; and a drain of whatever the last wake
38
+ * webPlatform with name "webext" and WORKER_ENV_DEFAULTS, with the manifest version as a detected
39
+ * service.version (below OTEL_RESOURCE_ATTRIBUTES and the serviceVersion option); setupWith. A wake
40
+ * to a denied consent clears the queue before the delivery is built. Then: the runtime.onMessage
41
+ * listener for ExportMessages from this extension's own contexts (sender.id === runtime.id),
42
+ * which puts each accepted batch in the queue, replies, and drains; the worker's fetch instrumentation; and a drain of whatever the last wake
42
43
  * left. Rejects like setup on a bad configuration.
43
44
  *
44
45
  * The export listener is registered before the first await, so the message that woke the worker
@@ -71,6 +72,21 @@ export function setupWorker(options = {}) {
71
72
  function leaseForTimeout(timeoutMillis) {
72
73
  return Math.max(30_000, 3 * timeoutMillis);
73
74
  }
75
+ /**
76
+ * platform with the manifest version as a detected service.version, so OTEL_RESOURCE_ATTRIBUTES and
77
+ * the serviceVersion option both beat it, as core merges the layers.
78
+ */
79
+ function withManifestVersion(platform, version) {
80
+ if (version.trim() === "")
81
+ return platform;
82
+ return {
83
+ ...platform,
84
+ async detectResource(hermetic) {
85
+ const layers = await platform.detectResource(hermetic);
86
+ return { ...layers, detected: { ...layers.detected, "service.version": version } };
87
+ },
88
+ };
89
+ }
74
90
  function refused(reason) {
75
91
  return { libo11y: PROTOCOL_VERSION, type: "export-reply", ok: false, reason };
76
92
  }
@@ -89,18 +105,41 @@ async function accept(message, target) {
89
105
  return refused("the worker's telemetry is not set up");
90
106
  if (!isExportMessage(message))
91
107
  return refused("malformed export message");
92
- await target.refreshConsent();
93
- if (!target.gate.recording())
108
+ let epoch = target.grantEpoch();
109
+ const beforeRevocation = target.consentSync.observedRevocation();
110
+ const stillGranted = () => epoch === target.grantEpoch() && target.gate.recording();
111
+ if (!(await target.consentSync.refresh()))
112
+ return refused("stored consent could not be read");
113
+ const revocation = target.consentSync.observedRevocation();
114
+ if ((message.revocation ?? 0) !== revocation)
94
115
  return refused(CONSENT_CLOSED);
95
- const entry = await target.queue.put({ signal: message.signal, body: message.body });
96
- if (entry === undefined)
97
- return refused("the queue refused the batch");
98
- if (!target.gate.recording()) {
99
- // Revoked while the batch was being stored: the revoke's clear may have run before the put.
100
- await target.queue.remove([entry.id]);
116
+ // Catching up to the message's own revocation generation re-opened consent cleanly.
117
+ if (revocation !== beforeRevocation)
118
+ epoch = target.grantEpoch();
119
+ if (target.sdkDisabled)
120
+ return ACCEPTED;
121
+ if (!stillGranted())
101
122
  return refused(CONSENT_CLOSED);
123
+ // Register the write before starting it, and keep it pending until any rollback finishes.
124
+ const pending = Promise.resolve().then(async () => {
125
+ await target.markQueue(revocation);
126
+ if (!stillGranted())
127
+ return refused(CONSENT_CLOSED);
128
+ const entry = await target.queue.put({ signal: message.signal, body: message.body });
129
+ if (!stillGranted()) {
130
+ if (entry !== undefined)
131
+ await target.queue.remove([entry.id]);
132
+ return refused(CONSENT_CLOSED);
133
+ }
134
+ return entry === undefined ? refused("the queue refused the batch") : ACCEPTED;
135
+ });
136
+ target.pendingAccepts.add(pending);
137
+ try {
138
+ return await pending;
139
+ }
140
+ finally {
141
+ target.pendingAccepts.delete(pending);
102
142
  }
103
- return ACCEPTED;
104
143
  }
105
144
  // answer accepts message, replies, and drains on acceptance. It never rejects: a failure is a
106
145
  // refusal, and a reply that cannot be sent (the sender went away) still leaves the batch drained.
@@ -119,8 +158,8 @@ async function answer(message, target, sendResponse) {
119
158
  catch (err) {
120
159
  diag.debug("o11y: webext worker could not answer an export", err);
121
160
  }
122
- if (reply.ok)
123
- void target?.delivery.drain();
161
+ if (reply.ok && target !== undefined && !target.sdkDisabled)
162
+ void target.delivery.drain();
124
163
  }
125
164
  /** How many early traced messages the worker holds at most; more are left to other contexts. */
126
165
  const MAX_HELD_TRACED = 100;
@@ -144,6 +183,8 @@ function queueOptions(options) {
144
183
  }
145
184
  /** setupWorker over deps. Internal: the seam the unit tests use. */
146
185
  export async function setupWorkerWith(options, deps) {
186
+ const hermetic = options.hermetic === true;
187
+ const sdkDisabled = !hermetic && (options.env?.OTEL_SDK_DISABLED ?? "").trim().toLowerCase() === "true";
147
188
  const chrome = deps.chrome;
148
189
  if (chrome === undefined) {
149
190
  throw new Error("o11y: setupWorker needs the extension API (chrome.runtime) of a service worker");
@@ -153,28 +194,29 @@ export async function setupWorkerWith(options, deps) {
153
194
  const ready = new Promise((resolve) => {
154
195
  settle = resolve;
155
196
  });
156
- const onExport = (message, sender, sendResponse) => {
157
- if (!isExportFrame(message) || sender.id !== chrome.runtime.id)
197
+ const acceptForwarded = options.acceptForwarded !== false;
198
+ const onConsentWrite = consentWriteListener(chrome);
199
+ const onMessage = (message, sender, sendResponse) => {
200
+ if (onConsentWrite(message, sender, sendResponse))
201
+ return true;
202
+ if (!acceptForwarded || !isExportFrame(message) || sender.id !== chrome.runtime.id)
158
203
  return undefined;
159
204
  void ready.then((target) => answer(message, target, sendResponse));
160
205
  return true;
161
206
  };
162
- const acceptForwarded = options.acceptForwarded !== false;
163
- if (acceptForwarded)
164
- chrome.runtime.onMessage.addListener(onExport);
207
+ chrome.runtime.onMessage.addListener(onMessage);
165
208
  const removeExportListener = () => {
166
- if (acceptForwarded)
167
- chrome.runtime.onMessage.removeListener(onExport);
209
+ chrome.runtime.onMessage.removeListener(onMessage);
168
210
  };
169
211
  // The application can add its traced listeners only once this resolves, after the browser has
170
212
  // dispatched the message that woke the worker. So traced messages that no traced listener can
171
213
  // take yet are held, and replayed one task after setup resolves to the listeners added by then.
172
214
  // Held messages nobody takes are left unanswered, for another context's listener to answer.
173
- const tracedListeners = [];
215
+ const tracedListeners = new Set();
174
216
  const held = [];
175
217
  let holding = true;
176
218
  const onEarlyTraced = (message, sender, sendResponse) => {
177
- if (!holding || tracedListeners.length > 0 || held.length >= MAX_HELD_TRACED)
219
+ if (!holding || tracedListeners.size > 0 || held.length >= MAX_HELD_TRACED)
178
220
  return undefined;
179
221
  if (!isTracedMessage(message) || sender.id !== chrome.runtime.id)
180
222
  return undefined;
@@ -211,31 +253,61 @@ export async function setupWorkerWith(options, deps) {
211
253
  }
212
254
  };
213
255
  const steps = [];
256
+ // Kept apart from steps: a working handle shuts the delivery down under its deadline itself.
257
+ let stopDelivery;
214
258
  let built;
215
259
  let core;
216
- let sync;
260
+ const storage = chrome.storage?.local;
261
+ let storedRevocation;
262
+ let queueRevocation;
263
+ let queueUsable = true;
264
+ let persistentQueue = false;
265
+ let consentSync;
266
+ const markQueue = async (generation) => {
267
+ // A memory fallback cannot attest to any IndexedDB batches left by an earlier wake.
268
+ if (!persistentQueue || generation <= queueRevocation)
269
+ return;
270
+ await storage?.set({ [QUEUE_REVOCATION_KEY]: generation });
271
+ queueRevocation = Math.max(queueRevocation, generation);
272
+ };
217
273
  try {
218
- const stored = await readStoredConsent(chrome);
274
+ const queue = await deps.openQueue(queueOptions(options));
275
+ persistentQueue = queue.kind !== "memory";
276
+ steps.push(() => queue.close());
277
+ // The worker is the only queue consumer. Leases left by an earlier wake have no active send.
278
+ await queue.releaseLeases();
279
+ const snapshot = await readConsentSnapshot(chrome);
280
+ const stored = snapshot.state;
281
+ storedRevocation = snapshot.revocation;
282
+ queueRevocation = snapshot.queueRevocation;
219
283
  const initial = stored ?? options.consent?.initial;
220
284
  const controller = deps.createConsentController({
221
285
  ...options.consent,
222
286
  ...(initial === undefined ? {} : { initial }),
223
287
  });
224
288
  const initialState = controller.consent.state();
225
- if (stored === undefined && initialState !== "pending" && chrome.storage !== undefined) {
226
- chrome.storage.local.set({ [CONSENT_STORAGE_KEY]: initialState }).catch((err) => {
289
+ if (stored === undefined && initialState !== "pending" && storage !== undefined) {
290
+ try {
291
+ if (initialState === "denied")
292
+ storedRevocation = await writeRevocation(storage, storedRevocation);
293
+ else
294
+ await storage.set({ [CONSENT_STORAGE_KEY]: initialState });
295
+ }
296
+ catch (err) {
227
297
  diag.warn("o11y: storing the initial consent state", err);
228
- });
298
+ }
229
299
  }
230
- sync = syncConsent(controller, chrome);
231
- steps.push(sync.stop);
232
- const queue = await deps.openQueue(queueOptions(options));
233
- steps.push(() => queue.close());
234
- // The worker is the only context that uses its queue, so a lease held now is one the browser
235
- // cut off when it stopped an earlier wake mid-send. Released before the delivery exists, so no
236
- // send of this wake is in flight yet, and the first drain sends those entries at once.
237
- await queue.releaseLeases();
238
- const endpoints = deps.resolveEndpoints(options, options.hermetic === true);
300
+ // A regrant can arrive before the worker wakes. Clear any queue from an earlier grant
301
+ // before delivery starts, even when the extension currently has consent.
302
+ if (controller.consent.state() === "denied" || storedRevocation > queueRevocation) {
303
+ await queue.clear(true);
304
+ await markQueue(storedRevocation);
305
+ }
306
+ const deliveryGate = {
307
+ recording: () => queueUsable && (consentSync?.verified() ?? false) && controller.recording(),
308
+ subscribe: controller.subscribe,
309
+ };
310
+ const endpoints = deps.resolveEndpoints(options, hermetic);
239
311
  const t = options.transport ?? {};
240
312
  const transport = deps.createHttpTransport({
241
313
  endpoints,
@@ -247,7 +319,8 @@ export async function setupWorkerWith(options, deps) {
247
319
  const delivery = deps.createDelivery({
248
320
  transport,
249
321
  queue,
250
- gate: controller,
322
+ gate: deliveryGate,
323
+ disabled: sdkDisabled,
251
324
  persistFirst: true,
252
325
  mode: () => "normal",
253
326
  ...(t.initialBackoffMillis === undefined ? {} : { initialBackoffMillis: t.initialBackoffMillis }),
@@ -255,8 +328,8 @@ export async function setupWorkerWith(options, deps) {
255
328
  // A lease shorter than a send could let the next drain claim the entry mid-send and resend it.
256
329
  ...(t.timeoutMillis === undefined ? {} : { leaseMillis: leaseForTimeout(t.timeoutMillis) }),
257
330
  });
258
- steps.unshift(() => delivery.shutdown());
259
- const platform = deps.webPlatform({
331
+ stopDelivery = () => delivery.shutdown();
332
+ const web = deps.webPlatform({
260
333
  name: "webext",
261
334
  exportOptions: options,
262
335
  endpoints,
@@ -266,51 +339,55 @@ export async function setupWorkerWith(options, deps) {
266
339
  envDefaults: WORKER_ENV_DEFAULTS,
267
340
  ...(options.contextManager === undefined ? {} : { contextManager: options.contextManager }),
268
341
  });
269
- const coreOptions = {
270
- ...options,
271
- console: options.console ?? false,
272
- serviceVersion: options.serviceVersion ?? chrome.runtime.getManifest().version,
273
- };
342
+ const platform = withManifestVersion(web, chrome.runtime.getManifest().version);
343
+ const coreOptions = { ...options, console: options.console ?? false };
274
344
  core = await setupWith(coreOptions, platform);
275
- built = { controller, queue, delivery, endpoints };
345
+ built = { controller, deliveryGate, queue, delivery, endpoints };
276
346
  }
277
347
  catch (err) {
278
348
  removeExportListener();
279
349
  releaseHeld();
280
350
  settle(undefined);
281
- await cleanup(steps);
351
+ await cleanup([...(stopDelivery === undefined ? [] : [stopDelivery]), ...steps]);
282
352
  throw err;
283
353
  }
284
- const { controller, queue, delivery, endpoints } = built;
354
+ const { controller, deliveryGate, queue, delivery, endpoints } = built;
285
355
  const telemetry = core;
356
+ const sync = syncConsent(controller, chrome, storedRevocation, true);
357
+ consentSync = sync;
358
+ steps.push(sync.stop);
359
+ let grantEpoch = 0;
360
+ const pendingAccepts = new Set();
361
+ const unregisterGate = controller.subscribe((open) => {
362
+ if (!open)
363
+ grantEpoch++;
364
+ });
286
365
  // The queue is emptied first, whatever the flush does: a flush waits for exports in flight, up to
287
366
  // its deadline, and a worker stopped in that time would otherwise keep the queue for a later grant.
288
367
  const unregisterRevoke = controller.onRevoke(async () => {
289
- const cleared = delivery.clear();
290
- try {
291
- await telemetry.forceFlush();
292
- }
293
- finally {
294
- await cleared;
368
+ queueUsable = false;
369
+ const generation = sync.revocation();
370
+ const accepted = Promise.allSettled(pendingAccepts);
371
+ const purge = async () => {
372
+ const [cleared, writes] = await Promise.all([delivery.clear(true).catch(() => false), accepted]);
373
+ if (cleared === false || writes.some((result) => result.status === "rejected"))
374
+ await queue.clear(true);
375
+ await markQueue(await generation);
376
+ queueUsable = true;
377
+ };
378
+ const outcomes = await Promise.allSettled([purge(), telemetry.forceFlush()]);
379
+ for (const outcome of outcomes) {
380
+ if (outcome.status === "rejected")
381
+ throw outcome.reason;
295
382
  }
296
383
  });
297
- const messaging = createTracedMessaging(chrome, telemetry.propagator);
384
+ const messaging = createTracedMessaging(chrome, telemetry.propagator, tracedListeners);
298
385
  const uninstalls = [];
299
386
  // Core's handle extended in place, so identity-keyed lookups such as exemplarStoreOf still work.
300
387
  const handle = telemetry;
301
388
  Object.defineProperty(handle, "consent", { value: controller.consent, enumerable: true });
302
389
  Object.assign(handle, {
303
- onMessage: (listener) => {
304
- const onRuntimeMessage = tracedListener(telemetry.propagator, listener);
305
- tracedListeners.push(onRuntimeMessage);
306
- chrome.runtime.onMessage.addListener(onRuntimeMessage);
307
- return () => {
308
- const i = tracedListeners.indexOf(onRuntimeMessage);
309
- if (i >= 0)
310
- tracedListeners.splice(i, 1);
311
- chrome.runtime.onMessage.removeListener(onRuntimeMessage);
312
- };
313
- },
390
+ onMessage: messaging.onMessage,
314
391
  sendMessage: messaging.sendMessage,
315
392
  sendTabMessage: (tabId, payload) => sendTracedTabMessage(chrome, telemetry.propagator, tabId, payload),
316
393
  });
@@ -320,10 +397,13 @@ export async function setupWorkerWith(options, deps) {
320
397
  shutdownPromise ??= (async () => {
321
398
  removeExportListener();
322
399
  releaseHeld();
323
- const report = await coreShutdown(opts);
400
+ // One deadline: core's providers, then the delivery's drain in what is left of it.
401
+ const report = await shutdownWithin(coreShutdown, delivery, opts);
324
402
  await cleanup([
325
403
  ...uninstalls,
404
+ messaging.dispose,
326
405
  unregisterRevoke,
406
+ unregisterGate,
327
407
  () => {
328
408
  if (activeConsent() === controller.consent)
329
409
  setActiveConsent(undefined);
@@ -334,7 +414,9 @@ export async function setupWorkerWith(options, deps) {
334
414
  })();
335
415
  return shutdownPromise;
336
416
  };
417
+ let refreshed = false;
337
418
  try {
419
+ refreshed = await sync.refresh();
338
420
  setActiveConsent(controller.consent);
339
421
  if (options.fetch !== false) {
340
422
  const f = typeof options.fetch === "object" ? options.fetch : {};
@@ -353,8 +435,18 @@ export async function setupWorkerWith(options, deps) {
353
435
  await handle.shutdown();
354
436
  throw err;
355
437
  }
356
- settle({ gate: controller, queue, delivery, refreshConsent: sync?.refresh ?? (async () => { }) });
438
+ settle({
439
+ sdkDisabled,
440
+ gate: deliveryGate,
441
+ queue,
442
+ delivery,
443
+ grantEpoch: () => grantEpoch,
444
+ pendingAccepts,
445
+ consentSync: sync,
446
+ markQueue,
447
+ });
357
448
  setTimeout(releaseHeld, 0);
358
- void delivery.drain();
449
+ if (refreshed)
450
+ void delivery.drain();
359
451
  return handle;
360
452
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@libo11y/webext",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "The libo11y Manifest V3 extension platform for TypeScript: setup for the service worker with a queue persisted to IndexedDB on every batch, setup for content scripts and extension pages that forward their records to the worker by runtime messaging, and trace context that crosses with every message.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -17,20 +17,23 @@
17
17
  },
18
18
  "repository": {
19
19
  "type": "git",
20
- "url": "git+https://github.com/jamesainslie/libo11y.git",
20
+ "url": "git+https://github.com/libo11y/libo11y.git",
21
21
  "directory": "ts/packages/webext"
22
22
  },
23
23
  "dependencies": {
24
- "@libo11y/core": "0.4.0",
25
- "@libo11y/spec": "0.4.0",
26
- "@libo11y/web": "0.4.0",
27
- "@opentelemetry/api": "1.10.0",
24
+ "@libo11y/core": "0.6.0",
25
+ "@libo11y/spec": "0.6.0",
26
+ "@libo11y/web": "0.6.0",
28
27
  "@opentelemetry/sdk-logs": "3.1.1",
29
28
  "@opentelemetry/sdk-metrics": "3.1.1",
30
29
  "@opentelemetry/sdk-trace": "3.1.1"
31
30
  },
31
+ "peerDependencies": {
32
+ "@opentelemetry/api": ">=1.10.0 <1.11.0"
33
+ },
32
34
  "devDependencies": {
33
- "@libo11y/test": "0.4.0",
35
+ "@libo11y/test": "0.6.0",
36
+ "@opentelemetry/api": "1.10.0",
34
37
  "fake-indexeddb": "6.2.7"
35
38
  },
36
39
  "files": [