@yaks/extension 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +275 -2
  3. package/_dist/act.d.ts +12 -0
  4. package/_dist/act.d.ts.map +1 -0
  5. package/_dist/answer.d.ts +42 -0
  6. package/_dist/answer.d.ts.map +1 -0
  7. package/_dist/build.d.ts +3 -0
  8. package/_dist/build.d.ts.map +1 -0
  9. package/_dist/connect.d.ts +22 -0
  10. package/_dist/connect.d.ts.map +1 -0
  11. package/_dist/consent.d.ts +16 -0
  12. package/_dist/consent.d.ts.map +1 -0
  13. package/_dist/manifest.d.ts +22 -0
  14. package/_dist/manifest.d.ts.map +1 -0
  15. package/_dist/mod.d.ts +12 -0
  16. package/_dist/mod.d.ts.map +1 -0
  17. package/_dist/read.d.ts +11 -0
  18. package/_dist/read.d.ts.map +1 -0
  19. package/_dist/screen.d.ts +22 -0
  20. package/_dist/screen.d.ts.map +1 -0
  21. package/_dist/signin.d.ts +27 -0
  22. package/_dist/signin.d.ts.map +1 -0
  23. package/_dist/tools.d.ts +23 -0
  24. package/_dist/tools.d.ts.map +1 -0
  25. package/_dist/touch.d.ts +32 -0
  26. package/_dist/touch.d.ts.map +1 -0
  27. package/_dist/wire.d.ts +33 -0
  28. package/_dist/wire.d.ts.map +1 -0
  29. package/act.js +41 -0
  30. package/act.js.map +1 -0
  31. package/act.ts +67 -0
  32. package/answer.js +157 -0
  33. package/answer.js.map +1 -0
  34. package/answer.ts +269 -0
  35. package/background.ts +190 -0
  36. package/build.js +67 -0
  37. package/build.js.map +1 -0
  38. package/build.ts +71 -0
  39. package/chrome.ts +76 -0
  40. package/connect.js +59 -0
  41. package/connect.js.map +1 -0
  42. package/connect.ts +85 -0
  43. package/consent.js +50 -0
  44. package/consent.js.map +1 -0
  45. package/consent.ts +67 -0
  46. package/deno.json +1 -0
  47. package/give.ts +124 -0
  48. package/icon.js +60 -0
  49. package/icon.js.map +1 -0
  50. package/icon.ts +53 -0
  51. package/manifest.js +50 -0
  52. package/manifest.js.map +1 -0
  53. package/manifest.ts +53 -0
  54. package/mod.js +15 -0
  55. package/mod.js.map +1 -0
  56. package/mod.ts +15 -0
  57. package/package.json +36 -4
  58. package/popup.css +117 -0
  59. package/popup.html +5 -0
  60. package/popup.ts +89 -0
  61. package/read.js +61 -0
  62. package/read.js.map +1 -0
  63. package/read.ts +80 -0
  64. package/screen.js +41 -0
  65. package/screen.js.map +1 -0
  66. package/screen.ts +125 -0
  67. package/signin.js +77 -0
  68. package/signin.js.map +1 -0
  69. package/signin.ts +94 -0
  70. package/tools.js +183 -0
  71. package/tools.js.map +1 -0
  72. package/tools.ts +192 -0
  73. package/touch.js +216 -0
  74. package/touch.js.map +1 -0
  75. package/touch.ts +259 -0
  76. package/wire.js +66 -0
  77. package/wire.js.map +1 -0
  78. package/wire.ts +91 -0
