@krate/app 0.0.0-stage → 0.5.0-rc.7

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 (132) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +88 -2
  3. package/dist/automation.d.ts +11 -0
  4. package/dist/automation.d.ts.map +1 -0
  5. package/dist/automation.js +27 -0
  6. package/dist/badge.d.ts +13 -0
  7. package/dist/badge.d.ts.map +1 -0
  8. package/dist/badge.js +34 -0
  9. package/dist/chrome.d.ts +90 -0
  10. package/dist/chrome.d.ts.map +1 -0
  11. package/dist/chrome.js +133 -0
  12. package/dist/client.d.ts +26 -0
  13. package/dist/client.d.ts.map +1 -0
  14. package/dist/client.js +545 -0
  15. package/dist/clipboard.d.ts +19 -0
  16. package/dist/clipboard.d.ts.map +1 -0
  17. package/dist/clipboard.js +51 -0
  18. package/dist/cookies.d.ts +44 -0
  19. package/dist/cookies.d.ts.map +1 -0
  20. package/dist/cookies.js +45 -0
  21. package/dist/crash.d.ts +35 -0
  22. package/dist/crash.d.ts.map +1 -0
  23. package/dist/crash.js +28 -0
  24. package/dist/db.d.ts +14 -0
  25. package/dist/db.d.ts.map +1 -0
  26. package/dist/db.js +23 -0
  27. package/dist/dialog.d.ts +36 -0
  28. package/dist/dialog.d.ts.map +1 -0
  29. package/dist/dialog.js +23 -0
  30. package/dist/downloads.d.ts +35 -0
  31. package/dist/downloads.d.ts.map +1 -0
  32. package/dist/downloads.js +30 -0
  33. package/dist/driver.d.ts +190 -0
  34. package/dist/driver.d.ts.map +1 -0
  35. package/dist/driver.js +637 -0
  36. package/dist/errors.d.ts +7 -0
  37. package/dist/errors.d.ts.map +1 -0
  38. package/dist/errors.js +11 -0
  39. package/dist/events.d.ts +6 -0
  40. package/dist/events.d.ts.map +1 -0
  41. package/dist/events.js +47 -0
  42. package/dist/extension.d.ts +10 -0
  43. package/dist/extension.d.ts.map +1 -0
  44. package/dist/extension.js +25 -0
  45. package/dist/fakehost.d.ts +18 -0
  46. package/dist/fakehost.d.ts.map +1 -0
  47. package/dist/fakehost.js +199 -0
  48. package/dist/fs.d.ts +26 -0
  49. package/dist/fs.d.ts.map +1 -0
  50. package/dist/fs.js +38 -0
  51. package/dist/host.d.ts +4 -0
  52. package/dist/host.d.ts.map +1 -0
  53. package/dist/host.js +25 -0
  54. package/dist/index.d.ts +19 -0
  55. package/dist/index.d.ts.map +1 -0
  56. package/dist/index.js +40 -0
  57. package/dist/kv.d.ts +6 -0
  58. package/dist/kv.d.ts.map +1 -0
  59. package/dist/kv.js +19 -0
  60. package/dist/lifecycle.d.ts +22 -0
  61. package/dist/lifecycle.d.ts.map +1 -0
  62. package/dist/lifecycle.js +85 -0
  63. package/dist/login.d.ts +10 -0
  64. package/dist/login.d.ts.map +1 -0
  65. package/dist/login.js +8 -0
  66. package/dist/media.d.ts +50 -0
  67. package/dist/media.d.ts.map +1 -0
  68. package/dist/media.js +70 -0
  69. package/dist/menu.d.ts +71 -0
  70. package/dist/menu.d.ts.map +1 -0
  71. package/dist/menu.js +114 -0
  72. package/dist/mock.d.ts +14 -0
  73. package/dist/mock.d.ts.map +1 -0
  74. package/dist/mock.js +47 -0
  75. package/dist/notify.d.ts +25 -0
  76. package/dist/notify.d.ts.map +1 -0
  77. package/dist/notify.js +32 -0
  78. package/dist/offscreen.d.ts +24 -0
  79. package/dist/offscreen.d.ts.map +1 -0
  80. package/dist/offscreen.js +27 -0
  81. package/dist/os.d.ts +20 -0
  82. package/dist/os.d.ts.map +1 -0
  83. package/dist/os.js +43 -0
  84. package/dist/page.d.ts +69 -0
  85. package/dist/page.d.ts.map +1 -0
  86. package/dist/page.js +61 -0
  87. package/dist/permission.d.ts +5 -0
  88. package/dist/permission.d.ts.map +1 -0
  89. package/dist/permission.js +18 -0
  90. package/dist/port.d.ts +35 -0
  91. package/dist/port.d.ts.map +1 -0
  92. package/dist/port.js +159 -0
  93. package/dist/power.d.ts +19 -0
  94. package/dist/power.d.ts.map +1 -0
  95. package/dist/power.js +35 -0
  96. package/dist/remote.d.ts +156 -0
  97. package/dist/remote.d.ts.map +1 -0
  98. package/dist/remote.js +115 -0
  99. package/dist/screen.d.ts +25 -0
  100. package/dist/screen.d.ts.map +1 -0
  101. package/dist/screen.js +23 -0
  102. package/dist/shortcut.d.ts +2 -0
  103. package/dist/shortcut.d.ts.map +1 -0
  104. package/dist/shortcut.js +44 -0
  105. package/dist/testing.d.ts +6 -0
  106. package/dist/testing.d.ts.map +1 -0
  107. package/dist/testing.js +9 -0
  108. package/dist/theme.d.ts +12 -0
  109. package/dist/theme.d.ts.map +1 -0
  110. package/dist/theme.js +13 -0
  111. package/dist/tray.d.ts +18 -0
  112. package/dist/tray.d.ts.map +1 -0
  113. package/dist/tray.js +23 -0
  114. package/dist/types.d.ts +16 -0
  115. package/dist/types.d.ts.map +1 -0
  116. package/dist/types.js +1 -0
  117. package/dist/updater.d.ts +36 -0
  118. package/dist/updater.d.ts.map +1 -0
  119. package/dist/updater.js +58 -0
  120. package/dist/window.d.ts +154 -0
  121. package/dist/window.d.ts.map +1 -0
  122. package/dist/window.js +205 -0
  123. package/dist/wire.d.ts +26 -0
  124. package/dist/wire.d.ts.map +1 -0
  125. package/dist/wire.js +328 -0
  126. package/dist/worker-host.d.ts +6 -0
  127. package/dist/worker-host.d.ts.map +1 -0
  128. package/dist/worker-host.js +36 -0
  129. package/dist/worker.d.ts +62 -0
  130. package/dist/worker.d.ts.map +1 -0
  131. package/dist/worker.js +86 -0
  132. package/package.json +188 -3
