@mark1russell7/otel-ts 0.0.0-bootstrap.0 → 0.1.2

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.
Files changed (113) hide show
  1. package/README.md +417 -2
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/before-flush.d.ts +21 -0
  4. package/dist/before-flush.d.ts.map +1 -0
  5. package/dist/before-flush.js +46 -0
  6. package/dist/before-flush.js.map +1 -0
  7. package/dist/common.d.ts +11 -0
  8. package/dist/common.d.ts.map +1 -0
  9. package/dist/common.js +22 -0
  10. package/dist/common.js.map +1 -0
  11. package/dist/constants.d.ts +12 -0
  12. package/dist/constants.d.ts.map +1 -0
  13. package/dist/constants.js +12 -0
  14. package/dist/constants.js.map +1 -0
  15. package/dist/context-manager.d.ts +36 -0
  16. package/dist/context-manager.d.ts.map +1 -0
  17. package/dist/context-manager.js +60 -0
  18. package/dist/context-manager.js.map +1 -0
  19. package/dist/core.d.ts +14 -0
  20. package/dist/core.d.ts.map +1 -0
  21. package/dist/core.js +26 -0
  22. package/dist/core.js.map +1 -0
  23. package/dist/env.d.ts +6 -0
  24. package/dist/env.d.ts.map +1 -0
  25. package/dist/env.js +8 -0
  26. package/dist/env.js.map +1 -0
  27. package/dist/faro.d.ts +8 -0
  28. package/dist/faro.d.ts.map +1 -0
  29. package/dist/faro.js +24 -0
  30. package/dist/faro.js.map +1 -0
  31. package/dist/id.d.ts +22 -0
  32. package/dist/id.d.ts.map +1 -0
  33. package/dist/id.js +54 -0
  34. package/dist/id.js.map +1 -0
  35. package/dist/index.d.ts +14 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +33 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/init.d.ts +8 -0
  40. package/dist/init.d.ts.map +1 -0
  41. package/dist/init.js +135 -0
  42. package/dist/init.js.map +1 -0
  43. package/dist/lifecycle.d.ts +33 -0
  44. package/dist/lifecycle.d.ts.map +1 -0
  45. package/dist/lifecycle.js +39 -0
  46. package/dist/lifecycle.js.map +1 -0
  47. package/dist/logs.d.ts +6 -0
  48. package/dist/logs.d.ts.map +1 -0
  49. package/dist/logs.js +17 -0
  50. package/dist/logs.js.map +1 -0
  51. package/dist/metrics.d.ts +5 -0
  52. package/dist/metrics.d.ts.map +1 -0
  53. package/dist/metrics.js +37 -0
  54. package/dist/metrics.js.map +1 -0
  55. package/dist/node-testing.d.ts +23 -0
  56. package/dist/node-testing.d.ts.map +1 -0
  57. package/dist/node-testing.js +71 -0
  58. package/dist/node-testing.js.map +1 -0
  59. package/dist/node.d.ts +37 -0
  60. package/dist/node.d.ts.map +1 -0
  61. package/dist/node.js +54 -0
  62. package/dist/node.js.map +1 -0
  63. package/dist/resource.d.ts +38 -0
  64. package/dist/resource.d.ts.map +1 -0
  65. package/dist/resource.js +54 -0
  66. package/dist/resource.js.map +1 -0
  67. package/dist/session-processors.d.ts +9 -0
  68. package/dist/session-processors.d.ts.map +1 -0
  69. package/dist/session-processors.js +37 -0
  70. package/dist/session-processors.js.map +1 -0
  71. package/dist/session.d.ts +21 -0
  72. package/dist/session.d.ts.map +1 -0
  73. package/dist/session.js +76 -0
  74. package/dist/session.js.map +1 -0
  75. package/dist/trace-echo.d.ts +60 -0
  76. package/dist/trace-echo.d.ts.map +1 -0
  77. package/dist/trace-echo.js +118 -0
  78. package/dist/trace-echo.js.map +1 -0
  79. package/dist/tracing.d.ts +7 -0
  80. package/dist/tracing.d.ts.map +1 -0
  81. package/dist/tracing.js +48 -0
  82. package/dist/tracing.js.map +1 -0
  83. package/dist/types.d.ts +210 -0
  84. package/dist/types.d.ts.map +1 -0
  85. package/dist/types.js +2 -0
  86. package/dist/types.js.map +1 -0
  87. package/dist/zone.d.ts +14 -0
  88. package/dist/zone.d.ts.map +1 -0
  89. package/dist/zone.js +40 -0
  90. package/dist/zone.js.map +1 -0
  91. package/package.json +84 -5
  92. package/src/before-flush.ts +64 -0
  93. package/src/common.ts +46 -0
  94. package/src/constants.ts +12 -0
  95. package/src/context-manager.ts +82 -0
  96. package/src/core.ts +38 -0
  97. package/src/env.ts +7 -0
  98. package/src/faro.ts +29 -0
  99. package/src/id.ts +59 -0
  100. package/src/index.ts +45 -0
  101. package/src/init.ts +177 -0
  102. package/src/lifecycle.ts +52 -0
  103. package/src/logs.ts +30 -0
  104. package/src/metrics.ts +63 -0
  105. package/src/node-testing.ts +88 -0
  106. package/src/node.ts +89 -0
  107. package/src/resource.ts +73 -0
  108. package/src/session-processors.ts +48 -0
  109. package/src/session.ts +86 -0
  110. package/src/trace-echo.ts +137 -0
  111. package/src/tracing.ts +64 -0
  112. package/src/types.ts +261 -0
  113. package/src/zone.ts +52 -0
