@zyro-sec/util 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/docs/layer-node.md +155 -0
  2. package/package.json +68 -4
  3. package/script/build.ts +9 -0
  4. package/script/pack.ts +5 -0
  5. package/src/abort.test.ts +16 -0
  6. package/src/abort.ts +9 -0
  7. package/src/activity-calendar.test.ts +136 -0
  8. package/src/activity-calendar.ts +50 -0
  9. package/src/artifact.test.ts +29 -0
  10. package/src/artifact.ts +95 -0
  11. package/src/base64.test.ts +12 -0
  12. package/src/base64.ts +29 -0
  13. package/src/binary.test.ts +19 -0
  14. package/src/binary.ts +30 -0
  15. package/src/bom.test.ts +21 -0
  16. package/src/bom.ts +46 -0
  17. package/src/cross-spawn-spawner.ts +694 -0
  18. package/src/duration.ts +22 -0
  19. package/src/effect/app-node-platform.ts +40 -0
  20. package/src/effect/app-node.ts +14 -0
  21. package/src/effect/layer-node.ts +360 -0
  22. package/src/effect-flock.ts +313 -0
  23. package/src/encode.test.ts +32 -0
  24. package/src/encode.ts +39 -0
  25. package/src/execute-output.test.ts +36 -0
  26. package/src/execute-output.ts +23 -0
  27. package/src/flock.ts +346 -0
  28. package/src/fs-util.ts +271 -0
  29. package/src/glob.ts +38 -0
  30. package/src/global-roots.ts +19 -0
  31. package/src/global-roots.workerd.ts +16 -0
  32. package/src/global.ts +88 -0
  33. package/src/hash.ts +11 -0
  34. package/src/heap-snapshot.ts +44 -0
  35. package/src/no-timeout-fetch.test.ts +33 -0
  36. package/src/no-timeout-fetch.ts +5 -0
  37. package/src/npm-config.ts +41 -0
  38. package/src/npm.ts +557 -0
  39. package/src/observability/logging.ts +179 -0
  40. package/src/observability/otlp.ts +109 -0
  41. package/src/observability/shared.ts +8 -0
  42. package/src/observability.ts +60 -0
  43. package/src/open.test.ts +16 -0
  44. package/src/open.ts +12 -0
  45. package/src/patch.ts +382 -0
  46. package/src/path.test.ts +89 -0
  47. package/src/path.ts +149 -0
  48. package/src/process-signal.test.ts +38 -0
  49. package/src/process-signal.ts +23 -0
  50. package/src/process.ts +270 -0
  51. package/src/qr.ts +323 -0
  52. package/src/record.ts +3 -0
  53. package/src/retry.test.ts +87 -0
  54. package/src/retry.ts +51 -0
  55. package/src/runtime/import.bun.ts +10 -0
  56. package/src/runtime/import.node.ts +61 -0
  57. package/src/runtime/import.workerd.ts +9 -0
  58. package/src/runtime-import.ts +1 -0
  59. package/src/session-mention.test.ts +19 -0
  60. package/src/session-mention.ts +24 -0
  61. package/src/session-title-fallback.ts +36 -0
  62. package/src/session-turn.test.ts +131 -0
  63. package/src/session-turn.ts +82 -0
  64. package/src/teardown.ts +19 -0
  65. package/src/text-boundary.test.ts +39 -0
  66. package/src/text-boundary.ts +36 -0
  67. package/src/uuid.test.ts +80 -0
  68. package/src/uuid.ts +15 -0
  69. package/test/fixtures/qr.json +625 -0
  70. package/test/glob.test.ts +11 -0
  71. package/test/global-roots.test.ts +62 -0
  72. package/test/global.test.ts +99 -0
  73. package/test/observability-otlp.test.ts +45 -0
  74. package/test/qr.test.ts +113 -0
  75. package/test/session-title-fallback.test.ts +49 -0
  76. package/tsconfig.build.json +12 -0
  77. package/tsconfig.dist.json +10 -0
  78. package/tsconfig.json +14 -0
  79. package/README.md +0 -3
