@abide/bridge 0.6.2 → 0.7.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/desktop.ts CHANGED
@@ -1,17 +1,107 @@
1
1
  // WHAT THE LINK HANDLER SHOWS THE VISITOR, on each desktop it installs on: the question before a pairing
2
- // (44.42) and a notification for each line the bridge says. Every question is passed as an argument or
3
- // a variable, never written into a script, so nothing a site names is read as code.
2
+ // (44.42) and a notification for each line the bridge says. The question is each desktop's own —
3
+ // macOS's `NSAlert` (`macAlert.ts`), a Windows Forms dialog, zenity or kdialog on Linux — by the asking
4
+ // app's name and icon (44.90), laid out as the desktop lays its own, with Allow pressed by Return and Don't Allow by Escape. Everything shown is passed as an
5
+ // argument, a variable or a file, never written into a script, so nothing a site names is read as code.
4
6
  //
5
7
  // 44.64 — A QUESTION THAT CANNOT BE SHOWN IS A NO: a Linux desktop with neither `zenity` nor `kdialog`
6
8
  // pairs nothing from a link.
7
9
 
8
- /** What the visitor answered: don't pair, pair this once, or pair and stop asking for this site. */
9
- export type Answer = 'deny' | 'once' | 'always'
10
+ import { rm } from 'node:fs/promises' // bun has no remove of its own
11
+ import { tmpdir } from 'node:os' // bun exposes no temporary directory of its own
12
+
13
+ import { macAlert } from './macAlert.ts'
14
+
15
+ /**
16
+ * What the visitor answered: don't pair, pair as the link asks, or — offered only where it asks for full
17
+ * access (44.86) — pair with the site's own tools alone.
18
+ */
19
+ export type Answer = 'deny' | 'allow' | 'siteTools'
20
+
21
+ /**
22
+ * What the visitor is asked: by the app `title` names, with its `icon` where the site has one, a
23
+ * headline shown bold where the desktop can, and the body under it.
24
+ */
25
+ export type Question = {
26
+ title: string
27
+ headline: string
28
+ body: string
29
+ icon: Uint8Array | undefined
30
+ }
10
31
 
11
32
  const TITLE = 'abide bridge'
12
33
  const DENY = 'Don’t Allow'
