@r_masseater/masseater-utils 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/LICENSE +87 -0
  2. package/README.md +97 -1
  3. package/dist/context-B_4aJtEC.mjs +6 -0
  4. package/dist/context-B_4aJtEC.mjs.map +1 -0
  5. package/dist/failure-CjeINRVu.mjs +19 -0
  6. package/dist/failure-CjeINRVu.mjs.map +1 -0
  7. package/dist/github-workflow.d.mts +77 -0
  8. package/dist/github-workflow.mjs +110 -0
  9. package/dist/github-workflow.mjs.map +1 -0
  10. package/dist/index-CUo4CRam.d.mts +1 -0
  11. package/dist/index-Cb8YSEwo.d.mts +31 -0
  12. package/dist/index-DudHILTn.d.mts +6 -0
  13. package/dist/index-KNezbJnC.d.mts +121 -0
  14. package/dist/kestrion-node.d.mts +6 -0
  15. package/dist/kestrion-node.mjs +9 -0
  16. package/dist/kestrion-node.mjs.map +1 -0
  17. package/dist/kestrion-npm.d.mts +25 -0
  18. package/dist/kestrion-npm.mjs +54 -0
  19. package/dist/kestrion-npm.mjs.map +1 -0
  20. package/dist/kestrion-pnpm.d.mts +29 -0
  21. package/dist/kestrion-pnpm.mjs +68 -0
  22. package/dist/kestrion-pnpm.mjs.map +1 -0
  23. package/dist/kestrion.d.mts +2 -0
  24. package/dist/kestrion.mjs +46 -0
  25. package/dist/kestrion.mjs.map +1 -0
  26. package/dist/mapped-import-mapper.d.mts +24 -0
  27. package/dist/mapped-import-mapper.mjs +34 -0
  28. package/dist/mapped-import-mapper.mjs.map +1 -0
  29. package/dist/mapped-import-vite.d.mts +21 -0
  30. package/dist/mapped-import-vite.mjs +49 -0
  31. package/dist/mapped-import-vite.mjs.map +1 -0
  32. package/dist/mapped-import.d.mts +2 -0
  33. package/dist/mapped-import.mjs +36 -0
  34. package/dist/mapped-import.mjs.map +1 -0
  35. package/dist/node-main.d.mts +19 -0
  36. package/dist/node-main.mjs +59 -0
  37. package/dist/node-main.mjs.map +1 -0
  38. package/dist/normalize-CogX79EO.mjs +76 -0
  39. package/dist/normalize-CogX79EO.mjs.map +1 -0
  40. package/dist/otlp-ohapzeFh.mjs +18 -0
  41. package/dist/otlp-ohapzeFh.mjs.map +1 -0
  42. package/dist/otlp-schema-CDBPGJ5s.mjs +125 -0
  43. package/dist/otlp-schema-CDBPGJ5s.mjs.map +1 -0
  44. package/dist/otlp-spans-D88555DO.mjs +52 -0
  45. package/dist/otlp-spans-D88555DO.mjs.map +1 -0
  46. package/dist/package-json-CYRyaF9U.mjs +58 -0
  47. package/dist/package-json-CYRyaF9U.mjs.map +1 -0
  48. package/dist/plugin-kit.d.mts +5663 -0
  49. package/dist/plugin-kit.mjs +11501 -0
  50. package/dist/plugin-kit.mjs.map +1 -0
  51. package/dist/receive-S2txZwcV.mjs +61 -0
  52. package/dist/receive-S2txZwcV.mjs.map +1 -0
  53. package/dist/route-handlers-Cn3O2hmf.mjs +14 -0
  54. package/dist/route-handlers-Cn3O2hmf.mjs.map +1 -0
  55. package/dist/route-handlers-E2lwhaAf.d.mts +14 -0
  56. package/dist/run-Cc5W9mi8.mjs +13 -0
  57. package/dist/run-Cc5W9mi8.mjs.map +1 -0
  58. package/dist/run-D59Owiv1.d.mts +5 -0
  59. package/dist/skerm.d.mts +6 -0
  60. package/dist/skerm.mjs +128 -0
  61. package/dist/skerm.mjs.map +1 -0
  62. package/dist/span-BKjRu617.mjs +60 -0
  63. package/dist/span-BKjRu617.mjs.map +1 -0
  64. package/dist/telemetry-BEWIE8tU.d.mts +51 -0
  65. package/dist/vitest-otlp-collector-files.d.mts +8 -0
  66. package/dist/vitest-otlp-collector-files.mjs +13 -0
  67. package/dist/vitest-otlp-collector-files.mjs.map +1 -0
  68. package/dist/vitest-otlp-current-receiver-8c7rIP1N.mjs +13 -0
  69. package/dist/vitest-otlp-current-receiver-8c7rIP1N.mjs.map +1 -0
  70. package/dist/vitest-otlp-current-receiver-DphmM9Ha.d.mts +10 -0
  71. package/dist/vitest-otlp-semconv.d.mts +3 -0
  72. package/dist/vitest-otlp-semconv.mjs +92 -0
  73. package/dist/vitest-otlp-semconv.mjs.map +1 -0
  74. package/dist/vitest-otlp-setup.d.mts +1 -0
  75. package/dist/vitest-otlp-setup.mjs +295 -0
  76. package/dist/vitest-otlp-setup.mjs.map +1 -0
  77. package/dist/vitest-otlp-tail-to-otlp.mjs +271 -0
  78. package/dist/vitest-otlp-tail-to-otlp.mjs.map +1 -0
  79. package/dist/vitest-otlp-workers.d.mts +26 -0
  80. package/dist/vitest-otlp-workers.mjs +54 -0
  81. package/dist/vitest-otlp-workers.mjs.map +1 -0
  82. package/dist/vitest-otlp.d.mts +51 -0
  83. package/dist/vitest-otlp.mjs +66 -0
  84. package/dist/vitest-otlp.mjs.map +1 -0
  85. package/dist/workers-tracing-alchemy.d.mts +22 -0
  86. package/dist/workers-tracing-alchemy.mjs +124 -0
  87. package/dist/workers-tracing-alchemy.mjs.map +1 -0
  88. package/dist/workers-tracing-browser-logs.d.mts +4 -0
  89. package/dist/workers-tracing-browser-logs.mjs +67 -0
  90. package/dist/workers-tracing-browser-logs.mjs.map +1 -0
  91. package/dist/workers-tracing-browser-spans.d.mts +4 -0
  92. package/dist/workers-tracing-browser-spans.mjs +13 -0
  93. package/dist/workers-tracing-browser-spans.mjs.map +1 -0
  94. package/dist/workers-tracing-effect-tracing.d.mts +8 -0
  95. package/dist/workers-tracing-effect-tracing.mjs +68 -0
  96. package/dist/workers-tracing-effect-tracing.mjs.map +1 -0
  97. package/dist/workers-tracing-effect-tracing.plain.d.mts +7 -0
  98. package/dist/workers-tracing-effect-tracing.plain.mjs +9 -0
  99. package/dist/workers-tracing-effect-tracing.plain.mjs.map +1 -0
  100. package/dist/workers-tracing-elysia.d.mts +5 -0
  101. package/dist/workers-tracing-elysia.mjs +53 -0
  102. package/dist/workers-tracing-elysia.mjs.map +1 -0
  103. package/dist/workers-tracing-elysia.plain.d.mts +3 -0
  104. package/dist/workers-tracing-elysia.plain.mjs +3 -0
  105. package/dist/workers-tracing-oxlint.d.mts +6 -0
  106. package/dist/workers-tracing-oxlint.mjs +8 -0
  107. package/dist/workers-tracing-oxlint.mjs.map +1 -0
  108. package/dist/workers-tracing-tanstack-start.d.mts +22 -0
  109. package/dist/workers-tracing-tanstack-start.mjs +28 -0
  110. package/dist/workers-tracing-tanstack-start.mjs.map +1 -0
  111. package/dist/workers-tracing-tanstack-start.plain.d.mts +9 -0
  112. package/dist/workers-tracing-tanstack-start.plain.mjs +10 -0
  113. package/dist/workers-tracing-tanstack-start.plain.mjs.map +1 -0
  114. package/dist/workers-tracing-trace-sink.d.mts +7 -0
  115. package/dist/workers-tracing-trace-sink.mjs +29 -0
  116. package/dist/workers-tracing-trace-sink.mjs.map +1 -0
  117. package/dist/workers-tracing-workers-ai.d.mts +33 -0
  118. package/dist/workers-tracing-workers-ai.mjs +108 -0
  119. package/dist/workers-tracing-workers-ai.mjs.map +1 -0
  120. package/package.json +252 -5
  121. package/skills/add-scroll-chip-row/SKILL.md +59 -0
  122. package/skills/assert-exported-telemetry/SKILL.md +131 -0
  123. package/skills/find-cache-folder/SKILL.md +36 -0
  124. package/skills/import-custom-format/SKILL.md +76 -0
  125. package/skills/read-hook-input/SKILL.md +39 -0
  126. package/skills/read-node-ecosystem/SKILL.md +131 -0
  127. package/skills/run-effect-main/SKILL.md +82 -0
  128. package/skills/trace-workers/SKILL.md +152 -0
  129. package/skills/write-actions-steps/SKILL.md +76 -0
  130. package/src/app/skerm.css +143 -0