package/dist/zone.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ import type * as Types from "./types.js";
2
+ export * from "./common.js";
3
+ /** The context manager names of this entry: "zone" (default) and "stack" */
4
+ export type ContextManagerOption = Types.ContextManagerOption<"zone" | "stack">;
5
+ /** The configuration of `init()` in this entry */
6
+ export type OtelTsConfig = Types.OtelTsConfig<"zone" | "stack">;
7
+ /**
8
+ * Starts traces, metrics and logs. The default `contextManager` is "zone".
9
+ *
10
+ * @throws For `contextManager: "async"`: async-browser-context cannot share
11
+ * the page with zone.js. Import `init` from `@mark1russell7/otel-ts`.
12
+ */
13
+ export declare function init(config?: OtelTsConfig): Types.OtelTsInstance;
14
+ //# sourceMappingURL=zone.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zone.d.ts","sourceRoot":"","sources":["../src/zone.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,KAAK,KAAK,MAAM,YAAY,CAAC;AAEzC,cAAc,aAAa,CAAC;AAE5B,4EAA4E;AAC5E,MAAM,MAAM,oBAAoB,GAAG,KAAK,CAAC,oBAAoB,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC;AAEhF,kDAAkD;AAClD,MAAM,MAAM,YAAY,GAAG,KAAK,CAAC,YAAY,CAAC,MAAM,GAAG,OAAO,CAAC,CAAC;AAWhE;;;;;GAKG;AACH,wBAAgB,IAAI,CAAC,MAAM,CAAC,EAAE,YAAY,GAAG,KAAK,CAAC,cAAc,CAEhE"}
package/dist/zone.js ADDED
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The zone.js entry, `@mark1russell7/otel-ts/zone`. The same API as
3
+ * `@mark1russell7/otel-ts`, but it keeps the active span with zone.js: the
4
+ * default `contextManager` is "zone".
5
+ *
6
+ * ```ts
7
+ * import { init } from "@mark1russell7/otel-ts/zone";
8
+ *
9
+ * const otel = init();
10
+ * ```
11
+ *
12
+ * zone.js (through `@opentelemetry/context-zone`) patches `Promise`, the
13
+ * timers and the event listeners of the page when this entry loads. This
14
+ * entry does not import async-browser-context: the two libraries cannot share
15
+ * a page.
16
+ *
17
+ * @packageDocumentation
18
+ */
19
+ import { ZoneContextManager } from "@opentelemetry/context-zone";
20
+ import { createStackContextManager, } from "./context-manager.js";
21
+ import { initWith } from "./init.js";
22
+ export * from "./common.js";
23
+ const managers = {
24
+ entry: "zone",
25
+ defaultName: "zone",
26
+ factories: {
27
+ zone: () => new ZoneContextManager(),
28
+ stack: createStackContextManager,
29
+ },
30
+ };
31
+ /**
32
+ * Starts traces, metrics and logs. The default `contextManager` is "zone".
33
+ *
34
+ * @throws For `contextManager: "async"`: async-browser-context cannot share
35
+ * the page with zone.js. Import `init` from `@mark1russell7/otel-ts`.
36
+ */
37
+ export function init(config) {
38
+ return initWith(managers, config);
39
+ }
40
+ //# sourceMappingURL=zone.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"zone.js","sourceRoot":"","sources":["../src/zone.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AACH,OAAO,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,EACL,yBAAyB,GAE1B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,QAAQ,EAAE,MAAM,WAAW,CAAC;AAGrC,cAAc,aAAa,CAAC;AAQ5B,MAAM,QAAQ,GAAyB;IACrC,KAAK,EAAE,MAAM;IACb,WAAW,EAAE,MAAM;IACnB,SAAS,EAAE;QACT,IAAI,EAAE,GAAG,EAAE,CAAC,IAAI,kBAAkB,EAAE;QACpC,KAAK,EAAE,yBAAyB;KACjC;CACF,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,IAAI,CAAC,MAAqB;IACxC,OAAO,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;AACpC,CAAC"}
package/package.json CHANGED
@@ -1,12 +1,91 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package",
2
3
  "name": "@mark1russell7/otel-ts",