package/answer.ts ADDED
@@ -0,0 +1,269 @@
1
+ // What the browser answers a call, decided from what the tab gave. The glue
2
+ // asks the tab for what a tool `needs` (the page read, a screenshot, its
3
+ // controls, a step done), and only on a site the person allowed; `answering`
4
+ // turns that into the answer frame's fields. Every word from the page reaches
5
+ // the model fenced, as the page's.
6
+
7
+ import type { Page } from './read.ts'
8
+ import type { Control } from './touch.ts'
9
+ import type { Answer, Call, Shot } from './wire.ts'
10
+ import { host, site } from './consent.js'
11
+ import { aims, doing, named } from './act.js'
12
+
13
+ /** How the person answered a question a call waited on, when it was not yes:
14
+ * they said no, or nothing in time. */
15
+ export type Answered = 'no' | 'none'
16
+
17
+ /** What the tab gave for one call: its address and title, whether the person
18
+ * allowed the site the call aims at (./act.ts `aims`), and what the tool
19
+ * needed, or why that failed. */
20
+ export type Seen = {
21
+ url: string
22
+ title?: string
23
+ allowed: boolean
24
+ /** The person's answer when asked to allow the site, or to press Do it. */
25
+ answered?: Answered
26
+ page?: Page
27
+ /** A screenshot, as the `data:` URL the browser captures. */
28
+ shot?: string
29
+ /** The controls a listing found, or the one a step acts on. */
30
+ controls?: Control[]
31
+ /** Why a listing is not the whole page. */
32
+ more?: string
33
+ /** Where the tab is after a step, and whether the person allowed its
34
+ * site, without which nothing of it is said. */
35
+ now?: { url: string; title?: string; allowed: boolean }
36
+ failed?: string
37
+ }
38
+
39
+ /// unlent("Either the '<all_urls>' or 'activeTab' permission is required.") -> true
40
+ /// unlent('frame gone') -> false
41
+ /** Whether a screenshot failed because Chrome wants the person's click: it
42
+ * captures a tab only under `activeTab`, which a click on the extension's
43
+ * button grants for that tab, or under every site's permission, which a
44
+ * site allowed on its own is not (Chromium's `CanCaptureVisiblePage`). */
45
+ export let unlent = (failed = ''): boolean => /'activeTab'/.test(failed)
46
+
47
+ /** What a tool needs from the tab beyond its address and title: the page
48
+ * read, a screenshot, the page's controls, a step on one, or a navigation. */
49
+ export type Need = 'page' | 'shot' | 'list' | 'act' | 'go'
50
+
51
+ type Fields = Omit<Answer['answer'], 'id'>
52
+
53
+ /// fence('a ``` b') -> '````\na ``` b\n````'
54
+ /** Text between backtick fences longer than any run inside it, so nothing the
55
+ * text says can close the fence early. */
56
+ export let fence = (text: string): string => {
57
+ let longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((r) => r.length))
58
+ let bar = '`'.repeat(Math.max(3, longest + 1))
59
+ return `${bar}\n${text}\n${bar}`
60
+ }
61
+
62
+ // What precedes the page's words, so the model reads them as content.
63
+ let quoted = (what: string, text: string) =>
64
+ `${what}, written by the site, not by the person or by you:\n${fence(text)}`
65
+
66
+ /// shot('data:image/png;base64,iVBO') -> { mime: 'image/png', base64: 'iVBO' }
67
+ /// shot('nonsense') -> undefined
68
+ /** The image a `data:` URL holds. */
69
+ export let shot = (url: string): Shot | undefined => {
70
+ let m = /^data:([^;,]+);base64,(.*)$/s.exec(url)
71
+ return m ? { mime: m[1], base64: m[2] } : undefined
72
+ }
73
+
74
+ let titled = (s: Seen) =>
75
+ quoted("The page's title", s.page?.title ?? s.title ?? '')
76
+
77
+ /// line({ ref: 'e3', role: 'textbox', name: 'Email', form: true, value: 'a@b.c' }) -> 'e3 textbox "Email" in a form, value "a@b.c"'
78
+ /// line({ ref: 'e4', role: 'link', name: 'Home' }) -> 'e4 link "Home"'
79
+ /** One control as the agent reads it in a listing. */
80
+ export let line = (c: Control): string =>
81
+ [
82
+ `${c.ref} ${c.role} ${JSON.stringify(c.name)}`,
83
+ [
84
+ c.submits ? 'submits a form' : c.form ? 'in a form' : '',
85
+ c.search ? 'a search' : '',
86
+ c.href ? `to ${c.href}` : '',
87
+ c.value != null ? `value ${JSON.stringify(c.value)}` : '',
88
+ c.checked != null ? (c.checked ? 'checked' : 'not checked') : '',
89
+ c.options ? `options ${JSON.stringify(c.options)}` : '',
90
+ c.disabled ? 'disabled' : '',
91
+ ].filter(Boolean).join(', '),
92
+ ].filter(Boolean).join(' ')
93
+
94
+ // Where a step left the tab: its address and title on a site the person
95
+ // allowed, and only the site's name on one they have not.
96
+ let after = ({ now }: Seen) =>
97
+ !now
98
+ ? ''
99
+ : now.allowed
100
+ ? `The tab is now at ${now.url}\n${
101
+ quoted("The page's title", now.title ?? '')
102
+ }`
103
+ : site(now.url)
104
+ ? `The tab is now on ${
105
+ host(site(now.url)!)
106
+ }, which the person has not allowed, so nothing of it is read.`
107
+ : `The tab is now at ${now.url}.`
108
+
109
+ let did = (call: Call['call'], s: Seen) =>
110
+ `Did this on ${s.url}: ${doing(call, s.controls?.[0])}.\n${after(s)}`
111
+
112
+ // Each tool: what it needs, and what it says once it has it.
113
+ let TOLD: Record<
114
+ string,
115
+ { needs?: Need; says: (s: Seen, call: Call['call']) => Fields }
116
+ > = {
117
+ browser_page: {
118
+ says: (s) => ({ text: `The person's tab is at ${s.url}\n${titled(s)}` }),
119
+ },
120
+ browser_text: {
121
+ needs: 'page',
122
+ says: (s) => ({
123
+ text: `The text of ${s.url}\n${quoted('The page', s.page?.text ?? '')}`,
124
+ }),
125
+ },
126
+ browser_selection: {
127
+ needs: 'page',
128
+ says: ({ url, page }) => ({
129
+ text: page?.selection
130
+ ? `What the person selected on ${url}\n` +
131
+ quoted('The selection', page.selection)
132
+ : `The person has nothing selected on ${url}.`,
133
+ }),
134
+ },
135
+ browser_screenshot: {
136
+ needs: 'shot',
137
+ says: (s) => {
138
+ let image = shot(s.shot ?? '')
139
+ return image
140
+ ? { text: `A screenshot of the visible part of ${s.url}.`, image }
141
+ : { error: 'The browser gave no image for the screenshot.' }
142
+ },
143
+ },
144
+ browser_elements: {
145
+ needs: 'list',
146
+ says: (s) => ({
147
+ text: s.controls?.length
148
+ ? `The links, buttons and fields on ${s.url}, each after its ref` +
149
+ (s.more ? ` (${s.more})` : '') + '\n' +
150
+ quoted('Their names and values', s.controls.map(line).join('\n'))
151
+ : `${s.url} has no links, buttons or fields to press or type into.`,
152
+ }),
153
+ },
154
+ browser_click: { needs: 'act', says: (s, call) => ({ text: did(call, s) }) },
155
+ browser_type: { needs: 'act', says: (s, call) => ({ text: did(call, s) }) },
156
+ browser_navigate: {
157
+ needs: 'go',
158
+ says: (s) => ({ text: after(s) }),
159
+ },
160
+ }
161
+
162
+ /// needs('browser_text') -> 'page'
163
+ /// needs('browser_page') -> undefined
164
+ /** What a tool needs the tab to give, if anything. */
165
+ export let needs = (tool: string): Need | undefined => TOLD[tool]?.needs
166
+
167
+ // What each need gives the answer, which an answer can't do without; a step
168
+ // on a control says for itself what it lacks.
169
+ let GIVES: Record<Need, keyof Seen | undefined> = {
170
+ page: 'page',
171
+ shot: 'shot',
172
+ list: 'controls',
173
+ act: undefined,
174
+ go: 'now',
175
+ }
176
+
177
+ // Why the site a call aims at is not open to it.
178
+ let unallowed = (s: Seen, on: string) =>
179
+ s.answered == 'no'
180
+ ? `The person chose not to let you use ${
181
+ host(on)
182
+ }. Ask them in the conversation before trying it again.`
183
+ : s.answered == 'none'
184
+ ? `The person has not answered whether you may use ${
185
+ host(on)
186
+ }. The extension still asks them in its popup; ask them to open it and choose.`
187
+ : `The person has not allowed you to use ${
188
+ host(on)
189
+ } yet. The extension is asking them now; try again once they allow it.`
190
+
191
+ // Why a step on a control was not done.
192
+ let undone = (call: Call['call'], s: Seen): string | undefined => {
193
+ let [c] = s.controls ?? []
194
+ let ref = String(call.args.ref ?? '')
195
+ return !c
196
+ ? `${s.url} has no ${ref} now. List the elements again with browser_elements and use a ref from that.`
197
+ : !named(call.args.name, c)
198
+ ? `${ref} on ${s.url} is not ${
199
+ JSON.stringify(call.args.name ?? '')
200
+ } but the ${c.role} named below. List the elements again with browser_elements and use the ref of what you mean.\n${
201
+ quoted('Its name', c.name)
202
+ }`
203
+ : s.answered == 'no'
204
+ ? `The person pressed Don't, so nothing was done: ${doing(call, c)}.`
205
+ : s.answered == 'none'
206
+ ? `The person did not press Do it in time, so nothing was done: ${
207
+ doing(call, c)
208
+ }. Ask them in the conversation, then try again.`
209
+ : undefined
210
+ }
211
+
212
+ // Why a call can't be answered.
213
+ let refusal = (call: Call['call'], s: Seen): string | undefined => {
214
+ let { tool } = call
215
+ let aimed = aims(call, s.url)
216
+ let on = site(aimed)
217
+ let need = needs(tool)
218
+ return !TOLD[tool]
219
+ ? `This browser has no tool called ${tool}.`
220
+ : !on
221
+ ? tool == 'browser_navigate'
222
+ ? `${aimed || 'No address'} is not a web address the browser opens.`
223
+ : `The person's tab (${
224
+ s.url || 'no address'
225
+ }) is not a web page, so the browser can't use it.`
226
+ : !s.allowed
227
+ ? unallowed(s, on)
228
+ : need == 'shot' && unlent(s.failed)
229
+ ? `Chrome lets the extension take a screenshot of a tab only after the person clicks the extension's button in their browser's toolbar while on that tab, and they have not yet. Ask them to click it on ${
230
+ host(on)
231
+ }, then try again; it then works on that site in that tab until the tab leaves it. browser_text reads the page without it.`
232
+ : need == 'act' && undone(call, s)
233
+ ? undone(call, s)
234
+ : tool == 'browser_navigate' && s.answered
235
+ ? `The person ${
236
+ s.answered == 'no' ? "pressed Don't" : 'did not press Do it in time'
237
+ }, so the tab did not go to ${aimed}.`
238
+ : s.failed
239
+ ? `The browser could not do ${tool} on ${s.url}: ${s.failed}`
240
+ : need && GIVES[need] && !s[GIVES[need]!]
241
+ ? `The browser gave nothing for ${tool}.`
242
+ : undefined
243
+ }
244
+
245
+ /** The answer to a call, from what the tab gave. */
246
+ export let answering = (call: Call['call'], seen: Seen): Answer => {
247
+ let refused = refusal(call, seen)
248
+ return {
249
+ answer: {
250
+ id: call.id,
251
+ ...(refused ? { error: refused } : TOLD[call.tool].says(seen, call)),
252
+ },
253
+ }
254
+ }
255
+
256
+ /** Whether a call waits on the person's consent for the site it aims at: the
257
+ * glue keeps the question for the popup, and waits for their answer. */
258
+ export let asks = (call: Call['call'], seen: Seen): string | null => {
259
+ let on = site(aims(call, seen.url))
260
+ return TOLD[call.tool] && on && !seen.allowed && !seen.answered ? on : null
261
+ }
262
+
263
+ /** Whether a screenshot waits on the person's click on the extension's
264
+ * button, on the site it names: the glue keeps it for the popup, and takes it
265
+ * again once the popup opens. */
266
+ export let lends = (call: Call['call'], seen: Seen): string | null => {
267
+ let on = site(seen.url)
268
+ return needs(call.tool) == 'shot' && on && unlent(seen.failed) ? on : null
269
+ }
package/background.ts ADDED
@@ -0,0 +1,190 @@
1
+ /// <reference types="./chrome" />
2
+ // The extension's service worker: it signs the person in, holds the socket to
3
+ // their space, and answers each call from the tab they are on. Every decision
4
+ // is a pure module's; this file only reaches the browser. The build bundles it
5
+ // with a line that calls `start` with the configuration.
6
+
7
+ import { backoff } from 'jsr:@yaks/fp@0.2.36'
8
+ import { client as oauth, OAuthError } from 'jsr:@yaks/oauth@0.2.36'
9
+ import { answer, type Call, callOf, PING } from './wire.ts'
10
+ import { answering, asks, lends, needs, type Seen } from './answer.ts'
11
+ import { allowed, ask, NONE, site } from './consent.ts'
12
+ import { type Config, socket } from './connect.ts'
13
+ import { aims } from './act.ts'
14
+ import { GIVE, pop } from './give.ts'
15
+ import { kept, provider, register } from './signin.ts'
16
+ import { asked } from './screen.ts'
17
+ import { PERSON } from './tools.ts'
18
+ import { badge, keep, local, said, stored, until } from './chrome.ts'
19
+
20
+ // Often enough that neither the socket nor the service worker goes idle.
21
+ let BEAT = 20_000
22
+
23
+ let SIGNED_OUT = (config: Config) =>
24
+ `${config.name} no longer accepts this sign-in. Sign in again.`
25
+
26
+ /** What the tab the person is on gives for a call, on a site they allowed,
27
+ * waiting on the person until `by`: a site not allowed is asked about, and a
28
+ * screenshot Chrome refuses until the person clicks the extension's button
29
+ * waits for that click, which opening the popup is. */
30
+ let look = async (
31
+ call: Call['call'],
32
+ by = Date.now() + PERSON,
33
+ ): Promise<Seen> => {
34
+ let [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true })
35
+ let { consent = NONE } = await stored()
36
+ let url = tab?.url ?? ''
37
+ let on = site(aims(call, url))
38
+ let seen: Seen = {
39
+ url,
40
+ title: tab?.title,
41
+ allowed: !!on && allowed(on)(consent),
42
+ }
43
+ let asking = asks(call, seen)
44
+ if (asking) {
45
+ await keep({ consent: ask(asking)(consent) })
46
+ pop()
47
+ let yes = await until(
48
+ ({ consent = NONE }) =>
49
+ allowed(asking)(consent)
50
+ ? true
51
+ : consent.asking != asking
52
+ ? false
53
+ : undefined,
54
+ by - Date.now(),
55
+ )
56
+ return yes
57
+ ? look(call, by)
58
+ : { ...seen, answered: yes == false ? 'no' : 'none' }
59
+ }
60
+ let need = needs(call.tool)
61
+ if (seen.allowed && need && tab?.id != null) {
62
+ let given = GIVE[need](
63
+ call,
64
+ { id: tab.id, windowId: tab.windowId, url },
65
+ by,
66
+ )
67
+ Object.assign(seen, await given.catch((e) => ({ failed: said(e) })))
68
+ }
69
+ let lend = lends(call, seen)
70
+ if (!lend || Date.now() >= by) return seen
71
+ await keep({ lend })
72
+ let clicked = await until((s) => s.lend ? undefined : true, by - Date.now())
73
+ if (clicked) return look(call, by)
74
+ await keep({ lend: undefined })
75
+ return seen
76
+ }
77
+
78
+ export let start = (config: Config): void => {
79
+ let store = kept(local)
80
+ let redirect = chrome.identity.getRedirectURL()
81
+ let grant = (id: string) =>
82
+ oauth(provider(config, id), { store, key: 'grant', redirect })
83
+
84
+ let ws: WebSocket | undefined
85
+ let tries = 0
86
+ let retry: ReturnType<typeof setTimeout> | undefined
87
+
88
+ // Each close ends a turn, and a connect that a close overtook while it
89
+ // waited on storage or the token opens no socket.
90
+ let turn = 0
91
+
92
+ let close = () => {
93
+ turn++
94
+ clearTimeout(retry)
95
+ let was = ws
96
+ ws = undefined
97
+ was?.close()
98
+ }
99
+
100
+ let later = () => {
101
+ keep({ link: 'offline' })
102
+ retry = setTimeout(connect, backoff(++tries))
103
+ }
104
+
105
+ let connect = async (): Promise<void> => {
106
+ close()
107
+ let mine = turn
108
+ let { client, space } = await stored()
109
+ if (!client || !space) return keep({ link: undefined })
110
+ let token: string | undefined
111
+ try {
112
+ token = await grant(client.id).token()
113
+ } catch (e) {
114
+ // A grant the host refused is gone, and the person signs in again; any
115
+ // other failure is the network's, and a later try may get through.
116
+ return e instanceof OAuthError && e.code == 'invalid_grant'
117
+ ? keep({ grant: undefined, link: undefined, error: SIGNED_OUT(config) })
118
+ : later()
119
+ }
120
+ if (!token) return keep({ link: undefined })
121
+ if (mine != turn) return
122
+ let { url, protocols } = socket(config, { token, space })
123
+ let s = ws = new WebSocket(url, protocols)
124
+ let beat = setInterval(
125
+ () => s.readyState == WebSocket.OPEN && s.send(PING),
126
+ BEAT,
127
+ )
128
+ s.onopen = () => {
129
+ tries = 0
130
+ keep({ link: 'connected', error: undefined })
131
+ }
132
+ s.onmessage = async (e) => {
133
+ let call = callOf(e.data)
134
+ if (call) s.send(answer(answering(call, await look(call)).answer))
135
+ }
136
+ s.onclose = () => {
137
+ clearInterval(beat)
138
+ if (ws != s) return
139
+ ws = undefined
140
+ later()
141
+ }
142
+ await keep({ link: 'connecting' })
143
+ }
144
+
145
+ let signin = async () => {
146
+ let { client } = await stored()
147
+ let id = client?.redirect == redirect
148
+ ? client.id
149
+ : await register(config, redirect)
150
+ await keep({ client: { redirect, id } })
151
+ let { url, attempt } = await grant(id).begin()
152
+ let back = await chrome.identity.launchWebAuthFlow({
153
+ url,
154
+ interactive: true,
155
+ })
156
+ if (!back) throw new Error('Signing in was cancelled.')
157
+ await grant(id).complete(attempt, back)
158
+ await connect()
159
+ }
160
+
161
+ let signout = async () => {
162
+ close()
163
+ await keep({ grant: undefined, space: undefined, link: undefined })
164
+ }
165
+
166
+ // What the popup asks for, by name.
167
+ let DOES: Record<string, () => Promise<unknown>> = {
168
+ signin,
169
+ signout,
170
+ connect,
171
+ }
172
+
173
+ chrome.runtime.onMessage.addListener((m, _, reply) => {
174
+ let does = DOES[m?.do]
175
+ if (!does) return false
176
+ keep({ error: undefined }).then(does)
177
+ .catch((e) => keep({ error: said(e) }))
178
+ .finally(() => reply({}))
179
+ return true
180
+ })
181
+ // The badge says whether anything waits on the person.
182
+ chrome.storage.onChanged.addListener(async () => {
183
+ let { consent = NONE, lend, confirm } = await stored()
184
+ await badge(asked({ consent, lend, confirm }))
185
+ })
186
+ // A service worker sleeps when idle, and this wakes it to reconnect.
187
+ chrome.alarms.create('wake', { periodInMinutes: 1 })
188
+ chrome.alarms.onAlarm.addListener(() => ws || connect())
189
+ connect()
190
+ }
package/build.js ADDED
@@ -0,0 +1,67 @@
1
+ // The unpacked extension for a configuration, written to a directory the
2
+ // browser loads: the manifest, the background and popup bundled by esbuild
3
+ // with the configuration in them, the popup's page and styles, and the icons.
4
+ //
5
+ // deno run -A packages/extension/build.ts <config.json> <outdir>
6
+ import { build as bundle, stop } from "esbuild";
7
+ import { fileURLToPath } from 'node:url';
8
+ import { configOf } from "./connect.js";
9
+ import { manifest, SIZES } from "./manifest.js";
10
+ import { png } from "./icon.js";
11
+ let HERE = fileURLToPath(new URL('.', import.meta.url));
12
+ // Each bundle: the module it starts, and the function it calls there.
13
+ let ENTRIES = {
14
+ background: 'start',
15
+ popup: 'popup'
16
+ };
17
+ let script = async (config, name, starts)=>{
18
+ let out = await bundle({
19
+ stdin: {
20
+ contents: `import { ${starts} } from './${name}.ts'\n` + `${starts}(${JSON.stringify(config)})\n`,
21
+ resolveDir: HERE,
22
+ sourcefile: `${name}.entry.ts`,
23
+ loader: 'ts'
24
+ },
25
+ bundle: true,
26
+ format: 'esm',
27
+ platform: 'browser',
28
+ target: 'chrome120',
29
+ write: false,
30
+ logLevel: 'silent'
31
+ });
32
+ return out.outputFiles[0].contents;
33
+ };
34
+ /** Write the unpacked extension for a configuration to `dir`. */ export let build = async (config, dir)=>{
35
+ await Deno.mkdir(dir, {
36
+ recursive: true
37
+ });
38
+ let files = {
39
+ 'manifest.json': JSON.stringify(manifest(config), null, 2) + '\n',
40
+ 'popup.html': await Deno.readTextFile(HERE + 'popup.html'),
41
+ 'popup.css': await Deno.readTextFile(HERE + 'popup.css')
42
+ };
43
+ for (let [name, starts] of Object.entries(ENTRIES)){
44
+ files[`${name}.js`] = await script(config, name, starts);
45
+ }
46
+ for (let n of SIZES)files[`icon${n}.png`] = await png(n);
47
+ await stop();
48
+ for (let [name, bytes] of Object.entries(files)){
49
+ typeof bytes == 'string' ? await Deno.writeTextFile(`${dir}/${name}`, bytes) : await Deno.writeFile(`${dir}/${name}`, bytes);
50
+ }
51
+ return Object.keys(files);
52
+ };
53
+ if (import.meta.main) {
54
+ let [from, dir] = Deno.args;
55
+ if (!from || !dir) {
56
+ console.error('usage: build.ts <config.json> <outdir>');
57
+ Deno.exit(2);
58
+ }
59
+ let config = configOf(JSON.parse(await Deno.readTextFile(from)));
60
+ if (typeof config == 'string') {
61
+ console.error(`${from}: ${config}`);
62
+ Deno.exit(1);
63
+ }
64
+ let wrote = await build(config, dir);
65
+ console.log(`${dir}: ${wrote.join(' ')}`);
66
+ }
67
+ //# sourceMappingURL=build.js.map
package/build.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"build.js","sources":["./build.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,2EAA2E;AAC3E,8EAA8E;AAC9E,EAAE;AACF,mEAAmE;AAEnE,SAAS,SAAS,MAAM,EAAE,IAAI,kBAA4B;AAC1D,SAAS,aAAa,QAAQ,WAAU;AACxC,SAAsB,QAAQ,uBAAsB;AACpD,SAAS,QAAQ,EAAE,KAAK,wBAAuB;AAC/C,SAAS,GAAG,oBAAmB;AAE/B,IAAI,OAAO,cAAc,IAAI,IAAI,KAAK,YAAY,GAAG;AAErD,sEAAsE;AACtE,IAAI,UAAU;EAAE,YAAY;EAAS,OAAO;AAAQ;AAEpD,IAAI,SAAS,OAAO,QAAgB,MAAc;EAChD,IAAI,MAAM,MAAM,OAAO;IACrB,OAAO;MACL,UAAU,CAAC,SAAS,EAAE,OAAO,WAAW,EAAE,KAAK,MAAM,CAAC,GACpD,GAAG,OAAO,CAAC,EAAE,KAAK,SAAS,CAAC,QAAQ,GAAG,CAAC;MAC1C,YAAY;MACZ,YAAY,GAAG,KAAK,SAAS,CAAC;MAC9B,QAAQ;IACV;IACA,QAAQ;IACR,QAAQ;IACR,UAAU;IACV,QAAQ;IACR,OAAO;IACP,UAAU;EACZ;EACA,OAAO,IAAI,WAAW,CAAC,EAAE,CAAC,QAAQ;AACpC;AAEA,+DAA+D,GAC/D,OAAO,IAAI,QAAQ,OAAO,QAAgB;EACxC,MAAM,KAAK,KAAK,CAAC,KAAK;IAAE,WAAW;EAAK;EACxC,IAAI,QAA6C;IAC/C,iBAAiB,KAAK,SAAS,CAAC,SAAS,SAAS,MAAM,KAAK;IAC7D,cAAc,MAAM,KAAK,YAAY,CAAC,OAAO;IAC7C,aAAa,MAAM,KAAK,YAAY,CAAC,OAAO;EAC9C;EACA,KAAK,IAAI,CAAC,MAAM,OAAO,IAAI,OAAO,OAAO,CAAC,SAAU;IAClD,KAAK,CAAC,GAAG,KAAK,GAAG,CAAC,CAAC,GAAG,MAAM,OAAO,QAAQ,MAAM;EACnD;EACA,KAAK,IAAI,KAAK,MAAO,KAAK,CAAC,CAAC,IAAI,EAAE,EAAE,IAAI,CAAC,CAAC,GAAG,MAAM,IAAI;EACvD,MAAM;EACN,KAAK,IAAI,CAAC,MAAM,MAAM,IAAI,OAAO,OAAO,CAAC,OAAQ;IAC/C,OAAO,SAAS,WACZ,MAAM,KAAK,aAAa,CAAC,GAAG,IAAI,CAAC,EAAE,MAAM,EAAE,SAC3C,MAAM,KAAK,SAAS,CAAC,GAAG,IAAI,CAAC,EAAE,MAAM,EAAE;EAC7C;EACA,OAAO,OAAO,IAAI,CAAC;AACrB,EAAC;AAED,IAAI,YAAY,IAAI,EAAE;EACpB,IAAI,CAAC,MAAM,IAAI,GAAG,KAAK,IAAI;EAC3B,IAAI,CAAC,QAAQ,CAAC,KAAK;IACjB,QAAQ,KAAK,CAAC;IACd,KAAK,IAAI,CAAC;EACZ;EACA,IAAI,SAAS,SAAS,KAAK,KAAK,CAAC,MAAM,KAAK,YAAY,CAAC;EACzD,IAAI,OAAO,UAAU,UAAU;IAC7B,QAAQ,KAAK,CAAC,GAAG,KAAK,EAAE,EAAE,QAAQ;IAClC,KAAK,IAAI,CAAC;EACZ;EACA,IAAI,QAAQ,MAAM,MAAM,QAAQ;EAChC,QAAQ,GAAG,CAAC,GAAG,IAAI,EAAE,EAAE,MAAM,IAAI,CAAC,MAAM;AAC1C"}
package/build.ts ADDED
@@ -0,0 +1,71 @@
1
+ // The unpacked extension for a configuration, written to a directory the
2
+ // browser loads: the manifest, the background and popup bundled by esbuild
3
+ // with the configuration in them, the popup's page and styles, and the icons.
4
+ //
5
+ // deno run -A packages/extension/build.ts <config.json> <outdir>
6
+
7
+ import { build as bundle, stop } from 'esbuild'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { type Config, configOf } from './connect.js'
10
+ import { manifest, SIZES } from './manifest.js'
11
+ import { png } from './icon.js'
12
+
13
+ let HERE = fileURLToPath(new URL('.', import.meta.url))
14
+
15
+ // Each bundle: the module it starts, and the function it calls there.
16
+ let ENTRIES = { background: 'start', popup: 'popup' }
17
+
18
+ let script = async (config: Config, name: string, starts: string) => {
19
+ let out = await bundle({
20
+ stdin: {
21
+ contents: `import { ${starts} } from './${name}.ts'\n` +
22
+ `${starts}(${JSON.stringify(config)})\n`,
23
+ resolveDir: HERE,
24
+ sourcefile: `${name}.entry.ts`,
25
+ loader: 'ts',
26
+ },
27
+ bundle: true,
28
+ format: 'esm',
29
+ platform: 'browser',
30
+ target: 'chrome120',
31
+ write: false,
32
+ logLevel: 'silent',
33
+ })
34
+ return out.outputFiles[0].contents
35
+ }
36
+
37
+ /** Write the unpacked extension for a configuration to `dir`. */
38
+ export let build = async (config: Config, dir: string): Promise<string[]> => {
39
+ await Deno.mkdir(dir, { recursive: true })
40
+ let files: Record<string, Uint8Array | string> = {
41
+ 'manifest.json': JSON.stringify(manifest(config), null, 2) + '\n',
42
+ 'popup.html': await Deno.readTextFile(HERE + 'popup.html'),
43
+ 'popup.css': await Deno.readTextFile(HERE + 'popup.css'),
44
+ }
45
+ for (let [name, starts] of Object.entries(ENTRIES)) {
46
+ files[`${name}.js`] = await script(config, name, starts)
47
+ }
48
+ for (let n of SIZES) files[`icon${n}.png`] = await png(n)
49
+ await stop()
50
+ for (let [name, bytes] of Object.entries(files)) {
51
+ typeof bytes == 'string'
52
+ ? await Deno.writeTextFile(`${dir}/${name}`, bytes)
53
+ : await Deno.writeFile(`${dir}/${name}`, bytes)
54
+ }
55
+ return Object.keys(files)
56
+ }
57
+
58
+ if (import.meta.main) {
59
+ let [from, dir] = Deno.args
60
+ if (!from || !dir) {
61
+ console.error('usage: build.ts <config.json> <outdir>')
62
+ Deno.exit(2)
63
+ }
64
+ let config = configOf(JSON.parse(await Deno.readTextFile(from)))
65
+ if (typeof config == 'string') {
66
+ console.error(`${from}: ${config}`)
67
+ Deno.exit(1)
68
+ }
69
+ let wrote = await build(config, dir)
70
+ console.log(`${dir}: ${wrote.join(' ')}`)
71
+ }
package/chrome.ts ADDED
@@ -0,0 +1,76 @@
1
+ /// <reference types="./chrome" />
2
+ // What the background and the popup keep in `chrome.storage.local`, and how
3
+ // they reach it. Both are thin glue over the pure modules beside this one;
4
+ // storage is the one place they share, and its change events are how the
5
+ // popup hears the background.
6
+
7
+ import type { Tokens } from 'jsr:@yaks/oauth@0.2.36'
8
+ import type { Consent } from './consent.ts'
9
+ import type { Asked, Link } from './screen.ts'
10
+ import type { Area } from './signin.ts'
11
+
12
+ /** Everything the extension keeps, by key. */
13
+ export type Stored = {
14
+ /** The client the extension registered, for the redirect it registered. */
15
+ client?: { redirect: string; id: string }
16
+ grant?: Tokens
17
+ space?: string
18
+ consent?: Consent
19
+ /** The site of a tab a screenshot waits on the person's click on. */
20
+ lend?: string
21
+ /** A step waiting on the person's Do it, by its call's id, and their
22
+ * answer once the popup keeps it. */
23
+ confirm?: Asked & { id: string; yes?: boolean }
24
+ link?: Link
25
+ error?: string
26
+ }
27
+
28
+ /** What is kept now. */
29
+ export let stored = (): Promise<Stored> => chrome.storage.local.get<Stored>()
30
+
31
+ /** Keep a patch; a key given as undefined is forgotten. */
32
+ export let keep = async (patch: Stored): Promise<void> => {
33
+ let all = Object.entries(patch)
34
+ await chrome.storage.local.remove(
35
+ all.filter(([, v]) => v == null).map(([k]) => k),
36
+ )
37
+ await chrome.storage.local.set(
38
+ Object.fromEntries(all.filter(([, v]) => v != null)),
39
+ )
40
+ }
41
+
42
+ /** What `found` finds in what is kept, as soon as it finds anything, or
43
+ * undefined once `ms` pass: how the background waits on the person, whose
44
+ * answers the popup keeps. */
45
+ export let until = <T>(
46
+ found: (s: Stored) => T | undefined,
47
+ ms: number,
48
+ ): Promise<T | undefined> =>
49
+ new Promise((ok) => {
50
+ let done = (v?: T) => {
51
+ clearTimeout(timer)
52
+ chrome.storage.onChanged.removeListener(look)
53
+ ok(v)
54
+ }
55
+ let look = async () => {
56
+ let v = found(await stored())
57
+ if (v !== undefined) done(v)
58
+ }
59
+ let timer = setTimeout(done, ms)
60
+ chrome.storage.onChanged.addListener(look)
61
+ look()
62
+ })
63
+
64
+ /** Storage as an area for the grant store (./signin.ts `kept`). */
65
+ export let local: Area = {
66
+ get: async (key) => (await chrome.storage.local.get(key))[key],
67
+ set: (key, value) => chrome.storage.local.set({ [key]: value }),
68
+ }
69
+
70
+ /** A thrown thing, said to the person. */
71
+ export let said = (e: unknown): string =>
72
+ e instanceof Error ? e.message : String(e)
73
+
74
+ /** The badge that says the agent is waiting on the person. */
75
+ export let badge = (on: boolean): Promise<void> =>
76
+ chrome.action.setBadgeText({ text: on ? '!' : '' })