@@ -0,0 +1,155 @@
1
+ # Layer Graphs
2
+
3
+ `LayerNode` describes replaceable wiring for ordinary Effect Layers. Declarations
4
+ and compilation do not acquire resources. Effect still owns acquisition,
5
+ memoization, scopes, and finalization.
6
+
7
+ There are three values to compose:
8
+
9
+ - A **Node** is a replaceable declaration with a fixed output, error, and tag
10
+ contract. `make` supplies its default implementation; `unbound` leaves that
11
+ implementation for the caller to supply.
12
+ - A **Graph** is a node or an ordered `group` of graphs. Grouping exposes the
13
+ selected roots, not their transitive dependencies. Groups are not replacement
14
+ targets.
15
+ - A **Replacement** is a checked instruction made by `node.replace(...)`.
16
+ Replacement arrays can be stored and concatenated without losing their checks.
17
+
18
+ ```ts
19
+ import { Context, Effect, Layer } from "effect"
20
+ import { LayerNode } from "@zyro-sec/util/effect/layer-node"
21
+
22
+ class Database extends Context.Service<Database, { readonly name: string }>()("example/Database") {}
23
+ class Users extends Context.Service<Users, { readonly name: string }>()("example/Users") {}
24
+
25
+ const tags = LayerNode.tags({ global: [], location: ["global"] })
26
+ const global = tags.make("global")
27
+ const location = tags.make("location")
28
+
29
+ const database = global({
30
+ service: Database,
31
+ layer: Layer.succeed(Database, { name: "live" }),
32
+ deps: [],
33
+ })
34
+ const users = location({
35
+ service: Users,
36
+ layer: Layer.effect(
37
+ Users,
38
+ Effect.map(Database, (db) => ({ name: db.name })),
39
+ ),
40
+ deps: [database],
41
+ })
42
+
43
+ const replacements: LayerNode.Replacements = [database.replace(Layer.succeed(Database, { name: "test" }))]
44
+
45
+ const layer = LayerNode.compile(LayerNode.group([database, users]), {
46
+ replacements,
47
+ shared: tags.values.global,
48
+ })
49
+ // Layer<Database | Users>: both selected roots remain available.
50
+ ```
51
+
52
+ ## Substitution
53
+
54
+ Replacements target the exact declaration, not its display name or service key.
55
+ Two independently declared nodes can provide the same service in different
56
+ branches without capturing each other's overrides.
57
+
58
+ Keep the original declaration as the target when configuring a default:
59
+
60
+ ```ts
61
+ const replacements = [Database.node.replace(Database.configured(options.database)), ...profile.replacements]
62
+ ```
63
+
64
+ The replacement may be a closed Layer or another node. It must provide all the
65
+ source's outputs, may provide additional outputs, must not introduce new errors,
66
+ and must retain the source's tag. An open Layer must first be wired into a node.
67
+ Replacing a node prunes its original dependencies; replacing it with another node
68
+ uses that node's dependencies instead.
69
+
70
+ The rules are:
71
+
72
+ - The last replacement for the same source wins, before any traversal.
73
+ - Replacements also apply inside replacement dependency graphs and through
74
+ replacement chains.
75
+ - Replacing a node with itself is the identity operation.
76
+ - Unreachable replacements neither acquire resources nor traverse their graphs.
77
+ - Unbound nodes and cycles in the effective graph fail during compilation.
78
+
79
+ A node's contract is invariant. It cannot be widened or narrowed to authorize a
80
+ replacement that would violate another use of the original declaration. A graph
81
+ can forget outputs like an ordinary Layer, but cannot be used as a weaker
82
+ replacement handle.
83
+
84
+ Choice and composition are different: `group([a, b])` provides both roots, while
85
+ `group([condition ? a : b])` promises only outputs common to both alternatives.
86
+ The same rule applies to conditional implementation Layers. Use tuples for known
87
+ roots; a dynamic array can be empty and therefore guarantees no service outputs.
88
+ Every alternative of a conditional replacement must satisfy the source contract.
89
+
90
+ ## Decoration
91
+
92
+ Use `mapLayer` to decorate a default implementation without duplicating or
93
+ inspecting its dependencies:
94
+
95
+ ```ts
96
+ const observed = database.mapLayer((layer) => layer.pipe(Layer.tap(() => Effect.logDebug("database ready"))))
97
+ const replacements = [database.replace(observed)]
98
+ ```
99
+
100
+ The callback is parametric in the Layer's requirements: it must preserve the
101
+ declared wiring and service/error contract. `mapLayer` returns a new node; it does
102
+ not mutate or automatically override the original. Only implemented nodes offer
103
+ this operation, not unbound slots or groups.
104
+
105
+ ## Lifetimes
106
+
107
+ Without `shared`, compilation uses Effect's enclosing memo map throughout.
108
+ With `shared: tag`, matching nodes and their dependency subgraphs use that map;
109
+ remaining wiring uses one fresh map per build. A shared service's dependencies
110
+ must live at least as long as the service, including untagged helpers. This keeps application globals shared while isolating each
111
+ Location, without exposing incomplete graphs or losing shared root outputs.
112
+
113
+ The enclosing memo map remains ambient during construction, so a lazy LayerMap
114
+ captures the shared ancestry rather than a Location's private cache. Cache
115
+ selection is internal metadata, not an extra service output of each dependency.
116
+
117
+ Native Layer identity still controls acquisition within each memo map. Use a
118
+ distinct implementation Layer for differently wired definitions; compilation
119
+ rejects conflicting wiring of the same Layer within one graph's memo domain.
120
+ Compiled wiring is memoized once per build and memo domain, so a shared dependency
121
+ graph is not expanded into a tree during acquisition. Original Layer identities
122
+ still determine service sharing across separately compiled builds. An explicitly
123
+ fresh implementation refreshes its acquisition when its wiring is built.
124
+
125
+ Groups preserve root startup order and associate transparently. A node's
126
+ dependencies are built concurrently through native `Layer.provide`. Named
127
+ startup actions and Context references are supported even when their required
128
+ service output type is `never`.
129
+
130
+ ## Migration
131
+
132
+ | Previous API | Current API |
133
+ | ------------------------------------------------ | ----------------------------------------------- |
134
+ | `[source, replacement]` | `source.replace(replacement)` |
135
+ | `compile(graph, replacements)` | `compile(graph, { replacements })` |
136
+ | `hoist`, compile both halves, `fresh`, `provide` | `compile(graph, { replacements, shared: tag })` |
137
+ | Spread a node and overwrite `implementation` | `node.mapLayer(transform)` |
138
+ | Generic root parameter `Node<A, E, any>` | `Graph<A, E>` |
139
+
140
+ An application can prepend a default binding and append caller overrides instead
141
+ of inspecting the original graph with `hasUnbound`. Unused defaults are pruned,
142
+ and defaults introduced as dependencies by an override are found naturally.
143
+
144
+ Code that reconstructed a replacement source by name must retain the original
145
+ declaration instead. Compiler representation fields are no longer public.
146
+
147
+ `PersistentPty.configured(options)` now returns a wired node, like the other Core
148
+ configuration factories. `PersistentPty.layer` remains the default raw Layer.
149
+
150
+ ## Verification
151
+
152
+ Run `bun run typecheck:dist` in `packages/util` to build the package and check the
153
+ same positive and negative contract tests against its emitted declarations.
154
+ This ensures package consumers receive the same inference and replacement checks
155
+ as callers importing the source.
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package.json",
2
3
  "name": "@zyro-sec/util",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
