switch-ext-kit 0.0.0-stage → 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.
package/src/shell.ts ADDED
@@ -0,0 +1,244 @@
1
+ // A shell command line's simple commands, ported from Switchboard's `sb guard`: enough of sh to say
2
+ // what a line runs, never to run it.
3
+
4
+ interface Lexer {
5
+ readonly line: string
6
+ i: number
7
+ word: string
8
+ inWord: boolean
9
+ words: string[]
10
+ readonly commands: string[][]
11
+ heredocs: { readonly delimiter: string; readonly tabs: boolean }[]
12
+ }
13
+
14
+ const at = (l: Lexer, offset = 0) => l.line.charAt(l.i + offset)
15
+
16
+ const until = (s: string, from: number, c: string) => {
17
+ const found = s.indexOf(c, from)
18
+ return found === -1 ? s.length : found
19
+ }
20
+
21
+ /** Where the bracket opened before `from` closes, past nested ones and quotes. */
22
+ const closing = (s: string, from: number) => {
23
+ let depth = 1
24
+ let quote = ""
25
+ for (let i = from; i < s.length; i += 1) {
26
+ const c = s.charAt(i)
27
+ if (quote !== "") {
28
+ quote = c === quote ? "" : quote
29
+ } else if (c === "'" || c === '"') {
30
+ quote = c
31
+ } else if (c === "\\") {
32
+ i += 1
33
+ } else if (c === "(" || c === ")") {
34
+ depth += c === "(" ? 1 : -1
35
+ if (depth === 0) {
36
+ return i
37
+ }
38
+ }
39
+ }
40
+ return s.length
41
+ }
42
+
43
+ const endWord = (l: Lexer) => {
44
+ if (l.inWord) {
45
+ l.words.push(l.word)
46
+ l.word = ""
47
+ l.inWord = false
48
+ }
49
+ }
50
+
51
+ const endCommand = (l: Lexer) => {
52
+ if (l.words.length > 0) {
53
+ l.commands.push(l.words)
54
+ l.words = []
55
+ }
56
+ }
57
+
58
+ /** `$(…)` or a backquote from `open`: its commands go first; what it prints stands as `$`. */
59
+ const substitution = (l: Lexer, open: number, backquote: boolean) => {
60
+ const close = backquote ? until(l.line, open, "`") : closing(l.line, open)
61
+ l.commands.push(...simpleCommands(l.line.slice(open, close)))
62
+ l.word += "$"
63
+ l.inWord = true
64
+ l.i = close + 1
65
+ }
66
+
67
+ const doubleQuoted = (l: Lexer) => {
68
+ l.i += 1
69
+ l.inWord = true
70
+ while (l.i < l.line.length && at(l) !== '"') {
71
+ const d = at(l)
72
+ if (d === "\\" && '"\\$`'.includes(at(l, 1)) && l.i + 1 < l.line.length) {
73
+ l.word += at(l, 1)
74
+ l.i += 2
75
+ } else if (d === "$" && at(l, 1) === "(") {
76
+ substitution(l, l.i + 2, false)
77
+ } else if (d === "`") {
78
+ substitution(l, l.i + 1, true)
79
+ } else {
80
+ l.word += d
81
+ l.i += 1
82
+ }
83
+ }
84
+ l.i += 1
85
+ }
86
+
87
+ const newline = (l: Lexer) => {
88
+ endWord(l)
89
+ endCommand(l)
90
+ l.i += 1
91
+ // Here documents' bodies, line by line to each delimiter.
92
+ for (const h of l.heredocs) {
93
+ while (l.i < l.line.length) {
94
+ const eol = until(l.line, l.i, "\n")
95
+ const body = l.line.slice(l.i, eol)
96
+ l.i = eol + 1
97
+ if ((h.tabs ? body.replace(/^\t+/u, "") : body) === h.delimiter) {
98
+ break
99
+ }
100
+ }
101
+ }
102
+ l.heredocs = []
103
+ }
104
+
105
+ const operator = (l: Lexer) => {
106
+ endWord(l)
107
+ // `2>&1` and `&>` are redirections, not a list's `&`.
108
+ if (at(l) === "&" && (at(l, 1) === ">" || at(l, -1) === ">")) {
109
+ l.i += 1
110
+ return
111
+ }
112
+ endCommand(l)
113
+ l.i += 1
114
+ }
115
+
116
+ const BREAKS = ";&|<>()"
117
+
118
+ const hereDocument = (l: Lexer) => {
119
+ let j = l.i + 2
120
+ const tabs = l.line.charAt(j) === "-"
121
+ j += tabs ? 1 : 0
122
+ while (l.line.charAt(j) === " " || l.line.charAt(j) === "\t") {
123
+ j += 1
124
+ }
125
+ let delimiter = ""
126
+ while (j < l.line.length && !/\s/u.test(l.line.charAt(j)) && !BREAKS.includes(l.line.charAt(j))) {
127
+ const d = l.line.charAt(j)
128
+ delimiter += d === "'" || d === '"' || d === "\\" ? "" : d
129
+ j += 1
130
+ }
131
+ l.heredocs.push({ delimiter, tabs })
132
+ l.i = j
133
+ }
134
+
135
+ /** The word a redirection sends to: skipped, quotes and all. */
136
+ const target = (l: Lexer) => {
137
+ while (at(l) === " " || at(l) === "\t") {
138
+ l.i += 1
139
+ }
140
+ let quote = ""
141
+ while (l.i < l.line.length) {
142
+ const t = at(l)
143
+ if (quote !== "") {
144
+ quote = t === quote ? "" : quote
145
+ } else if (t === "'" || t === '"') {
146
+ quote = t
147
+ } else if (/\s/u.test(t) || BREAKS.includes(t)) {
148
+ return
149
+ }
150
+ l.i += 1
151
+ }
152
+ }
153
+
154
+ const redirection = (l: Lexer) => {
155
+ // A file descriptor's number just before it isn't a word (`2>`).
156
+ if (l.inWord && /^\d+$/u.test(l.word)) {
157
+ l.word = ""
158
+ l.inWord = false
159
+ }
160
+ endWord(l)
161
+ if (at(l) === "<" && at(l, 1) === "<" && at(l, 2) !== "<") {
162
+ hereDocument(l)
163
+ return
164
+ }
165
+ l.i += 1
166
+ while (l.i < l.line.length && "<>|".includes(at(l))) {
167
+ l.i += 1
168
+ }
169
+ if (at(l) === "&") {
170
+ l.i += 1
171
+ while (l.i < l.line.length && /[\d-]/u.test(at(l))) {
172
+ l.i += 1
173
+ }
174
+ return
175
+ }
176
+ target(l)
177
+ }
178
+
179
+ const plain = (l: Lexer, c: string) => {
180
+ l.word += c
181
+ l.inWord = true
182
+ l.i += 1
183
+ }
184
+
185
+ const step = (l: Lexer) => {
186
+ const c = at(l)
187
+ if (c === "\\") {
188
+ const next = at(l, 1)
189
+ if (next !== "" && next !== "\n") {
190
+ plain(l, next)
191
+ l.i += 1
192
+ return
193
+ }
194
+ l.i += 2
195
+ } else if (c === "'") {
196
+ const close = until(l.line, l.i + 1, "'")
197
+ l.word += l.line.slice(l.i + 1, close)
198
+ l.inWord = true
199
+ l.i = close + 1
200
+ } else if (c === '"') {
201
+ doubleQuoted(l)
202
+ } else if (c === "$" && at(l, 1) === "(") {
203
+ substitution(l, l.i + 2, false)
204
+ } else if (c === "`") {
205
+ substitution(l, l.i + 1, true)
206
+ } else if (c === "#" && !l.inWord) {
207
+ l.i = until(l.line, l.i, "\n")
208
+ } else if (c === " " || c === "\t") {
209
+ endWord(l)
210
+ l.i += 1
211
+ } else if (c === "\n") {
212
+ newline(l)
213
+ } else if (";&|()".includes(c)) {
214
+ operator(l)
215
+ } else if (c === "<" || c === ">") {
216
+ redirection(l)
217
+ } else {
218
+ plain(l, c)
219
+ }
220
+ }
221
+
222
+ /**
223
+ * A command line's simple commands, each as its words with quotes taken off, in the order they'd
224
+ * run: split at `;`, `&`, `|`, newlines and parentheses, with each `$(…)` and backquoted command
225
+ * among them, ahead of the command it's in. Redirections, comments and here documents' bodies
226
+ * aren't words.
227
+ */
228
+ export const simpleCommands = (line: string): string[][] => {
229
+ const l: Lexer = {
230
+ line,
231
+ i: 0,
232
+ word: "",
233
+ inWord: false,
234
+ words: [],
235
+ commands: [],
236
+ heredocs: [],
237
+ }
238
+ while (l.i < line.length) {
239
+ step(l)
240
+ }
241
+ endWord(l)
242
+ endCommand(l)
243
+ return l.commands
244
+ }
package/src/shim.ts ADDED
@@ -0,0 +1,302 @@
1
+ // Filters on an extension's MCP messages, as its host relays them. `switchboard` turns a
2
+ // Switchboard appendage (sbmcp: events with `_meta["switchboard/record"]`) into a Switch extension,
3
+ // so its tools carry over as they are; `readOnly` keeps only the tools that only look.
4
+ import { CONNECTIONS, VERSION } from "./app.ts"
5
+ import { MESSAGE_SCHEMA, SENDER_SCHEMA } from "./messages.ts"
6
+
7
+ export type Json = Record<string, unknown>
8
+
9
+ export interface Filter {
10
+ /** A message on its way to the extension: forwarded (maybe changed), or answered here instead. */
11
+ readonly inbound: (m: Json) => { readonly forward: Json | null; readonly answer: Json | null }
12
+ /** A message from the extension: passed on (maybe changed), or dropped. */
13
+ readonly outbound: (m: Json) => Json | null
14
+ }
15
+
16
+ export const isJson = (v: unknown): v is Json =>
17
+ typeof v === "object" && v !== null && !Array.isArray(v)
18
+
19
+ const field = (m: Json, key: string): Json => {
20
+ const v = m[key]
21
+ return isJson(v) ? v : {}
22
+ }
23
+
24
+ const list = (v: unknown): readonly unknown[] => (Array.isArray(v) ? v : [])
25
+
26
+ const pass = (m: Json) => ({ forward: m, answer: null })
27
+
28
+ /** Remembers the ids of requests by method, to know what a response answers. */
29
+ const asked = () => {
30
+ const ids = new Map<unknown, string>()
31
+ return {
32
+ note: (m: Json) => {
33
+ if (m.id !== undefined && typeof m.method === "string") {
34
+ ids.set(m.id, m.method)
35
+ }
36
+ },
37
+ /** The method a response answers, once; "" for anything else. */
38
+ take: (m: Json) => {
39
+ if (m.method !== undefined) {
40
+ return ""
41
+ }
42
+ const method = ids.get(m.id) ?? ""
43
+ ids.delete(m.id)
44
+ return method
45
+ },
46
+ }
47
+ }
48
+
49
+ const RECORD = "switchboard/record"
50
+
51
+ /** What a shimmed event carries: its Switchboard record, envelope and body. */
52
+ const RECORD_SCHEMA = {
53
+ type: "object",
54
+ properties: {
55
+ kind: { type: "string" },
56
+ stream: { type: "string" },
57
+ data: {},
58
+ about: { type: "array", items: { type: "string" } },
59
+ refs: { type: "array", items: { type: "string" } },
60
+ importance: { type: "number" },
61
+ sender: SENDER_SCHEMA,
62
+ message: MESSAGE_SCHEMA,
63
+ },
64
+ required: ["kind", "stream", "data"],
65
+ }
66
+
67
+ /** A channel's message (Claude Code's channels, `notifications/claude/channel`), as an event. */
68
+ const CHANNEL = "notifications/claude/channel"
69
+ const CHANNEL_EVENT = "message"
70
+
71
+ const ENVELOPE = ["about", "refs", "importance", "sender", "message"] as const
72
+
73
+ /**
74
+ * A Switchboard appendage as an extension. Its event types gain the extension's prefix (`pr` becomes
75
+ * `github-prs.pr`); each occurrence's payload is its record: `kind` and `stream` (where the type, or
76
+ * the occurrence, says it lands; else `event` in `events/<extension>`), the record's `about`, `refs` and
77
+ * `importance`, and its body as `data`. A fixed record id is the event id, so a resend is one event.
78
+ */
79
+ export const switchboard = (extension: string): Filter => {
80
+ const prefix = `${extension}.`
81
+ const requests = asked()
82
+ const placed = new Map<string, Json>()
83
+
84
+ const renamed = (e: Json): Json => {
85
+ const name = String(e.name)
86
+ placed.set(name, field(field(e, "_meta"), RECORD))
87
+ return {
88
+ ...e,
89
+ name: `${prefix}${name}`,
90
+ delivery: ["push"],
91
+ payloadSchema: RECORD_SCHEMA,
92
+ _meta: { [VERSION]: 1 },
93
+ }
94
+ }
95
+
96
+ const occurrence = (params: Json): Json => {
97
+ const name = String(params.name)
98
+ const where = placed.get(name) ?? {}
99
+ const meta = field(params, "_meta")
100
+ const envelope = field(meta, RECORD)
101
+ const stream = [envelope.stream, where.stream].find((x) => typeof x === "string")
102
+ const payload: Json = {
103
+ kind: typeof where.kind === "string" ? where.kind : "event",
104
+ stream: typeof stream === "string" ? stream : `events/${extension}`,
105
+ data: params.data ?? null,
106
+ }
107
+ for (const key of ENVELOPE) {
108
+ if (envelope[key] !== undefined) {
109
+ payload[key] = envelope[key]
110
+ }
111
+ }
112
+ const { [RECORD]: _, ...rest } = meta
113
+ return {
114
+ ...params,
115
+ name: `${prefix}${name}`,
116
+ eventId: typeof envelope.id === "string" ? envelope.id : params.eventId,
117
+ data: payload,
118
+ _meta: rest,
119
+ }
120
+ }
121
+
122
+ /**
123
+ * A channel's message: one of the user's own front doors (a bot only they can message), so its
124
+ * sender is them. Its meta's `chat_id`, `message_id`, `user` and `ts` are the channel plugins'.
125
+ */
126
+ const fromChannel = (m: Json) => {
127
+ const params = field(m, "params")
128
+ const meta = field(params, "meta")
129
+ const text = (k: string) => (typeof meta[k] === "string" ? meta[k] : "")
130
+ const id =
131
+ text("message_id") === "" ? crypto.randomUUID() : `${text("chat_id")}:${text("message_id")}`
132
+ const ts = text("ts") === "" ? new Date().toISOString() : text("ts")
133
+ const content = typeof params.content === "string" ? params.content : ""
134
+ return occurrence({
135
+ name: CHANNEL_EVENT,
136
+ eventId: id,
137
+ timestamp: ts,
138
+ // Its place in the extension's own outbox, if it keeps one: acknowledged once the brain has it.
139
+ cursor: typeof params.cursor === "string" ? params.cursor : null,
140
+ data: { content, meta },
141
+ _meta: {
142
+ [RECORD]: {
143
+ sender: { handle: text("user") || text("user_id"), via: extension, me: true },
144
+ message: {
145
+ id: `${extension}:${id}`,
146
+ conversation: `${extension}:${text("chat_id")}`,
147
+ text: content,
148
+ at: Date.parse(ts),
149
+ channel: extension,
150
+ },
151
+ },
152
+ },
153
+ })
154
+ }
155
+
156
+ // A channel server has no events of its own: its messages become one.
157
+ let channel = false
158
+ const channelEvent = (): Json => {
159
+ placed.set(CHANNEL_EVENT, { kind: "message", stream: `comms/${extension}` })
160
+ return {
161
+ name: `${prefix}${CHANNEL_EVENT}`,
162
+ delivery: ["push"],
163
+ payloadSchema: RECORD_SCHEMA,
164
+ _meta: { [VERSION]: 1 },
165
+ }
166
+ }
167
+
168
+ return {
169
+ inbound: (m) => {
170
+ requests.note(m)
171
+ const params = field(m, "params")
172
+ const { name } = params
173
+ if (channel && m.method === "events/stream" && name === `${prefix}${CHANNEL_EVENT}`) {
174
+ return { forward: null, answer: { jsonrpc: "2.0", id: m.id, result: {} } }
175
+ }
176
+ if (
177
+ (m.method === "events/stream" || m.method === "events/poll") &&
178
+ typeof name === "string" &&
179
+ name.startsWith(prefix)
180
+ ) {
181
+ return pass({ ...m, params: { ...params, name: name.slice(prefix.length) } })
182
+ }
183
+ return pass(m)
184
+ },
185
+ outbound: (m) => {
186
+ const answers = requests.take(m)
187
+ if ((answers === "initialize" || answers === "server/discover") && isJson(m.result)) {
188
+ const experimental = field(field(m.result, "capabilities"), "experimental")
189
+ channel = isJson(experimental["claude/channel"])
190
+ return m
191
+ }
192
+ if (answers === "events/list") {
193
+ const listed = isJson(m.result) ? list(m.result.events).filter(isJson).map(renamed) : []
194
+ if (!channel && !isJson(m.result)) {
195
+ return m
196
+ }
197
+ const events = channel ? [...listed, channelEvent()] : listed
198
+ return { jsonrpc: "2.0", id: m.id, result: { ...field(m, "result"), events } }
199
+ }
200
+ if (m.method === "notifications/events/event") {
201
+ return { ...m, params: occurrence(field(m, "params")) }
202
+ }
203
+ if (m.method === CHANNEL) {
204
+ return { jsonrpc: "2.0", method: "notifications/events/event", params: fromChannel(m) }
205
+ }
206
+ return m
207
+ },
208
+ }
209
+ }
210
+
211
+ const refused = (id: unknown, name: string): Json => ({
212
+ jsonrpc: "2.0",
213
+ id,
214
+ result: { content: [{ type: "text", text: `${name} isn't read-only` }], isError: true },
215
+ })
216
+
217
+ /** Read-only business tools, plus the declared account sign-in/status used privately by Connections. */
218
+ export const readOnly = (): Filter => {
219
+ const requests = asked()
220
+ const looks = new Set<string>()
221
+ const auth = new Set<string>()
222
+ return {
223
+ inbound: (m) => {
224
+ if (m.method === "tools/call") {
225
+ const name = String(field(m, "params").name)
226
+ return looks.has(name) ? pass(m) : { forward: null, answer: refused(m.id, name) }
227
+ }
228
+ requests.note(m)
229
+ return pass(m)
230
+ },
231
+ outbound: (m) => {
232
+ const method = requests.take(m)
233
+ if ((method === "initialize" || method === "server/discover") && isJson(m.result)) {
234
+ auth.clear()
235
+ looks.clear()
236
+ const connections = field(field(field(m.result, "capabilities"), "extensions"), CONNECTIONS)
237
+ for (const declared of list(connections.needs).filter(isJson)) {
238
+ if (declared.kind === "key") {
239
+ continue
240
+ }
241
+ const session = field(declared, "session")
242
+ for (const name of [session.signIn, session.status]) {
243
+ if (typeof name === "string" && name !== "") {
244
+ auth.add(name)
245
+ }
246
+ }
247
+ }
248
+ }
249
+ if (method === "tools/list" && isJson(m.result)) {
250
+ looks.clear()
251
+ const tools = list(m.result.tools)
252
+ .filter(isJson)
253
+ .filter(
254
+ (t) =>
255
+ field(t, "annotations").speaksForPerson !== true &&
256
+ (field(t, "annotations").readOnlyHint === true || auth.has(String(t.name))),
257
+ )
258
+ .map((t) =>
259
+ auth.has(String(t.name))
260
+ ? {
261
+ ...t,
262
+ _meta: {
263
+ ...field(t, "_meta"),
264
+ ui: { ...field(field(t, "_meta"), "ui"), visibility: ["app"] },
265
+ },
266
+ }
267
+ : t,
268
+ )
269
+ for (const t of tools) {
270
+ looks.add(String(t.name))
271
+ }
272
+ return { ...m, result: { ...m.result, tools } }
273
+ }
274
+ return m
275
+ },
276
+ }
277
+ }
278
+
279
+ /** Filters in order on the way in, reversed on the way out. */
280
+ export const chain = (filters: readonly Filter[]): Filter => ({
281
+ inbound: (m) => {
282
+ let current = m
283
+ for (const f of filters) {
284
+ const step = f.inbound(current)
285
+ if (step.forward === null) {
286
+ return step
287
+ }
288
+ current = step.forward
289
+ }
290
+ return pass(current)
291
+ },
292
+ outbound: (m) => {
293
+ let current: Json | null = m
294
+ for (const f of filters.toReversed()) {
295
+ if (current === null) {
296
+ return null
297
+ }
298
+ current = f.outbound(current)
299
+ }
300
+ return current
301
+ },
302
+ })
package/src/stdio.ts ADDED
@@ -0,0 +1,27 @@
1
+ // An extension's entry: its app served as MCP on stdio, until the client (its host) goes. Its host
2
+ // runs it in its own folder, which holds its outbox (`events.db`) beside the rest of its state.
3
+ import path from "node:path"
4
+ import { StdioServerTransport } from "@modelcontextprotocol/server/stdio"
5
+ import { Effect, Layer } from "effect"
6
+
7
+ import { AppEvents, serve } from "./app.ts"
8
+ import type { App, AppEventsService } from "./app.ts"
9
+
10
+ /**
11
+ * Where an extension keeps the events it emitted until the core has them: in its folder, the
12
+ * folder it runs in. Resolved when served, never on import: the desktop webview imports this
13
+ * package's root, and there `node:path` is empty, so a call at load blanked its window.
14
+ */
15
+ export const OUTBOX_FILE = "events.db"
16
+
17
+ /** Serves `app` on stdio with `layer`, its services (`Layer.empty` for none), until stdin closes. */
18
+ export const serveStdio = async <R, E>(
19
+ app: App<R>,
20
+ layer: Layer.Layer<R, E, AppEventsService>,
21
+ ): Promise<void> => {
22
+ await Effect.runPromise(
23
+ Effect.scoped(Effect.flatten(serve(app, new StdioServerTransport()))).pipe(
24
+ Effect.provide(Layer.provideMerge(layer, AppEvents.layer(app, path.resolve(OUTBOX_FILE)))),
25
+ ),
26
+ )
27
+ }
package/src/ui.ts ADDED
@@ -0,0 +1,67 @@
1
+ // UI analytics: what the user did on a surface, felt like touch. Any app's UI emits these, under its
2
+ // app.
3
+ import { Schema } from "effect"
4
+
5
+ import type { AppEvent } from "./app.ts"
6
+ import { defineEvent } from "./events.ts"
7
+ import type { DefinedEvent, Draft } from "./events.ts"
8
+
9
+ /** `surface` is where (a screen, widget or window: "clock/timers"); `item` is what in it. */
10
+ export interface Seen {
11
+ readonly surface: string
12
+ readonly item?: string
13
+ }
14
+
15
+ /** Seen for a while: how long, in ms. */
16
+ export interface Stayed extends Seen {
17
+ readonly ms: number
18
+ }
19
+
20
+ export interface Moved {
21
+ readonly surface: string
22
+ readonly from: string
23
+ readonly to: string
24
+ }
25
+
26
+ const seen = { surface: Schema.String, item: Schema.optionalKey(Schema.String) }
27
+ const stayed = Schema.Struct({ ...seen, ms: Schema.Finite })
28
+
29
+ /** Came into view. */
30
+ export const Viewed: DefinedEvent<"ui.viewed", Seen> = defineEvent(
31
+ "ui.viewed",
32
+ 1,
33
+ Schema.Struct(seen),
34
+ )
35
+
36
+ /** Opened, then left within `BACKED_OUT_MS`. */
37
+ export const BackedOut: DefinedEvent<"ui.backed_out", Stayed> = defineEvent(
38
+ "ui.backed_out",
39
+ 1,
40
+ stayed,
41
+ )
42
+
43
+ /** Moved from one item to another on the same surface. */
44
+ export const Switched: DefinedEvent<"ui.switched", Moved> = defineEvent(
45
+ "ui.switched",
46
+ 1,
47
+ Schema.Struct({ surface: Schema.String, from: Schema.String, to: Schema.String }),
48
+ )
49
+
50
+ /** Stayed on it for `ms`, then left. */
51
+ export const Dwelled: DefinedEvent<"ui.dwelled", Stayed> = defineEvent("ui.dwelled", 1, stayed)
52
+
53
+ export const uiEvents: readonly AppEvent[] = [Viewed, BackedOut, Switched, Dwelled]
54
+
55
+ export const BACKED_OUT_MS = 2000
56
+
57
+ /** What leaving something opened at `opened` (ms) says: backed out if quick, else a dwell. */
58
+ export const left = (
59
+ surface: string,
60
+ item: string | undefined,
61
+ opened: number,
62
+ now: number = Date.now(),
63
+ ): Draft => {
64
+ const ms = Math.max(0, now - opened)
65
+ const where = item === undefined ? { surface } : { surface, item }
66
+ return ms < BACKED_OUT_MS ? BackedOut.make({ ...where, ms }) : Dwelled.make({ ...where, ms })
67
+ }