@@ -0,0 +1,131 @@
1
+ ---
2
+ name: assert-exported-telemetry
3
+ description: >
4
+ Use when a Vitest test must prove which OpenTelemetry spans, logs or metrics the code under test
5
+ really exported: the otlp() plugin, waitForSpans, waitForLogs, waitForMetrics, clearTelemetry,
6
+ the semconv check with Weaver, and tailWorker for Cloudflare Workers under Miniflare.
7
+ metadata:
8
+ type: core
9
+ library: "@r_masseater/masseater-utils"
10
+ sources:
11
+ - src/app/vitest-otlp*
12
+ - src/features/receive-otlp/**
13
+ - README.md
14
+ ---
15
+
16
+ # assert-exported-telemetry
17
+
18
+ `otlp()` starts an OTLP receiver in every Vitest worker and points the `OTEL_*` variables at it. A test then waits for the telemetry that actually left the process, instead of mocking the exporter. Use it to show that auto-instrumentation, `OTEL_*` settings and attribute names work end to end.
19
+
20
+ ## Setup
21
+
22
+ ```sh
23
+ vp add -D @r_masseater/masseater-utils effect
24
+ ```
25
+
26
+ ```ts
27
+ import { otlp } from "@r_masseater/masseater-utils/vitest-otlp";
28
+ import { defineConfig } from "vite-plus";
29
+
30
+ export default defineConfig({
31
+ plugins: [otlp()],
32
+ });
33
+ ```
34
+
35
+ The plugin adds a setup file, which sets the variables below before the tests run.
36
+
37
+ | Variable | Value |
38
+ | ----------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
39
+ | `OTEL_EXPORTER_OTLP_ENDPOINT` | The receiver's HTTP endpoint, or its gRPC endpoint when `OTEL_EXPORTER_OTLP_PROTOCOL=grpc` |
40
+ | `OTEL_EXPORTER_OTLP_{TRACES,METRICS,LOGS}_ENDPOINT` | Emptied so the shared endpoint wins |
41
+ | `OTEL_{TRACES,METRICS,LOGS}_EXPORTER` | `otlp` |
42
+ | `OTEL_BSP_SCHEDULE_DELAY`, `OTEL_BLRP_SCHEDULE_DELAY` | `50`, unless already set |
43
+ | `OTEL_METRIC_EXPORT_INTERVAL`, `OTEL_METRIC_EXPORT_TIMEOUT` | `100`, unless already set |
44
+
45
+ Start the SDK inside the test, after the setup file has run, so it reads these values.
46
+
47
+ ## Waiting for telemetry
48
+
49
+ ```ts
50
+ import { NodeSDK } from "@opentelemetry/sdk-node";
51
+ import { clearTelemetry, waitForSpans } from "@r_masseater/masseater-utils/vitest-otlp";
52
+ import { Effect } from "effect";
53
+ import { beforeEach, expect, test } from "vite-plus/test";
54
+
55
+ declare const checkout: Effect.Effect<void>;
56
+
57
+ beforeEach(() => Effect.runPromise(clearTelemetry));
58
+
59
+ test("checkout is traced", () =>
60
+ Effect.gen(function* () {
61
+ const sdk = new NodeSDK();
62
+ sdk.start();
63
+ yield* checkout;
64
+ yield* Effect.promise(() => sdk.shutdown());
65
+
66
+ const spans = yield* waitForSpans({ where: (span) => span.name === "checkout" });
67
+ expect(spans).toMatchObject([{ attributes: { "order.id": "o-1" } }]);
68
+ }).pipe(Effect.runPromise));
69
+ ```
70
+
71
+ `waitForSpans`, `waitForLogs` and `waitForMetrics` poll the receiver.
72
+ They succeed with every matching item once enough have arrived, and take the options below.
73
+
74
+ | Option | Default | Meaning |
75
+ | ---------- | ---------- | -------------------------------------------------------------------- |
76
+ | `where` | every item | Predicate on `ReceivedSpan`, `ReceivedLogRecord` or `ReceivedMetric` |
77
+ | `count` | `1` | How many matching items must arrive |
78
+ | `timeout` | 5 seconds | `Duration` before failing with `TelemetryNotReceived` |
79
+ | `interval` | 20 ms | `Duration` between polls |
80
+
81
+ `receivedSpans`, `receivedLogs` and `receivedMetrics` return what has arrived so far without waiting. `receiverAddress` gives the HTTP and gRPC endpoints. All of them fail with `ReceiverNotRunning` when the plugin is not configured.
82
+
83
+ ## Semantic conventions
84
+
85
+ `otlp({ semconv: true })` also runs OpenTelemetry Weaver against everything received.
86
+ The run fails when the telemetry violates the semantic conventions.
87
+ Pass an object to change `registry`, the `weaver` binary or `failOn`.
88
+ `failOn` is `violation`, `improvement` or `information`.
89
+ Weaver must be on `PATH` unless `weaver` names it.
90
+
91
+ ## Cloudflare Workers
92
+
93
+ `tailWorker()` from `@r_masseater/masseater-utils/vitest-otlp/workers` bundles a tail worker.
94
+ It forwards a Worker's traces and logs to the receiver.
95
+ Add it to Miniflare's `workers` and list its name in the traced Worker's `streamingTails`.
96
+
97
+ ```ts
98
+ import { waitForSpans } from "@r_masseater/masseater-utils/vitest-otlp";
99
+ import { tailWorker } from "@r_masseater/masseater-utils/vitest-otlp/workers";
100
+ import { Effect } from "effect";
101
+ import { Miniflare } from "miniflare";
102
+ import { test } from "vite-plus/test";
103
+
104
+ test("caching writes to KV", () =>
105
+ Effect.gen(function* () {
106
+ const tail = yield* tailWorker({ serviceName: "app" });
107
+ const miniflare = new Miniflare({
108
+ workers: [
109
+ {
110
+ name: "app",
111
+ scriptPath: "worker.js",
112
+ kvNamespaces: ["CACHE"],
113
+ streamingTails: [tail.name],
114
+ },
115
+ tail,
116
+ ],
117
+ });
118
+ yield* Effect.promise(() => miniflare.dispatchFetch("http://localhost/"));
119
+ yield* waitForSpans({ where: (span) => span.name === "kv_put" });
120
+ yield* Effect.promise(() => miniflare.dispose());
121
+ }).pipe(Effect.runPromise));
122
+ ```
123
+
124
+ `tailWorker` takes `name` (default `vitest-otlp-tail`), `compatibilityDate` and `serviceName` (default `worker`). It fails with `TailWorkerBuildFailed` when bundling fails.
125
+
126
+ ## Common mistakes
127
+
128
+ - Starting the OpenTelemetry SDK at module top level in a file that is imported before the setup file runs. The SDK then keeps the old endpoint.
129
+ - Asserting right after the code runs without `waitFor*`. Batch processors export later, so read through `waitFor*` or shut the SDK down first.
130
+ - Sharing received telemetry between tests. Call `clearTelemetry` in `beforeEach` when tests check counts.
131
+ - Mocking the exporter instead. That proves nothing about what leaves the process.
@@ -0,0 +1,36 @@
1
+ ---
2
+ name: find-cache-folder
3
+ description: >
4
+ Use when a Claude Code plugin hook or script must keep downloaded or built files between runs,
5
+ such as a model, a binary or an installed tool: cacheRootOf gives the folder under
6
+ XDG_CACHE_HOME or ~/.cache.
7
+ metadata:
8
+ type: core
9
+ library: "@r_masseater/masseater-utils"
10
+ sources:
11
+ - src/app/plugin-kit*
12
+ - src/shared/lib/cache.ts
13
+ - README.md
14
+ ---
15
+
16
+ # find-cache-folder
17
+
18
+ A plugin's own directory is replaced when the plugin updates, so files that are costly to fetch again belong in the user's cache folder. `cacheRootOf` gives that folder and keeps every plugin on the same rule.
19
+
20
+ ## Setup
21
+
22
+ ```sh
23
+ bun add @r_masseater/masseater-utils
24
+ ```
25
+
26
+ Commit the `bun.lock` that `bun add` writes. Claude Code installs the dependencies of a plugin from its `package.json` and a text `bun.lock` when it caches the plugin.
27
+
28
+ ## Find the folder
29
+
30
+ ```ts
31
+ import { cacheRootOf } from "@r_masseater/masseater-utils/plugin-kit";
32
+
33
+ const root = await cacheRootOf(["my-plugin", "runtime"]);
34
+ ```
35
+
36
+ The folder is `$XDG_CACHE_HOME/my-plugin/runtime`, or `~/.cache/my-plugin/runtime` when `XDG_CACHE_HOME` is unset or empty. The function builds the path only and creates nothing. It rejects with `CacheRootError` when neither `XDG_CACHE_HOME` nor `HOME` (or `USERPROFILE` on Windows) is set. `cacheRootEffect` is the same lookup as an Effect: provide a `ConfigProvider` to test it with a fake environment.
@@ -0,0 +1,76 @@
1
+ ---
2
+ name: import-custom-format
3
+ description: >
4
+ Use when TypeScript must import a file in a custom format with editor support: describing the
5
+ mapping as segments (text, verbatim, alias, atom), producing ts-content-mapper output with
6
+ mappedOutput, and loading the file as a module with the contentImport Vite plugin.
7
+ metadata:
8
+ type: core
9
+ library: "@r_masseater/masseater-utils"
10
+ sources:
11
+ - src/entities/segment/**
12
+ - src/features/map-content/**
13
+ - src/features/import-content/**
14
+ - README.md
15
+ ---
16
+
17
+ # import-custom-format
18
+
19
+ Importing `./song.my` from TypeScript needs two things: a module Vite can load, and a mapping the TypeScript server can follow. This library gives both from one description of the file.
20
+
21
+ ## Setup
22
+
23
+ ```sh
24
+ vp add @r_masseater/masseater-utils effect vite-plus
25
+ ```
26
+
27
+ ## Describe the file as segments
28
+
29
+ ```ts
30
+ import { nameLiteral, renderSegments, text } from "@r_masseater/masseater-utils/mapped-import";
31
+ import { Option } from "effect";
32
+
33
+ const segments = [
34
+ text("export const "),
35
+ ...nameLiteral({ name: "greeting", span: Option.some({ start: 0, end: 8 }) }),
36
+ ];
37
+ const declaration = renderSegments({ content: "greeting", segments });
38
+ ```
39
+
40
+ Use `verbatim` for text copied from the file, `alias` for text that stands for a span, `atom` for text that must be treated as one unit, and `text` for text with no source.
41
+
42
+ ## Load it in Vite
43
+
44
+ ```ts
45
+ import { contentImport } from "@r_masseater/masseater-utils/mapped-import/vite";
46
+ import { Effect, Option } from "effect";
47
+
48
+ export const plugin = contentImport({
49
+ name: "my-format",
50
+ extension: ".my",
51
+ load: ({ content }) =>
52
+ Effect.succeed({
53
+ code: `export default ${JSON.stringify(content)};`,
54
+ declaration: Option.none(),
55
+ watchFiles: [],
56
+ }),
57
+ });
58
+ ```
59
+
60
+ When `declaration` is set, it is written to `<file>.d.my.ts` only if it changed.
61
+
62
+ ## Map for the TypeScript server
63
+
64
+ ```ts
65
+ import { mappedOutput } from "@r_masseater/masseater-utils/mapped-import/mapper";
66
+ ```
67
+
68
+ Pass the request and the mapped result. Errors need a `fallback` text, so the server still has something to type check.
69
+
70
+ ## Common mistakes
71
+
72
+ ### Writing the declaration yourself
73
+
74
+ Wrong: write `<file>.d.my.ts` in `load` with the file system.
75
+
76
+ Correct: return it as `declaration` and let the plugin write it only when it changed.
@@ -0,0 +1,39 @@
1
+ ---
2
+ name: read-hook-input
3
+ description: >
4
+ Use when a Claude Code plugin hook or script must read JSON it did not write, such as a hook
5
+ payload on stdin or a settings file: parseJson to parse without throwing and isRecord to narrow
6
+ the result to a plain object.
7
+ metadata:
8
+ type: core
9
+ library: "@r_masseater/masseater-utils"
10
+ sources:
11
+ - src/app/plugin-kit*
12
+ - src/shared/lib/record.ts
13
+ - README.md
14
+ ---
15
+
16
+ # read-hook-input
17
+
18
+ A hook payload comes from outside the hook, so its shape is not guaranteed. `parseJson` and `isRecord` read it without a cast and without a thrown error.
19
+
20
+ ## Setup
21
+
22
+ ```sh
23
+ bun add @r_masseater/masseater-utils
24
+ ```
25
+
26
+ Commit the `bun.lock` that `bun add` writes. Claude Code installs the dependencies of a plugin from its `package.json` and a text `bun.lock` when it caches the plugin.
27
+
28
+ ## Read a payload
29
+
30
+ ```ts
31
+ import { isRecord, parseJson } from "@r_masseater/masseater-utils/plugin-kit";
32
+
33
+ const parsed = parseJson(text);
34
+ if (parsed._tag === "Some" && isRecord(parsed.value)) {
35
+ console.log(parsed.value["tool_name"]);
36
+ }
37
+ ```
38
+
39
+ `parseJson` returns `{ _tag: "None" }` when the text is not JSON and never throws. `isRecord` is false for `null`, arrays and primitives, so check it before reading keys.
@@ -0,0 +1,131 @@
1
+ ---
2
+ name: read-node-ecosystem
3
+ description: >
4
+ Use when TypeScript code must read or write a package.json, read pnpm-workspace.yaml,
5
+ pnpm-lock.yaml or the projects of a pnpm workspace, or find an installed package, as Effect
6
+ values: PackageJson, decodePackageJson, readPackageJson, updatePackageJson, readWorkspaceManifest,
7
+ lockedGraph, findWorkspaceProjects and findPackageJson.
8
+ metadata:
9
+ type: core
10
+ library: "@r_masseater/masseater-utils"
11
+ sources:
12
+ - src/app/kestrion*
13
+ - src/entities/package-json/**
14
+ - src/features/find-node-package/**
15
+ - src/features/read-npm/**
16
+ - src/features/read-pnpm/**
17
+ - README.md
18
+ ---
19
+
20
+ # read-node-ecosystem
21
+
22
+ `@r_masseater/masseater-utils/kestrion` runs the official readers of npm, pnpm and Node.js and returns Effect values. Use it instead of parsing these files yourself or writing a Schema for the few fields you need, so every reader agrees with the tool that owns the file.
23
+
24
+ ## Setup
25
+
26
+ ```sh
27
+ vp add @r_masseater/masseater-utils effect @npmcli/package-json
28
+ ```
29
+
30
+ Add the `@pnpm/*` package of each pnpm function you call. The main entry and `./node` need nothing more.
31
+
32
+ ## Read a package.json
33
+
34
+ ```ts
35
+ import { decodePackageJson, readPackageJson } from "@r_masseater/masseater-utils/kestrion/npm";
36
+ import { Effect } from "effect";
37
+
38
+ const name = readPackageJson("libs/a").pipe(Effect.map((manifest) => manifest.name));
39
+ const fromText = decodePackageJson(text);
40
+ ```
41
+
42
+ Every field of `PackageJson` is optional. Check a field before you use it. Use `readVersionedPackageJson` when `name` and `version` must exist.
43
+
44
+ ## Write a package.json
45
+
46
+ ```ts
47
+ import { updatePackageJson } from "@r_masseater/masseater-utils/kestrion/npm";
48
+
49
+ const added = updatePackageJson("libs/a", { optionalDependencies: { b: "1.0.0" } });
50
+ ```
51
+
52
+ `updatePackageJson` keeps the file's indentation and line endings. Use `writePackageJson` only for a new file.
53
+
54
+ ## Read the fields
55
+
56
+ ```ts
57
+ import {
58
+ binEntriesOf,
59
+ exportEntriesOf,
60
+ runtimeDependencyNames,
61
+ } from "@r_masseater/masseater-utils/kestrion";
62
+ ```
63
+
64
+ `exportEntriesOf` and `binEntriesOf` return pairs of a subpath or command and its target. Do not walk `exports` or `bin` by hand.
65
+
66
+ ## Read pnpm
67
+
68
+ ```ts
69
+ import { lockedGraph, readWorkspaceManifest } from "@r_masseater/masseater-utils/kestrion/pnpm";
70
+ ```
71
+
72
+ Each call fails with `PnpmUnreadable`. Handle it where a missing or broken file is acceptable, for example with `Effect.orElseSucceed`.
73
+
74
+ ## Find an installed package
75
+
76
+ ```ts
77
+ import { findPackageJson } from "@r_masseater/masseater-utils/kestrion/node";
78
+
79
+ const file = findPackageJson("effect", import.meta.url);
80
+ ```
81
+
82
+ Pass `import.meta.url` of your own module, so the package resolves as your `import` would.
83
+
84
+ ## Common mistakes
85
+
86
+ ### Declaring a partial Schema for package.json
87
+
88
+ Wrong:
89
+
90
+ ```ts
91
+ const Manifest = Schema.Struct({ name: Schema.optional(Schema.String) });
92
+ const manifest = Schema.decodeOption(Schema.fromJsonString(Manifest))(text);
93
+ ```
94
+
95
+ Correct:
96
+
97
+ ```ts
98
+ import { decodePackageJson } from "@r_masseater/masseater-utils/kestrion/npm";
99
+
100
+ const manifest = decodePackageJson(text);
101
+ ```
102
+
103
+ ### Calling an upstream reader directly
104
+
105
+ Wrong:
106
+
107
+ ```ts
108
+ import { readWorkspaceManifest } from "@pnpm/workspace.workspace-manifest-reader";
109
+ ```
110
+
111
+ Correct:
112
+
113
+ ```ts
114
+ import { readWorkspaceManifest } from "@r_masseater/masseater-utils/kestrion/pnpm";
115
+ ```
116
+
117
+ ### Resolving package.json through exports
118
+
119
+ Wrong:
120
+
121
+ ```ts
122
+ const file = fileURLToPath(import.meta.resolve("effect/package.json"));
123
+ ```
124
+
125
+ Correct:
126
+
127
+ ```ts
128
+ import { findPackageJson } from "@r_masseater/masseater-utils/kestrion/node";
129
+
130
+ const file = findPackageJson("effect", import.meta.url);
131
+ ```
@@ -0,0 +1,82 @@
1
+ ---
2
+ name: run-effect-main
3
+ description: >
4
+ Use when an Effect program must run as a Node.js entry point with the Node services, an HTTP
5
+ client and OTLP tracing provided: runMain, runMainWith, and whileParentAlive for a child
6
+ process that must stop when its parent exits.
7
+ metadata:
8
+ type: core
9
+ library: "@r_masseater/masseater-utils"
10
+ sources:
11
+ - src/app/node-main*
12
+ - src/features/run-main/**
13
+ - src/features/watch-parent/**
14
+ - README.md
15
+ ---
16
+
17
+ # run-effect-main
18
+
19
+ `runMain` is the one call that starts an Effect program in Node.js. It provides the Node services and a fetch based HTTP client, sends traces, logs and metrics over OTLP, and ends the process when the program ends.
20
+
21
+ ## Setup
22
+
23
+ ```sh
24
+ vp add @r_masseater/masseater-utils effect
25
+ ```
26
+
27
+ ## Start a program
28
+
29
+ ```ts
30
+ import { runMain } from "@r_masseater/masseater-utils/node-main";
31
+ import { Console, Effect } from "effect";
32
+
33
+ runMain("my-tool")(Console.log("hello").pipe(Effect.withSpan("greet")));
34
+ ```
35
+
36
+ The argument is the service name that tracing reports. Use the name of the tool, not the name of a file.
37
+
38
+ ## Provide services of your own
39
+
40
+ ```ts
41
+ import { runMainWith } from "@r_masseater/masseater-utils/node-main";
42
+ import { Effect, Layer } from "effect";
43
+
44
+ runMainWith({ serviceName: "my-tool", services: Layer.empty })(Effect.void);
45
+ ```
46
+
47
+ `services` is built once and merged with the Node services, so the program can use everything it provides.
48
+
49
+ A failure prints one line, `<service name>: <message>`, and exits with code 1. Give a usage error or an unreadable input a message that tells the user what to do, because the line is all they see. An error without a `message` field prints only its name and its text fields, which reads worse than a sentence. An error that already printed its own report sets `[Runtime.errorReported]` to `false`, so nothing more is printed for it.
50
+
51
+ ## Stop a child with its parent
52
+
53
+ ```ts
54
+ import { whileParentAlive } from "@r_masseater/masseater-utils/node-main";
55
+ import { Effect, Option } from "effect";
56
+
57
+ const watched = Effect.never.pipe(whileParentAlive(Option.some("12345")));
58
+ ```
59
+
60
+ `whileParentAlive` checks the parent pid every two seconds. With `Option.none()` the program is never interrupted.
61
+
62
+ ## Common mistakes
63
+
64
+ ### Calling `NodeRuntime.runMain` directly
65
+
66
+ Wrong:
67
+
68
+ ```ts
69
+ import { runMain } from "@effect/platform-node/NodeRuntime";
70
+
71
+ runMain(program);
72
+ ```
73
+
74
+ Correct:
75
+
76
+ ```ts
77
+ import { runMain } from "@r_masseater/masseater-utils/node-main";
78
+
79
+ runMain("my-tool")(program);
80
+ ```
81
+
82
+ The direct call has no tracing and none of the services the program expects.
@@ -0,0 +1,152 @@
1
+ ---
2
+ name: trace-workers
3
+ description: >
4
+ Use when adding application spans to Cloudflare Workers traces with @r_masseater/masseater-utils/workers-tracing:
5
+ withWorkersTracing for Alchemy stacks, TanStack Start and Elysia middleware, running Effect
6
+ programs so withSpan and fn become spans, browser spans and logs, runWorkersAi, traceSink and the
7
+ workers-traces command that checks spans in CI.
8
+ metadata:
9
+ type: core
10
+ library: "@r_masseater/masseater-utils"
11
+ library_version: 0.1.0
12
+ sources:
13
+ - src/app/workers-tracing*
14
+ - src/features/sink-traces/**
15
+ - src/features/receive-browser/**
16
+ - src/entities/log/**
17
+ - src/entities/span/**
18
+ - bin/**
19
+ - README.md
20
+ ---
21
+
22
+ # trace-workers
23
+
24
+ Cloudflare Workers traces each request and every binding call by itself.
25
+ Those calls include D1, KV, R2, Durable Objects and `fetch`.
26
+ This package nests the application's own steps above those spans in the same trace.
27
+ The steps are the route, the server function and each `Effect.withSpan` or `Effect.fn`.
28
+ Traces are kept only on the Workers Paid plan.
29
+
30
+ ## Entries
31
+
32
+ | Entry | Use |
33
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
34
+ | `./alchemy` | `withWorkersTracing` turns on logs, traces and Workers Issues for every Worker of a stack. `traceSink` deploys the sink the CLI reads |
35
+ | `./tanstack-start` | `requestSpan` and `serverFnSpan` middleware |
36
+ | `./elysia` | Drop-in `Elysia` whose requests and routes become spans, and `routeHandlers` for mounting it in a file route |
37
+ | `./effect` | `run`, `runner` and `layer`, which send Effect spans and logs into the Workers trace |
38
+ | `./browser-spans` | `browserSpans({ service })`, a handler that accepts OTLP JSON spans from the browser |
39
+ | `./browser-logs` | `browserLogs({ service })`, a handler that accepts OTLP JSON logs from the browser, such as Web Vitals and clicks |
40
+ | `./workers-ai` | `runWorkersAi`, which retries out-of-capacity errors and records `gen_ai.*` attributes |
41
+ | `./oxlint` | `restrictedSyntax`, which bans `env.AI.run` outside `runWorkersAi` |
42
+
43
+ On Node.js and in the browser, `./effect`, `./tanstack-start` and `./elysia` resolve to pass-through versions.
44
+ The same imports therefore work in tests and client bundles.
45
+
46
+ ## Setup
47
+
48
+ ```ts no-check
49
+ import { providers, state } from "@alchemy.run/cloudflare";
50
+ import { withWorkersTracing } from "@r_masseater/masseater-utils/workers-tracing/alchemy";
51
+ import { Stack } from "alchemy";
52
+
53
+ export default Stack(
54
+ "my-app",
55
+ { providers: withWorkersTracing()(providers()), state: state() },
56
+ app,
57
+ );
58
+ ```
59
+
60
+ TanStack Start sets the middleware in `src/start.ts`.
61
+
62
+ ```ts no-check
63
+ import {
64
+ requestSpan,
65
+ serverFnSpan,
66
+ } from "@r_masseater/masseater-utils/workers-tracing/tanstack-start";
67
+ import { createStart } from "@tanstack/react-start";
68
+
69
+ export const startInstance = createStart(() => ({
70
+ requestMiddleware: [requestSpan],
71
+ functionMiddleware: [serverFnSpan],
72
+ }));
73
+ ```
74
+
75
+ Elysia: import `Elysia` from `@r_masseater/masseater-utils/workers-tracing/elysia` instead of `elysia`.
76
+
77
+ ## Running Effect programs
78
+
79
+ Every Effect that should appear in the trace runs through `run` or a `runner`. Running it with `Effect.runPromise` loses the Workers tracer, so its spans never reach the trace.
80
+
81
+ ```ts no-check
82
+ import { run, runner } from "@r_masseater/masseater-utils/workers-tracing/effect";
83
+
84
+ await run(loadInvite(id));
85
+
86
+ const runWithDb = runner(DatabaseLive);
87
+ await runWithDb(saveItem(item));
88
+ ```
89
+
90
+ Use `layer` when another runtime must own the program, for example `ManagedRuntime.make(Layer.merge(layer, AppLive))`.
91
+
92
+ ## Browser telemetry
93
+
94
+ Point the OpenTelemetry Browser SDK's OTLP JSON exporters at the app's own Worker and answer them with these handlers.
95
+
96
+ ```ts no-check
97
+ import { browserLogs } from "@r_masseater/masseater-utils/workers-tracing/browser-logs";
98
+ import { browserSpans } from "@r_masseater/masseater-utils/workers-tracing/browser-spans";
99
+
100
+ const spans = browserSpans({ service: "my-app" });
101
+ const logs = browserLogs({ service: "my-app" });
102
+ ```
103
+
104
+ Each handler takes a `Request` and returns a `Response`.
105
+ It accepts only same-origin `POST` requests of at most 64 KiB and 256 items.
106
+ It keeps only the items whose `service.name` is `service`, and writes each one to Workers Logs as `otlp.span` or `otlp.log` with its trace ID, span ID and attributes.
107
+ Do not trace these routes, or every export creates more telemetry.
108
+
109
+ ## Workers AI
110
+
111
+ ```ts no-check
112
+ import { runWorkersAi } from "@r_masseater/masseater-utils/workers-tracing/workers-ai";
113
+
114
+ const answer =
115
+ yield *
116
+ runWorkersAi({
117
+ operation: "chat",
118
+ model: "@cf/cloudflare/clef-flash",
119
+ call: () => env.AI.run("@cf/cloudflare/clef-flash", { messages }),
120
+ });
121
+ ```
122
+
123
+ It fails with `WorkersAiError` and logs a cut-off answer. Add `restrictedSyntax` from `./oxlint` to `no-restricted-syntax` so direct `env.AI.run` calls are caught.
124
+
125
+ ## Checking spans in CI
126
+
127
+ Deploy `traceSink()` once per account as its own stack.
128
+ Then name its destination in `withWorkersTracing({ destinations: ["workers-tracing"] })`.
129
+ The sink logs every received span, and `workers-traces` reads them back through the Workers Observability API.
130
+
131
+ ```sh
132
+ workers-traces --request https://app.example.com/ --expect "GET /" --expect invite.load --wait 60
133
+ ```
134
+
135
+ | Flag | Default | Meaning |
136
+ | ----------- | -------------------------------------------------- | ----------------------------------------------------- |
137
+ | `--account` | `CLOUDFLARE_ACCOUNT_ID` | Cloudflare account ID |
138
+ | `--sink` | `WORKERS_TRACES_SINK`, else `workers-tracing-sink` | The traceSink Worker name |
139
+ | `--service` | all | Show only this Worker's spans |
140
+ | `--minutes` | `15` | How far back to look |
141
+ | `--limit` | `500` | Most spans to read |
142
+ | `--request` | none | Send a GET first and look only at the trace it starts |
143
+ | `--expect` | none | Span name that must be present; repeatable |
144
+ | `--wait` | `0` | Seconds to retry until every expected span arrives |
145
+
146
+ The `workers-traces` command comes from the separate `@r_masseater/workers-tracing` package, because a command needs its Cloudflare client installed. Add it with `vp add -D @r_masseater/workers-tracing`. The CLI needs a Cloudflare API token that can read Workers Observability.
147
+
148
+ ## Common mistakes
149
+
150
+ - Calling `Effect.runPromise` in a Worker. The spans exist but are not attached to the request's trace.
151
+ - Adding a tracer layer from `@effect/opentelemetry` as well. Workers already exports the trace, and a second exporter duplicates spans.
152
+ - Expecting spans on the Workers Free plan. Traces are not kept there.