4
+ "version": "1.0.1",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/anomalyco/opencode.git",
10
+ "directory": "packages/util"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "imports": {
16
+ "#global-roots": {
17
+ "workerd": "./src/global-roots.workerd.ts",
18
+ "default": "./src/global-roots.ts"
19
+ },
20
+ "#runtime-import": {
21
+ "workerd": "./src/runtime/import.workerd.ts",
22
+ "bun": "./src/runtime/import.bun.ts",
23
+ "node": "./src/runtime/import.node.ts",
24
+ "default": "./src/runtime/import.bun.ts"
25
+ }
26
+ },
27
+ "scripts": {
28
+ "build": "bun run script/build.ts",
29
+ "pack": "bun run script/pack.ts",
30
+ "test": "bun test --only-failures",
31
+ "typecheck": "bun check --no-script",
32
+ "typecheck:tsc": "tsc --noEmit",
33
+ "typecheck:dist": "bun run build && bun typecheck --project tsconfig.dist.json"
34
+ },
35
+ "dependencies": {
36
+ "@effect/opentelemetry": "4.1.0",
37
+ "@effect/platform-node": "4.1.0",
38
+ "@effect/platform-node-shared": "4.1.0",
39
+ "@npmcli/arborist": "9.4.0",
40
+ "@npmcli/config": "10.8.1",
41
+ "@opentelemetry/api": "1.9.0",
42
+ "@opentelemetry/api-logs": "0.219.0",
43
+ "@opentelemetry/context-async-hooks": "2.8.0",
44
+ "@opentelemetry/exporter-trace-otlp-http": "0.219.0",
45
+ "@opentelemetry/resources": "2.8.0",
46
+ "@opentelemetry/sdk-logs": "0.219.0",
47
+ "@opentelemetry/sdk-metrics": "2.8.0",
48
+ "@opentelemetry/sdk-trace-base": "2.8.0",
49
+ "@opentelemetry/sdk-trace-node": "2.8.0",
50
+ "cross-spawn": "7.0.6",
51
+ "effect": "4.1.0",
52
+ "glob": "13.0.5",
53
+ "mime-types": "3.0.2",
54
+ "minimatch": "10.2.5",
55
+ "npm-package-arg": "13.0.2",
56
+ "open": "11.0.4",
57
+ "pacote": "21.5.1"
58
+ },
59
+ "devDependencies": {
60
+ "@tsconfig/bun": "1.0.9",
61
+ "@types/bun": "1.4.3",
62
+ "@types/cross-spawn": "6.0.6",
63
+ "@types/node": "24.12.2",
64
+ "@types/npm-package-arg": "6.1.4",
65
+ "@types/npmcli__arborist": "6.3.3",
66
+ "@types/pacote": "11.1.8",
67
+ "@typescript/native": "npm:typescript@7.1.0-beta",
68
+ "jsqr": "1.4.0"
69
+ }
70
+ }
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { $ } from "bun"
4
+ import { fileURLToPath } from "node:url"
5
+
6
+ process.chdir(fileURLToPath(new URL("..", import.meta.url)))
7
+
8
+ await $`rm -rf dist`
9
+ await $`bun tsc -p tsconfig.build.json`
package/script/pack.ts ADDED
@@ -0,0 +1,5 @@
1
+ #!/usr/bin/env bun
2
+ import path from "node:path"
3
+ import { pack } from "@zyro-sec/script/pack"
4
+
5
+ await pack(path.resolve(import.meta.dir, ".."))
@@ -0,0 +1,16 @@
1
+ import { expect, test } from "bun:test"
2
+ import { abort } from "./abort.js"
3
+
4
+ test("aborts with an AbortError that does not record the caller's stack", () => {
5
+ const controller = new AbortController()
6
+ function disposeComponent() {
7
+ abort(controller)
8
+ }
9
+
10
+ disposeComponent()
11
+
12
+ expect(controller.signal.aborted).toBe(true)
13
+ expect(controller.signal.reason).toBeInstanceOf(DOMException)
14
+ expect(controller.signal.reason.name).toBe("AbortError")
15
+ expect(String(controller.signal.reason.stack)).not.toContain("disposeComponent")
16
+ })
package/src/abort.ts ADDED
@@ -0,0 +1,9 @@
1
+ // `controller.abort()` makes a new DOMException that records the caller's stack, and V8 keeps every frame's function
2
+ // and closure alive until something reads `.stack`. Aborting from a Solid cleanup or update then pins the whole batch
3
+ // it ran in, disposed computations and detached DOM included, for as long as the signal is reachable. This reason is
4
+ // made once, so its stack holds only this module's load.
5
+ const reason = new DOMException("signal is aborted without reason", "AbortError")
6
+
7
+ export function abort(controller: AbortController | undefined) {
8
+ controller?.abort(reason)
9
+ }
@@ -0,0 +1,136 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { activityCalendar } from "./activity-calendar.js"
3
+
4
+ const input = {
5
+ from: new Date(2026, 0, 1).getTime(),
6
+ to: new Date(2026, 0, 8).getTime(),
7
+ maxWeeks: 53,
8
+ activity: [
9
+ { date: "2026-01-01", steps: 1 },
10
+ { date: "2026-01-02", steps: 50 },
11
+ ],
12
+ }
13
+
14
+ describe("activity calendar", () => {
15
+ test("aligns Monday-first weeks and excludes cells outside the end-exclusive range", () => {
16
+ const calendar = activityCalendar(input)
17
+ expect(calendar.clipped).toBe(false)
18
+ expect(calendar.weeks).toHaveLength(2)
19
+ expect(calendar.weeks[0][0]).toEqual({ date: "2025-12-29", steps: 0, level: -1 })
20
+ expect(calendar.weeks[0][3]).toEqual({ date: "2026-01-01", steps: 1, level: 2 })
21
+ expect(calendar.weeks[0][4]).toEqual({ date: "2026-01-02", steps: 50, level: 4 })
22
+ expect(calendar.weeks[1][2]).toEqual({ date: "2026-01-07", steps: 0, level: 0 })
23
+ expect(calendar.weeks[1][3].level).toBe(-1)
24
+ expect(calendar.months).toEqual([{ week: 0, label: "Jan", span: 2 }])
25
+ })
26
+
27
+ test("clips to the latest weeks and keeps empty days distinct from out-of-range cells", () => {
28
+ const calendar = activityCalendar({ ...input, activity: [], maxWeeks: 1 })
29
+ expect(calendar.clipped).toBe(true)
30
+ expect(calendar.weeks).toHaveLength(1)
31
+ expect(calendar.weeks[0][0]).toEqual({ date: "2026-01-05", steps: 0, level: 0 })
32
+ expect(calendar.weeks[0][3].level).toBe(-1)
33
+ })
34
+
35
+ test("caps long histories at 53 weeks", () => {
36
+ const calendar = activityCalendar({ ...input, from: new Date(2020, 0, 1).getTime(), maxWeeks: 200 })
37
+ expect(calendar.clipped).toBe(true)
38
+ expect(calendar.weeks).toHaveLength(53)
39
+ expect(calendar.weeks.at(-1)?.[2].date).toBe("2026-01-07")
40
+ expect(calendar.months.reduce((sum, month) => sum + month.span, 0)).toBe(53)
41
+ })
42
+
43
+ test("returns month positions and spans for partial first and last months", () => {
44
+ const calendar = activityCalendar({
45
+ ...input,
46
+ from: new Date(2026, 3, 29).getTime(),
47
+ to: new Date(2026, 4, 20).getTime(),
48
+ })
49
+ expect(calendar.months).toEqual([
50
+ { week: 0, label: "Apr", span: 1 },
51
+ { week: 1, label: "May", span: 3 },
52
+ ])
53
+ const partial = activityCalendar({
54
+ ...input,
55
+ from: new Date(2026, 3, 1).getTime(),
56
+ to: new Date(2026, 3, 2).getTime(),
57
+ })
58
+ expect(partial.months).toEqual([{ week: 0, label: "Apr", span: 1 }])
59
+ })
60
+
61
+ test("places month labels across a year boundary", () => {
62
+ const calendar = activityCalendar({
63
+ ...input,
64
+ from: new Date(2025, 11, 22).getTime(),
65
+ to: new Date(2026, 0, 12).getTime(),
66
+ })
67
+ expect(calendar.months).toEqual([
68
+ { week: 0, label: "Dec", span: 1 },
69
+ { week: 1, label: "Jan", span: 2 },
70
+ ])
71
+ })
72
+
73
+ test("keeps exactly seven distinct cells per week across DST and leap days", () => {
74
+ const calendar = activityCalendar({
75
+ from: new Date(2024, 1, 26).getTime(),
76
+ to: new Date(2024, 2, 12).getTime(),
77
+ maxWeeks: 53,
78
+ activity: [
79
+ { date: "2024-02-29", steps: 1 },
80
+ { date: "2024-03-10", steps: 1 },
81
+ ],
82
+ })
83
+ expect(calendar.weeks).toHaveLength(3)
84
+ expect(
85
+ calendar.weeks
86
+ .flat()
87
+ .filter((day) => day.steps > 0)
88
+ .map((day) => day.date),
89
+ ).toEqual(["2024-02-29", "2024-03-10"])
90
+ expect(new Set(calendar.weeks.flat().map((day) => day.date)).size).toBe(21)
91
+ })
92
+
93
+ test("uses the highest intensity for a single distinct positive count", () => {
94
+ const calendar = activityCalendar({ ...input, activity: input.activity.map((day) => ({ ...day, steps: 10 })) })
95
+ expect(
96
+ calendar.weeks
97
+ .flat()
98
+ .filter((day) => day.steps > 0)
99
+ .map((day) => day.level),
100
+ ).toEqual([4, 4])
101
+ })
102
+
103
+ test("ranks distinct activity counts in four levels", () => {
104
+ const calendar = activityCalendar({
105
+ ...input,
106
+ to: new Date(2026, 0, 10).getTime(),
107
+ activity: Array.from({ length: 8 }, (_, index) => ({ date: `2026-01-0${index + 1}`, steps: index + 1 })),
108
+ })
109
+ expect(
110
+ calendar.weeks
111
+ .flat()
112
+ .filter((day) => day.steps > 0)
113
+ .map((day) => day.level),
114
+ ).toEqual([1, 1, 2, 2, 3, 3, 4, 4])
115
+ })
116
+
117
+ test("keeps intensity relative to the requested range when older weeks are clipped", () => {
118
+ const calendar = activityCalendar({
119
+ ...input,
120
+ maxWeeks: 1,
121
+ activity: [
122
+ { date: "2026-01-01", steps: 50 },
123
+ { date: "2026-01-05", steps: 1 },
124
+ ],
125
+ })
126
+ expect(calendar.weeks[0][0].level).toBe(2)
127
+ })
128
+
129
+ test("returns an empty calendar for an empty range", () => {
130
+ expect(activityCalendar({ ...input, to: input.from, activity: [] })).toEqual({
131
+ weeks: [],
132
+ months: [],
133
+ clipped: false,
134
+ })
135
+ })
136
+ })
@@ -0,0 +1,50 @@
1
+ export function activityCalendar(input: {
2
+ activity: readonly { date: string; steps: number }[]
3
+ from: number
4
+ to: number
5
+ maxWeeks: number
6
+ }) {
7
+ // Extract local dates first, then use UTC ordinals so DST cannot add or drop cells.
8
+ const ordinal = (time: number) => {
9
+ const date = new Date(time)
10
+ return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / 86_400_000
11
+ }
12
+ const from = ordinal(input.from)
13
+ const to = ordinal(input.to - 1)
14
+ const monday = from - ((new Date(from * 86_400_000).getUTCDay() + 6) % 7)
15
+ const total = input.to <= input.from ? 0 : Math.floor((to - monday) / 7) + 1
16
+ const count = Math.min(total, 53, Math.max(1, Math.floor(input.maxWeeks)))
17
+ const start = monday + Math.max(0, total - count) * 7
18
+ const values = new Map(input.activity.map((day) => [day.date, day.steps]))
19
+ const levels = [...new Set([...values.values()].filter((steps) => steps > 0))].sort((a, b) => a - b)
20
+ const weeks = Array.from({ length: count }, (_, week) =>
21
+ Array.from({ length: 7 }, (_, day) => {
22
+ const date = start + week * 7 + day
23
+ const key = new Date(date * 86_400_000).toISOString().slice(0, 10)
24
+ const steps = values.get(key) ?? 0
25
+ return {
26
+ date: key,
27
+ steps,
28
+ level:
29
+ date < from || date > to
30
+ ? -1
31
+ : steps === 0
32
+ ? 0
33
+ : Math.max(1, Math.ceil(((levels.indexOf(steps) + 1) / levels.length) * 4)),
34
+ }
35
+ }),
36
+ )
37
+ const formatter = new Intl.DateTimeFormat("en-US", { month: "short", timeZone: "UTC" })
38
+ // Thursday identifies the month owning most of a week; partial edge weeks stay inside the range.
39
+ const months = weeks
40
+ .map((_, week) => ({
41
+ week,
42
+ label: formatter.format(Math.min(to, Math.max(from, start + week * 7 + 3)) * 86_400_000),
43
+ }))
44
+ .filter((month, index, months) => index === 0 || month.label !== months[index - 1].label)
45
+ return {
46
+ weeks,
47
+ months: months.map((month, index) => ({ ...month, span: (months[index + 1]?.week ?? count) - month.week })),
48
+ clipped: count < total,
49
+ }
50
+ }
@@ -0,0 +1,29 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { artifactKind } from "./artifact.js"
3
+
4
+ describe("artifactKind", () => {
5
+ test.each([
6
+ ["shot.PNG", "image"],
7
+ ["logo.svg", "svg"],
8
+ ["song.mp3", "audio"],
9
+ ["demo.mp4", "video"],
10
+ ["clip.webm", "video"],
11
+ ["paper.pdf", "pdf"],
12
+ ["out/index.html", "html"],
13
+ ["README.md", "markdown"],
14
+ ["flow.mmd", "mermaid"],
15
+ ["data.csv", "table"],
16
+ ["data.tsv", "table"],
17
+ ["Inter.woff2", "font"],
18
+ ["report.docx", "document"],
19
+ ["budget.XLSX", "spreadsheet"],
20
+ ["deck.pptx", "presentation"],
21
+ ["legacy.doc", "text"],
22
+ ["src/app.ts", "text"],
23
+ ["Makefile", "text"],
24
+ [".env", "text"],
25
+ ["archive.tar.gz", "text"],
26
+ ] as const)("classifies %s as %s", (path, kind) => {
27
+ expect(artifactKind(path)).toBe(kind)
28
+ })
29
+ })
@@ -0,0 +1,95 @@
1
+ /** How the app shows a file, from its extension. */
2
+ export type ArtifactKind =
3
+ | "image"
4
+ | "svg"
5
+ | "audio"
6
+ | "video"
7
+ | "pdf"
8
+ | "html"
9
+ | "markdown"
10
+ | "mermaid"
11
+ | "table"
12
+ | "font"
13
+ | "document"
14
+ | "spreadsheet"
15
+ | "presentation"
16
+ | "text"
17
+
18
+ const officeKinds = new Map<string, ArtifactKind>([
19
+ ["application/vnd.openxmlformats-officedocument.wordprocessingml.document", "document"],
20
+ ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "spreadsheet"],
21
+ ["application/vnd.openxmlformats-officedocument.presentationml.presentation", "presentation"],
22
+ ])
23
+
24
+ const mimes = new Map([
25
+ ["png", "image/png"],
26
+ ["jpg", "image/jpeg"],
27
+ ["jpeg", "image/jpeg"],
28
+ ["gif", "image/gif"],
29
+ ["webp", "image/webp"],
30
+ ["avif", "image/avif"],
31
+ ["bmp", "image/bmp"],
32
+ ["ico", "image/x-icon"],
33
+ ["tif", "image/tiff"],
34
+ ["tiff", "image/tiff"],
35
+ ["heic", "image/heic"],
36
+ ["svg", "image/svg+xml"],
37
+ ["mp3", "audio/mpeg"],
38
+ ["wav", "audio/wav"],
39
+ ["ogg", "audio/ogg"],
40
+ ["oga", "audio/ogg"],
41
+ ["m4a", "audio/mp4"],
42
+ ["aac", "audio/aac"],
43
+ ["flac", "audio/flac"],
44
+ ["opus", "audio/ogg"],
45
+ ["weba", "audio/webm"],
46
+ ["mp4", "video/mp4"],
47
+ ["m4v", "video/mp4"],
48
+ ["webm", "video/webm"],
49
+ ["mov", "video/quicktime"],
50
+ ["ogv", "video/ogg"],
51
+ ["mkv", "video/x-matroska"],
52
+ ["pdf", "application/pdf"],
53
+ ["html", "text/html"],
54
+ ["htm", "text/html"],
55
+ ["md", "text/markdown"],
56
+ ["markdown", "text/markdown"],
57
+ ["mdx", "text/markdown"],
58
+ ["mmd", "text/vnd.mermaid"],
59
+ ["mermaid", "text/vnd.mermaid"],
60
+ ["csv", "text/csv"],
61
+ ["tsv", "text/tab-separated-values"],
62
+ ["ttf", "font/ttf"],
63
+ ["otf", "font/otf"],
64
+ ["woff", "font/woff"],
65
+ ["woff2", "font/woff2"],
66
+ ["docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"],
67
+ ["xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
68
+ ["pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"],
69
+ ])
70
+
71
+ function artifactExtension(path: string) {
72
+ const name = path.split(/[\\/]/).pop() ?? ""
73
+ const index = name.lastIndexOf(".")
74
+ if (index <= 0) return ""
75
+ return name.slice(index + 1).toLowerCase()
76
+ }
77
+
78
+ export function artifactMime(path: string) {
79
+ return mimes.get(artifactExtension(path))
80
+ }
81
+
82
+ export function artifactKind(path: string): ArtifactKind {
83
+ const mime = artifactMime(path)
84
+ if (!mime) return "text"
85
+ if (mime === "image/svg+xml") return "svg"
86
+ if (mime === "application/pdf") return "pdf"
87
+ if (mime === "text/html") return "html"
88
+ if (mime === "text/markdown") return "markdown"
89
+ if (mime === "text/vnd.mermaid") return "mermaid"
90
+ if (mime === "text/csv" || mime === "text/tab-separated-values") return "table"
91
+ if (mime.startsWith("image/")) return "image"
92
+ if (mime.startsWith("audio/")) return "audio"
93
+ if (mime.startsWith("font/")) return "font"
94
+ return officeKinds.get(mime) ?? "video"
95
+ }
@@ -0,0 +1,12 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { base64ToBytes, bytesToBase64 } from "./base64.js"
3
+
4
+ describe("base64", () => {
5
+ test("encodes as standard base64 and decodes back to the same bytes", () => {
6
+ const bytes = Uint8Array.from({ length: 70_000 }, (_, index) => index % 256)
7
+ const encoded = bytesToBase64(bytes)
8
+
9
+ expect(encoded).toBe(Buffer.from(bytes).toString("base64"))
10
+ expect(base64ToBytes(encoded)).toEqual(bytes)
11
+ })
12
+ })
package/src/base64.ts ADDED
@@ -0,0 +1,29 @@
1
+ // The native codecs (Chromium 140, Firefox 133, Safari 18.2) run about 100 times faster than a string round trip. The
2
+ // type libraries declare them, but older web browsers lack them, so each is read as possibly missing first.
3
+ const nativeEncode: (() => string) | undefined = Uint8Array.prototype.toBase64
4
+ const nativeDecode: ((value: string) => Uint8Array) | undefined = Uint8Array.fromBase64
5
+
6
+ /** Encodes bytes as standard base64. */
7
+ export function bytesToBase64(bytes: Uint8Array) {
8
+ if (nativeEncode) return bytes.toBase64()
9
+
10
+ const parts: string[] = []
11
+
12
+ for (let index = 0; index < bytes.length; index += 0x8000) {
13
+ parts.push(String.fromCharCode(...bytes.subarray(index, index + 0x8000)))
14
+ }
15
+
16
+ return btoa(parts.join(""))
17
+ }
18
+
19
+ /** Decodes standard base64 into bytes. */
20
+ export function base64ToBytes(value: string) {
21
+ if (nativeDecode) return Uint8Array.fromBase64(value)
22
+
23
+ const binary = atob(value)
24
+ const bytes = new Uint8Array(binary.length)
25
+
26
+ for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index)
27
+
28
+ return bytes
29
+ }
@@ -0,0 +1,19 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { Binary } from "./binary.js"
3
+
4
+ describe("binary search", () => {
5
+ test("finds sorted values and their insertion points", () => {
6
+ const values = [{ id: "a" }, { id: "c" }, { id: "e" }]
7
+ expect(Binary.search(values, "c", (item) => item.id)).toEqual({ found: true, index: 1 })
8
+ expect(Binary.search(values, "d", (item) => item.id)).toEqual({ found: false, index: 2 })
9
+ expect(Binary.search(values, "0", (item) => item.id)).toEqual({ found: false, index: 0 })
10
+ })
11
+
12
+ test("inserts before the first matching sorted value", () => {
13
+ const values = [{ id: "a" }, { id: "c" }, { id: "c" }, { id: "e" }]
14
+ const item = { id: "c" }
15
+
16
+ expect(Binary.insert(values, item, (value) => value.id)).toBe(values)
17
+ expect(values).toEqual([{ id: "a" }, item, { id: "c" }, { id: "c" }, { id: "e" }])
18
+ })
19
+ })