@swipt/cli 0.1.0-nightly.78 → 0.1.0-nightly.79

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 (68) hide show
  1. package/dist/availability.d.ts +5 -0
  2. package/dist/availability.js +349 -0
  3. package/dist/availability.js.map +1 -0
  4. package/dist/client.d.ts +25 -0
  5. package/dist/client.js +248 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/connection.d.ts +24 -0
  8. package/dist/connection.js +293 -0
  9. package/dist/connection.js.map +1 -0
  10. package/dist/coredevice.d.ts +22 -0
  11. package/dist/coredevice.js +329 -0
  12. package/dist/coredevice.js.map +1 -0
  13. package/dist/device.d.ts +130 -0
  14. package/dist/device.js +539 -0
  15. package/dist/device.js.map +1 -0
  16. package/dist/i18n.d.ts +2 -0
  17. package/dist/i18n.js +57 -0
  18. package/dist/i18n.js.map +1 -0
  19. package/dist/ignore.d.ts +8 -0
  20. package/dist/ignore.js +112 -0
  21. package/dist/ignore.js.map +1 -0
  22. package/dist/metro.d.ts +10 -0
  23. package/dist/metro.js +349 -0
  24. package/dist/metro.js.map +1 -0
  25. package/dist/output.d.ts +20 -0
  26. package/dist/output.js +116 -0
  27. package/dist/output.js.map +1 -0
  28. package/dist/project.d.ts +18 -0
  29. package/dist/project.js +696 -0
  30. package/dist/project.js.map +1 -0
  31. package/dist/proto/common_pb.js +34 -0
  32. package/dist/proto/common_pb.js.map +1 -0
  33. package/dist/proto/logs_pb.js +15 -0
  34. package/dist/proto/logs_pb.js.map +1 -0
  35. package/dist/proto/repl_pb.js +15 -0
  36. package/dist/proto/repl_pb.js.map +1 -0
  37. package/dist/proto/swiplets_pb.js +28 -0
  38. package/dist/proto/swiplets_pb.js.map +1 -0
  39. package/dist/proto/system_pb.js +15 -0
  40. package/dist/proto/system_pb.js.map +1 -0
  41. package/dist/sideload.d.ts +17 -0
  42. package/dist/sideload.js +1098 -0
  43. package/dist/sideload.js.map +1 -0
  44. package/dist/swipt.d.ts +1 -0
  45. package/dist/swipt.js +631 -0
  46. package/dist/swipt.js.map +1 -0
  47. package/dist/version.d.ts +2 -0
  48. package/dist/version.js +15 -0
  49. package/dist/version.js.map +1 -0
  50. package/package.json +21 -7
  51. package/availability.mjs +0 -642
  52. package/client.mjs +0 -375
  53. package/connection.mjs +0 -450
  54. package/coredevice.mjs +0 -464
  55. package/device.mjs +0 -837
  56. package/i18n.mjs +0 -71
  57. package/ignore.mjs +0 -149
  58. package/metro.mjs +0 -432
  59. package/output.mjs +0 -177
  60. package/project.mjs +0 -1013
  61. package/proto/common_pb.js +0 -98
  62. package/proto/logs_pb.js +0 -34
  63. package/proto/repl_pb.js +0 -55
  64. package/proto/swiplets_pb.js +0 -179
  65. package/proto/system_pb.js +0 -27
  66. package/sideload.mjs +0 -1696
  67. package/swipt.mjs +0 -726
  68. package/version.mjs +0 -16