13
- const ONCE = 'Allow'
14
- const ALWAYS = 'Always Allow'
34
+ const ALLOW = 'Allow'
35
+ const SITE_TOOLS = 'Only Site Tools'
36
+
37
+ // A Windows Forms dialog: the icon at the left, the headline in bold over the body, and the buttons in
38
+ // `ABIDE_BRIDGE_BUTTONS` in order from the left, as Windows lays OK before Cancel, the first pressed by Enter and the last by Escape. It prints the
39
+ // index of the button pressed; closing it is the first.
40
+ const WINDOWS_DIALOG = `
41
+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing
42
+ [System.Windows.Forms.Application]::EnableVisualStyles()
43
+ $form = New-Object System.Windows.Forms.Form
44
+ $form.Text = $env:ABIDE_BRIDGE_TITLE
45
+ $form.FormBorderStyle = 'FixedDialog'
46
+ $form.MaximizeBox = $false
47
+ $form.MinimizeBox = $false
48
+ $form.StartPosition = 'CenterScreen'
49
+ $form.TopMost = $true
50
+ $form.AutoSize = $true
51
+ $form.AutoSizeMode = 'GrowAndShrink'
52
+ $form.Padding = New-Object System.Windows.Forms.Padding(20)
53
+ $form.Font = New-Object System.Drawing.Font('Segoe UI', 9)
54
+ $grid = New-Object System.Windows.Forms.TableLayoutPanel
55
+ $grid.AutoSize = $true
56
+ $grid.ColumnCount = 2
57
+ $grid.RowCount = 3
58
+ $form.Controls.Add($grid)
59
+ if ($env:ABIDE_BRIDGE_ICON) {
60
+ $image = [System.Drawing.Image]::FromFile($env:ABIDE_BRIDGE_ICON)
61
+ $picture = New-Object System.Windows.Forms.PictureBox
62
+ $picture.Image = $image
63
+ $picture.SizeMode = 'Zoom'
64
+ $picture.Width = 64
65
+ $picture.Height = 64
66
+ $picture.Margin = New-Object System.Windows.Forms.Padding(0, 0, 16, 0)
67
+ $grid.Controls.Add($picture, 0, 0)
68
+ $grid.SetRowSpan($picture, 2)
69
+ $form.Icon = [System.Drawing.Icon]::FromHandle((New-Object System.Drawing.Bitmap($image, 32, 32)).GetHicon())
70
+ }
71
+ $headline = New-Object System.Windows.Forms.Label
72
+ $headline.Text = $env:ABIDE_BRIDGE_HEADLINE
73
+ $headline.AutoSize = $true
74
+ $headline.MaximumSize = New-Object System.Drawing.Size(420, 0)
75
+ $headline.Font = New-Object System.Drawing.Font('Segoe UI', 11, [System.Drawing.FontStyle]::Bold)
76
+ $grid.Controls.Add($headline, 1, 0)
77
+ $body = New-Object System.Windows.Forms.Label
78
+ $body.Text = $env:ABIDE_BRIDGE_BODY
79
+ $body.AutoSize = $true
80
+ $body.MaximumSize = New-Object System.Drawing.Size(420, 0)
81
+ $body.Margin = New-Object System.Windows.Forms.Padding(3, 10, 3, 0)
82
+ $grid.Controls.Add($body, 1, 1)
83
+ $row = New-Object System.Windows.Forms.FlowLayoutPanel
84
+ $row.FlowDirection = 'LeftToRight'
85
+ $row.Anchor = 'Right'
86
+ $row.AutoSize = $true
87
+ $row.Margin = New-Object System.Windows.Forms.Padding(0, 18, 0, 0)
88
+ $grid.Controls.Add($row, 1, 2)
89
+ $script:pressed = 0
90
+ $labels = $env:ABIDE_BRIDGE_BUTTONS -split [char]10
91
+ for ($at = 0; $at -lt $labels.Length; $at++) {
92
+ $button = New-Object System.Windows.Forms.Button
93
+ $button.Text = $labels[$at]
94
+ $button.AutoSize = $true
95
+ $button.Tag = $at
96
+ $button.Add_Click({ param($clicked) $script:pressed = $clicked.Tag; $form.Close() })
97
+ $row.Controls.Add($button)
98
+ }
99
+ $form.AcceptButton = $row.Controls[0]
100
+ $form.CancelButton = $row.Controls[$row.Controls.Count - 1]
101
+ $form.Add_Shown({ $form.Activate() })
102
+ [void]$form.ShowDialog()
103
+ $script:pressed
104
+ `
15
105
 
16
106
  /** Runs `command`, answering its exit code and what it printed, or `undefined` where it could not start. */
17
107
  async function ran(
@@ -31,125 +121,143 @@ async function ran(
31
121
  }
32
122
  }
33
123
 
34
- /** Runs one AppleScript with `argument` as `item 1 of argv`. */
124
+ /** Runs one AppleScript with `argv` as its `argv`. */
35
125
  function appleScript(
36
126
  lines: string[],
37
- argument: string,
127
+ ...argv: string[]
38
128
  ): ReturnType<typeof ran> {
39
129
  const script: string[] = ['-e', 'on run argv']
40
130
  for (const line of lines) script.push('-e', line)
41
131
  script.push('-e', 'end run')
42
- return ran(['osascript', ...script, argument])
132
+ return ran(['osascript', ...script, ...argv])
133
+ }
134
+
135
+ /** Writes `icon` where a dialog can read it as a file, answering where, or `undefined` for none. */
136
+ async function iconFile(
137
+ icon: Uint8Array | undefined,
138
+ ): Promise<string | undefined> {
139
+ if (icon === undefined) return undefined
140
+ const file = `${tmpdir()}/abide-bridge-icon-${crypto.randomUUID()}.png`
141
+ await Bun.write(file, icon)
142
+ return file
43
143
  }
44
144
 