3
- "version": "0.0.0-bootstrap.0",
4
- "description": "A placeholder that lets npm trust the release workflow of mark1russell7/otel-ts. Use a later version.",
4
+ "version": "0.1.2",
5
+ "description": "Frontend observability in one init() call — OpenTelemetry + Grafana Faro for any TypeScript web app",
6
+ "homepage": "https://github.com/mark1russell7/otel-ts#readme",
7
+ "bugs": {
8
+ "url": "https://github.com/mark1russell7/otel-ts/issues"
9
+ },
5
10
  "repository": {
6
11
  "type": "git",
7
12
  "url": "git+https://github.com/mark1russell7/otel-ts.git"
8
13
  },
9
- "publishConfig": {
10
- "access": "public"
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./zone": {
23
+ "types": "./dist/zone.d.ts",
24
+ "import": "./dist/zone.js"
25
+ },
26
+ "./core": {
27
+ "types": "./dist/core.d.ts",
28
+ "import": "./dist/core.js"
29
+ },
30
+ "./node": {
31
+ "types": "./dist/node.d.ts",
32
+ "import": "./dist/node.js"
33
+ },
34
+ "./node/testing": {
35
+ "types": "./dist/node-testing.d.ts",
36
+ "import": "./dist/node-testing.js"
37
+ }
38
+ },
39
+ "files": [
40
+ "dist",
41
+ "src"
42
+ ],
43
+ "sideEffects": false,
44
+ "dependencies": {
45
+ "@grafana/faro-web-sdk": "^2.3.0",
46
+ "@grafana/faro-web-tracing": "^2.3.0",
47
+ "@opentelemetry/api": "^1.9.0",
48
+ "@opentelemetry/api-logs": "^0.213.0",
49
+ "@opentelemetry/auto-instrumentations-web": "^0.59.0",
50
+ "@opentelemetry/context-zone": "^2.2.0",
51
+ "@opentelemetry/core": "^2.6.0",
52
+ "@opentelemetry/exporter-logs-otlp-http": "^0.213.0",
53
+ "@opentelemetry/exporter-metrics-otlp-http": "^0.213.0",
54
+ "@opentelemetry/exporter-trace-otlp-http": "^0.213.0",
55
+ "@opentelemetry/instrumentation": "^0.213.0",
56
+ "@opentelemetry/instrumentation-long-task": "^0.58.0",
57
+ "@opentelemetry/resources": "^2.6.0",
58
+ "@opentelemetry/sdk-logs": "^0.213.0",
59
+ "@opentelemetry/sdk-metrics": "^2.6.0",
60
+ "@opentelemetry/sdk-trace-base": "^2.6.0",
61
+ "@opentelemetry/sdk-trace-web": "^2.2.0",
62
+ "@opentelemetry/semantic-conventions": "^1.40.0",
63
+ "async-browser-context": "^0.2.2",
64
+ "page-lifecycle-tracker": "^0.1.0"
65
+ },
66
+ "peerDependencies": {
67
+ "@opentelemetry/sdk-node": ">=0.200.0"
68
+ },
69
+ "peerDependenciesMeta": {
70
+ "@opentelemetry/sdk-node": {
71
+ "optional": true
72
+ }
73
+ },
74
+ "devDependencies": {
75
+ "@mark1russell7/grafana-infra": "github:mark1russell7/grafana-infra",
76
+ "@opentelemetry/sdk-node": "~0.213.0",
77
+ "@types/node": "^26.6.5",
78
+ "happy-dom": "^20.14.5",
79
+ "typescript": "^5.9.0",
80
+ "vitest": "^4.1.11"
81
+ },
82
+ "scripts": {
83
+ "build": "tsc -b",
84
+ "typecheck": "tsc --noEmit",
85
+ "clean": "rm -rf dist .tsbuildinfo",
86
+ "infra:up": "cd node_modules/@mark1russell7/grafana-infra && docker compose up -d",
87
+ "infra:down": "cd node_modules/@mark1russell7/grafana-infra && docker compose down",
88
+ "infra:logs": "cd node_modules/@mark1russell7/grafana-infra && docker compose logs -f",
89
+ "test": "vitest run"
11
90
  }