package/dist/driver.js ADDED
@@ -0,0 +1,637 @@
1
+ // Test driver for Krate Native apps. Node only: it starts the krate-shell in
2
+ // dev mode and drives it over the dev control channel (packages/native
3
+ // PROTOCOL.md, "Dev control channel"). Pages are driven at the DOM level:
4
+ // clicks, typing and key presses are synthesized events, not operating-system
5
+ // input.
6
+ import { spawn } from "node:child_process";
7
+ import { mkdtempSync, rmSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { createInterface } from "node:readline";
11
+ /** Environment variable that names the krate-shell binary (set by `krate native test`). */
12
+ export const SHELL_ENV = "KRATE_TEST_SHELL";
13
+ /** Environment variable that names the built app directory (set by `krate native test`). */
14
+ export const APP_ENV = "KRATE_TEST_APP";
15
+ /** An error from a host function the app (or an SDK id) answered with. */
16
+ export class HostCallError extends Error {
17
+ constructor(code, message, data) {
18
+ super(`${code}: ${message}`);
19
+ this.name = "HostCallError";
20
+ this.code = code;
21
+ this.data = data;
22
+ }
23
+ }
24
+ // pageLib is installed once per page (globalThis.__krateDriver) and holds the
25
+ // DOM-level helpers. It is plain ES2019 source, sent over the control channel.
26
+ const pageLib = String.raw `(function(){
27
+ var sleep = function(ms){ return new Promise(function(r){ setTimeout(r, ms); }); };
28
+ var visible = function(el){ return !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length); };
29
+ var mods = {control:"ctrlKey", ctrl:"ctrlKey", shift:"shiftKey", alt:"altKey", meta:"metaKey", cmd:"metaKey", command:"metaKey"};
30
+ var focusables = 'a[href],button,input,select,textarea,[tabindex],[contenteditable=""],[contenteditable="true"]';
31
+ function usable(el){
32
+ return !el.disabled && visible(el) && el.getAttribute("tabindex") !== "-1" && !(el.type === "hidden");
33
+ }
34
+ function ev(el, type, init){
35
+ var C = type.indexOf("pointer") === 0 && typeof PointerEvent === "function" ? PointerEvent : MouseEvent;
36
+ el.dispatchEvent(new C(type, Object.assign({bubbles:true, cancelable:true, composed:true, view:window, button:0}, init || {})));
37
+ }
38
+ function setValue(el, v){
39
+ var proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype
40
+ : el instanceof HTMLSelectElement ? HTMLSelectElement.prototype : HTMLInputElement.prototype;
41
+ var d = Object.getOwnPropertyDescriptor(proto, "value");
42
+ if (d && d.set) d.set.call(el, v); else el.value = v;
43
+ }
44
+ function fire(el, name, data, inputType){
45
+ var e;
46
+ try { e = new InputEvent(name, {bubbles:true, cancelable:false, composed:true, data:data, inputType:inputType}); }
47
+ catch (_) { e = new Event(name, {bubbles:true}); }
48
+ el.dispatchEvent(e);
49
+ }
50
+ function textual(el){
51
+ return el instanceof HTMLTextAreaElement || (el instanceof HTMLInputElement &&
52
+ /^(text|search|url|tel|email|password|number|)$/.test(el.type));
53
+ }
54
+ var lib = {
55
+ state: function(sel){
56
+ var el = document.querySelector(sel);
57
+ if (!el) return {found:false, visible:false, enabled:false};
58
+ return {found:true, visible:visible(el), enabled:!el.disabled};
59
+ },
60
+ exists: function(sel){ return !!document.querySelector(sel); },
61
+ count: function(sel){ return document.querySelectorAll(sel).length; },
62
+ text: function(sel){ var el = document.querySelector(sel); return el ? el.textContent : null; },
63
+ value: function(sel){ var el = document.querySelector(sel); return el ? (el.value !== undefined ? el.value : null) : null; },
64
+ click: function(sel){
65
+ var el = document.querySelector(sel);
66
+ if (el.scrollIntoView) el.scrollIntoView({block:"center", inline:"center"});
67
+ if (el.focus) el.focus({preventScroll:true});
68
+ var r = el.getBoundingClientRect(), p = {clientX:r.left + r.width / 2, clientY:r.top + r.height / 2};
69
+ ev(el, "pointerdown", p); ev(el, "mousedown", p); ev(el, "pointerup", p); ev(el, "mouseup", p);
70
+ el.click();
71
+ },
72
+ fill: function(sel, text){
73
+ var el = document.querySelector(sel);
74
+ if (el.focus) el.focus({preventScroll:true});
75
+ if (el.isContentEditable) {
76
+ el.textContent = text; fire(el, "input", text, "insertText"); return;
77
+ }
78
+ if (!(el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement || el instanceof HTMLSelectElement))
79
+ throw new Error("fill: " + sel + " is a <" + el.localName + ">, not a text field, select or editable element");
80
+ if (el instanceof HTMLSelectElement) {
81
+ setValue(el, text);
82
+ if (el.value !== text) throw new Error("fill: " + sel + " has no option with value " + JSON.stringify(text));
83
+ fire(el, "input", null, "insertReplacementText"); el.dispatchEvent(new Event("change", {bubbles:true})); return;
84
+ }
85
+ if (/^(checkbox|radio|file|button|submit|reset|image)$/.test(el.type))
86
+ throw new Error("fill: " + sel + " is an input of type " + el.type + "; use click()");
87
+ setValue(el, text);
88
+ fire(el, "input", text, "insertText");
89
+ el.dispatchEvent(new Event("change", {bubbles:true}));
90
+ if (el.setSelectionRange && textual(el) && el.type !== "number" && el.type !== "email") try { el.setSelectionRange(text.length, text.length); } catch (_) {}
91
+ },
92
+ press: function(combo, sel){
93
+ if (sel) { var t = document.querySelector(sel); if (t && t.focus) t.focus({preventScroll:true}); }
94
+ var parts = combo.split("+"), key = parts.pop();
95
+ if (key === "" && parts.length) { key = "+"; parts.pop(); }
96
+ var m = {ctrlKey:false, shiftKey:false, altKey:false, metaKey:false};
97
+ parts.forEach(function(p){
98
+ var k = mods[p.toLowerCase()];
99
+ if (p === "ControlOrMeta") k = /Mac|iPhone|iPad/.test(navigator.platform) ? "metaKey" : "ctrlKey";
100
+ if (!k) throw new Error("press: unknown modifier " + p + " in " + combo);
101
+ m[k] = true;
102
+ });
103
+ var el = document.activeElement && document.activeElement !== document.documentElement ? document.activeElement : document.body;
104
+ if (key === "Space") key = " ";
105
+ var init = Object.assign({key:key, code:key.length === 1 ? (/[a-z]/i.test(key) ? "Key" + key.toUpperCase() : /\d/.test(key) ? "Digit" + key : "") : key,
106
+ bubbles:true, cancelable:true, composed:true, view:window}, m);
107
+ var down = new KeyboardEvent("keydown", init);
108
+ el.dispatchEvent(down);
109
+ if (!down.defaultPrevented) {
110
+ var printable = key.length === 1 && !m.ctrlKey && !m.metaKey;
111
+ if (printable || key === "Enter") el.dispatchEvent(new KeyboardEvent("keypress", init));
112
+ if (printable && textual(el)) {
113
+ var s = el.selectionStart == null ? el.value.length : el.selectionStart, e2 = el.selectionEnd == null ? s : el.selectionEnd;
114
+ setValue(el, el.value.slice(0, s) + key + el.value.slice(e2));
115
+ try { el.setSelectionRange(s + 1, s + 1); } catch (_) {}
116
+ fire(el, "input", key, "insertText");
117
+ } else if (printable && el.isContentEditable) {
118
+ el.textContent += key; fire(el, "input", key, "insertText");
119
+ } else if (key === "Backspace" && textual(el)) {
120
+ var s2 = el.selectionStart == null ? el.value.length : el.selectionStart, e3 = el.selectionEnd == null ? s2 : el.selectionEnd;
121
+ if (s2 === e3 && s2 > 0) s2--;
122
+ if (s2 !== e3 || e3 > 0) {
123
+ setValue(el, el.value.slice(0, s2) + el.value.slice(e3));
124
+ try { el.setSelectionRange(s2, s2); } catch (_) {}
125
+ fire(el, "input", null, "deleteContentBackward");
126
+ }
127
+ } else if (key === "Enter") {
128
+ if (el instanceof HTMLTextAreaElement) {
129
+ var s3 = el.selectionStart, e4 = el.selectionEnd;
130
+ setValue(el, el.value.slice(0, s3) + "\n" + el.value.slice(e4));
131
+ try { el.setSelectionRange(s3 + 1, s3 + 1); } catch (_) {}
132
+ fire(el, "input", "\n", "insertLineBreak");
133
+ } else if (el instanceof HTMLInputElement && el.form && textual(el)) {
134
+ try { el.form.requestSubmit(); } catch (_) { el.form.submit(); }
135
+ } else if (el instanceof HTMLButtonElement || el instanceof HTMLAnchorElement) {
136
+ el.click();
137
+ }
138
+ } else if (key === " " && (el instanceof HTMLButtonElement || (el instanceof HTMLInputElement && /^(checkbox|radio|button|submit)$/.test(el.type)))) {
139
+ el.click();
140
+ } else if (key === "Tab") {
141
+ var list = Array.prototype.filter.call(document.querySelectorAll(focusables), usable);
142
+ var i = list.indexOf(el), n = list.length;
143
+ if (n) list[(i + (m.shiftKey ? -1 : 1) + n) % n].focus();
144
+ }
145
+ }
146
+ var up = document.activeElement && document.activeElement !== document.documentElement ? document.activeElement : el;
147
+ up.dispatchEvent(new KeyboardEvent("keyup", init));
148
+ },
149
+ errors: function(){
150
+ var out = [], seen = {};
151
+ [].concat(globalThis.__krateDriverErrs || [], globalThis.__krateErrs || []).forEach(function(e){
152
+ var s = String(e); if (!seen[s]) { seen[s] = 1; out.push(s); }
153
+ });
154
+ return out;
155
+ },
156
+ call: async function(fn, args){
157
+ var enc = new TextEncoder(), json = enc.encode(JSON.stringify({calls:[{id:1, fn:fn, args:args}]}));
158
+ var body = new Uint8Array(4 + json.length + 2);
159
+ new DataView(body.buffer).setUint32(0, json.length);
160
+ body.set(json, 4);
161
+ var res = await fetch("/__krate/call", {method:"POST", body:body, headers:{"content-type":"application/x-krate-frames"}});
162
+ var buf = new Uint8Array(await res.arrayBuffer());
163
+ if (buf.length < 4) throw new Error("host call " + fn + ": empty answer (HTTP " + res.status + ")");
164
+ var n = new DataView(buf.buffer, buf.byteOffset).getUint32(0);
165
+ var frame = JSON.parse(new TextDecoder().decode(buf.subarray(4, 4 + n)));
166
+ if (frame.error) return {err:frame.error};
167
+ if (frame.err) return {err:frame.err};
168
+ if (frame.stream) return {err:{code:"unsupported", message:"the call returned a stream; the driver reads plain results only", data:null}};
169
+ return {ok:frame.ok === undefined ? null : frame.ok};
170
+ }
171
+ };
172
+ return lib;
173
+ })()`;
174
+ const libRef = `(globalThis.__krateDriver||(globalThis.__krateDriver=${pageLib}))`;
175
+ class Channel {
176
+ constructor(proc) {
177
+ this.proc = proc;
178
+ this.pending = [];
179
+ this.tail = Promise.resolve();
180
+ this.exited = false;
181
+ this.exitInfo = "";
182
+ this.stderr = [];
183
+ createInterface({ input: proc.stdout }).on("line", (l) => this.onLine(l));
184
+ createInterface({ input: proc.stderr }).on("line", (l) => {
185
+ this.stderr.push(l);
186
+ if (this.stderr.length > 500)
187
+ this.stderr.shift();
188
+ });
189
+ proc.on("exit", (code, sig) => {
190
+ this.exited = true;
191
+ this.exitInfo = sig ? `killed by ${sig}` : `exited with code ${code}`;
192
+ const err = new Error(`krate-shell ${this.exitInfo}${this.tailLog()}`);
193
+ this.ready?.reject(err);
194
+ this.ready = undefined;
195
+ for (const p of this.pending.splice(0))
196
+ p.reject(err);
197
+ });
198
+ proc.on("error", (e) => {
199
+ const err = new Error(`could not start krate-shell: ${e.message}`);
200
+ this.ready?.reject(err);
201
+ this.ready = undefined;
202
+ });
203
+ }
204
+ tailLog() {
205
+ const t = this.stderr.slice(-30).join("\n");
206
+ return t ? `\nshell output:\n${t}` : "";
207
+ }
208
+ onLine(l) {
209
+ if (this.ready) {
210
+ if (l === "ready") {
211
+ this.ready.resolve();
212
+ this.ready = undefined;
213
+ }
214
+ return; // "url ..." and other startup lines
215
+ }
216
+ const p = this.pending.shift();
217
+ if (!p)
218
+ return;
219
+ if (l === "ok")
220
+ p.resolve("");
221
+ else if (l.startsWith("ok "))
222
+ p.resolve(l.slice(3));
223
+ else if (l.startsWith("error "))
224
+ p.reject(new Error(l.slice(6)));
225
+ else
226
+ p.reject(new Error(`unexpected reply from krate-shell: ${l}`));
227
+ }
228
+ waitReady(timeoutMs) {
229
+ return new Promise((resolve, reject) => {
230
+ const timer = setTimeout(() => {
231
+ this.ready = undefined;
232
+ reject(new Error(`the app did not become ready within ${timeoutMs} ms${this.tailLog()}`));
233
+ }, timeoutMs);
234
+ this.ready = {
235
+ resolve: () => (clearTimeout(timer), resolve()),
236
+ reject: (e) => (clearTimeout(timer), reject(e)),
237
+ };
238
+ if (this.exited)
239
+ this.ready.reject(new Error(`krate-shell ${this.exitInfo}${this.tailLog()}`));
240
+ });
241
+ }
242
+ // send runs one command; commands go out one at a time, in order.
243
+ send(cmd) {
244
+ const run = () => new Promise((resolve, reject) => {
245
+ if (this.exited)
246
+ return reject(new Error(`krate-shell ${this.exitInfo}${this.tailLog()}`));
247
+ if (/[\r\n]/.test(cmd))
248
+ return reject(new Error("a control command must be one line"));
249
+ this.pending.push({ resolve, reject });
250
+ this.proc.stdin.write(cmd + "\n", (e) => {
251
+ if (e)
252
+ reject(e);
253
+ });
254
+ });
255
+ const next = this.tail.then(run, run);
256
+ this.tail = next.catch(() => undefined);
257
+ return next;
258
+ }
259
+ }
260
+ // transient errors come from a page that is still loading or navigating.
261
+ function transient(e) {
262
+ const m = e instanceof Error ? e.message : String(e);
263
+ return /^query: (the page|no answer)|did not run the script|no open window|no view /.test(m);
264
+ }
265
+ function sleep(ms) {
266
+ return new Promise((r) => setTimeout(r, ms));
267
+ }
268
+ /**
269
+ * Calls fn (in the test process, not the page) until it returns a truthy value
270
+ * and returns that value. A throw counts as "not yet"; the last one is the
271
+ * failure's reason when the time runs out. Use it for conditions that mix
272
+ * pages and host events.
273
+ */
274
+ export async function poll(fn, opts = {}) {
275
+ const timeout = opts.timeout ?? 5000;
276
+ const deadline = Date.now() + timeout;
277
+ let why = "it returned a falsy value";
278
+ for (;;) {
279
+ try {
280
+ const v = await fn();
281
+ if (v)
282
+ return v;
283
+ why = "it returned a falsy value";
284
+ }
285
+ catch (e) {
286
+ why = e instanceof Error ? e.message : String(e);
287
+ }
288
+ if (Date.now() >= deadline)
289
+ throw new Error(`poll: timed out after ${timeout} ms; ${why}`);
290
+ await sleep(opts.interval ?? 50);
291
+ }
292
+ }
293
+ function describe(fn) {
294
+ return typeof fn === "function" ? "the predicate" : JSON.stringify(fn);
295
+ }
296
+ /** One webview of the app. Get one from App.page, App.window(id).view() or App.waitForView. */
297
+ export class Page {
298
+ constructor(app, id) {
299
+ this.app = app;
300
+ this.id = id;
301
+ }
302
+ async run(code) {
303
+ // @json: the source is a JSON string, so the command stays one line.
304
+ const out = await this.app.send(`query-in ${this.id} @json ${JSON.stringify(code)}`);
305
+ return JSON.parse(out);
306
+ }
307
+ /**
308
+ * Runs a function (or an expression string, not statements) in the page and returns its
309
+ * JSON value; a returned promise is awaited. The function is serialized, so
310
+ * it cannot use variables of the test: pass them as arguments, which must be
311
+ * JSON values.
312
+ */
313
+ async evaluate(fn, ...args) {
314
+ // The page's content security policy forbids eval, so the source goes in
315
+ // as code, not as a string.
316
+ const expr = typeof fn === "function" ? `(${fn.toString()}).apply(null,${JSON.stringify(args)})` : `(${fn})`;
317
+ return this.run(expr);
318
+ }
319
+ /** The current address of the page. */
320
+ url() {
321
+ return this.run("location.href");
322
+ }
323
+ title() {
324
+ return this.run("document.title");
325
+ }
326
+ /** Whether an element matches the selector right now. */
327
+ exists(selector) {
328
+ return this.run(`${libRef}.exists(${JSON.stringify(selector)})`);
329
+ }
330
+ /** How many elements match the selector right now. */
331
+ count(selector) {
332
+ return this.run(`${libRef}.count(${JSON.stringify(selector)})`);
333
+ }
334
+ // actionable waits for the element to exist, be visible and be enabled.
335
+ async actionable(selector, what, opts = {}) {
336
+ const timeout = opts.timeout ?? this.app.timeout;
337
+ const deadline = Date.now() + timeout;
338
+ let why = "no element matches it";
339
+ for (;;) {
340
+ try {
341
+ const s = await this.run(`${libRef}.state(${JSON.stringify(selector)})`);
342
+ if (s.found && s.visible && s.enabled)
343
+ return;
344
+ why = !s.found ? "no element matches it" : !s.visible ? "the element is not visible" : "the element is disabled";
345
+ }
346
+ catch (e) {
347
+ if (!transient(e))
348
+ throw e;
349
+ why = `the page is not ready (${e.message})`;
350
+ }
351
+ if (Date.now() >= deadline) {
352
+ throw new Error(`${what}(${JSON.stringify(selector)}): timed out after ${timeout} ms; ${why}`);
353
+ }
354
+ await sleep(opts.interval ?? 50);
355
+ }
356
+ }
357
+ /** Clicks the first match: pointer and mouse events, then click. Waits for it to be visible and enabled. */
358
+ async click(selector, opts) {
359
+ await this.actionable(selector, "click", opts);
360
+ await this.run(`${libRef}.click(${JSON.stringify(selector)})`);
361
+ }
362
+ /** Sets a text field, select or editable element to text and fires input and change. */
363
+ async fill(selector, text, opts) {
364
+ await this.actionable(selector, "fill", opts);
365
+ await this.run(`${libRef}.fill(${JSON.stringify(selector)},${JSON.stringify(text)})`);
366
+ }
367
+ /** Types text into an element one key at a time. */
368
+ async type(selector, text, opts) {
369
+ await this.actionable(selector, "type", opts);
370
+ for (const ch of text)
371
+ await this.press(ch, { selector });
372
+ }
373
+ /**
374
+ * Sends a key to the focused element (or to options.selector): "Enter",
375
+ * "Escape", "Tab", "a", "Control+a", "Shift+Tab". It dispatches keydown,
376
+ * keypress and keyup, and does the default action of the common keys (text
377
+ * insertion, Backspace, Enter submitting a form or activating a button,
378
+ * Space on buttons, Tab moving focus). It is not real keyboard input.
379
+ */
380
+ async press(key, opts = {}) {
381
+ if (opts.selector)
382
+ await this.actionable(opts.selector, "press");
383
+ await this.run(`${libRef}.press(${JSON.stringify(key)},${JSON.stringify(opts.selector ?? "")})`);
384
+ }
385
+ /** The textContent of the first match. Waits for the element to exist. */
386
+ async text(selector, opts = {}) {
387
+ await this.waitFor(selector, opts);
388
+ const t = await this.run(`${libRef}.text(${JSON.stringify(selector)})`);
389
+ if (t === null)
390
+ throw new Error(`text(${JSON.stringify(selector)}): the element went away`);
391
+ return t;
392
+ }
393
+ /** The value of an input, textarea or select. */
394
+ async value(selector, opts = {}) {
395
+ await this.waitFor(selector, opts);
396
+ const v = await this.run(`${libRef}.value(${JSON.stringify(selector)})`);
397
+ if (v === null)
398
+ throw new Error(`value(${JSON.stringify(selector)}): the element has no value`);
399
+ return v;
400
+ }
401
+ /**
402
+ * Waits until a selector matches an element, or until a predicate function
403
+ * (run in the page, may be async) returns a truthy value, and returns that
404
+ * value (undefined for a selector).
405
+ */
406
+ async waitFor(target, opts = {}) {
407
+ const timeout = opts.timeout ?? this.app.timeout;
408
+ const deadline = Date.now() + timeout;
409
+ let last = "";
410
+ for (;;) {
411
+ try {
412
+ if (typeof target === "string") {
413
+ if (await this.exists(target))
414
+ return undefined;
415
+ last = "no element matches it";
416
+ }
417
+ else {
418
+ const v = (await this.evaluate(target));
419
+ if (v)
420
+ return v;
421
+ last = `it returned ${JSON.stringify(v ?? null)}`;
422
+ }
423
+ }
424
+ catch (e) {
425
+ if (!transient(e))
426
+ throw e;
427
+ last = `the page is not ready (${e.message})`;
428
+ }
429
+ if (Date.now() >= deadline) {
430
+ throw new Error(`waitFor(${describe(target)}): timed out after ${timeout} ms; ${last}`);
431
+ }
432
+ await sleep(opts.interval ?? 50);
433
+ }
434
+ }
435
+ /** The errors the page threw so far: uncaught errors, unhandled rejections and errors the Krate runtime caught. */
436
+ errors() {
437
+ return this.run(`${libRef}.errors()`);
438
+ }
439
+ /**
440
+ * Calls a host function as the page would (`<module id>.<Export>` for the
441
+ * app's own functions, or an SDK id such as "krate/kv.get"). Arguments and
442
+ * the result must be plain JSON values; streams are not supported. It runs
443
+ * with this view's permissions. Rejects with a HostCallError.
444
+ */
445
+ async call(fn, ...args) {
446
+ const r = await this.run(`${libRef}.call(${JSON.stringify(fn)},${JSON.stringify(args)})`);
447
+ if (r.err)
448
+ throw new HostCallError(r.err.code, r.err.message, r.err.data);
449
+ return r.ok;
450
+ }
451
+ /**
452
+ * Not available yet: the platform layer has no webview capture API. Use
453
+ * evaluate() to assert on the DOM instead. Rejects.
454
+ */
455
+ screenshot() {
456
+ return Promise.reject(new Error("page.screenshot() is not available yet: the native platform layer has no webview capture API (a follow-up)"));
457
+ }
458
+ }
459
+ /** A window and its views. */
460
+ export class AppWindow {
461
+ constructor(app, id) {
462
+ this.app = app;
463
+ this.id = id;
464
+ }
465
+ views() {
466
+ return this.app.views().then((vs) => vs.filter((v) => v.window === this.id));
467
+ }
468
+ /** The window's view with this id; the primary view without an id. */
469
+ view(id = this.id) {
470
+ return this.app.page(id);
471
+ }
472
+ }
473
+ /** A running app. */
474
+ export class App {
475
+ /** @internal use launch() */
476
+ constructor(ch, timeout, cleanup) {
477
+ this.ch = ch;
478
+ this.cleanup = cleanup;
479
+ this.timeout = timeout;
480
+ this.emit = {
481
+ tray: (kind = "click", id = "") => this.send(`emit tray ${JSON.stringify({ kind, id })}`).then(() => undefined),
482
+ menu: (id, o = {}) => this.send(`emit menu ${JSON.stringify({ id, window: o.window ?? "main", checked: o.checked ?? false })}`).then(() => undefined),
483
+ shortcut: (accelerator) => this.send(`emit shortcut ${JSON.stringify({ accelerator })}`).then(() => undefined),
484
+ };
485
+ }
486
+ /** @internal */
487
+ send(cmd) {
488
+ return this.ch.send(cmd);
489
+ }
490
+ /** Lines the shell and the host code wrote to stderr (the last 500). */
491
+ logs() {
492
+ return [...this.ch.stderr];
493
+ }
494
+ /** Every open view of every window, windows in creation order, primary views first. */
495
+ async views() {
496
+ return JSON.parse(await this.send("views"));
497
+ }
498
+ /** The open windows with their views. */
499
+ async windows() {
500
+ const byWindow = new Map();
501
+ for (const v of await this.views()) {
502
+ const list = byWindow.get(v.window) ?? [];
503
+ list.push(v);
504
+ byWindow.set(v.window, list);
505
+ }
506
+ return [...byWindow].map(([id, views]) => ({ id, views }));
507
+ }
508
+ /** A window by id ("main" is the first). It does not check that it is open. */
509
+ window(id = "main") {
510
+ return new AppWindow(this, id);
511
+ }
512
+ /** A view by id ("main" is the first window's primary view). It does not check that it is open. */
513
+ page(id = "main") {
514
+ return new Page(this, id);
515
+ }
516
+ /** Waits for a window (or view) to open, for example after the app opens a new window. */
517
+ async waitForView(id, opts = {}) {
518
+ const timeout = opts.timeout ?? this.timeout;
519
+ const deadline = Date.now() + timeout;
520
+ for (;;) {
521
+ if ((await this.views()).some((v) => v.id === id))
522
+ return this.page(id);
523
+ if (Date.now() >= deadline) {
524
+ const open = (await this.views()).map((v) => v.id).join(", ") || "none";
525
+ throw new Error(`waitForView(${JSON.stringify(id)}): timed out after ${timeout} ms; open views: ${open}`);
526
+ }
527
+ await sleep(opts.interval ?? 50);
528
+ }
529
+ }
530
+ /** Waits until n views are open (counting every window's views). */
531
+ async waitForViewCount(n, opts = {}) {
532
+ const timeout = opts.timeout ?? this.timeout;
533
+ const deadline = Date.now() + timeout;
534
+ for (;;) {
535
+ const vs = await this.views();
536
+ if (vs.length === n)
537
+ return vs;
538
+ if (Date.now() >= deadline)
539
+ throw new Error(`waitForViewCount(${n}): timed out after ${timeout} ms; ${vs.length} open`);
540
+ await sleep(opts.interval ?? 50);
541
+ }
542
+ }
543
+ /** Quits the app and removes its isolated data. Safe to call twice. */
544
+ close() {
545
+ this.closed ?? (this.closed = (async () => {
546
+ const proc = this.ch.proc;
547
+ if (!this.ch.exited) {
548
+ const exited = new Promise((r) => proc.once("exit", () => r()));
549
+ try {
550
+ proc.stdin.end();
551
+ }
552
+ catch {
553
+ // already closed
554
+ }
555
+ const killer = setTimeout(() => proc.kill(), 5000);
556
+ await exited;
557
+ clearTimeout(killer);
558
+ }
559
+ this.cleanup();
560
+ })());
561
+ return this.closed;
562
+ }
563
+ }
564
+ const live = new Set();
565
+ process.once("exit", () => {
566
+ for (const p of live)
567
+ p.kill();
568
+ });
569
+ function isolation(dir) {
570
+ switch (process.platform) {
571
+ case "win32":
572
+ return { APPDATA: join(dir, "roaming"), LOCALAPPDATA: join(dir, "local") };
573
+ case "darwin":
574
+ return { HOME: dir };
575
+ default:
576
+ return {
577
+ XDG_DATA_HOME: join(dir, "data"),
578
+ XDG_CONFIG_HOME: join(dir, "config"),
579
+ XDG_CACHE_HOME: join(dir, "cache"),
580
+ XDG_STATE_HOME: join(dir, "state"),
581
+ };
582
+ }
583
+ }
584
+ /**
585
+ * Starts the app and resolves when it is ready. Under `krate native test` the
586
+ * shell and the built app come from the environment; outside it pass
587
+ * options.shell and options.appDir.
588
+ */
589
+ export async function launch(options = {}) {
590
+ const shell = options.shell ?? process.env[SHELL_ENV];
591
+ const appDir = options.appDir ?? process.env[APP_ENV];
592
+ if (!shell || !appDir) {
593
+ throw new Error(`launch(): no app to start. Run the test with "krate native test", which builds the app and sets ${SHELL_ENV} and ${APP_ENV}, or pass { shell, appDir }.`);
594
+ }
595
+ let dir = "";
596
+ let env = { ...process.env, KRATE_TEST: "1" };
597
+ if (options.isolate !== false) {
598
+ dir = mkdtempSync(join(tmpdir(), "krate-test-"));
599
+ env = { ...env, ...isolation(dir) };
600
+ }
601
+ Object.assign(env, options.env);
602
+ const cleanup = () => {
603
+ if (dir) {
604
+ try {
605
+ rmSync(dir, { recursive: true, force: true });
606
+ }
607
+ catch {
608
+ // best effort
609
+ }
610
+ }
611
+ };
612
+ const proc = spawn(shell, ["--dev", appDir], { env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
613
+ live.add(proc);
614
+ proc.once("exit", () => live.delete(proc));
615
+ const ch = new Channel(proc);
616
+ const app = new App(ch, options.timeout ?? 5000, cleanup);
617
+ const startTimeout = options.startTimeout ?? 60000;
618
+ const started = Date.now();
619
+ try {
620
+ await ch.waitReady(startTimeout);
621
+ // "ready" means the first window exists, not that its page has loaded:
622
+ // wait for that too, inside the start-up budget, so a test's first wait
623
+ // is not spent on a cold start (seen on CI runners: over 5s).
624
+ const views = await app.views();
625
+ if (views.some((v) => v.id === "main")) {
626
+ await app.page("main").waitFor(() => document.readyState === "complete", {
627
+ timeout: Math.max(1000, startTimeout - (Date.now() - started)),
628
+ });
629
+ }
630
+ }
631
+ catch (e) {
632
+ proc.kill();
633
+ cleanup();
634
+ throw e;
635
+ }
636
+ return app;
637
+ }
@@ -0,0 +1,7 @@
1
+ export declare class KrateError extends Error {
2
+ readonly code: string;
3
+ readonly data: unknown;
4
+ constructor(code: string, message: string, data?: unknown);
5
+ }
6
+ export declare function isKrateError(e: unknown): e is KrateError;
7
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,qBAAa,UAAW,SAAQ,KAAK;IACnC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;gBAEX,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,GAAE,OAAc;CAMhE;AAED,wBAAgB,YAAY,CAAC,CAAC,EAAE,OAAO,GAAG,CAAC,IAAI,UAAU,CAExD"}
package/dist/errors.js ADDED
@@ -0,0 +1,11 @@
1
+ export class KrateError extends Error {
2
+ constructor(code, message, data = null) {
3
+ super(message);
4
+ this.name = "KrateError";
5
+ this.code = code;
6
+ this.data = data;
7
+ }
8
+ }
9
+ export function isKrateError(e) {
10
+ return e instanceof KrateError;
11
+ }
@@ -0,0 +1,6 @@
1
+ export interface SubscribeOptions {
2
+ onError?: (e: unknown) => void;
3
+ }
4
+ export declare function subscribe<T>(id: string, fn: (v: T) => void, opts?: SubscribeOptions): () => void;
5
+ export declare function clean<T extends Record<string, unknown>>(o: T): Record<string, unknown>;
6
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAIA,MAAM,WAAW,gBAAgB;IAG/B,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,KAAK,IAAI,CAAC;CAChC;AAOD,wBAAgB,SAAS,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,IAAI,EAAE,IAAI,GAAE,gBAAqB,GAAG,MAAM,IAAI,CA0BpG;AAGD,wBAAgB,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAItF"}