package/device.mjs DELETED
@@ -1,837 +0,0 @@
1
- import { createRequire } from "node:module";
2
- import crypto from "node:crypto";
3
- import fs from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { setTimeout as sleep } from "node:timers/promises";
7
-
8
- import { fromJson, toJson } from "@bufbuild/protobuf";
9
- import { ValueSchema, timestampFromMs } from "@bufbuild/protobuf/wkt";
10
-
11
- import { UsageError, unauthenticated } from "./client.mjs";
12
- import { attach } from "./connection.mjs";
13
- import { tr } from "./i18n.mjs";
14
- import { Ignorer, relativePath } from "./ignore.mjs";
15
- import {
16
- columns,
17
- dateTime,
18
- printLog,
19
- printScriptError,
20
- serviceEnabledText,
21
- serviceStatusText,
22
- serviceText,
23
- } from "./output.mjs";
24
- import { AvailabilityChecker } from "./availability.mjs";
25
- import { buildProject, loadProject } from "./project.mjs";
26
- import { LogLevel } from "./proto/common_pb.js";
27
- import { ServiceStatus } from "./proto/swiplets_pb.js";
28
-
29
- const uploadChunk = 256 << 10;
30
- const rebuildDelay = 300;
31
- const logReconnect = 2000;
32
-
33
- const { version } = createRequire(import.meta.url)("./package.json");
34
-
35
- const readStdin = () => fs.readFileSync(0);
36
-
37
- const indented = (value) =>
38
- JSON.stringify(value, null, 2).replaceAll("\n", "\n ");
39
-
40
- function elapsed(since) {
41
- const ms = Date.now() - since;
42
- if (ms < 1000) {
43
- return `${ms}ms`;
44
- }
45
- const seconds = ms / 1000;
46
- if (seconds < 60) {
47
- return `${Number(seconds.toFixed(3))}s`;
48
- }
49
- return `${Math.floor(seconds / 60)}m${Number((seconds % 60).toFixed(3))}s`;
50
- }
51
-
52
- const session = (context, run) => attach(context).then(run);
53
-
54
- export function printVersion() {
55
- console.log(
56
- "swipt",
57
- version,
58
- `node ${process.versions.node}`,
59
- `${process.platform}/${process.arch}`,
60
- );
61
- }
62
-
63
- export const logs = (context) =>
64
- session(context, async (client) => {
65
- const { options } = context;
66
- const levels = ["error", "warn", "info", "debug"];
67
- const index = levels.indexOf(options.level);
68
- if (index < 0) {
69
- throw new UsageError(tr("--level is error, warn, info or debug"));
70
- }
71
- const request = {
72
- follow: options.follow,
73
- tail: options.tail ?? 100,
74
- swipletId: options.swiplet ?? "",
75
- level: index + 1,
76
- };
77
- if (options.since > 0) {
78
- request.since = timestampFromMs(Date.now() - options.since);
79
- if (options.tail === undefined) {
80
- request.tail = 0xffffffff;
81
- }
82
- }
83
- for await (const response of client.logs.readLogs(request, {
84
- signal: context.signal,
85
- })) {
86
- printLog(response.entry, true);
87
- }
88
- });
89
-
90
- export const stop = (context) =>
91
- session(context, async (client) => {
92
- await client.system.shutdown({}, { signal: context.signal });
93
- console.log(tr("stopped"));
94
- });
95
-
96
- function readInput(value) {
97
- if (value === undefined || value === "") {
98
- return undefined;
99
- }
100
- let data = value;
101
- try {
102
- if (value === "-") {
103
- data = readStdin().toString();
104
- } else if (value.startsWith("@")) {
105
- data = fs.readFileSync(value.slice(1), "utf8");
106
- }
107
- } catch (error) {
108
- throw new Error(`read --input: ${error.message}`);
109
- }
110
- try {
111
- return fromJson(ValueSchema, JSON.parse(data));
112
- } catch (error) {
113
- throw new UsageError(
114
- tr("--input is not JSON: {error}", { error: error.message }),
115
- );
116
- }
117
- }
118
-
119
- const notInstalled = (id) =>
120
- new Error(tr("there is no swiplet {id}", { id: JSON.stringify(id) }));
121
-
122
- export const list = (context) =>
123
- session(context, async (client) => {
124
- const { swiplets } = await client.swiplets.listSwiplets(
125
- {},
126
- { signal: context.signal },
127
- );
128
- const rows = swiplets.map((swiplet) => {
129
- let service = "";
130
- let status = "";
131
- if (swiplet.service) {
132
- service = serviceEnabledText(swiplet.service.enabled);
133
- status = serviceStatusText(swiplet.service.status);
134
- if (swiplet.service.error) {
135
- status += `: ${swiplet.service.error.name}: ${swiplet.service.error.message}`;
136
- }
137
- }
138
- return [
139
- swiplet.id,
140
- swiplet.title,
141
- swiplet.version,
142
- swiplet.actions.map((action) => action.name).join(","),
143
- service,
144
- status,
145
- ];
146
- });
147
- console.log(
148
- columns([
149
- [
150
- tr("ID"),
151
- tr("TITLE"),
152
- tr("VERSION"),
153
- tr("ACTIONS"),
154
- tr("SERVICE"),
155
- tr("STATUS"),
156
- ],
157
- ...rows,
158
- ]),
159
- );
160
- });
161
-
162
- export const show = (context) =>
163
- session(context, async (client) => {
164
- const { swiplets } = await client.swiplets.listSwiplets(
165
- {},
166
- { signal: context.signal },
167
- );
168
- const swiplet = swiplets.find((it) => it.id === context.args[0]);
169
- if (!swiplet) {
170
- throw notInstalled(context.args[0]);
171
- }
172
- console.log(swiplet.id, JSON.stringify(swiplet.title), swiplet.version);
173
- if (swiplet.hasUi) {
174
- console.log(tr("ui: yes"));
175
- }
176
- if (swiplet.service) {
177
- console.log(
178
- tr("service: {status}", {
179
- status: serviceText(swiplet.id, swiplet.service),
180
- }),
181
- );
182
- }
183
- for (const action of swiplet.actions) {
184
- console.log();
185
- console.log(
186
- action.exposedToShortcuts
187
- ? tr("action {name} {title} (Shortcuts)", {
188
- name: action.name,
189
- title: JSON.stringify(action.title),
190
- })
191
- : tr("action {name} {title}", {
192
- name: action.name,
193
- title: JSON.stringify(action.title),
194
- }),
195
- );
196
- if (action.description !== "") {
197
- console.log(` ${action.description}`);
198
- }
199
- if (action.inputSchema) {
200
- console.log(
201
- ` ${tr("input: {schema}", { schema: indented(action.inputSchema) })}`,
202
- );
203
- }
204
- if (action.outputSchema) {
205
- console.log(
206
- ` ${tr("output: {schema}", { schema: indented(action.outputSchema) })}`,
207
- );
208
- }
209
- }
210
- });
211
-
212
- export const call = (context) =>
213
- session(context, async (client) => {
214
- const [id, action] = context.args;
215
- const input = readInput(context.options.input);
216
- let result;
217
- for await (const response of client.swiplets.callAction(
218
- { swipletId: id, action, input },
219
- { signal: context.signal },
220
- )) {
221
- if (response.part.case === "log") {
222
- printLog(response.part.value, false);
223
- } else if (response.part.case === "result") {
224
- result = response.part.value;
225
- }
226
- }
227
- if (result?.outcome.case === "output") {
228
- console.log(
229
- JSON.stringify(toJson(ValueSchema, result.outcome.value), null, 2),
230
- );
231
- return;
232
- }
233
- if (result?.outcome.case === "error") {
234
- throw printScriptError(result.outcome.value);
235
- }
236
- throw new Error("the server sent no result");
237
- });
238
-
239
- async function watchServices(client, id, signal) {
240
- for await (const response of client.swiplets.watchServices(
241
- { swipletId: id },
242
- { signal },
243
- )) {
244
- console.log(
245
- `${response.swipletId}: ${serviceText(response.swipletId, response.service)}`,
246
- );
247
- }
248
- }
249
-
250
- export const setService = (enabled) => (context) =>
251
- session(context, async (client) => {
252
- const id = context.args[0];
253
- const response = await client.swiplets.setServiceEnabled(
254
- { swipletId: id, enabled },
255
- { signal: context.signal },
256
- );
257
- if (context.options.watch) {
258
- await watchServices(client, id, context.signal);
259
- return;
260
- }
261
- console.log(`${id}: ${serviceText(id, response.service)}`);
262
- });
263
-
264
- export const serviceWatch = (context) =>
265
- session(context, (client) =>
266
- watchServices(client, context.args[0] ?? "", context.signal),
267
- );
268
-
269
- export const remove = (context) =>
270
- session(context, async (client) => {
271
- await client.swiplets.removeSwiplet(
272
- { swipletId: context.args[0] },
273
- { signal: context.signal },
274
- );
275
- console.log(tr("removed {name}", { name: context.args[0] }));
276
- });
277
-
278
- const isLocal = (name) => {
279
- const normalized = path.posix.normalize(name);
280
- return (
281
- !path.posix.isAbsolute(normalized) &&
282
- normalized !== ".." &&
283
- !normalized.startsWith("../")
284
- );
285
- };
286
-
287
- class FileSink {
288
- files = new Map();
289
- saved = 0;
290
-
291
- constructor(root) {
292
- this.root = root;
293
- }
294
-
295
- target(name) {
296
- if (!isLocal(name)) {
297
- throw new Error(
298
- `the server sent the path ${name}, which leaves the output directory`,
299
- );
300
- }
301
- return path.join(this.root, ...name.split("/"));
302
- }
303
-
304
- begin(name, directory) {
305
- const target = this.target(name);
306
- if (directory) {
307
- fs.mkdirSync(target, { recursive: true });
308
- return;
309
- }
310
- fs.mkdirSync(path.dirname(target), { recursive: true });
311
- const previous = this.files.get(name);
312
- if (previous !== undefined) {
313
- fs.closeSync(previous);
314
- }
315
- this.files.set(name, fs.openSync(target, "w"));
316
- this.saved++;
317
- }
318
-
319
- write(name, offset, data) {
320
- const file = this.files.get(name);
321
- if (file === undefined) {
322
- throw new Error(`the server sent data for ${name} before announcing it`);
323
- }
324
- fs.writeSync(file, data, 0, data.length, Number(offset));
325
- }
326
-
327
- close() {
328
- for (const file of this.files.values()) {
329
- fs.closeSync(file);
330
- }
331
- }
332
- }
333
-
334
- const printSaved = (target, count) =>
335
- console.error(tr("saved {count} file(s) to {path}", { count, path: target }));
336
-
337
- const dataCommands = (target) => ({
338
- list: (context) =>
339
- session(context, async (client) => {
340
- const {
341
- id,
342
- args: [directory = ""],
343
- } = target(context.args);
344
- const { files } = await client.swiplets.listDataFiles(
345
- {
346
- swipletId: id,
347
- path: directory,
348
- recursive: context.options.recursive,
349
- },
350
- { signal: context.signal },
351
- );
352
- const rows = files.map((file) => [
353
- file.directory ? "-" : String(file.size),
354
- dateTime(file.modified),
355
- file.directory ? `${file.path}/` : file.path,
356
- ]);
357
- if (rows.length > 0) {
358
- console.log(columns(rows));
359
- }
360
- }),
361
- read: (context) =>
362
- session(context, async (client) => {
363
- const {
364
- id,
365
- wholeDirectory,
366
- subdirectory,
367
- args: [given],
368
- } = target(context.args);
369
- const output = context.options.output ?? "";
370
- const requested = path.posix
371
- .normalize(`/${given}`)
372
- .replace(/^\/+|\/+$/g, "");
373
- const printing = output === "" || output === "-";
374
- const directory = () =>
375
- new UsageError(
376
- requested === ""
377
- ? wholeDirectory(JSON.stringify(given))
378
- : subdirectory(JSON.stringify(requested)),
379
- );
380
- const relativeTo = (name) =>
381
- name.slice(requested.length).replace(/^\//, "");
382
- let sink;
383
- let single;
384
- const contents = [];
385
- try {
386
- for await (const response of client.swiplets.readDataFile(
387
- { swipletId: id, path: given },
388
- { signal: context.signal },
389
- )) {
390
- if (response.part.case === "file") {
391
- const file = response.part.value;
392
- if (file.path === requested && !file.directory) {
393
- single = file;
394
- continue;
395
- }
396
- if (!sink) {
397
- if (printing) {
398
- throw directory();
399
- }
400
- sink = new FileSink(output);
401
- }
402
- sink.begin(relativeTo(file.path), file.directory);
403
- } else if (response.part.case === "chunk") {
404
- const chunk = response.part.value;
405
- if (single && chunk.path === single.path) {
406
- contents.push(chunk.data);
407
- continue;
408
- }
409
- if (!sink) {
410
- throw new Error(
411
- `the server sent data for ${chunk.path} before announcing it`,
412
- );
413
- }
414
- sink.write(relativeTo(chunk.path), chunk.offset, chunk.data);
415
- }
416
- }
417
- } finally {
418
- sink?.close();
419
- }
420
- if (sink) {
421
- printSaved(sink.root, sink.saved);
422
- return;
423
- }
424
- if (!single) {
425
- if (printing) {
426
- throw directory();
427
- }
428
- fs.mkdirSync(output, { recursive: true });
429
- printSaved(output, 0);
430
- return;
431
- }
432
- const data = Buffer.concat(contents);
433
- if (printing) {
434
- process.stdout.write(data);
435
- return;
436
- }
437
- let destination = output;
438
- if (
439
- fs.existsSync(destination) &&
440
- fs.statSync(destination).isDirectory()
441
- ) {
442
- destination = path.join(destination, path.posix.basename(single.path));
443
- }
444
- fs.writeFileSync(destination, data);
445
- printSaved(destination, 1);
446
- }),
447
- write: (context) =>
448
- session(context, async (client) => {
449
- const {
450
- id,
451
- args: [name, file],
452
- } = target(context.args);
453
- const data =
454
- file === undefined || file === "-"
455
- ? readStdin()
456
- : fs.readFileSync(file);
457
- await client.swiplets.writeDataFile(
458
- (async function* () {
459
- yield {
460
- part: { case: "header", value: { swipletId: id, path: name } },
461
- };
462
- for (let offset = 0; offset < data.length; offset += uploadChunk) {
463
- yield {
464
- part: {
465
- case: "data",
466
- value: data.subarray(offset, offset + uploadChunk),
467
- },
468
- };
469
- }
470
- })(),
471
- { signal: context.signal },
472
- );
473
- }),
474
- remove: (context) =>
475
- session(context, async (client) => {
476
- const {
477
- id,
478
- args: [name],
479
- } = target(context.args);
480
- await client.swiplets.removeDataFile(
481
- { swipletId: id, path: name, recursive: context.options.recursive },
482
- { signal: context.signal },
483
- );
484
- }),
485
- clear: (context) =>
486
- session(context, async (client) => {
487
- const { id } = target(context.args);
488
- const { files } = await client.swiplets.listDataFiles(
489
- { swipletId: id },
490
- { signal: context.signal },
491
- );
492
- for (const file of files) {
493
- await client.swiplets.removeDataFile(
494
- { swipletId: id, path: file.path, recursive: true },
495
- { signal: context.signal },
496
- );
497
- }
498
- }),
499
- });
500
-
501
- export const swipletData = dataCommands(([id, ...args]) => ({
502
- id,
503
- wholeDirectory: (name) =>
504
- tr(
505
- "{path} names the data directory of {swiplet}; save it with --output DIRECTORY",
506
- { path: name, swiplet: id },
507
- ),
508
- subdirectory: (name) =>
509
- tr(
510
- "{path} is a directory in the data directory of {swiplet}; save it with --output DIRECTORY",
511
- { path: name, swiplet: id },
512
- ),
513
- args,
514
- }));
515
-
516
- export const replData = dataCommands((args) => ({
517
- id: "@repl",
518
- wholeDirectory: (name) =>
519
- tr(
520
- "{path} names the data directory of the REPL; save it with --output DIRECTORY",
521
- { path: name },
522
- ),
523
- subdirectory: (name) =>
524
- tr(
525
- "{path} is a directory in the data directory of the REPL; save it with --output DIRECTORY",
526
- { path: name },
527
- ),
528
- args,
529
- }));
530
-
531
- async function deploy(client, archive, signal) {
532
- const data = fs.readFileSync(archive);
533
- return client.swiplets.deploySwiplet(
534
- (async function* () {
535
- for (
536
- let offset = 0;
537
- offset < data.length || offset === 0;
538
- offset += uploadChunk
539
- ) {
540
- yield { chunk: data.subarray(offset, offset + uploadChunk) };
541
- }
542
- })(),
543
- { signal },
544
- );
545
- }
546
-
547
- const printDeployed = (deployed, toStdout) =>
548
- (toStdout ? console.log : console.error)(
549
- deployed.replaced
550
- ? tr("replaced {id} {version}", {
551
- id: deployed.swiplet.id,
552
- version: deployed.swiplet.version,
553
- })
554
- : tr("installed {id} {version}", {
555
- id: deployed.swiplet.id,
556
- version: deployed.swiplet.version,
557
- }),
558
- );
559
-
560
- export async function install(context) {
561
- const [archive] = context.args;
562
- if (!fs.existsSync(archive)) {
563
- throw new Error(tr("there is no archive at {path}", { path: archive }));
564
- }
565
- await session(context, async (client) =>
566
- printDeployed(await deploy(client, archive, context.signal), true),
567
- );
568
- }
569
-
570
- export async function deployProject(context) {
571
- const { archive } = await buildProject(path.resolve(context.args[0] ?? "."));
572
- await session(context, async (client) =>
573
- printDeployed(await deploy(client, archive, context.signal), true),
574
- );
575
- }
576
-
577
- async function follow(signal, fatal, run) {
578
- let reported;
579
- while (!signal.aborted) {
580
- try {
581
- await run();
582
- } catch (error) {
583
- if (unauthenticated(error)) {
584
- fatal(error);
585
- return;
586
- }
587
- if (!signal.aborted && error.message !== reported) {
588
- reported = error.message;
589
- console.error(tr("error: {message}", { message: error.message }));
590
- }
591
- }
592
- try {
593
- await sleep(logReconnect, undefined, { signal });
594
- } catch {
595
- return;
596
- }
597
- }
598
- }
599
-
600
- export async function develop(context) {
601
- const { signal, printError } = context;
602
- const project = loadProject(path.resolve(context.args[0] ?? "."));
603
- const root = project.root;
604
- const client = await attach(context);
605
- const controller = new AbortController();
606
- const inner = AbortSignal.any([signal, controller.signal]);
607
- let fatalReject;
608
- const fatal = new Promise((_, reject) => {
609
- fatalReject = reject;
610
- });
611
- follow(inner, fatalReject, async () => {
612
- for await (const response of client.swiplets.watchServices(
613
- {},
614
- { signal: inner },
615
- )) {
616
- if (
617
- response.swipletId === project.config.id &&
618
- response.service?.status === ServiceStatus.FAILED
619
- ) {
620
- console.error(
621
- `${response.swipletId}: ${serviceText(response.swipletId, response.service)}`,
622
- );
623
- }
624
- }
625
- });
626
- if (!context.options["no-logs"]) {
627
- follow(inner, fatalReject, async () => {
628
- for await (const response of client.logs.readLogs(
629
- { swipletId: project.config.id, follow: true },
630
- { signal: inner },
631
- )) {
632
- printLog(response.entry, false);
633
- }
634
- });
635
- }
636
- let deployed = "";
637
- const checker = new AvailabilityChecker();
638
- const cycle = async () => {
639
- const started = Date.now();
640
- let built;
641
- try {
642
- built = await buildProject(root, checker);
643
- } catch (error) {
644
- if (!inner.aborted) {
645
- console.error(tr("error: {message}", { message: error.message }));
646
- }
647
- return;
648
- }
649
- if (built.digest === deployed) {
650
- console.error(
651
- tr(
652
- "built in {elapsed}; it came out as deployed, so nothing was deployed",
653
- { elapsed: elapsed(started) },
654
- ),
655
- );
656
- return;
657
- }
658
- let result;
659
- try {
660
- result = await deploy(client, built.archive, inner);
661
- } catch (error) {
662
- if (unauthenticated(error)) {
663
- throw error;
664
- }
665
- if (!inner.aborted) {
666
- printError(error, "deploy");
667
- }
668
- return;
669
- }
670
- deployed = built.digest;
671
- printDeployed(result, false);
672
- console.error(
673
- tr("built and deployed in {elapsed}; watching {directory}", {
674
- elapsed: elapsed(started),
675
- directory: root,
676
- }),
677
- );
678
- };
679
- const watch = () =>
680
- new Promise((resolve, reject) => {
681
- let ignore = new Ignorer(root);
682
- let timer;
683
- const watcher = fs.watch(root, { recursive: true }, (_, filename) => {
684
- if (filename === null) {
685
- return;
686
- }
687
- const name = path.join(root, filename);
688
- if (path.basename(name) === ".gitignore") {
689
- ignore = new Ignorer(root);
690
- }
691
- let isDirectory = false;
692
- try {
693
- isDirectory = fs.statSync(name).isDirectory();
694
- } catch {
695
- isDirectory = false;
696
- }
697
- const relative = relativePath(root, name);
698
- if (relative === "" || ignore.ignored(relative, isDirectory)) {
699
- return;
700
- }
701
- clearTimeout(timer);
702
- timer = setTimeout(() => cycle().catch(reject), rebuildDelay);
703
- });
704
- watcher.on("error", (error) => printError(error, "watch the project"));
705
- inner.addEventListener(
706
- "abort",
707
- () => {
708
- clearTimeout(timer);
709
- watcher.close();
710
- resolve();
711
- },
712
- { once: true },
713
- );
714
- });
715
- try {
716
- await cycle();
717
- await Promise.race([watch(), fatal]);
718
- } finally {
719
- controller.abort();
720
- checker.close();
721
- }
722
- }
723
-
724
- const isFile = (name) => {
725
- try {
726
- return fs.statSync(name).isFile();
727
- } catch {
728
- return false;
729
- }
730
- };
731
-
732
- export const isProgram = (first) => first === "-" || isFile(first);
733
-
734
- function readScript([first, ...args]) {
735
- if (first === undefined || first === "-") {
736
- return {
737
- code: readStdin().toString(),
738
- args,
739
- program: true,
740
- file: "input.js",
741
- };
742
- }
743
- if (isFile(first)) {
744
- return {
745
- code: fs.readFileSync(first, "utf8"),
746
- args,
747
- program: true,
748
- file: first,
749
- };
750
- }
751
- if (args.length > 0) {
752
- throw new UsageError(
753
- tr("{argument} is not a file, and CODE takes no ARG", {
754
- argument: JSON.stringify(first),
755
- }),
756
- );
757
- }
758
- return { code: first, args, program: false, file: "input.js" };
759
- }
760
-
761
- class ImageSink {
762
- directory = "";
763
-
764
- constructor(output) {
765
- this.output = output;
766
- }
767
-
768
- save(data) {
769
- if (this.directory === "") {
770
- if (this.output !== undefined && this.output !== "") {
771
- this.directory = path.resolve(this.output);
772
- fs.mkdirSync(this.directory, { recursive: true });
773
- } else {
774
- this.directory = fs.mkdtempSync(path.join(os.tmpdir(), "swipt-repl-"));
775
- }
776
- }
777
- const name = path.join(
778
- this.directory,
779
- `image-${crypto.randomBytes(5).toString("hex")}.png`,
780
- );
781
- fs.writeFileSync(name, data);
782
- return name;
783
- }
784
- }
785
-
786
- export const api = (context) =>
787
- session(context, async (client) => {
788
- process.stdout.write(
789
- (await client.repl.getDeclarations({}, { signal: context.signal }))
790
- .typescript,
791
- );
792
- });
793
-
794
- export const reset = (context) =>
795
- session(context, (client) =>
796
- client.repl.reset({}, { signal: context.signal }),
797
- );
798
-
799
- export async function run(context) {
800
- const { args, options, signal } = context;
801
- const script = readScript(args);
802
- await session(context, async (client) => {
803
- const images = new ImageSink(options.output);
804
- let failure;
805
- for await (const response of client.repl.execute(
806
- { code: script.code, args: script.args, program: script.program },
807
- { signal },
808
- )) {
809
- switch (response.part.case) {
810
- case "console": {
811
- const output = response.part.value;
812
- (output.level === LogLevel.ERROR || output.level === LogLevel.WARN
813
- ? console.error
814
- : console.log)(output.text);
815
- break;
816
- }
817
- case "value":
818
- console.log(response.part.value.text);
819
- break;
820
- case "image":
821
- console.log(`[image: ${images.save(response.part.value)}]`);
822
- break;
823
- case "error":
824
- failure = response.part.value;
825
- break;
826
- }
827
- }
828
- if (failure) {
829
- throw printScriptError({
830
- ...failure,
831
- stack: failure.stack.map((frame) =>
832
- frame.file === "input.js" ? { ...frame, file: script.file } : frame,
833
- ),
834
- });
835
- }
836
- });
837
- }