12
- }
91
+ }
@@ -0,0 +1,64 @@
1
+ import type { FlushCause } from "./types.js";
2
+
3
+ export type BeforeFlushListener = (cause: FlushCause) => void;
4
+
5
+ export interface BeforeFlushListeners {
6
+ /** Adds a listener. @returns A function that removes it */
7
+ add(listener: BeforeFlushListener): () => void;
8
+
9
+ /**
10
+ * Calls every listener synchronously, in registration order, with the
11
+ * cause of the flush. A listener that throws does not stop the others; the
12
+ * first error is logged.
13
+ */
14
+ run(cause?: FlushCause): void;
15
+ }
16
+
17
+ /**
18
+ * Functions that run just before telemetry is flushed, so that values they
19
+ * record (e.g. a page's final Web Vitals) go out in that flush. `init()`
20
+ * runs them at the start of `forceFlush()` and `shutdown()`, which is also
21
+ * what its page-hide handlers call. So they don't depend on the order in
22
+ * which `pagehide` listeners run (which differs between browsers).
23
+ */
24
+ export function createBeforeFlushListeners(): BeforeFlushListeners {
25
+ // Wrapped, so the same function can be added twice and removed once
26
+ const entries = new Set<{ listener: BeforeFlushListener }>();
27
+ let running = false;
28
+ let errorLogged = false;
29
+
30
+ return {
31
+ add(listener) {
32
+ const entry = { listener };
33
+ entries.add(entry);
34
+ return () => {
35
+ entries.delete(entry);
36
+ };
37
+ },
38
+
39
+ run(cause = {}) {
40
+ // A listener that flushes again must not start another round
41
+ if (running) return;
42
+ running = true;
43
+
44
+ try {
45
+ // A snapshot: listeners may add or remove listeners
46
+ for (const { listener } of [...entries]) {
47
+ try {
48
+ listener(cause);
49
+ } catch (error) {
50
+ if (!errorLogged) {
51
+ errorLogged = true;
52
+ console.error(
53
+ "[otel-ts] An onBeforeFlush listener threw; telemetry is flushed anyway. Later listener errors are not logged.",
54
+ error,
55
+ );
56
+ }
57
+ }
58
+ }
59
+ } finally {
60
+ running = false;
61
+ }
62
+ },
63
+ };
64
+ }
package/src/common.ts ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * The API that each entry exports, except `init()` and the types of its
3
+ * configuration: `@mark1russell7/otel-ts`, `@mark1russell7/otel-ts/zone` and
4
+ * `@mark1russell7/otel-ts/core` each export their own.
5
+ */
6
+
7
+ // =============================================================================
8
+ // Types
9
+ // =============================================================================
10
+
11
+ export type {
12
+ ContextManagerName,
13
+ FlushCause,
14
+ HistogramAggregation,
15
+ MetricsTemporality,
16
+ OtelTsInstance,
17
+ } from "./types.js";
18
+
19
+ // =============================================================================
20
+ // Identity
21
+ // =============================================================================
22
+
23
+ export { createInstanceId } from "./id.js";
24
+
25
+ // =============================================================================
26
+ // Session
27
+ // =============================================================================
28
+
29
+ export { getOrCreateSessionId } from "./session.js";
30
+
31
+ // =============================================================================
32
+ // The trace of a remote change
33
+ // =============================================================================
34
+
35
+ export { runInRemoteTrace, type RemoteTraceOptions } from "./trace-echo.js";
36
+
37
+ // =============================================================================
38
+ // Constants
39
+ // =============================================================================
40
+
41
+ export {
42
+ DEFAULT_METRICS_EXPORT_INTERVAL_MS,
43
+ DEFAULT_OTLP_ENDPOINT,
44
+ DEFAULT_SERVICE_NAME,
45
+ DEFAULT_SERVICE_VERSION,
46
+ } from "./constants.js";
@@ -0,0 +1,12 @@
1
+ export const DEFAULT_OTLP_ENDPOINT = "http://localhost:4318";
2
+ export const DEFAULT_SERVICE_NAME = "frontend-app";
3
+ export const DEFAULT_SERVICE_VERSION = "0.0.0";
4
+ export const DEFAULT_METRICS_EXPORT_INTERVAL_MS = 15_000;
5
+ export const SESSION_STORAGE_KEY = "otel_session_id";
6
+ export const SESSION_TTL_MS = 30 * 60 * 1000;
7
+
8
+ /**
9
+ * Semantic-conventions `session.id`. It has Development status, so the
10
+ * stable `@opentelemetry/semantic-conventions` entry point does not export it.
11
+ */
12
+ export const ATTR_SESSION_ID = "session.id";
@@ -0,0 +1,82 @@
1
+ import type { ContextManager } from "@opentelemetry/api";
2
+ import { StackContextManager } from "@opentelemetry/sdk-trace-web";
3
+ import type { ContextManagerName, ContextManagerOption } from "./types.js";
4
+
5
+ /**
6
+ * The entries of the package. Each entry loads at most one context library,
7
+ * because zone.js and async-browser-context patch the same functions with
8
+ * different rules: they cannot share a page.
9
+ */
10
+ export const ENTRIES = {
11
+ /** async-browser-context */
12
+ main: "@mark1russell7/otel-ts",
13
+ /** zone.js */
14
+ zone: "@mark1russell7/otel-ts/zone",
15
+ /** No context library */
16
+ core: "@mark1russell7/otel-ts/core",
17
+ } as const;
18
+
19
+ export type Entry = keyof typeof ENTRIES;
20
+
21
+ /** The context managers of one entry */
22
+ export interface EntryContextManagers {
23
+ readonly entry: Entry;
24
+ /** The name that `init()` uses when the config has no `contextManager` */
25
+ readonly defaultName: ContextManagerName;
26
+ /** Makes the manager for each name that the entry has */
27
+ readonly factories: Partial<Record<ContextManagerName, () => ContextManager>>;
28
+ }
29
+
30
+ /** The entry that has each name. Each entry has "stack". */
31
+ const ENTRY_OF: Record<ContextManagerName, Entry> = {
32
+ async: "main",
33
+ zone: "zone",
34
+ stack: "core",
35
+ };
36
+
37
+ /** The context library that each entry loads */
38
+ const LIBRARY_OF: Record<Entry, string | undefined> = {
39
+ main: "async-browser-context",
40
+ zone: "zone.js",
41
+ core: undefined,
42
+ };
43
+
44
+ /** The error message for a name that `entry` does not have */
45
+ export function unavailableMessage(name: string, entry: Entry): string {
46
+ const home = Object.hasOwn(ENTRY_OF, name)
47
+ ? ENTRY_OF[name as ContextManagerName]
48
+ : undefined;
49
+ if (home === undefined) {
50
+ return `[otel-ts] Unknown contextManager "${name}". Use "async", "zone" or "stack", or a ContextManager.`;
51
+ }
52
+ const library = LIBRARY_OF[entry];
53
+ const reason = library
54
+ ? `This entry loads ${library}, and zone.js and async-browser-context cannot share a page: they patch the same functions with different rules.`
55
+ : "This entry loads no context library.";
56
+ return (
57
+ `[otel-ts] contextManager: "${name}" is not available in "${ENTRIES[entry]}". ${reason} ` +
58
+ `Import init from "${ENTRIES[home]}" in place of "${ENTRIES[entry]}".`
59
+ );
60
+ }
61
+
62
+ /** Makes the stack manager. Each entry has it. */
63
+ export const createStackContextManager = (): ContextManager =>
64
+ new StackContextManager();
65
+
66
+ /**
67
+ * The context manager for the `contextManager` option, in the entry of
68
+ * `managers`. Gives back a `ContextManager` instance of the app.
69
+ *
70
+ * @throws For a name that the entry does not have
71
+ */
72
+ export function createContextManager(
73
+ option: ContextManagerOption,
74
+ managers: EntryContextManagers,
75
+ ): ContextManager {
76
+ if (typeof option !== "string") return option;
77
+ const factory = Object.hasOwn(managers.factories, option)
78
+ ? managers.factories[option]
79
+ : undefined;
80
+ if (!factory) throw new Error(unavailableMessage(option, managers.entry));
81
+ return factory();
82
+ }
package/src/core.ts ADDED
@@ -0,0 +1,38 @@
1
+ /**
2
+ * The core entry, `@mark1russell7/otel-ts/core`. The same API as
3
+ * `@mark1russell7/otel-ts`, but it imports no context library and patches
4
+ * nothing: the default `contextManager` is "stack". The app can also give its
5
+ * own `ContextManager`.
6
+ *
7
+ * @packageDocumentation
8
+ */
9
+ import {
10
+ createStackContextManager,
11
+ type EntryContextManagers,
12
+ } from "./context-manager.js";
13
+ import { initWith } from "./init.js";
14
+ import type * as Types from "./types.js";
15
+
16
+ export * from "./common.js";
17
+
18
+ /** The context manager names of this entry: only "stack" (default) */
19
+ export type ContextManagerOption = Types.ContextManagerOption<"stack">;
20
+
21
+ /** The configuration of `init()` in this entry */
22
+ export type OtelTsConfig = Types.OtelTsConfig<"stack">;
23
+
24
+ const managers: EntryContextManagers = {
25
+ entry: "core",
26
+ defaultName: "stack",
27
+ factories: { stack: createStackContextManager },
28
+ };
29
+
30
+ /**
31
+ * Starts traces, metrics and logs. The default `contextManager` is "stack".
32
+ *
33
+ * @throws For `contextManager: "async"` or `"zone"`: import `init` from
34
+ * `@mark1russell7/otel-ts` or from `@mark1russell7/otel-ts/zone`.
35
+ */
36
+ export function init(config?: OtelTsConfig): Types.OtelTsInstance {
37
+ return initWith(managers, config);
38
+ }
package/src/env.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * True in a page (`window` and `document` exist); false in Web Workers and
3
+ * other runtimes without a DOM.
4
+ */
5
+ export function hasDom(): boolean {
6
+ return typeof window !== "undefined" && typeof document !== "undefined";
7
+ }
package/src/faro.ts ADDED
@@ -0,0 +1,29 @@
1
+ import {
2
+ initializeFaro,
3
+ getWebInstrumentations,
4
+ type Faro,
5
+ } from "@grafana/faro-web-sdk";
6
+ import { TracingInstrumentation } from "@grafana/faro-web-tracing";
7
+ import type { ResolvedConfig } from "./types.js";
8
+
9
+ /**
10
+ * Starts Faro, sending to `url`. Without a URL (or transports) Faro has
11
+ * nowhere to send data and logs an error, so `init()` skips it then.
12
+ */
13
+ export function setupFaro(config: ResolvedConfig, url: string): Faro {
14
+ return initializeFaro({
15
+ url,
16
+ app: {
17
+ name: config.faroAppName ?? config.serviceName,
18
+ version: config.serviceVersion,
19
+ },
20
+ instrumentations: [
21
+ ...getWebInstrumentations({
22
+ captureConsole: true,
23
+ enablePerformanceInstrumentation: true,
24
+ enableContentSecurityPolicyInstrumentation: true,
25
+ }),
26
+ new TracingInstrumentation(),
27
+ ],
28
+ });
29
+ }
package/src/id.ts ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Returns a new random version 4 UUID (RFC 9562).
3
+ *
4
+ * `crypto.randomUUID()` exists only in secure contexts: HTTPS pages and
5
+ * http://localhost. Pages served over plain http:// from any other host lack
6
+ * it but still have `crypto.getRandomValues()`, so this falls back to that,
7
+ * and to `Math.random()` where there is no Web Crypto at all. The result is
8
+ * an identifier, not a secret: the fallbacks only need to make collisions
9
+ * unlikely.
10
+ */
11
+ export function randomUuid(): string {
12
+ const webCrypto = getWebCrypto();
13
+
14
+ if (typeof webCrypto?.randomUUID === "function") {
15
+ return webCrypto.randomUUID();
16
+ }
17
+
18
+ const bytes = new Uint8Array(16);
19
+
20
+ if (typeof webCrypto?.getRandomValues === "function") {
21
+ webCrypto.getRandomValues(bytes);
22
+ } else {
23
+ for (let i = 0; i < bytes.length; i++) {
24
+ bytes[i] = Math.floor(Math.random() * 256);
25
+ }
26
+ }
27
+
28
+ bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
29
+ bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC 9562 variant (10xx)
30
+
31
+ const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0"));
32
+ return [
33
+ hex.slice(0, 4),
34
+ hex.slice(4, 6),
35
+ hex.slice(6, 8),
36
+ hex.slice(8, 10),
37
+ hex.slice(10, 16),
38
+ ]
39
+ .map((group) => group.join(""))
40
+ .join("-");
41
+ }
42
+
43
+ /**
44
+ * Returns a new value for the `service.instance.id` resource attribute: a
45
+ * random version 4 UUID.
46
+ *
47
+ * `init()` calls this once per call when no `serviceInstanceId` is given, so
48
+ * every SDK instance (each page load, each Web Worker) is its own metric
49
+ * writer. Call it yourself only to know the value before `init()`; never
50
+ * persist it or derive it from the session ID.
51
+ */
52
+ export function createInstanceId(): string {
53
+ return randomUuid();
54
+ }
55
+
56
+ /** Web Crypto where it exists; missing members are checked by the caller */
57
+ function getWebCrypto(): Partial<Crypto> | undefined {
58
+ return typeof crypto === "undefined" ? undefined : crypto;
59
+ }
package/src/index.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The main entry, `@mark1russell7/otel-ts`. It keeps the active span with
3
+ * async-browser-context: the default `contextManager` is "async".
4
+ *
5
+ * async-browser-context patches `Promise.prototype.then`, the timers, the
6
+ * event listeners and other callback APIs when this entry loads, also when
7
+ * the app selects "stack". `@mark1russell7/otel-ts/core` patches nothing, and
8
+ * `@mark1russell7/otel-ts/zone` uses zone.js.
9
+ *
10
+ * @packageDocumentation
11
+ */
12
+ import { AsyncContextManager } from "async-browser-context/opentelemetry";
13
+ import {
14
+ createStackContextManager,
15
+ type EntryContextManagers,
16
+ } from "./context-manager.js";
17
+ import { initWith } from "./init.js";
18
+ import type * as Types from "./types.js";
19
+
20
+ export * from "./common.js";
21
+
22
+ /** The context manager names of this entry: "async" (default) and "stack" */
23
+ export type ContextManagerOption = Types.ContextManagerOption<"async" | "stack">;
24
+
25
+ /** The configuration of `init()` in this entry */
26
+ export type OtelTsConfig = Types.OtelTsConfig<"async" | "stack">;
27
+
28
+ const managers: EntryContextManagers = {
29
+ entry: "main",
30
+ defaultName: "async",
31
+ factories: {
32
+ async: () => new AsyncContextManager(),
33
+ stack: createStackContextManager,
34
+ },
35
+ };
36
+
37
+ /**
38
+ * Starts traces, metrics and logs. The default `contextManager` is "async".
39
+ *
40
+ * @throws For `contextManager: "zone"`: zone.js cannot share the page with
41
+ * async-browser-context. Import `init` from `@mark1russell7/otel-ts/zone`.
42
+ */
43
+ export function init(config?: OtelTsConfig): Types.OtelTsInstance {
44
+ return initWith(managers, config);
45
+ }