-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathkeyAutoAdd.ts
More file actions
228 lines (208 loc) · 6.45 KB
/
keyAutoAdd.ts
File metadata and controls
228 lines (208 loc) · 6.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// cSpell:ignore allowtransparency
import browser, { type Runtime } from '@/shared/browser';
import { CONNECTION_NAME } from '@/background/services/keyAutoAdd';
import {
errorWithKeyToJSON,
isErrorWithKey,
sleep,
withResolvers,
type ErrorWithKeyLike,
} from '@/shared/helpers';
import type {
BackgroundToKeyAutoAddMessage,
BeginPayload,
Details,
KeyAutoAddToBackgroundMessage,
KeyAutoAddToBackgroundMessagesMap,
Step,
StepRun,
StepRunHelpers,
StepWithStatus,
} from './types';
export type { StepRun } from './types';
export const LOGIN_WAIT_TIMEOUT = 10 * 60 * 1000;
export class KeyAutoAdd {
private port: Runtime.Port;
private ui: HTMLIFrameElement;
private stepsInput: Map<string, Step>;
private steps: StepWithStatus[];
private outputs = new Map<StepRun, unknown>();
constructor(steps: Step[]) {
this.stepsInput = new Map(steps.map((step) => [step.name, step]));
this.steps = steps.map((step) => ({
name: step.name,
status: 'pending',
maxDuration: step.maxDuration || 4 * 1000,
}));
}
init() {
this.port = browser.runtime.connect({ name: CONNECTION_NAME });
this.port.onMessage.addListener(
(message: BackgroundToKeyAutoAddMessage) => {
if (message.action === 'BEGIN') {
void this.runAll(message.payload);
}
},
);
}
private setNotificationSize(size: 'notification' | 'fullscreen' | 'hidden') {
let styles: Partial<CSSStyleDeclaration>;
const defaultStyles: Partial<CSSStyleDeclaration> = {
outline: 'none',
border: 'none',
zIndex: '9999',
position: 'fixed',
top: '0',
left: '0',
};
if (size === 'notification') {
styles = {
width: '22em',
height: '8em',
fontSize: '16px',
position: 'fixed',
top: '1rem',
right: '1rem',
left: 'initial',
boxShadow: 'rgba(0, 0, 0, 0.1) 0px 0px 6px 3px',
borderRadius: '0.5rem',
};
} else if (size === 'fullscreen') {
styles = {
width: '100vw',
height: '100vh',
};
} else {
styles = {
width: '0',
height: '0',
position: 'absolute',
};
}
this.ui.style.cssText = '';
Object.assign(this.ui.style, defaultStyles);
Object.assign(this.ui.style, styles);
const iframeUrl = new URL(
browser.runtime.getURL('pages/progress-connect/index.html'),
);
const params = new URLSearchParams({ mode: size });
iframeUrl.hash = `?${params.toString()}`;
if (this.ui.src !== iframeUrl.href && size !== 'hidden') {
this.ui.src = iframeUrl.href;
}
}
private addNotification() {
const { resolve, reject, promise } = withResolvers<void>();
if (this.ui) {
resolve();
return promise;
}
const pageUrl = browser.runtime.getURL('pages/progress-connect/index.html');
const iframe = document.createElement('iframe');
iframe.setAttribute('allowtransparency', 'true');
iframe.src = pageUrl;
document.body.appendChild(iframe);
iframe.addEventListener('load', () => {
resolve();
void sleep(500).then(() =>
this.postMessage('PROGRESS', { steps: this.steps }),
);
});
iframe.addEventListener('error', reject, { once: true });
this.ui = iframe;
this.setNotificationSize('hidden');
return promise;
}
private async runAll(payload: BeginPayload) {
const helpers: StepRunHelpers = {
output: <T extends StepRun>(fn: T) => {
if (!this.outputs.has(fn)) {
// Was never run? Was skipped?
throw new Error('Given step has no output');
}
return this.outputs.get(fn) as Awaited<ReturnType<T>>;
},
skip: (details) => {
throw new SkipError(
typeof details === 'string' ? { message: details } : details,
);
},
setNotificationSize: (size: 'notification' | 'fullscreen') => {
this.setNotificationSize(size);
},
};
await this.addNotification();
this.postMessage('PROGRESS', { steps: this.steps });
for (let stepIdx = 0; stepIdx < this.steps.length; stepIdx++) {
const step = this.steps[stepIdx];
const stepInfo = this.stepsInput.get(step.name)!;
this.setStatus(stepIdx, 'active', {
expiresAt: stepInfo.maxDuration
? new Date(Date.now() + stepInfo.maxDuration).valueOf()
: undefined,
});
const minWait = sleep(2000);
try {
const run = this.stepsInput.get(step.name)!.run;
const [res] = await Promise.all([run(payload, helpers), minWait]);
this.outputs.set(run, res);
this.setStatus(stepIdx, 'success', {});
} catch (error) {
if (error instanceof SkipError) {
const details = error.toJSON();
this.setStatus(stepIdx, 'skipped', { details });
continue;
}
const details = errorToDetails(error);
this.setStatus(stepIdx, 'error', { details: details });
await minWait;
this.postMessage('ERROR', { details, stepName: step.name, stepIdx });
this.port.disconnect();
return;
}
}
this.postMessage('PROGRESS', { steps: this.steps });
this.postMessage('SUCCESS', true);
this.port.disconnect();
}
private postMessage<T extends keyof KeyAutoAddToBackgroundMessagesMap>(
action: T,
payload: KeyAutoAddToBackgroundMessagesMap[T],
) {
const message = { action, payload } as KeyAutoAddToBackgroundMessage;
this.port.postMessage(message);
}
private setStatus<T extends StepWithStatus['status']>(
stepIdx: number,
status: T,
data: Omit<
Extract<StepWithStatus, { status: T }>,
'name' | 'status' | 'maxDuration'
>,
) {
// @ts-expect-error what's missing is part of data, TypeScript!
this.steps[stepIdx] = {
name: this.steps[stepIdx].name,
status,
maxDuration: this.steps[stepIdx].maxDuration,
...data,
};
this.postMessage('PROGRESS', { steps: this.steps });
}
}
class SkipError extends Error {
public readonly error?: ErrorWithKeyLike;
constructor(err: ErrorWithKeyLike | { message: string }) {
const { message, error } = errorToDetails(err);
super(message);
this.error = error;
}
toJSON(): Details {
return { message: this.message, error: this.error };
}
}
function errorToDetails(err: { message: string } | ErrorWithKeyLike): Details {
return isErrorWithKey(err)
? { error: errorWithKeyToJSON(err), message: err.key }
: { message: err.message as string };
}