moi-computer 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,7 @@
16
16
  // are paths relative to it (`"widgets/hello"` → `.moi/widgets/hello.server.ts`).
17
17
  // This is the contract documented in the widgets SKILL.
18
18
  import { LRUCache } from 'lru-cache'
19
+ import { readFileSync } from 'node:fs'
19
20
  import { tmpdir } from 'node:os'
20
21
  import { join } from 'path'
21
22
 
@@ -38,6 +39,16 @@ type Slot = {
38
39
  readyPromise: Promise<void>
39
40
  pending: Map<string, Pending>
40
41
  killed: boolean
42
+ // Introspection only (surfaced by /status) — not load-bearing.
43
+ ready: boolean
44
+ spawnedAt: number
45
+ lastCallAt: number | null
46
+ calls: number
47
+ errors: number
48
+ timeouts: number
49
+ // Module keys the worker has loaded and cached (reported via 'loaded' IPC,
50
+ // pruned when reloadModules evicts them).
51
+ modules: Set<string>
41
52
  }
42
53
 
43
54
  function rejectAndClearPending(slot: Slot, reason: string) {
@@ -76,7 +87,14 @@ function spawnSlot(workspacePath: string, workspaceEnv: Record<string, string>):
76
87
  worker: undefined as never,
77
88
  readyPromise,
78
89
  pending: new Map(),
79
- killed: false
90
+ killed: false,
91
+ ready: false,
92
+ spawnedAt: Date.now(),
93
+ lastCallAt: null,
94
+ calls: 0,
95
+ errors: 0,
96
+ timeouts: 0,
97
+ modules: new Set()
80
98
  }
81
99
 
