@zyro-sec/util 1.0.1 → 1.0.3

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 (78) hide show
  1. package/docs/layer-node.md +155 -155
  2. package/package.json +5 -1
  3. package/script/build.ts +9 -9
  4. package/script/pack.ts +5 -5
  5. package/src/abort.ts +9 -9
  6. package/src/activity-calendar.ts +50 -50
  7. package/src/artifact.ts +95 -95
  8. package/src/base64.ts +29 -29
  9. package/src/binary.ts +30 -30
  10. package/src/bom.ts +46 -46
  11. package/src/cross-spawn-spawner.ts +694 -694
  12. package/src/duration.ts +22 -22
  13. package/src/effect/app-node-platform.ts +40 -40
  14. package/src/effect/app-node.ts +14 -14
  15. package/src/effect/layer-node.ts +360 -360
  16. package/src/effect-flock.ts +313 -313
  17. package/src/encode.ts +39 -39
  18. package/src/execute-output.ts +23 -23
  19. package/src/flock.ts +346 -346
  20. package/src/fs-util.ts +271 -271
  21. package/src/glob.ts +38 -38
  22. package/src/global-roots.ts +19 -19
  23. package/src/global-roots.workerd.ts +16 -16
  24. package/src/global.ts +88 -88
  25. package/src/hash.ts +11 -11
  26. package/src/heap-snapshot.ts +44 -44
  27. package/src/no-timeout-fetch.ts +5 -5
  28. package/src/npm-config.ts +41 -41
  29. package/src/npm.ts +557 -557
  30. package/src/observability/logging.ts +179 -179
  31. package/src/observability/otlp.ts +109 -109
  32. package/src/observability/shared.ts +8 -8
  33. package/src/observability.ts +60 -60
  34. package/src/open.ts +12 -12
  35. package/src/patch.ts +382 -382
  36. package/src/path.ts +149 -149
  37. package/src/process-signal.ts +23 -23
  38. package/src/process.ts +270 -270
  39. package/src/qr.ts +323 -323
  40. package/src/record.ts +3 -3
  41. package/src/retry.ts +51 -51
  42. package/src/runtime/import.bun.ts +10 -10
  43. package/src/runtime/import.node.ts +61 -61
  44. package/src/runtime/import.workerd.ts +9 -9
  45. package/src/runtime-import.ts +1 -1
  46. package/src/session-mention.ts +24 -24
  47. package/src/session-title-fallback.ts +36 -36
  48. package/src/session-turn.ts +82 -82
  49. package/src/teardown.ts +19 -19
  50. package/src/text-boundary.ts +36 -36
  51. package/src/uuid.ts +15 -15
  52. package/test/fixtures/qr.json +625 -625
  53. package/tsconfig.build.json +12 -12
  54. package/tsconfig.dist.json +10 -10
  55. package/tsconfig.json +14 -14
  56. package/src/abort.test.ts +0 -16
  57. package/src/activity-calendar.test.ts +0 -136
  58. package/src/artifact.test.ts +0 -29
  59. package/src/base64.test.ts +0 -12
  60. package/src/binary.test.ts +0 -19
  61. package/src/bom.test.ts +0 -21
  62. package/src/encode.test.ts +0 -32
  63. package/src/execute-output.test.ts +0 -36
  64. package/src/no-timeout-fetch.test.ts +0 -33
  65. package/src/open.test.ts +0 -16
  66. package/src/path.test.ts +0 -89
  67. package/src/process-signal.test.ts +0 -38
  68. package/src/retry.test.ts +0 -87
  69. package/src/session-mention.test.ts +0 -19
  70. package/src/session-turn.test.ts +0 -131
  71. package/src/text-boundary.test.ts +0 -39
  72. package/src/uuid.test.ts +0 -80
  73. package/test/glob.test.ts +0 -11
  74. package/test/global-roots.test.ts +0 -62
  75. package/test/global.test.ts +0 -99
  76. package/test/observability-otlp.test.ts +0 -45
  77. package/test/qr.test.ts +0 -113
  78. package/test/session-title-fallback.test.ts +0 -49