45
- /** A PowerShell script, run with `text` in `ABIDE_BRIDGE_TEXT`, answering what it printed. */
46
- async function powerShell(script: string, text: string): Promise<string> {
47
- const done = await ran(
48
- ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command', script],
49
- { ABIDE_BRIDGE_TEXT: text },
50
- )
51
- return done?.code === 0 ? done.printed : ''
145
+ /**
146
+ * The buttons a question is answered with: Allow first, the default Return presses, the site's own
147
+ * tools next, and Don't Allow last, which Escape presses — each laid where the desktop lays them.
148
+ */
149
+ export function buttonsOf(offerSiteTools: boolean): string[] {
150
+ return offerSiteTools ? [ALLOW, SITE_TOOLS, DENY] : [ALLOW, DENY]
151
+ }
152
+
153
+ /** The answer the button at `index` of `buttonsOf(offerSiteTools)` gives; any other is a no. */
154
+ export function answerAt(index: number, offerSiteTools: boolean): Answer {
155
+ const pressed = buttonsOf(offerSiteTools)[index]
156
+ if (pressed === SITE_TOOLS) return 'siteTools'
157
+ return pressed === ALLOW ? 'allow' : 'deny'
52
158
  }
53
159
 
54
160
  /**
55
161
  * The command that shows `question` on a Linux desktop, by the first of `zenity` and `kdialog` it
56
- * `has`, or `undefined` where it has neither.
162
+ * `has`, or `undefined` where it has neither — with the app's icon from the file `icon` where there is
163
+ * one, and offering the site's own tools alone as a third button where `offerSiteTools`.
57
164
  */
58
165
  export function linuxQuestion(
59
- question: string,
60
- offerAlways: boolean,
166
+ question: Question,
167
+ offerSiteTools: boolean,
61
168
  has: (tool: string) => boolean,
169
+ icon?: string,
62
170
  ): string[] | undefined {
63
171
  if (has('zenity'))
64
172
  return [
65
173
  'zenity',
66
174
  '--question',
67
175
  '--title',
68
- TITLE,
176
+ question.title,
177
+ ...(icon === undefined ? [] : ['--window-icon', icon]),
69
178
  '--text',
70
- question,
71
- '--no-markup',
179
+ // Pango markup, so all a site names is escaped.
180
+ `<b>${Bun.escapeHTML(question.headline)}</b>\n\n${Bun.escapeHTML(question.body)}`,
72
181
  '--ok-label',
73
- ONCE,
182
+ ALLOW,
74
183
  '--cancel-label',
75
184
  DENY,
76
- ...(offerAlways ? ['--extra-button', ALWAYS] : []),
185
+ ...(offerSiteTools ? ['--extra-button', SITE_TOOLS] : []),
77
186
  ]
78
187
  if (has('kdialog'))
79
188
  return [
80
189
  'kdialog',
81
190
  '--title',
82
- TITLE,
83
- offerAlways ? '--yesnocancel' : '--yesno',
84
- question,
191
+ question.title,
192
+ ...(icon === undefined ? [] : ['--icon', icon]),
193
+ offerSiteTools ? '--yesnocancel' : '--yesno',
194
+ `${question.headline}\n\n${question.body}`,
85
195
  '--yes-label',
86
- ONCE,
87
- ...(offerAlways
88
- ? ['--no-label', ALWAYS, '--cancel-label', DENY]
196
+ ALLOW,
197
+ ...(offerSiteTools
198
+ ? ['--no-label', SITE_TOOLS, '--cancel-label', DENY]
89
199
  : ['--no-label', DENY]),
90
200
  ]
91
201
  return undefined
92
202
  }
93
203
 
94
- /** Asks the visitor `question`, offering to always allow where `offerAlways`; closing it is a no. */
204
+ /**
205
+ * Asks the visitor `question`, offering the site's own tools alone where `offerSiteTools`; closing it
206
+ * is a no.
207
+ */
95
208
  export async function ask(
96
- question: string,
97
- offerAlways: boolean,
209
+ question: Question,
210
+ offerSiteTools: boolean,
98
211
  ): Promise<Answer> {
99
212
  const platform = process.platform
100
- if (platform === 'darwin') {
101
- const buttons = offerAlways
102
- ? `{"${DENY}", "${ALWAYS}", "${ONCE}"}`
103
- : `{"${DENY}", "${ONCE}"}`
104
- const pressed = await appleScript(
105
- [
106
- `display dialog (item 1 of argv) with title "${TITLE}" buttons ${buttons} default button "${DENY}" cancel button "${DENY}" with icon caution`,
107
- 'button returned of result',
108
- ],
109
- question,
213
+ const buttons = buttonsOf(offerSiteTools)
214
+ if (platform === 'darwin')
215
+ return answerAt(
216
+ macAlert(question.headline, question.body, question.icon, buttons),
217
+ offerSiteTools,
110
218
  )
111
- if (pressed?.code !== 0) return 'deny'
112
- return pressed.printed === ALWAYS
113
- ? 'always'
114
- : pressed.printed === ONCE
115
- ? 'once'
116
- : 'deny'
117
- }
118
- if (platform === 'win32') {
119
- // A message box's buttons carry no labels of their own, so always is a second question.
120
- const box = (buttons: string, text: string): Promise<string> =>
121
- powerShell(
122
- `Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show($env:ABIDE_BRIDGE_TEXT, '${TITLE}', '${buttons}', 'Warning', 'Button2')`,
123
- text,
219
+ if (platform !== 'win32' && platform !== 'linux') return 'deny'
220
+ const icon = await iconFile(question.icon)
221
+ try {
222
+ if (platform === 'win32') {
223
+ const shown = await ran(
224
+ [
225
+ 'powershell.exe',
226
+ '-NoProfile',
227
+ '-NonInteractive',
228
+ '-Command',
229
+ WINDOWS_DIALOG,
230
+ ],
231
+ {
232
+ ABIDE_BRIDGE_TITLE: question.title,
233
+ ABIDE_BRIDGE_HEADLINE: question.headline,
234
+ ABIDE_BRIDGE_BODY: question.body,
235
+ ABIDE_BRIDGE_ICON: icon ?? '',
236
+ ABIDE_BRIDGE_BUTTONS: buttons.join('\n'),
237
+ },
124
238
  )
125
- if ((await box('YesNo', `${question}\n\nAllow it?`)) !== 'Yes')
126
- return 'deny'
127
- if (!offerAlways) return 'once'
128
- return (await box(
129
- 'YesNo',
130
- 'Always allow this site, as the same account, without asking?',
131
- )) === 'Yes'
132
- ? 'always'
133
- : 'once'
239
+ return shown?.code === 0
240
+ ? answerAt(Number(shown.printed), offerSiteTools)
241
+ : 'deny'
242
+ }
243
+ const command = linuxQuestion(
244
+ question,
245
+ offerSiteTools,
246
+ (tool) => Bun.which(tool) !== null,
247
+ icon,
248
+ )
249
+ if (command === undefined) return 'deny'
250
+ const shown = await ran(command)
251
+ if (shown === undefined) return 'deny'
252
+ if (shown.code === 0) return 'allow'
253
+ if (!offerSiteTools) return 'deny'
254
+ // zenity prints the extra button it closed with; kdialog's no is the middle of three.
255
+ if (command[0] === 'zenity')
256
+ return shown.printed === SITE_TOOLS ? 'siteTools' : 'deny'
257
+ return shown.code === 1 ? 'siteTools' : 'deny'
258
+ } finally {
259
+ if (icon !== undefined) await rm(icon, { force: true })
134
260
  }
135
- if (platform !== 'linux') return 'deny'
136
- const command = linuxQuestion(
137
- question,
138
- offerAlways,
139
- (tool) => Bun.which(tool) !== null,
140
- )
141
- if (command === undefined) return 'deny'
142
- const shown = await ran(command)
143
- if (shown === undefined) return 'deny'
144
- if (command[0] === 'zenity')
145
- return shown.code === 0
146
- ? 'once'
147
- : shown.printed === ALWAYS
148
- ? 'always'
149
- : 'deny'
150
- // kdialog: yes is once, and no is always where always was offered.
151
- if (shown.code === 0) return 'once'
152
- return offerAlways && shown.code === 1 ? 'always' : 'deny'
153
261
  }
154
262
 
155
263
  /** Shows `line` as a notification, where this desktop has a way to. */
package/src/grant.ts CHANGED
@@ -3,9 +3,15 @@
3
3
  // a server's as `mcp__<server>` — and of those, the MCP tools whose server the visitor's own Claude Code
4
4
  // configuration holds. A site names tools and never a server: a server is a command this machine runs.
5
5
 
6
- /** What Claude Code names the one MCP server the bridge hands it, and so the prefix on each of its tools. */
6
+ /** What Claude Code names the MCP server the bridge relays to the site, and so the prefix on each of its tools. */
7
7
  export const SERVER_NAME = 'app'
8
8
 
9
+ /**
10
+ * What Claude Code names the MCP server the bridge answers itself, whose one tool is asked each
11
+ * permission prompt — hidden from the model, which never sees a `--permission-prompt-tool`. 44.81.
12
+ */
13
+ export const PERMISSION_SERVER = 'abide_bridge'
14
+
9
15
  /** What `asked` is given, and why each tool it is not given is not. */
10
16
  export type Grant = {
11
17
  /** Built-in tools, as Claude Code's `--tools` names them. */
@@ -52,7 +58,7 @@ export function takeFlag(
52
58
  }
53
59
 
54
60
  /** The tools the visitor granted, each `--tools` value split on commas and spaces. */
55
- function grantedOf(values: string[] | undefined): Set<string> {
61
+ function grantedOf(values: readonly string[] | undefined): Set<string> {
56
62
  const granted = new Set<string>()
57
63
  for (const value of values ?? [])
58
64
  for (const tool of value.split(/[\s,]+/))
@@ -61,7 +67,7 @@ function grantedOf(values: string[] | undefined): Set<string> {
61
67
  }
62
68
 
63
69
  /** The server an MCP tool name is of — `calendar` for `mcp__calendar__meetings` or `mcp__calendar` — or `undefined` for a built-in. */
64
- function serverOf(tool: string): string | undefined {
70
+ export function serverOf(tool: string): string | undefined {
65
71
  if (!tool.startsWith('mcp__')) return undefined
66
72
  const rest = tool.slice('mcp__'.length)
67
73
  const end = rest.indexOf('__')
@@ -119,8 +125,9 @@ export async function visitorServers(
119
125
  configuration.mcpServers ?? {},
120
126
  ))
121
127
  servers.set(toolNameOf(name), server)
122
- // The bridge's own server is the site's, never one of the visitor's.
128
+ // The bridge's own servers are never one of the visitor's.
123
129
  servers.delete(SERVER_NAME)
130
+ servers.delete(PERMISSION_SERVER)
124
131
  return servers
125
132
  }
126
133
 
@@ -160,7 +167,8 @@ export function grantOf(
160
167
 
161
168
  /**
162
169
  * What a site asking for `asked` is given by a visitor who passed `claudeArgs`, beside those args with
163
- * `--tools` and `--mcp-config` taken out. The visitor's servers are read only where an MCP tool is asked.
170
+ * `--tools` and `--mcp-config` taken out — every tool asked, where the bridge runs `full` (44.82). The
171
+ * visitor's servers are read only where an MCP tool is asked.
164
172
  *
165
173
  * Throws where an `--mcp-config` they named cannot be read, unless `unreadable` is given: then that is
166
174
  * said to it, and the grant is of no server.
@@ -168,10 +176,12 @@ export function grantOf(
168
176
  export async function grantFor(
169
177
  asked: readonly string[],
170
178
  claudeArgs: readonly string[],
179
+ full: boolean,
171
180
  unreadable?: (message: string) => void,
172
181
  ): Promise<{ grant: Grant; args: string[] }> {
173
182
  const args = [...claudeArgs]
174
- const granted = grantedOf(takeFlag(args, ['--tools']))
183
+ const given = takeFlag(args, ['--tools'])
184
+ const granted = grantedOf(full ? asked : given)
175
185
  const sources = takeFlag(args, ['--mcp-config'])
176
186
  let asksMcp = false
177
187
  for (const tool of asked) if (serverOf(tool) !== undefined) asksMcp = true
package/src/install.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // `abide-bridge install`: WHAT OPENS PAIRING LINKS ON THIS COMPUTER, built here rather than downloaded,
2
2
  // with the handler it starts (`opened.ts`, bundled into one file so nothing it imports can be left
3
- // behind) and what install found beside it. Each desktop registers a scheme its own way (44.43):
3
+ // behind) and what install found beside it. 44.89 — run from a checkout, the handler is instead one
4
+ // line starting the checkout's own, so an edit there is what the next link opens. Each desktop registers a scheme its own way (44.43):
4
5
  //
5
6
  // MACOS hands a URL to an app as an Apple Event, never as an argument, so the app is an AppleScript
6
7
  // applet (`osacompile`, on every Mac) whose `open location` starts the handler with the link. Built
@@ -34,6 +35,25 @@ export function handlerDirectory(directory: string): string {
34
35
  return `${directory}/handler`
35
36
  }
36
37
 
38
+ /**
39
+ * The bridge package `directory` — one directly inside it, as `bin` — belongs to, where it is a
40
+ * checkout rather than a release: outside any `node_modules`, where `bun x` and every package manager
41
+ * put one.
42
+ */
43
+ export function checkoutOf(directory: string): string | undefined {
44
+ const separated = directory.replaceAll('\\', '/')
45
+ if (separated.includes('/node_modules/')) return undefined
46
+ return separated.slice(0, separated.lastIndexOf('/'))
47
+ }
48
+
49
+ /** The handler of an install from `checkout`: the checkout's own, with this directory's settings. */
50
+ export function checkoutHandler(checkout: string): string {
51
+ return `import { open } from ${JSON.stringify(`${checkout}/src/opened.ts`)}
52
+
53
+ process.exit(await open(process.argv[2] ?? '', import.meta.dir))
54
+ `
55
+ }
56
+
37
57
  /** Where `XDG_DATA_HOME` points, or its default under the visitor's home. */
38
58
  function dataHome(): string {
39
59
  const declared = Bun.env.XDG_DATA_HOME
@@ -243,15 +263,22 @@ export async function install(
243
263
  supported()
244
264
  const directory = options.directory ?? installDirectory()
245
265
  const register = options.register !== false
246
- const bundled = await Bun.build({
247
- entrypoints: [`${import.meta.dir}/opened.ts`],
248
- outdir: handlerDirectory(directory),
249
- target: 'bun',
250
- })
251
- if (!bundled.success)
252
- throw new Error(
253
- `the link handler did not bundle: ${bundled.logs.join('\n')}`,
266
+ if (settings.checkout !== undefined)
267
+ await Bun.write(
268
+ handlerIn(directory),
269
+ checkoutHandler(settings.checkout),
254
270
  )
271
+ else {
272
+ const bundled = await Bun.build({
273
+ entrypoints: [`${import.meta.dir}/opened.ts`],
274
+ outdir: handlerDirectory(directory),
275
+ target: 'bun',
276
+ })
277
+ if (!bundled.success)
278
+ throw new Error(
279
+ `the link handler did not bundle: ${bundled.logs.join('\n')}`,
280
+ )
281
+ }
255
282
  await Bun.write(
256
283
  `${handlerDirectory(directory)}/settings.json`,
257
284
  JSON.stringify(settings, null, 4),
@@ -0,0 +1,144 @@
1
+ // THE QUESTION AS macOS's OWN ALERT, over the Objective-C runtime through `bun:ffi`: an `NSAlert` this
2
+ // process shows itself, so it comes to the front, carries the asking app's icon, and answers which
3
+ // button was pressed. abide drives AppKit the same way (`packages/abide/src/server/appKit.ts`), and
4
+ // exports none of it; the handler is bundled into one file, so this is the few calls an alert needs.
5
+ //
6
+ // LOADED WHEN ASKED, never at import: the handler runs on Linux and Windows too, where neither library
7
+ // is there to open.
8
+
9
+ import { CFunction, dlopen, FFIType } from 'bun:ffi'
10
+
11
+ type Id = number | null
12
+
13
+ /** The first button's answer from `runModal`; each button after it answers one more. */
14
+ const FIRST_BUTTON = 1000
15
+ // NSApplicationActivationPolicyAccessory: in front of the browser, with no Dock icon of its own.
16
+ const ACCESSORY = 1
17
+ // NSAlertStyleWarning: the alert's own icon, with nothing laid over it.
18
+ const WARNING = 0
19
+
20
+ const ENCODER = new TextEncoder()
21
+ function text(value: string): Uint8Array {
22
+ return ENCODER.encode(`${value}\0`)
23
+ }
24
+
25
+ /**
26
+ * Shows `headline` in bold over `body`, with `icon` where it is an image macOS reads, and `buttons` —
27
+ * the first the default, pressed by Return, and the last pressed by Escape. Answers the index of the
28
+ * button pressed.
29
+ */
30
+ export function macAlert(
31
+ headline: string,
32
+ body: string,
33
+ icon: Uint8Array | undefined,
34
+ buttons: readonly string[],
35
+ ): number {
36
+ const runtime = dlopen('/usr/lib/libobjc.A.dylib', {
37
+ objc_getClass: { args: [FFIType.cstring], returns: FFIType.ptr },
38
+ sel_registerName: { args: [FFIType.cstring], returns: FFIType.ptr },
39
+ objc_msgSend: { args: [], returns: FFIType.void },
40
+ })
41
+ // Loaded for the classes it registers, which `objc_getClass` then finds by name.
42
+ dlopen('/System/Library/Frameworks/AppKit.framework/AppKit', {
43
+ NSApplicationMain: { args: [], returns: FFIType.i32 },
44
+ })
45
+ const messenger = (
46
+ runtime.symbols.objc_msgSend as unknown as { ptr: number }
47
+ ).ptr
48
+ const senders = new Map<string, ReturnType<typeof CFunction>>()
49
+ function sendTyped(
50
+ receiver: Id,
51
+ name: string,
52
+ args: FFIType[],
53
+ returns: FFIType,
54
+ ...values: (Id | number | Uint8Array | boolean)[]
55
+ ): unknown {
56
+ const key = `${args.join(',')}>${returns}`
57
+ let sender = senders.get(key)
58
+ if (sender === undefined) {
59
+ sender = CFunction({
60
+ ptr: messenger as never,
61
+ args: [FFIType.ptr, FFIType.ptr, ...args],
62
+ returns,
63
+ })
64
+ senders.set(key, sender)
65
+ }
66
+ return sender(
67
+ receiver,
68
+ runtime.symbols.sel_registerName(text(name)),
69
+ ...values,
70
+ )
71
+ }
72
+ const send = (receiver: Id, name: string, ...values: Id[]): Id =>
73
+ sendTyped(
74
+ receiver,
75
+ name,
76
+ values.map(() => FFIType.ptr),
77
+ FFIType.ptr,
78
+ ...values,
79
+ ) as Id
80
+ const classNamed = (name: string): Id =>
81
+ runtime.symbols.objc_getClass(text(name)) as Id
82
+ const string = (value: string): Id =>
83
+ sendTyped(
84
+ classNamed('NSString'),
85
+ 'stringWithUTF8String:',
86
+ [FFIType.ptr],
87
+ FFIType.ptr,
88
+ text(value),
89
+ ) as Id
90
+
91
+ try {
92
+ const application = send(
93
+ classNamed('NSApplication'),
94
+ 'sharedApplication',
95
+ )
96
+ sendTyped(
97
+ application,
98
+ 'setActivationPolicy:',
99
+ [FFIType.i64],
100
+ FFIType.bool,
101
+ ACCESSORY,
102
+ )
103
+ send(application, 'finishLaunching')
104
+ sendTyped(
105
+ application,
106
+ 'activateIgnoringOtherApps:',
107
+ [FFIType.bool],
108
+ FFIType.void,
109
+ true,
110
+ )
111
+ const alert = send(send(classNamed('NSAlert'), 'alloc'), 'init')
112
+ sendTyped(alert, 'setAlertStyle:', [FFIType.u64], FFIType.void, WARNING)
113
+ send(alert, 'setMessageText:', string(headline))
114
+ send(alert, 'setInformativeText:', string(body))
115
+ if (icon !== undefined && icon.length > 0) {
116
+ const data = sendTyped(
117
+ classNamed('NSData'),
118
+ 'dataWithBytes:length:',
119
+ [FFIType.ptr, FFIType.u64],
120
+ FFIType.ptr,
121
+ icon,
122
+ icon.length,
123
+ ) as Id
124
+ const image = send(
125
+ send(classNamed('NSImage'), 'alloc'),
126
+ 'initWithData:',
127
+ data,
128
+ )
129
+ // An icon macOS cannot read leaves the alert its own.
130
+ if (image !== null && image !== 0) send(alert, 'setIcon:', image)
131
+ }
132
+ // Laid out as AppKit lays any alert: the first button added is the default, and where each
133
+ // goes is AppKit's. Escape, which it gives only a button titled Cancel, is the last's.
134
+ let last: Id = null
135
+ for (const button of buttons)
136
+ last = send(alert, 'addButtonWithTitle:', string(button))
137
+ send(last, 'setKeyEquivalent:', string('\u001b'))
138
+ const pressed = sendTyped(alert, 'runModal', [], FFIType.i64) as
139
+ number | bigint
140
+ return Number(pressed) - FIRST_BUTTON
141
+ } finally {
142
+ runtime.close()
143
+ }
144
+ }