82
100
  slot.worker = Bun.spawn([process.execPath, WORKER_PATH], {
@@ -106,13 +124,25 @@ function spawnSlot(workspacePath: string, workspaceEnv: Record<string, string>):
106
124
  if (slots.peek(workspacePath) === slot) slots.delete(workspacePath)
107
125
  },
108
126
  ipc(message) {
109
- const msg = message as { type: string; id?: string; data?: string; message?: string }
127
+ const msg = message as {
128
+ type: string
129
+ id?: string
130
+ data?: string
131
+ message?: string
132
+ module?: string
133
+ }
110
134
 
111
135
  if (msg.type === 'ready') {
136
+ slot.ready = true
112
137
  readyResolve()
113
138
  return
114
139
  }
115
140
 
141
+ if (msg.type === 'loaded' && msg.module) {
142
+ slot.modules.add(msg.module)
143
+ return
144
+ }
145
+
116
146
  if (msg.id) {
117
147
  const p = slot.pending.get(msg.id)
118
148
  if (!p) return
@@ -122,6 +152,7 @@ function spawnSlot(workspacePath: string, workspaceEnv: Record<string, string>):
122
152
  if (msg.type === 'result') {
123
153
  p.resolve(msg.data!)
124
154
  } else if (msg.type === 'error') {
155
+ slot.errors++
125
156
  p.reject(new Error(msg.message ?? 'Unknown error'))
126
157
  }
127
158
  }
@@ -165,14 +196,18 @@ export async function callFunction(
165
196
  // up current .env + custom overrides. Env is fixed at spawn — an already-warm
166
197
  // worker keeps its snapshot until restartWorker() reaps it. Widgets only see
167
198
  // secrets scoped to the 'widgets' sink.
168
- const workspaceEnv = await resolveWorkspaceEnv(workspacePath, 'widgets')
199
+ const workspaceEnv = await resolveWorkspaceEnv(workspacePath)
169
200
  const slot = getOrSpawn(workspacePath, workspaceEnv)
170
201
  await slot.readyPromise
171
202
 
203
+ slot.calls++
204
+ slot.lastCallAt = Date.now()
205
+
172
206
  const id = crypto.randomUUID()
173
207
  return new Promise((resolve, reject) => {
174
208
  const timer = setTimeout(() => {
175
209
  slot.pending.delete(id)
210
+ slot.timeouts++
176
211
  reject(new Error(`Function call timed out: ${module}/${name}`))
177
212
  }, CALL_TIMEOUT_MS)
178
213
 
@@ -206,6 +241,66 @@ export function restartWorker(workspacePath: string) {
206
241
  slots.delete(workspacePath)
207
242
  }
208
243
 
244
+ // Caps surfaced in /status so the numbers there are self-explanatory.
245
+ export const WORKER_LIMITS = {
246
+ maxWorkers: MAX_WORKERS,
247
+ idleTtlMs: WORKER_IDLE_TTL_MS,
248
+ callTimeoutMs: CALL_TIMEOUT_MS
249
+ } as const
250
+
251
+ export type WorkerDebugInfo = {
252
+ workspacePath: string
253
+ pid: number | undefined
254
+ ready: boolean
255
+ spawnedAt: number
256
+ lastCallAt: number | null
257
+ calls: number
258
+ errors: number
259
+ timeouts: number
260
+ pending: number
261
+ // ms until the LRU idle TTL reaps this worker (refreshed on every call)
262
+ ttlRemainingMs: number
263
+ // Resident memory of the worker process; null when /proc isn't available (macOS)
264
+ rssBytes: number | null
265
+ modules: string[]
266
+ }
267
+
268
+ // Best-effort RSS from /proc — Linux only, returns null elsewhere. VmRSS is in
269
+ // kB, so no page-size assumptions. Sync read of a tiny procfs file is cheap.
270
+ function readRss(pid: number | undefined): number | null {
271
+ if (!pid || process.platform !== 'linux') return null
272
+ try {
273
+ const m = readFileSync(`/proc/${pid}/status`, 'utf8').match(/^VmRSS:\s+(\d+)\s+kB/m)
274
+ return m ? Number(m[1]) * 1024 : null
275
+ } catch {
276
+ return null
277
+ }
278
+ }
279
+
280
+ // A snapshot of the live worker pool, for the /status page. Iteration and
281
+ // getRemainingTTL don't refresh LRU recency, so peeking is side-effect free.
282
+ export function getWorkersDebugSnapshot(): WorkerDebugInfo[] {
283
+ const out: WorkerDebugInfo[] = []
284
+ for (const [workspacePath, slot] of slots.entries()) {
285
+ if (slot.killed) continue
286
+ out.push({
287
+ workspacePath,
288
+ pid: slot.worker.pid,
289
+ ready: slot.ready,
290
+ spawnedAt: slot.spawnedAt,
291
+ lastCallAt: slot.lastCallAt,
292
+ calls: slot.calls,
293
+ errors: slot.errors,
294
+ timeouts: slot.timeouts,
295
+ pending: slot.pending.size,
296
+ ttlRemainingMs: slots.getRemainingTTL(workspacePath),
297
+ rssBytes: readRss(slot.worker.pid),
298
+ modules: [...slot.modules].sort()
299
+ })
300
+ }
301
+ return out
302
+ }
303
+
209
304
  export function reloadModules(modules: string[], workspacePath: string) {
210
305
  if (modules.length === 0) return
211
306
  // peek: don't refresh TTL just because files changed. If the worker was
@@ -214,5 +309,8 @@ export function reloadModules(modules: string[], workspacePath: string) {
214
309
  if (!slot || slot.killed) return
215
310
  try {
216
311
  slot.worker.send({ type: 'reload', modules })
312
+ // The worker evicts these from its module cache; it re-reports 'loaded'
313
+ // on the next call, so drop them from the introspection set too.
314
+ for (const m of modules) slot.modules.delete(m)
217
315
  } catch {}
218
316
  }
@@ -1,10 +1,10 @@
1
- import envPaths from 'env-paths'
2
1
  import { mkdir } from 'node:fs/promises'
3
2
  import { homedir } from 'node:os'
4
3
  import { join, resolve, sep } from 'path'
5
4
 
6
5
  import type { DiscoveredWorkspace, WorkspaceEntry, WorkspaceType } from '@/lib/types'
7
6
 
7
+ import { DATA_DIR } from './data-dir'
8
8
  import { type OpenClawAgent, discoverOpenClawAgents } from './openclaw'
9
9
 
10
10
  // Replace the home-dir prefix with `~` for display. Keeps the original
@@ -22,7 +22,6 @@ function withDisplayPath<T extends { path: string }>(entry: T): T & { displayPat
22
22
  return { ...entry, displayPath: tildify(entry.path) }
23
23
  }
24
24
 
25
- const DATA_DIR = envPaths('moi', { suffix: false }).data
26
25
  export const DEFAULT_REGISTRY_PATH = join(DATA_DIR, 'workspaces.json')
27
26
 
28
27
  // Overridable for tests
@@ -0,0 +1,19 @@
1
+ // The env "required" view aggregates `config.requiredEnv` declared by both
2
+ // widgets and views, each key mapped to the bundle ids that asked for it.
3
+ // Shared by the env API (api.ts) and the `moi env` CLI (cli-env.ts).
4
+ import { collectViewRequiredEnv } from './views'
5
+ import { collectRequiredEnv } from './widgets'
6
+
7
+ export async function requiredEnvFor(workspacePath: string): Promise<Record<string, string[]>> {
8
+ const [widgets, views] = await Promise.all([
9
+ collectRequiredEnv(workspacePath),
10
+ collectViewRequiredEnv(workspacePath)
11
+ ])
12
+ const out: Record<string, string[]> = {}
13
+ for (const map of [widgets, views]) {
14
+ for (const [key, ids] of Object.entries(map)) {
15
+ out[key] = [...(out[key] ?? []), ...ids]
16
+ }
17
+ }
18
+ return out
19
+ }
@@ -19,10 +19,22 @@ import {
19
19
  toRichText
20
20
  } from 'tldraw'
21
21
 
22
- import type { ScratchImageQuality, ScratchOp, ScratchOpResult, ScratchStyle } from '@/lib/types'
22
+ import { describeNewerWriter, sequencesAhead } from '@/lib/scratchpad-skew'
23
+ import type {
24
+ ScratchImageQuality,
25
+ ScratchOp,
26
+ ScratchOpResult,
27
+ ScratchStyle,
28
+ ScratchpadWriter
29
+ } from '@/lib/types'
23
30
 
24
31
  import { publishEvent } from './events'
25
- import { type ScratchpadDoc, loadScratchpadDoc, saveScratchpadDoc } from './scratchpad'
32
+ import {
33
+ SCRATCHPAD_WRITER,
34
+ type ScratchpadDoc,
35
+ loadScratchpadDoc,
36
+ saveScratchpadDoc
37
+ } from './scratchpad'
26
38
 
27
39
  // Server-side Scratchpad writer. The browser is no longer required to draw: we run
28
40
  // the same ops against a *headless* tldraw store here, persist the snapshot, and
@@ -65,10 +77,31 @@ function styleProps(style: ScratchStyle): Record<string, unknown> {
65
77
 
66
78
  // A fresh headless store hydrated from the saved snapshot (or empty). The
67
79
  // snapshot shape (`{ document }`) matches what the browser PUTs and loads.
68
- function buildStore(doc: ScratchpadDoc | null): TLStore {
80
+ // A failed load is inspected for version skew: tldraw has no down-migrations,
81
+ // so a snapshot written by a newer tldraw is unreadable here — but intact.
82
+ // That gets a loud, actionable error instead of tldraw's bare `migration-error`
83
+ // (which surfaces verbatim through the control port to the `moi scratch` CLI).
84
+ function buildStore(doc: ScratchpadDoc | null, writer: ScratchpadWriter | undefined): TLStore {
69
85
  const store = createTLStore({ shapeUtils: defaultShapeUtils, bindingUtils: defaultBindingUtils })
70
86
  if (doc?.store) {
71
- loadSnapshot(store, { document: doc } as unknown as Parameters<typeof loadSnapshot>[1])
87
+ try {
88
+ loadSnapshot(store, { document: doc } as unknown as Parameters<typeof loadSnapshot>[1])
89
+ } catch (err) {
90
+ const ahead = sequencesAhead(doc.schema, store.schema.serialize().sequences)
91
+ if (ahead.length > 0) {
92
+ throw new Error(
93
+ `Scratchpad was written by a newer moi (${describeNewerWriter(writer, ahead)}); ` +
94
+ `this server has tldraw ${SCRATCHPAD_WRITER.tldraw}. Restart the newer server or ` +
95
+ `update this install (bun install -g moi-computer@latest). ` +
96
+ `The canvas file is intact — do not reset it.`
97
+ )
98
+ }
99
+ // Not skew — the snapshot itself is bad. Keep the original cause visible.
100
+ throw new Error(
101
+ `Scratchpad snapshot failed to load (not a version mismatch — the file may be ` +
102
+ `corrupted): ${err instanceof Error ? err.message : String(err)}`
103
+ )
104
+ }
72
105
  }
73
106
  // Seed the document/page records a fresh (or partial) store needs to be valid.
74
107
  store.ensureStoreIsUsable()
@@ -368,8 +401,8 @@ export function executeScratchOp(
368
401
  op: ScratchOp
369
402
  ): Promise<ScratchOpResult> {
370
403
  return withLock(workspacePath, async () => {
371
- const { document } = await loadScratchpadDoc(workspacePath)
372
- const store = buildStore(document)
404
+ const { document, writer } = await loadScratchpadDoc(workspacePath)
405
+ const store = buildStore(document, writer)
373
406
  // add-image decodes/resizes the file first, so it's the one async op.
374
407
  const result = op.kind === 'add-image' ? await applyAddImage(store, op) : applyOp(store, op)
375
408
  const next = getSnapshot(store).document as unknown as ScratchpadDoc
@@ -1,5 +1,11 @@
1
1
  import { join } from 'path'
2
2
 
3
+ import tldrawPkg from 'tldraw/package.json'
4
+
5
+ import type { ScratchpadWriter } from '@/lib/types'
6
+
7
+ import moiPkg from '../package.json'
8
+
3
9
  // The Scratchpad is a shared tldraw canvas per workspace, persisted as a tldraw
4
10
  // *document* snapshot here (the per-tab `session` is intentionally dropped). Two
5
11
  // writers: the browser autosaves on user edits, and the server writes on agent
@@ -9,7 +15,17 @@ import { join } from 'path'
9
15
  // A tldraw document snapshot: `getSnapshot(store).document`. Opaque to us apart
10
16
  // from `.store` (the record map) which `read` walks. `null` means empty canvas.
11
17
  export type ScratchpadDoc = { store?: Record<string, unknown>; schema?: unknown }
12
- export type ScratchpadSnapshot = { document: ScratchpadDoc | null }
18
+ export type ScratchpadSnapshot = { document: ScratchpadDoc | null; writer?: ScratchpadWriter }
19
+
20
+ // This process's identity as a snapshot writer. The tldraw version is what
21
+ // matters for compatibility (the snapshot embeds its schema); the moi version is
22
+ // what a user can actually act on ("update moi"). Both resolve from this
23
+ // install's own package.json files, so they're correct in the repo-source and
24
+ // installed layouts alike.
25
+ export const SCRATCHPAD_WRITER: ScratchpadWriter = {
26
+ moi: moiPkg.version,
27
+ tldraw: tldrawPkg.version
28
+ }
13
29
 
14
30
  // One shape as surfaced by `moi scratch read` — a compact, agent-friendly view.
15
31
  export type ScratchShape = {
@@ -32,12 +48,21 @@ export function getScratchpadPath(workspacePath: string): string {
32
48
  return join(workspacePath, '.moi', '.scratchpad.json')
33
49
  }
34
50
 
51
+ // The writer stamp is trusted only off disk — we wrote it (saveScratchpadDoc
52
+ // stamps every save); a client PUT body never carries one through.
53
+ function parseWriter(value: unknown): ScratchpadWriter | undefined {
54
+ if (!value || typeof value !== 'object') return undefined
55
+ const w = value as { moi?: unknown; tldraw?: unknown }
56
+ if (typeof w.moi !== 'string' || typeof w.tldraw !== 'string') return undefined
57
+ return { moi: w.moi, tldraw: w.tldraw }
58
+ }
59
+
35
60
  export async function loadScratchpadDoc(workspacePath: string): Promise<ScratchpadSnapshot> {
36
61
  try {
37
62
  const text = await Bun.file(getScratchpadPath(workspacePath)).text()
38
63
  const parsed = JSON.parse(text)
39
64
  if (parsed && typeof parsed === 'object' && parsed.document) {
40
- return { document: parsed.document as ScratchpadDoc }
65
+ return { document: parsed.document as ScratchpadDoc, writer: parseWriter(parsed.writer) }
41
66
  }
42
67
  } catch {}
43
68
  return { document: null }
@@ -47,7 +72,23 @@ export async function saveScratchpadDoc(
47
72
  document: ScratchpadDoc,
48
73
  workspacePath: string
49
74
  ): Promise<void> {
50
- await Bun.write(getScratchpadPath(workspacePath), JSON.stringify({ document }, null, 2))
75
+ const path = getScratchpadPath(workspacePath)
76
+ await backupOnSchemaChange(path, document)
77
+ await Bun.write(path, JSON.stringify({ document, writer: SCRATCHPAD_WRITER }, null, 2))
78
+ }
79
+
80
+ // When a save is about to overwrite a snapshot with a *different* schema (i.e.
81
+ // the first write after a tldraw upgrade), keep the old file as `.bak` — the
82
+ // manual escape hatch after a downgrade, since the new file won't open in the
83
+ // older tldraw. One .bak, replaced on each schema change. Best-effort: a backup
84
+ // failure must never block the save.
85
+ async function backupOnSchemaChange(path: string, document: ScratchpadDoc): Promise<void> {
86
+ try {
87
+ const existing = JSON.parse(await Bun.file(path).text()) as { document?: ScratchpadDoc }
88
+ const oldSchema = existing?.document?.schema
89
+ if (!oldSchema || JSON.stringify(oldSchema) === JSON.stringify(document.schema)) return
90
+ await Bun.write(`${path}.bak`, Bun.file(path))
91
+ } catch {}
51
92
  }
52
93
 
53
94
  // tldraw embeds pasted/dropped images as `data:<mime>;base64,<blob>` URLs (on
package/server/status.ts CHANGED
@@ -1,12 +1,16 @@
1
1
  // Plain-text introspection of the running server, served at GET /status.
2
2
  // A quick "peek into the process": connected tabs, the in-memory live-session
3
- // registry (CC + OpenClaw), and each session's busy/idle state + last message —
4
- // handy when a chat appears stuck (loader spinning) and you want to know whether
5
- // the server still holds a live session for that thread and what it's doing.
3
+ // registry (CC + OpenClaw), each session's busy/idle state + last message, and
4
+ // the functions-worker pool (one child process per workspace) — handy when a
5
+ // chat appears stuck (loader spinning) and you want to know whether the server
6
+ // still holds a live session for that thread, or when a widget's server call
7
+ // hangs and you want to see whether its worker is alive and what it has loaded.
6
8
  import { type CCDebugSession, SESSION_LIMITS, getCCDebugSnapshot } from './cc-session'
7
9
  import { CONTROL_PORT, PORT } from './constants'
8
10
  import { debugEnabled } from './debug'
11
+ import { WORKER_LIMITS, type WorkerDebugInfo, getWorkersDebugSnapshot } from './functions'
9
12
  import { getOpenClawRunningSessions } from './openclaw-session'
13
+ import { tildify } from './registry'
10
14
  import { getClientCount } from './state'
11
15
 
12
16
  const STARTED_AT = Date.now()
@@ -30,6 +34,36 @@ function fmtAgo(ts: number, now: number): string {
30
34
  return `${Math.floor(m / 60)}h ${m % 60}m ago`
31
35
  }
32
36
 
37
+ function fmtMb(bytes: number): string {
38
+ return `${(bytes / (1024 * 1024)).toFixed(1)}mb`
39
+ }
40
+
41
+ function workerLine(w: WorkerDebugInfo, now: number): string {
42
+ // A worker with in-flight calls is busy; one still booting is spawning;
43
+ // otherwise it's warm and waiting for its idle TTL.
44
+ const mark = w.pending > 0 ? '▶ busy' : w.ready ? '○ warm' : '… spawning'
45
+ let callsBit = `calls=${w.calls}`
46
+ const problems: string[] = []
47
+ if (w.errors > 0) problems.push(`${w.errors} error${w.errors === 1 ? '' : 's'}`)
48
+ if (w.timeouts > 0) problems.push(`${w.timeouts} timeout${w.timeouts === 1 ? '' : 's'}`)
49
+ if (problems.length > 0) callsBit += ` (${problems.join(', ')})`
50
+
51
+ const bits = [
52
+ mark.padEnd(10),
53
+ `ws=${tildify(w.workspacePath)}`,
54
+ `pid=${w.pid ?? '?'}`,
55
+ callsBit,
56
+ `pending=${w.pending}`,
57
+ `age=${fmtDuration(now - w.spawnedAt)}`,
58
+ `lastCall=${w.lastCallAt === null ? 'never' : fmtAgo(w.lastCallAt, now)}`,
59
+ `reap=${w.ttlRemainingMs > 0 ? 'in ' + fmtDuration(w.ttlRemainingMs) : 'imminent'}`
60
+ ]
61
+ if (w.rssBytes !== null) bits.push(`rss=${fmtMb(w.rssBytes)}`)
62
+ let line = ' ' + bits.join(' ')
63
+ line += `\n modules: ${w.modules.length > 0 ? w.modules.join(', ') : '(none loaded)'}`
64
+ return line
65
+ }
66
+
33
67
  function sessionLine(s: CCDebugSession, now: number): string {
34
68
  const mark = s.busy ? '▶ busy' : s.closed ? '✗ closed' : '○ idle'
35
69
  const bits = [
@@ -90,5 +124,22 @@ export function renderStatus(): string {
90
124
  }
91
125
  lines.push('')
92
126
 
127
+ const workers = getWorkersDebugSnapshot()
128
+ lines.push(
129
+ `function workers ${workers.length}/${WORKER_LIMITS.maxWorkers} ` +
130
+ `(one per workspace, idle TTL ${fmtDuration(WORKER_LIMITS.idleTtlMs)}, ` +
131
+ `call timeout ${fmtDuration(WORKER_LIMITS.callTimeoutMs)})`
132
+ )
133
+ if (workers.length === 0) {
134
+ lines.push(' (none running — spawned lazily on the first server-function call)')
135
+ } else {
136
+ // Busiest / most-recently-called first.
137
+ const sorted = [...workers].sort(
138
+ (a, b) => b.pending - a.pending || (b.lastCallAt ?? 0) - (a.lastCallAt ?? 0)
139
+ )
140
+ for (const w of sorted) lines.push(workerLine(w, now))
141
+ }
142
+ lines.push('')
143
+
93
144
  return lines.join('\n') + '\n'
94
145
  }
@@ -1,10 +1,10 @@
1
1
  import { mkdir, rename } from 'node:fs/promises'
2
2
  import { join } from 'path'
3
3
 
4
- import envPaths from 'env-paths'
5
-
6
4
  import type { ThreadConfig } from '@/lib/types'
7
5
 
6
+ import { DATA_DIR } from './data-dir'
7
+
8
8
  // Per-thread model/effort overrides for chat threads. Stored OUTSIDE the user's
9
9
  // workspace (no repo churn) in ONE global JSON file in moi's data dir, alongside
10
10
  // the workspace registry. Keyed by workspace path then sessionId:
@@ -20,7 +20,6 @@ export type ThreadConfigPatch = {
20
20
 
21
21
  type Store = Record<string, Record<string, ThreadConfig>>
22
22
 
23
- const DATA_DIR = envPaths('moi', { suffix: false }).data
24
23
  let _path = join(DATA_DIR, 'thread-config.json')
25
24
 
26
25
  // Test seam: point the store at a scratch file (mirrors registry.setRegistryPath).
package/server/vendor.ts CHANGED
@@ -28,14 +28,21 @@ export async function serveVendorReact(req: Request): Promise<Response> {
28
28
  if (!(await file.exists())) {
29
29
  return new Response('Not found', { status: 404 })
30
30
  }
31
- return new Response(file, {
32
- headers: {
33
- 'Content-Type': 'text/javascript; charset=utf-8',
34
- // Stable URL across versions, so don't cache immutably — revalidate so a
35
- // `vendor:react` regen after a React bump is picked up.
36
- 'Cache-Control': prebuilt ? 'public, max-age=3600' : 'no-store'
37
- }
38
- })
31
+ // Revalidate on every load (no max-age): the same URLs serve different bytes
32
+ // when the mode flips (prebuilt `moi` vs `bun run dev` on one port) or after
33
+ // a `vendor:react` regen. The ETag encodes both, so browsers keep the bytes
34
+ // (304) but never reuse a stale mode — prod jsx-dev-runtime has no `jsxDEV`
35
+ // and would crash dev.
36
+ const etag = `"${MODE}-${file.lastModified}-${file.size}"`
37
+ const headers = {
38
+ 'Content-Type': 'text/javascript; charset=utf-8',
39
+ 'Cache-Control': 'no-cache',
40
+ ETag: etag
41
+ }
42
+ if (req.headers.get('if-none-match') === etag) {
43
+ return new Response(null, { status: 304, headers })
44
+ }
45
+ return new Response(file, { headers })
39
46
  }
40
47
 
41
48
  // `<locale>/<file>.json` only — mirrors the emojibase-data package layout the