@@ -1,19 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { parseSessionMention, serializeSessionMention, sessionMentions } from "./session-mention.js"
3
-
4
- const id = "ses_0123456789abcdefghijklmnop"
5
-
6
- test("session tokens round-trip independently of the title", () => {
7
- expect(serializeSessionMention({ id })).toBe(`@session:${id}`)
8
- expect(parseSessionMention(`@session:${id}`)).toEqual({ id })
9
- expect(parseSessionMention(id)).toEqual({ id })
10
- expect(sessionMentions(`See @session:${id}, then ${id}.`).map((match) => match.id)).toEqual([id, id])
11
- })
12
-
13
- test.each(["ses_123", `@session:${id}extra`, `x${id}`, `${id}/path`, `https://host/${id}`, `@other:${id}`, `${id}_x`])(
14
- "does not parse malformed or embedded IDs: %s",
15
- (text) => {
16
- expect(parseSessionMention(text)).toBeUndefined()
17
- expect(sessionMentions(text)).toEqual([])
18
- },
19
- )
@@ -1,131 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { SessionTurn } from "./session-turn.js"
3
-
4
- type Message = {
5
- id: string
6
- type: string
7
- time: { created: number; firstToken?: number; streamed?: number; completed?: number }
8
- tokens?: { output: number; reasoning: number }
9
- }
10
-
11
- test("measures turn duration from the user prompt across assistant steps", () => {
12
- const final = step("assistant-2", { created: 27_000, completed: 30_000 })
13
- const messages = [input("user-1", 1_000), step("assistant-1", { created: 8_000, completed: 11_000 }), final]
14
-
15
- expect(SessionTurn.duration(messages, final)).toBe(29_000)
16
- })
17
-
18
- test("measures decode throughput from the first streamed token", () => {
19
- const first = step("assistant-1", { created: 6_000, firstToken: 8_000, streamed: 10_000, completed: 20_000 }, 20, 5)
20
- const final = step("assistant-2", { created: 24_000, firstToken: 25_000, streamed: 28_000, completed: 31_000 }, 30, 10)
21
- const messages = [input("user-1", 1_000), first, final]
22
-
23
- // 65 tokens over the 5s the provider spent streaming them, not the 10s that include waiting for the first.
24
- expect(SessionTurn.tokensPerSecond(messages, final)).toBe(13)
25
- })
26
-
27
- test("falls back to the request window for steps recorded without a first token", () => {
28
- const first = step("assistant-1", { created: 6_000, streamed: 10_000, completed: 20_000 }, 20, 5)
29
- const final = step("assistant-2", { created: 24_000, firstToken: 25_000, streamed: 28_000, completed: 31_000 }, 30, 10)
30
- const messages = [input("user-1", 1_000), first, final]
31
-
32
- // The old step counts its 4s request window, the new one its 3s decode window.
33
- expect(SessionTurn.tokensPerSecond(messages, final)).toBe(65 / 7)
34
- })
35
-
36
- test("measures request throughput including reasoning without tool time", () => {
37
- const first = step("assistant-1", { created: 6_000, streamed: 10_000, completed: 20_000 }, 20, 5)
38
- const final = step("assistant-2", { created: 24_000, streamed: 30_000, completed: 31_000 }, 30, 10)
39
- const messages = [input("user-1", 1_000), first, final]
40
-
41
- expect(SessionTurn.tokensPerSecond(messages, final)).toBe(6.5)
42
- first.time.streamed = undefined
43
- expect(SessionTurn.tokensPerSecond(messages, final)).toBeUndefined()
44
- })
45
-
46
- test("omits turn throughput when a stream boundary is unavailable", () => {
47
- const final = step("assistant-1", { created: 1 }, 20)
48
- expect(SessionTurn.tokensPerSecond([final], final)).toBeUndefined()
49
- })
50
-
51
- test.each([false, true])(
52
- "measures historical footers without later inputs or incomplete steps (indexed: %s)",
53
- (indexed) => {
54
- const timed = (id: string, created: number, streamed: number, completed: number, output: number) =>
55
- step(id, { created, streamed, completed }, output, 2)
56
- const messages: Message[] = [
57
- timed("before-input", 0, 1_000, 2_000, 5),
58
- input("input", 3_000),
59
- timed("first-step", 4_000, 5_000, 6_000, 10),
60
- { type: "system", id: "system", time: { created: 6_500 } },
61
- timed("second-step", 7_000, 8_000, 9_000, 20),
62
- { type: "synthetic", id: "synthetic", time: { created: 10_000 } },
63
- timed("after-synthetic", 11_000, 13_000, 14_000, 12),
64
- input("later-input", 15_000),
65
- step("incomplete", { created: 1 }),
66
- ]
67
-
68
- expect(
69
- messages.flatMap((message, index) => {
70
- if (message.type !== "assistant") return []
71
- const options = { index: indexed ? index : undefined }
72
- return [
73
- [SessionTurn.duration(messages, message, options), SessionTurn.tokensPerSecond(messages, message, options)],
74
- ]
75
- }),
76
- ).toEqual([
77
- [2_000, 7],
78
- [3_000, 12],
79
- [6_000, 17],
80
- [4_000, 7],
81
- [0, undefined],
82
- ])
83
- },
84
- )
85
-
86
- test("preserves missing-anchor fallbacks without including the absent assistant's tokens", () => {
87
- const absent = step("absent", { created: 8_000, streamed: 9_000, completed: 10_000 }, 900)
88
- const stored = step("stored", { created: 6_000, streamed: 8_000, completed: 9_000 }, 20)
89
- const prompt = input("input", 5_000)
90
-
91
- expect(SessionTurn.duration([prompt, stored], absent)).toBe(5_000)
92
- expect(SessionTurn.tokensPerSecond([prompt, stored], absent)).toBe(10)
93
- expect(SessionTurn.duration([stored], absent)).toBe(2_000)
94
- expect(SessionTurn.tokensPerSecond([stored], absent)).toBe(10)
95
- expect(SessionTurn.duration([], absent)).toBe(2_000)
96
- expect(SessionTurn.tokensPerSecond([], absent)).toBeUndefined()
97
- })
98
-
99
- test("measures a marker-era turn from its first prompt across steers", () => {
100
- const timed = (id: string, created: number, streamed: number, completed: number, output: number) =>
101
- step(id, { created, streamed, completed }, output)
102
- const final = timed("second-step", 8_000, 9_000, 10_000, 20)
103
- const messages: Message[] = [
104
- input("old-input", 0),
105
- timed("old-step", 1_000, 2_000, 3_000, 5),
106
- { type: "idle", id: "idle-1", time: { created: 3_500 } },
107
- input("input", 4_000),
108
- timed("first-step", 5_000, 6_000, 7_000, 10),
109
- input("steer", 7_500),
110
- final,
111
- ]
112
-
113
- expect(SessionTurn.legacy(messages)).toBe(false)
114
- expect(SessionTurn.duration(messages, final)).toBe(6_000)
115
- expect(SessionTurn.tokensPerSecond(messages, final)).toBe(15)
116
- expect(SessionTurn.duration(messages, final, { index: 6, legacy: true })).toBe(2_500)
117
- expect(SessionTurn.tokensPerSecond(messages, final, { index: 6, legacy: true })).toBe(20)
118
- })
119
-
120
- function input(id: string, created: number): Message {
121
- return { type: "user", id, time: { created } }
122
- }
123
-
124
- function step(id: string, time: Message["time"], output?: number, reasoning = 0): Message {
125
- return {
126
- type: "assistant",
127
- id,
128
- time,
129
- tokens: output === undefined ? undefined : { output, reasoning },
130
- }
131
- }
@@ -1,39 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { TextBoundary } from "./text-boundary.js"
3
-
4
- const encoder = new TextEncoder()
5
- const samples = ["", "ascii", "ab😀cd", "😀é€\uFFFD😀"]
6
-
7
- describe("TextBoundary", () => {
8
- test.each(samples)("every head and tail of %j keeps whole characters within the limit", (text) => {
9
- for (let limit = 0; limit <= text.length + 1; limit++) {
10
- const head = TextBoundary.head(text, limit)
11
- const tail = TextBoundary.tail(text, limit)
12
- expect(text.startsWith(head)).toBe(true)
13
- expect(text.endsWith(tail)).toBe(true)
14
- for (const part of [head, tail]) {
15
- expect(part.isWellFormed()).toBe(true)
16
- expect(part.length).toBeLessThanOrEqual(limit)
17
- expect(part.length).toBeGreaterThanOrEqual(Math.min(limit, text.length) - 1)
18
- }
19
- }
20
- })
21
-
22
- test.each(samples)("every UTF-8 tail of %j keeps whole characters within the limit", (text) => {
23
- const bytes = encoder.encode(text)
24
- for (let limit = 0; limit <= bytes.length + 1; limit++) {
25
- const tail = TextBoundary.utf8Tail(bytes, limit)
26
- expect(text.endsWith(tail)).toBe(true)
27
- expect(encoder.encode(tail).length).toBeLessThanOrEqual(limit)
28
- expect(encoder.encode(tail).length).toBeGreaterThanOrEqual(Math.min(limit, bytes.length) - 3)
29
- }
30
- })
31
-
32
- test("keeps malformed input that is not at the cut", () => {
33
- expect(TextBoundary.head("a\ud83d", 2)).toBe("a\ud83d")
34
- expect(TextBoundary.head("a\ud83db", 2)).toBe("a")
35
- expect(TextBoundary.tail("\ude00a", 2)).toBe("\ude00a")
36
- expect(TextBoundary.tail("b\ude00a", 2)).toBe("a")
37
- expect(TextBoundary.utf8Tail(Uint8Array.of(0x80, 0x41), 2)).toBe("\uFFFDA")
38
- })
39
- })
package/src/uuid.test.ts DELETED
@@ -1,80 +0,0 @@
1
- import { afterEach, describe, expect, test } from "bun:test"
2
- import { uuid } from "./uuid.js"
3
-
4
- const cryptoDescriptor = Object.getOwnPropertyDescriptor(globalThis, "crypto")
5
-
6
- const secureDescriptor = Object.getOwnPropertyDescriptor(globalThis, "isSecureContext")
7
-
8
- const randomDescriptor = Object.getOwnPropertyDescriptor(Math, "random")
9
-
10
- const setCrypto = (value: Partial<Crypto>) => {
11
- Object.defineProperty(globalThis, "crypto", {
12
- configurable: true,
13
- value: value as Crypto,
14
- })
15
- }
16
-
17
- const setSecure = (value: boolean) => {
18
- Object.defineProperty(globalThis, "isSecureContext", {
19
- configurable: true,
20
- value,
21
- })
22
- }
23
-
24
- const setRandom = (value: () => number) => {
25
- Object.defineProperty(Math, "random", {
26
- configurable: true,
27
- value,
28
- })
29
- }
30
-
31
- afterEach(() => {
32
- if (cryptoDescriptor) {
33
- Object.defineProperty(globalThis, "crypto", cryptoDescriptor)
34
- }
35
-
36
- if (secureDescriptor) {
37
- Object.defineProperty(globalThis, "isSecureContext", secureDescriptor)
38
- }
39
-
40
- if (!secureDescriptor) {
41
- delete (globalThis as { isSecureContext?: boolean }).isSecureContext
42
- }
43
-
44
- if (randomDescriptor) {
45
- Object.defineProperty(Math, "random", randomDescriptor)
46
- }
47
- })
48
-
49
- describe("uuid", () => {
50
- test("uses randomUUID in secure contexts", () => {
51
- setCrypto({ randomUUID: () => "00000000-0000-0000-0000-000000000000" })
52
- setSecure(true)
53
- expect(uuid()).toBe("00000000-0000-0000-0000-000000000000")
54
- })
55
-
56
- const fallbacks: { name: string; secure: boolean; crypto: Partial<Crypto> }[] = [
57
- {
58
- name: "in insecure contexts",
59
- secure: false,
60
- crypto: { randomUUID: () => "00000000-0000-0000-0000-000000000000" },
61
- },
62
- {
63
- name: "when randomUUID throws",
64
- secure: true,
65
- crypto: {
66
- randomUUID: () => {
67
- throw new DOMException("Failed", "OperationError")
68
- },
69
- },
70
- },
71
- { name: "when randomUUID is unavailable", secure: true, crypto: {} },
72
- ]
73
-
74
- test.each(fallbacks)("falls back $name", (row) => {
75
- setCrypto(row.crypto)
76
- setSecure(row.secure)
77
- setRandom(() => 0.5)
78
- expect(uuid()).toBe("8")
79
- })
80
- })
package/test/glob.test.ts DELETED
@@ -1,11 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { Glob } from "../src/glob.js"
3
-
4
- test("a compiled matcher agrees with match", () => {
5
- const paths = ["a.ts", "src/b.ts", ".hidden/c.ts", "src/.d.ts", "e.js", "#notes", "src/nested/f.tsx"]
6
- for (const pattern of ["**/*.ts", "*.{ts,js}", "src/**", ".*/*", "#notes", "**/*.ts?(x)", "!(*.ts)"])
7
- for (const dot of [undefined, true, false]) {
8
- const matches = Glob.matcher(pattern, { dot })
9
- expect(paths.map(matches)).toEqual(paths.map((path) => Glob.match(pattern, path, { dot })))
10
- }
11
- })
@@ -1,62 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import os from "os"
3
- import path from "path"
4
- import { pathToFileURL } from "url"
5
-
6
- const module = pathToFileURL(path.join(import.meta.dir, "../src/global-roots.ts")).href
7
-
8
- describe("global roots", () => {
9
- test("uses XDG overrides", () => {
10
- const root = path.join(os.tmpdir(), "opencode-xdg-overrides")
11
- const env = {
12
- XDG_DATA_HOME: path.join(root, "data"),
13
- XDG_CACHE_HOME: path.join(root, "cache"),
14
- XDG_CONFIG_HOME: path.join(root, "config"),
15
- XDG_STATE_HOME: path.join(root, "state"),
16
- }
17
-
18
- expect(run(env)).toEqual({
19
- data: path.join(env.XDG_DATA_HOME, "opencode"),
20
- cache: path.join(env.XDG_CACHE_HOME, "opencode"),
21
- config: path.join(env.XDG_CONFIG_HOME, "opencode"),
22
- state: path.join(env.XDG_STATE_HOME, "opencode"),
23
- tmp: path.join(os.tmpdir(), "opencode"),
24
- })
25
- })
26
-
27
- test("empty XDG overrides use home directory defaults", () => {
28
- const home = path.join(os.tmpdir(), "opencode-xdg-home")
29
-
30
- expect(
31
- run({
32
- XDG_DATA_HOME: "",
33
- XDG_CACHE_HOME: "",
34
- XDG_CONFIG_HOME: "",
35
- XDG_STATE_HOME: "",
36
- ...(process.platform === "win32" ? { USERPROFILE: home } : { HOME: home }),
37
- }),
38
- ).toEqual({
39
- data: path.join(home, ".local", "share", "opencode"),
40
- cache: path.join(home, ".cache", "opencode"),
41
- config: path.join(home, ".config", "opencode"),
42
- state: path.join(home, ".local", "state", "opencode"),
43
- tmp: path.join(os.tmpdir(), "opencode"),
44
- })
45
- })
46
- })
47
-
48
- function run(env: Record<string, string>) {
49
- const result = Bun.spawnSync({
50
- cmd: [
51
- process.execPath,
52
- "-e",
53
- `const { roots } = await import(${JSON.stringify(module)}); console.log(JSON.stringify(roots("opencode")))`,
54
- ],
55
- env: { ...process.env, ...env },
56
- stdout: "pipe",
57
- stderr: "pipe",
58
- })
59
-
60
- expect(result.exitCode, result.stderr.toString()).toBe(0)
61
- return JSON.parse(result.stdout.toString())
62
- }
@@ -1,99 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import fs from "fs"
3
- import os from "os"
4
- import path from "path"
5
- import { pathToFileURL } from "url"
6
- import { Context, Effect, Layer } from "effect"
7
- import { Global } from "../src/global.js"
8
-
9
- describe("global", () => {
10
- test("importing the module does not create directories", () => {
11
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-global-import-"))
12
- const directories = ["data", "cache", "config", "state", "tmp"].map((directory) => path.join(root, directory))
13
- const module = pathToFileURL(path.join(import.meta.dir, "../src/global.ts")).href
14
- const result = Bun.spawnSync({
15
- cmd: [process.execPath, "-e", `const { Global } = await import(${JSON.stringify(module)}); void Global.Path.tmp`],
16
- env: {
17
- ...process.env,
18
- XDG_DATA_HOME: directories[0],
19
- XDG_CACHE_HOME: directories[1],
20
- XDG_CONFIG_HOME: directories[2],
21
- XDG_STATE_HOME: directories[3],
22
- // os.tmpdir() reads TMPDIR on POSIX and TEMP on Windows.
23
- TMPDIR: directories[4],
24
- TEMP: directories[4],
25
- },
26
- stderr: "pipe",
27
- })
28
-
29
- expect(result.exitCode, result.stderr.toString()).toBe(0)
30
- directories.forEach((directory) => expect(fs.existsSync(path.join(directory, "opencode"))).toBe(false))
31
- fs.rmSync(root, { recursive: true, force: true })
32
- })
33
-
34
- test("building layerWith creates service directories and preserves an explicit tmp", async () => {
35
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-global-layer-"))
36
- const directories = {
37
- data: path.join(root, "data"),
38
- config: path.join(root, "config"),
39
- state: path.join(root, "state"),
40
- log: path.join(root, "log"),
41
- bin: path.join(root, "bin"),
42
- repos: path.join(root, "repos"),
43
- tmp: path.join(root, "nested", "..", "tmp"),
44
- }
45
-
46
- const context = await Effect.runPromise(Effect.scoped(Layer.build(Global.layerWith(directories))))
47
-
48
- Object.values(directories).forEach((directory) => expect(fs.statSync(directory).isDirectory()).toBe(true))
49
- expect(Context.get(context, Global.Service).tmp).toBe(directories.tmp)
50
- fs.rmSync(root, { recursive: true, force: true })
51
- })
52
-
53
- test("building a layer with default tmp creates and canonicalizes it", () => {
54
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-global-layer-"))
55
- const directories = ["data", "cache", "config", "state", "tmp"].map((directory) => path.join(root, directory))
56
- const module = pathToFileURL(path.join(import.meta.dir, "../src/global.ts")).href
57
- const result = Bun.spawnSync({
58
- cmd: [
59
- process.execPath,
60
- "-e",
61
- `
62
- import { Context, Effect, Layer } from "effect"
63
- const { Global } = await import(${JSON.stringify(module)})
64
- const context = await Effect.runPromise(Effect.scoped(Layer.build(Global.layerWith({}))))
65
- process.stdout.write(Context.get(context, Global.Service).tmp)
66
- `,
67
- ],
68
- cwd: path.join(import.meta.dir, ".."),
69
- env: {
70
- ...process.env,
71
- XDG_DATA_HOME: directories[0],
72
- XDG_CACHE_HOME: directories[1],
73
- XDG_CONFIG_HOME: directories[2],
74
- XDG_STATE_HOME: directories[3],
75
- // os.tmpdir() reads TMPDIR on POSIX and TEMP on Windows.
76
- TMPDIR: directories[4],
77
- TEMP: directories[4],
78
- },
79
- stdout: "pipe",
80
- stderr: "pipe",
81
- })
82
-
83
- expect(result.exitCode, result.stderr.toString()).toBe(0)
84
- // The layer canonicalizes through the native realpath, which on Windows also expands 8.3 short
85
- // names such as RUNNER~1 that the JavaScript realpathSync leaves in place.
86
- expect(result.stdout.toString()).toBe(fs.realpathSync.native(path.join(directories[4], "opencode")))
87
- const created = [
88
- path.join(directories[0], "opencode"),
89
- path.join(directories[1], "opencode", "bin"),
90
- path.join(directories[2], "opencode"),
91
- path.join(directories[3], "opencode"),
92
- path.join(directories[0], "opencode", "log"),
93
- path.join(directories[0], "opencode", "repos"),
94
- path.join(directories[4], "opencode"),
95
- ]
96
- created.forEach((directory) => expect(fs.statSync(directory).isDirectory()).toBe(true))
97
- fs.rmSync(root, { recursive: true, force: true })
98
- })
99
- })
@@ -1,45 +0,0 @@
1
- import { expect, test } from "bun:test"
2
- import { Effect } from "effect"
3
- import { Otlp } from "../src/observability/otlp.js"
4
-
5
- test("exports a span through the configured OTLP trace endpoint", async () => {
6
- const requests: unknown[] = []
7
- const headers: string[] = []
8
- const paths: string[] = []
9
- const server = Bun.serve({
10
- hostname: "127.0.0.1",
11
- port: 0,
12
- async fetch(request) {
13
- paths.push(new URL(request.url).pathname)
14
- headers.push(request.headers.get("x-otel-test") ?? "")
15
- requests.push(await request.json())
16
- return Response.json({})
17
- },
18
- })
19
-
20
- try {
21
- await Effect.gen(function* () {
22
- const tracing = yield* Otlp.tracingLayer(
23
- { endpoint: server.url.origin, headers: "x-otel-test=present" },
24
- { client: "test", version: "1.0.0", channel: "local" },
25
- )
26
- yield* Effect.void.pipe(Effect.withSpan("otlp-smoke"), Effect.provide(tracing))
27
- }).pipe(Effect.scoped, Effect.runPromise)
28
-
29
- expect(requests).toHaveLength(1)
30
- expect(paths).toEqual(["/v1/traces"])
31
- expect(headers).toEqual(["present"])
32
- expect(requests[0]).toMatchObject({
33
- resourceSpans: [
34
- {
35
- resource: {
36
- attributes: expect.arrayContaining([{ key: "service.name", value: { stringValue: "opencode" } }]),
37
- },
38
- scopeSpans: [{ spans: [expect.objectContaining({ name: "otlp-smoke" })] }],
39
- },
40
- ],
41
- })
42
- } finally {
43
- server.stop(true)
44
- }
45
- })
package/test/qr.test.ts DELETED
@@ -1,113 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { randomBytes } from "node:crypto"
3
- import jsQR from "jsqr"
4
- import { encode, renderSVG, renderUnicodeCompact } from "../src/qr.js"
5
- import fixtures from "./fixtures/qr.json" with { type: "json" }
6
-
7
- // Fixtures were generated once with the uqr package, a port of Nayuki's reference encoder. Each row is hex with a
8
- // leading 1 bit so leading light modules survive.
9
- const golden = fixtures.map((fixture) => ({
10
- ...fixture,
11
- modules: fixture.rows.map((row) =>
12
- [
13
- ...BigInt("0x" + row)
14
- .toString(2)
15
- .slice(1),
16
- ].map((bit) => bit === "1"),
17
- ),
18
- }))
19
-
20
- describe("qr", () => {
21
- test.each(golden.map((fixture) => [fixture.version, fixture.text.slice(0, 40), fixture] as const))(
22
- "matches the reference encoder at version %i: %s",
23
- (version, _, fixture) => {
24
- const modules = encode(fixture.text)
25
- expect(modules.length).toBe(version * 4 + 17)
26
- expect(modules).toEqual(fixture.modules)
27
- },
28
- )
29
-
30
- // jsQR 1.4.0 places version 23's alignment patterns at 74 instead of 78, so it can't read that version.
31
- test.each(golden.filter((fixture) => fixture.version !== 23).map((fixture) => [fixture.version, fixture] as const))(
32
- "SVG and terminal output decode at version %i",
33
- (_, fixture) => {
34
- expect(decode(fromSVG(renderSVG(fixture.text, { border: 4 })))).toBe(fixture.text)
35
- expect(decode(fromUnicode(renderUnicodeCompact(fixture.text, { border: 1 })))).toBe(fixture.text)
36
- },
37
- )
38
-
39
- test("random pairing payloads decode", () => {
40
- Array.from({ length: 30 }, (_, i) => {
41
- const text = JSON.stringify({
42
- code: randomBytes(16).toString("base64url"),
43
- urls: Array.from({ length: 1 + (i % 5) }, (_, j) => `http://192.168.${i}.${j + 1}:4096`),
44
- })
45
- expect(decode(fromUnicode(renderUnicodeCompact(text, { border: (i % 3) + 1 })))).toBe(text)
46
- })
47
- })
48
-
49
- test("renders the SVG as uqr did", () => {
50
- const svg = renderSVG("hello", { border: 4, blackColor: "currentColor", whiteColor: "transparent" })
51
- expect(svg).toStartWith(
52
- '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 290 290"><rect fill="transparent" width="290" height="290"/><path fill="currentColor" d="M40,40h10v10h-10zM50,40h10v10h-10z',
53
- )
54
- expect(fromSVG(svg)).toEqual(withBorder(golden[0].modules, 4))
55
- })
56
-
57
- test("renders terminal rows in pairs and shows the background below the last odd row", () => {
58
- const lines = renderUnicodeCompact("hello", { border: 2 }).split("\n")
59
- expect(lines).toHaveLength(13)
60
- expect(lines.every((line) => line.length === 25)).toBe(true)
61
- expect(lines[0]).toBe("\u2588".repeat(25))
62
- expect(lines.at(-1)).toBe("\u2580".repeat(25))
63
- expect(fromUnicode(lines.join("\n"))).toEqual(withBorder(golden[0].modules, 2))
64
- })
65
-
66
- test("rejects text longer than version 40 holds", () => {
67
- expect(encode("a".repeat(2953))).toHaveLength(177)
68
- expect(() => encode("a".repeat(2954))).toThrow(RangeError)
69
- })
70
- })
71
-
72
- function withBorder(modules: boolean[][], border: number) {
73
- const width = modules.length + border * 2
74
- const light = Array<boolean>(border).fill(false)
75
- const edge = Array.from({ length: border }, () => Array<boolean>(width).fill(false))
76
- return [...edge, ...modules.map((row) => [...light, ...row, ...light]), ...edge]
77
- }
78
-
79
- function fromSVG(svg: string) {
80
- const width = Number(svg.match(/viewBox="0 0 (\d+)/)?.[1]) / 10
81
- const modules = Array.from({ length: width }, () => Array<boolean>(width).fill(false))
82
- for (const match of svg.matchAll(/M(\d+),(\d+)h10v10h-10z/g))
83
- modules[Number(match[2]) / 10][Number(match[1]) / 10] = true
84
- return modules
85
- }
86
-
87
- // Reverses the half-block encoding and drops the padding row under the last line.
88
- function fromUnicode(text: string) {
89
- const lines = text.split("\n")
90
- const halves = { "\u2588": [false, false], "\u2580": [false, true], "\u2584": [true, false], " ": [true, true] }
91
- return lines
92
- .flatMap((line) => {
93
- const pairs = [...line].map((char) => halves[char as keyof typeof halves])
94
- return [pairs.map((pair) => pair[0]), pairs.map((pair) => pair[1])]
95
- })
96
- .slice(0, lines[0].length)
97
- }
98
-
99
- // Draws the modules 4 pixels each with an extra quiet zone, then reads them back with jsQR.
100
- function decode(modules: boolean[][]) {
101
- const scale = 4
102
- const padded = withBorder(modules, 4)
103
- const width = padded.length * scale
104
- const pixels = new Uint8ClampedArray(width * width * 4).map((_, i) => {
105
- if (i % 4 === 3) return 255
106
- const pixel = Math.floor(i / 4)
107
- return padded[Math.floor(pixel / width / scale)][Math.floor((pixel % width) / scale)] ? 0 : 255
108
- })
109
- // jsqr is CommonJS, so under NodeNext its function is the module's `default` property.
110
- const result = jsQR.default(pixels, width, width)
111
- if (!result) throw new Error("jsQR could not read the QR Code")
112
- return new TextDecoder().decode(new Uint8Array(result.binaryData))
113
- }
@@ -1,49 +0,0 @@
1
- import { describe, expect, test } from "bun:test"
2
- import { SessionTitleFallback } from "../src/session-title-fallback.js"
3
-
4
- const root = { title: undefined, time: { created: 0 } }
5
- const child = { ...root, parentID: "ses_parent" }
6
-
7
- describe("SessionTitleFallback", () => {
8
- test("supplies timestamped compatibility titles", () => {
9
- expect(SessionTitleFallback.withTimestampedFallback(root)).toBe("New session - 1970-01-01T00:00:00.000Z")
10
- expect(SessionTitleFallback.withTimestampedFallback(child)).toBe("Child session - 1970-01-01T00:00:00.000Z")
11
- expect(SessionTitleFallback.withTimestampedFallback({ ...root, title: "Generated title" })).toBe("Generated title")
12
- expect(SessionTitleFallback.withTimestampedFallback({ ...root, title: "" })).toBe("")
13
- })
14
-
15
- test("supplies compact display labels", () => {
16
- expect(SessionTitleFallback.displayLabel(root)).toBe("New session")
17
- expect(SessionTitleFallback.displayLabel(child)).toBe("Child session")
18
- expect(SessionTitleFallback.displayLabel({ title: "", parentID: "ses_parent" })).toBe("Child session")
19
- expect(SessionTitleFallback.displayLabel({ title: "New session - 2026-07-30T18:45:03.662Z" })).toBe("New session")
20
- expect(SessionTitleFallback.displayLabel({ title: "Child session - 2026-07-30T18:45:03.662Z" })).toBe(
21
- "Child session",
22
- )
23
- expect(SessionTitleFallback.displayLabel({ title: "Generated title" })).toBe("Generated title")
24
- })
25
-
26
- test("recognizes historical fallback titles", () => {
27
- expect(SessionTitleFallback.isFallbackTitle(undefined)).toBeTrue()
28
- expect(SessionTitleFallback.isFallbackTitle("New session - 2026-07-30T18:45:03.662Z")).toBeTrue()
29
- expect(SessionTitleFallback.isFallbackTitle("Child session - 2026-07-30T18:45:03.662Z")).toBeTrue()
30
- expect(SessionTitleFallback.isFallbackTitle("")).toBeFalse()
31
- expect(SessionTitleFallback.isFallbackTitle("New session - custom")).toBeFalse()
32
- })
33
-
34
- test("recognizes only the fallback associated with a session", () => {
35
- expect(SessionTitleFallback.isExactRootFallback(root)).toBeTrue()
36
- expect(
37
- SessionTitleFallback.isExactRootFallback({ ...root, title: "New session - 1970-01-01T00:00:00.000Z" }),
38
- ).toBeTrue()
39
- expect(
40
- SessionTitleFallback.isExactRootFallback({ ...root, title: "New session - 2099-01-01T00:00:00.000Z" }),
41
- ).toBeFalse()
42
- expect(
43
- SessionTitleFallback.isExactRootFallback({
44
- ...child,
45
- title: "Child session - 1970-01-01T00:00:00.000Z",
46
- }),
47
- ).toBeFalse()
48
- })
49
- })