screenreader-speech-capture-client 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2414 @@
1
+ import os, { hostname } from "node:os";
2
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ // ../shared/src/api-version.ts
6
+ /**
7
+ * `<major>.<minor>` of the HTTP API. Minor versions only add things
8
+ * (docs/usage/http-api.md#versioning).
9
+ */
10
+ const API_VERSION = "1.14";
11
+ /** Path prefix of every API route. */
12
+ const API_PREFIX = "/api/v1";
13
+ const DEFAULT_CONFIG = {
14
+ lang: void 0,
15
+ message: void 0,
16
+ abortEarly: void 0,
17
+ abortPipeEarly: void 0
18
+ };
19
+ /**
20
+ * Returns the global configuration.
21
+ *
22
+ * @param config The config to merge.
23
+ *
24
+ * @returns The configuration.
25
+ */
26
+ /* @__NO_SIDE_EFFECTS__ */
27
+ function getGlobalConfig(config$1) {
28
+ if (!config$1 && true) return DEFAULT_CONFIG;
29
+ return {
30
+ lang: config$1?.lang ?? void 0,
31
+ message: config$1?.message,
32
+ abortEarly: config$1?.abortEarly ?? void 0,
33
+ abortPipeEarly: config$1?.abortPipeEarly ?? void 0
34
+ };
35
+ }
36
+ /**
37
+ * Stringifies an unknown input to a literal or type string.
38
+ *
39
+ * @param input The unknown input.
40
+ *
41
+ * @returns A literal or type string.
42
+ *
43
+ * @internal
44
+ */
45
+ /* @__NO_SIDE_EFFECTS__ */
46
+ function _stringify(input) {
47
+ const type = typeof input;
48
+ if (type === "string") return `"${input}"`;
49
+ if (type === "number" || type === "bigint" || type === "boolean") return `${input}`;
50
+ if (type === "object" || type === "function") return (input && Object.getPrototypeOf(input)?.constructor?.name) ?? "null";
51
+ return type;
52
+ }
53
+ /**
54
+ * Adds an issue to the dataset.
55
+ *
56
+ * @param context The issue context.
57
+ * @param label The issue label.
58
+ * @param dataset The input dataset.
59
+ * @param config The configuration.
60
+ * @param other The optional props.
61
+ *
62
+ * @internal
63
+ */
64
+ function _addIssue(context, label, dataset, config$1, other) {
65
+ const input = other && "input" in other ? other.input : dataset.value;
66
+ const expected = other?.expected ?? context.expects ?? null;
67
+ const received = other?.received ?? /* @__PURE__ */ _stringify(input);
68
+ const issue = {
69
+ kind: context.kind,
70
+ type: context.type,
71
+ input,
72
+ expected,
73
+ received,
74
+ message: `Invalid ${label}: ${expected ? `Expected ${expected} but r` : "R"}eceived ${received}`,
75
+ requirement: context.requirement,
76
+ path: other?.path,
77
+ issues: other?.issues,
78
+ lang: config$1.lang,
79
+ abortEarly: config$1.abortEarly,
80
+ abortPipeEarly: config$1.abortPipeEarly
81
+ };
82
+ const isSchema = context.kind === "schema";
83
+ const message$1 = other?.message ?? context.message ?? (context.reference, issue.lang, void 0) ?? (isSchema ? (issue.lang, void 0) : null) ?? config$1.message ?? (issue.lang, void 0);
84
+ if (message$1 !== void 0) issue.message = typeof message$1 === "function" ? message$1(issue) : message$1;
85
+ if (isSchema) dataset.typed = false;
86
+ if (dataset.issues) dataset.issues.push(issue);
87
+ else dataset.issues = [issue];
88
+ }
89
+ /**
90
+ * Disallows inherited object properties and prevents object prototype
91
+ * pollution by disallowing certain keys.
92
+ *
93
+ * @param object The object to check.
94
+ * @param key The key to check.
95
+ *
96
+ * @returns Whether the key is allowed.
97
+ *
98
+ * @internal
99
+ */
100
+ /* @__NO_SIDE_EFFECTS__ */
101
+ function _isValidObjectKey(object$1, key) {
102
+ return Object.prototype.hasOwnProperty.call(object$1, key) && key !== "__proto__" && key !== "prototype" && key !== "constructor";
103
+ }
104
+ /**
105
+ * Joins multiple `expects` values with the given separator.
106
+ *
107
+ * @param values The `expects` values.
108
+ * @param separator The separator.
109
+ *
110
+ * @returns The joined `expects` property.
111
+ *
112
+ * @internal
113
+ */
114
+ /* @__NO_SIDE_EFFECTS__ */
115
+ function _joinExpects(values$1, separator) {
116
+ const list = [...new Set(values$1)];
117
+ if (list.length > 1) return `(${list.join(` ${separator} `)})`;
118
+ return list[0] ?? "never";
119
+ }
120
+ /**
121
+ * Eagerly creates and attaches the Standard Schema properties of a schema.
122
+ *
123
+ * Hint: The contextual `this` type includes the standard properties that are
124
+ * attached before the schema is returned.
125
+ *
126
+ * @param schema The schema to attach standard properties to.
127
+ *
128
+ * @returns The schema with standard properties attached.
129
+ *
130
+ * @internal
131
+ */
132
+ function _standardSchema(schema) {
133
+ schema["~standard"] = {
134
+ version: 1,
135
+ vendor: "valibot",
136
+ validate: (value$1) => schema["~run"]({ value: value$1 }, /* @__PURE__ */ getGlobalConfig())
137
+ };
138
+ return schema;
139
+ }
140
+ /* @__NO_SIDE_EFFECTS__ */
141
+ function getDotPath(issue) {
142
+ if (issue.path) {
143
+ let key = "";
144
+ for (const item of issue.path) if (typeof item.key === "string" || typeof item.key === "number") if (key) key += `.${item.key}`;
145
+ else key += item.key;
146
+ else return null;
147
+ return key;
148
+ }
149
+ return null;
150
+ }
151
+ /**
152
+ * [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) timestamp regex. Allows a
153
+ * space as a date/time separator and an optional space before the UTC offset.
154
+ */
155
+ const ISO_TIMESTAMP_REGEX = /^\d{4}-(?:0[1-9]|1[0-2])-(?:[12]\d|0[1-9]|3[01])[T ](?:0\d|1\d|2[0-3])(?::[0-5]\d){2}(?:\.\d{1,9})?(?:Z| ?[+-](?:0\d|1\d|2[0-3])(?::?[0-5]\d)?)$/u;
156
+ /* @__NO_SIDE_EFFECTS__ */
157
+ function check(requirement, message$1) {
158
+ return {
159
+ kind: "validation",
160
+ type: "check",
161
+ reference: check,
162
+ async: false,
163
+ expects: null,
164
+ requirement,
165
+ message: message$1,
166
+ "~run"(dataset, config$1) {
167
+ if (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, "input", dataset, config$1);
168
+ return dataset;
169
+ }
170
+ };
171
+ }
172
+ /**
173
+ * Creates a description metadata action.
174
+ *
175
+ * @param description_ The description text.
176
+ *
177
+ * @returns A description action.
178
+ */
179
+ /* @__NO_SIDE_EFFECTS__ */
180
+ function description(description_) {
181
+ return {
182
+ kind: "metadata",
183
+ type: "description",
184
+ reference: description,
185
+ description: description_
186
+ };
187
+ }
188
+ /**
189
+ * Creates an examples metadata action.
190
+ *
191
+ * @param examples_ The examples.
192
+ *
193
+ * @returns An examples action.
194
+ *
195
+ * @beta
196
+ */
197
+ /* @__NO_SIDE_EFFECTS__ */
198
+ function examples(examples_) {
199
+ return {
200
+ kind: "metadata",
201
+ type: "examples",
202
+ reference: examples,
203
+ examples: examples_
204
+ };
205
+ }
206
+ /* @__NO_SIDE_EFFECTS__ */
207
+ function integer$3(message$1) {
208
+ return {
209
+ kind: "validation",
210
+ type: "integer",
211
+ reference: integer$3,
212
+ async: false,
213
+ expects: null,
214
+ requirement: Number.isInteger,
215
+ message: message$1,
216
+ "~run"(dataset, config$1) {
217
+ if (dataset.typed && !this.requirement(dataset.value)) _addIssue(this, "integer", dataset, config$1);
218
+ return dataset;
219
+ }
220
+ };
221
+ }
222
+ /* @__NO_SIDE_EFFECTS__ */
223
+ function isoTimestamp(message$1) {
224
+ return {
225
+ kind: "validation",
226
+ type: "iso_timestamp",
227
+ reference: isoTimestamp,
228
+ async: false,
229
+ expects: null,
230
+ requirement: ISO_TIMESTAMP_REGEX,
231
+ message: message$1,
232
+ "~run"(dataset, config$1) {
233
+ if (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, "timestamp", dataset, config$1);
234
+ return dataset;
235
+ }
236
+ };
237
+ }
238
+ /* @__NO_SIDE_EFFECTS__ */
239
+ function maxValue(requirement, message$1) {
240
+ return {
241
+ kind: "validation",
242
+ type: "max_value",
243
+ reference: maxValue,
244
+ async: false,
245
+ expects: `<=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,
246
+ requirement,
247
+ message: message$1,
248
+ "~run"(dataset, config$1) {
249
+ if (dataset.typed && !(dataset.value <= this.requirement)) _addIssue(this, "value", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });
250
+ return dataset;
251
+ }
252
+ };
253
+ }
254
+ /* @__NO_SIDE_EFFECTS__ */
255
+ function minValue(requirement, message$1) {
256
+ return {
257
+ kind: "validation",
258
+ type: "min_value",
259
+ reference: minValue,
260
+ async: false,
261
+ expects: `>=${requirement instanceof Date ? requirement.toJSON() : /* @__PURE__ */ _stringify(requirement)}`,
262
+ requirement,
263
+ message: message$1,
264
+ "~run"(dataset, config$1) {
265
+ if (dataset.typed && !(dataset.value >= this.requirement)) _addIssue(this, "value", dataset, config$1, { received: dataset.value instanceof Date ? dataset.value.toJSON() : /* @__PURE__ */ _stringify(dataset.value) });
266
+ return dataset;
267
+ }
268
+ };
269
+ }
270
+ /* @__NO_SIDE_EFFECTS__ */
271
+ function regex(requirement, message$1) {
272
+ return {
273
+ kind: "validation",
274
+ type: "regex",
275
+ reference: regex,
276
+ async: false,
277
+ expects: `${requirement}`,
278
+ requirement,
279
+ message: message$1,
280
+ "~run"(dataset, config$1) {
281
+ if (dataset.typed && !this.requirement.test(dataset.value)) _addIssue(this, "format", dataset, config$1);
282
+ return dataset;
283
+ }
284
+ };
285
+ }
286
+ /**
287
+ * Returns the fallback value of the schema.
288
+ *
289
+ * @param schema The schema to get it from.
290
+ * @param dataset The output dataset if available.
291
+ * @param config The config if available.
292
+ *
293
+ * @returns The fallback value.
294
+ */
295
+ /* @__NO_SIDE_EFFECTS__ */
296
+ function getFallback(schema, dataset, config$1) {
297
+ return typeof schema.fallback === "function" ? schema.fallback(dataset, config$1) : schema.fallback;
298
+ }
299
+ /**
300
+ * Returns the default value of the schema.
301
+ *
302
+ * @param schema The schema to get it from.
303
+ * @param dataset The input dataset if available.
304
+ * @param config The config if available.
305
+ *
306
+ * @returns The default value.
307
+ */
308
+ /* @__NO_SIDE_EFFECTS__ */
309
+ function getDefault(schema, dataset, config$1) {
310
+ return typeof schema.default === "function" ? schema.default(dataset, config$1) : schema.default;
311
+ }
312
+ /* @__NO_SIDE_EFFECTS__ */
313
+ function array(item, message$1) {
314
+ return _standardSchema({
315
+ kind: "schema",
316
+ type: "array",
317
+ reference: array,
318
+ expects: "Array",
319
+ async: false,
320
+ item,
321
+ message: message$1,
322
+ "~run"(dataset, config$1) {
323
+ const input = dataset.value;
324
+ if (Array.isArray(input)) {
325
+ dataset.typed = true;
326
+ dataset.value = [];
327
+ for (let key = 0; key < input.length; key++) {
328
+ const value$1 = input[key];
329
+ const itemDataset = this.item["~run"]({ value: value$1 }, config$1);
330
+ if (itemDataset.issues) {
331
+ const pathItem = {
332
+ type: "array",
333
+ origin: "value",
334
+ input,
335
+ key,
336
+ value: value$1
337
+ };
338
+ for (const issue of itemDataset.issues) {
339
+ if (issue.path) issue.path.unshift(pathItem);
340
+ else issue.path = [pathItem];
341
+ dataset.issues?.push(issue);
342
+ }
343
+ if (!dataset.issues) dataset.issues = itemDataset.issues;
344
+ if (config$1.abortEarly) {
345
+ dataset.typed = false;
346
+ break;
347
+ }
348
+ }
349
+ if (!itemDataset.typed) dataset.typed = false;
350
+ dataset.value.push(itemDataset.value);
351
+ }
352
+ } else _addIssue(this, "type", dataset, config$1);
353
+ return dataset;
354
+ }
355
+ });
356
+ }
357
+ /* @__NO_SIDE_EFFECTS__ */
358
+ function boolean(message$1) {
359
+ return _standardSchema({
360
+ kind: "schema",
361
+ type: "boolean",
362
+ reference: boolean,
363
+ expects: "boolean",
364
+ async: false,
365
+ message: message$1,
366
+ "~run"(dataset, config$1) {
367
+ if (typeof dataset.value === "boolean") dataset.typed = true;
368
+ else _addIssue(this, "type", dataset, config$1);
369
+ return dataset;
370
+ }
371
+ });
372
+ }
373
+ /* @__NO_SIDE_EFFECTS__ */
374
+ function nullable(wrapped, default_) {
375
+ return _standardSchema({
376
+ kind: "schema",
377
+ type: "nullable",
378
+ reference: nullable,
379
+ expects: `(${wrapped.expects} | null)`,
380
+ async: false,
381
+ wrapped,
382
+ default: default_,
383
+ "~run"(dataset, config$1) {
384
+ if (dataset.value === null) {
385
+ if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
386
+ if (dataset.value === null) {
387
+ dataset.typed = true;
388
+ return dataset;
389
+ }
390
+ }
391
+ return this.wrapped["~run"](dataset, config$1);
392
+ }
393
+ });
394
+ }
395
+ /* @__NO_SIDE_EFFECTS__ */
396
+ function number(message$1) {
397
+ return _standardSchema({
398
+ kind: "schema",
399
+ type: "number",
400
+ reference: number,
401
+ expects: "number",
402
+ async: false,
403
+ message: message$1,
404
+ "~run"(dataset, config$1) {
405
+ if (typeof dataset.value === "number" && !isNaN(dataset.value)) dataset.typed = true;
406
+ else _addIssue(this, "type", dataset, config$1);
407
+ return dataset;
408
+ }
409
+ });
410
+ }
411
+ /* @__NO_SIDE_EFFECTS__ */
412
+ function object(entries$1, message$1) {
413
+ return _standardSchema({
414
+ kind: "schema",
415
+ type: "object",
416
+ reference: object,
417
+ expects: "Object",
418
+ async: false,
419
+ entries: entries$1,
420
+ message: message$1,
421
+ "~run"(dataset, config$1) {
422
+ const input = dataset.value;
423
+ if (input && typeof input === "object") {
424
+ dataset.typed = true;
425
+ dataset.value = {};
426
+ for (const key in this.entries) {
427
+ const valueSchema = this.entries[key];
428
+ if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
429
+ const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
430
+ const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
431
+ if (valueDataset.issues) {
432
+ const pathItem = {
433
+ type: "object",
434
+ origin: "value",
435
+ input,
436
+ key,
437
+ value: value$1
438
+ };
439
+ for (const issue of valueDataset.issues) {
440
+ if (issue.path) issue.path.unshift(pathItem);
441
+ else issue.path = [pathItem];
442
+ dataset.issues?.push(issue);
443
+ }
444
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
445
+ if (config$1.abortEarly) {
446
+ dataset.typed = false;
447
+ break;
448
+ }
449
+ }
450
+ if (!valueDataset.typed) dataset.typed = false;
451
+ dataset.value[key] = valueDataset.value;
452
+ } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
453
+ else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
454
+ _addIssue(this, "key", dataset, config$1, {
455
+ input: void 0,
456
+ expected: `"${key}"`,
457
+ path: [{
458
+ type: "object",
459
+ origin: "key",
460
+ input,
461
+ key,
462
+ value: input[key]
463
+ }]
464
+ });
465
+ if (config$1.abortEarly) break;
466
+ }
467
+ }
468
+ } else _addIssue(this, "type", dataset, config$1);
469
+ return dataset;
470
+ }
471
+ });
472
+ }
473
+ /* @__NO_SIDE_EFFECTS__ */
474
+ function optional(wrapped, default_) {
475
+ return _standardSchema({
476
+ kind: "schema",
477
+ type: "optional",
478
+ reference: optional,
479
+ expects: `(${wrapped.expects} | undefined)`,
480
+ async: false,
481
+ wrapped,
482
+ default: default_,
483
+ "~run"(dataset, config$1) {
484
+ if (dataset.value === void 0) {
485
+ if (this.default !== void 0) dataset.value = /* @__PURE__ */ getDefault(this, dataset, config$1);
486
+ if (dataset.value === void 0) {
487
+ dataset.typed = true;
488
+ return dataset;
489
+ }
490
+ }
491
+ return this.wrapped["~run"](dataset, config$1);
492
+ }
493
+ });
494
+ }
495
+ /* @__NO_SIDE_EFFECTS__ */
496
+ function picklist(options, message$1) {
497
+ return _standardSchema({
498
+ kind: "schema",
499
+ type: "picklist",
500
+ reference: picklist,
501
+ expects: /* @__PURE__ */ _joinExpects(options.map(_stringify), "|"),
502
+ async: false,
503
+ options,
504
+ message: message$1,
505
+ "~run"(dataset, config$1) {
506
+ if (this.options.includes(dataset.value)) dataset.typed = true;
507
+ else _addIssue(this, "type", dataset, config$1);
508
+ return dataset;
509
+ }
510
+ });
511
+ }
512
+ /* @__NO_SIDE_EFFECTS__ */
513
+ function record(key, value$1, message$1) {
514
+ return _standardSchema({
515
+ kind: "schema",
516
+ type: "record",
517
+ reference: record,
518
+ expects: "Object",
519
+ async: false,
520
+ key,
521
+ value: value$1,
522
+ message: message$1,
523
+ "~run"(dataset, config$1) {
524
+ const input = dataset.value;
525
+ if (input && typeof input === "object") {
526
+ dataset.typed = true;
527
+ dataset.value = {};
528
+ for (const entryKey in input) if (/* @__PURE__ */ _isValidObjectKey(input, entryKey)) {
529
+ const entryValue = input[entryKey];
530
+ const keyDataset = this.key["~run"]({ value: entryKey }, config$1);
531
+ if (keyDataset.issues) {
532
+ const pathItem = {
533
+ type: "object",
534
+ origin: "key",
535
+ input,
536
+ key: entryKey,
537
+ value: entryValue
538
+ };
539
+ for (const issue of keyDataset.issues) {
540
+ issue.path = [pathItem];
541
+ dataset.issues?.push(issue);
542
+ }
543
+ if (!dataset.issues) dataset.issues = keyDataset.issues;
544
+ if (config$1.abortEarly) {
545
+ dataset.typed = false;
546
+ break;
547
+ }
548
+ }
549
+ const valueDataset = this.value["~run"]({ value: entryValue }, config$1);
550
+ if (valueDataset.issues) {
551
+ const pathItem = {
552
+ type: "object",
553
+ origin: "value",
554
+ input,
555
+ key: entryKey,
556
+ value: entryValue
557
+ };
558
+ for (const issue of valueDataset.issues) {
559
+ if (issue.path) issue.path.unshift(pathItem);
560
+ else issue.path = [pathItem];
561
+ dataset.issues?.push(issue);
562
+ }
563
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
564
+ if (config$1.abortEarly) {
565
+ dataset.typed = false;
566
+ break;
567
+ }
568
+ }
569
+ if (!keyDataset.typed || !valueDataset.typed) dataset.typed = false;
570
+ if (keyDataset.typed) dataset.value[keyDataset.value] = valueDataset.value;
571
+ }
572
+ } else _addIssue(this, "type", dataset, config$1);
573
+ return dataset;
574
+ }
575
+ });
576
+ }
577
+ /* @__NO_SIDE_EFFECTS__ */
578
+ function strictObject(entries$1, message$1) {
579
+ return _standardSchema({
580
+ kind: "schema",
581
+ type: "strict_object",
582
+ reference: strictObject,
583
+ expects: "Object",
584
+ async: false,
585
+ entries: entries$1,
586
+ message: message$1,
587
+ "~run"(dataset, config$1) {
588
+ const input = dataset.value;
589
+ if (input && typeof input === "object") {
590
+ dataset.typed = true;
591
+ dataset.value = {};
592
+ for (const key in this.entries) {
593
+ const valueSchema = this.entries[key];
594
+ if (key in input || (valueSchema.type === "exact_optional" || valueSchema.type === "optional" || valueSchema.type === "nullish") && valueSchema.default !== void 0) {
595
+ const value$1 = key in input ? input[key] : /* @__PURE__ */ getDefault(valueSchema);
596
+ const valueDataset = valueSchema["~run"]({ value: value$1 }, config$1);
597
+ if (valueDataset.issues) {
598
+ const pathItem = {
599
+ type: "object",
600
+ origin: "value",
601
+ input,
602
+ key,
603
+ value: value$1
604
+ };
605
+ for (const issue of valueDataset.issues) {
606
+ if (issue.path) issue.path.unshift(pathItem);
607
+ else issue.path = [pathItem];
608
+ dataset.issues?.push(issue);
609
+ }
610
+ if (!dataset.issues) dataset.issues = valueDataset.issues;
611
+ if (config$1.abortEarly) {
612
+ dataset.typed = false;
613
+ break;
614
+ }
615
+ }
616
+ if (!valueDataset.typed) dataset.typed = false;
617
+ dataset.value[key] = valueDataset.value;
618
+ } else if (valueSchema.fallback !== void 0) dataset.value[key] = /* @__PURE__ */ getFallback(valueSchema);
619
+ else if (valueSchema.type !== "exact_optional" && valueSchema.type !== "optional" && valueSchema.type !== "nullish") {
620
+ _addIssue(this, "key", dataset, config$1, {
621
+ input: void 0,
622
+ expected: `"${key}"`,
623
+ path: [{
624
+ type: "object",
625
+ origin: "key",
626
+ input,
627
+ key,
628
+ value: input[key]
629
+ }]
630
+ });
631
+ if (config$1.abortEarly) break;
632
+ }
633
+ }
634
+ if (!dataset.issues || !config$1.abortEarly) {
635
+ for (const key in input) if (!Object.prototype.hasOwnProperty.call(this.entries, key)) {
636
+ _addIssue(this, "key", dataset, config$1, {
637
+ input: key,
638
+ expected: "never",
639
+ path: [{
640
+ type: "object",
641
+ origin: "key",
642
+ input,
643
+ key,
644
+ value: input[key]
645
+ }]
646
+ });
647
+ break;
648
+ }
649
+ }
650
+ } else _addIssue(this, "type", dataset, config$1);
651
+ return dataset;
652
+ }
653
+ });
654
+ }
655
+ /* @__NO_SIDE_EFFECTS__ */
656
+ function string(message$1) {
657
+ return _standardSchema({
658
+ kind: "schema",
659
+ type: "string",
660
+ reference: string,
661
+ expects: "string",
662
+ async: false,
663
+ message: message$1,
664
+ "~run"(dataset, config$1) {
665
+ if (typeof dataset.value === "string") dataset.typed = true;
666
+ else _addIssue(this, "type", dataset, config$1);
667
+ return dataset;
668
+ }
669
+ });
670
+ }
671
+ /**
672
+ * Creates a unknown schema.
673
+ *
674
+ * @returns A unknown schema.
675
+ */
676
+ /* @__NO_SIDE_EFFECTS__ */
677
+ function unknown() {
678
+ return _standardSchema({
679
+ kind: "schema",
680
+ type: "unknown",
681
+ reference: unknown,
682
+ expects: "unknown",
683
+ async: false,
684
+ "~run"(dataset) {
685
+ dataset.typed = true;
686
+ return dataset;
687
+ }
688
+ });
689
+ }
690
+ /* @__NO_SIDE_EFFECTS__ */
691
+ function pipe(...pipe$1) {
692
+ return _standardSchema({
693
+ ...pipe$1[0],
694
+ pipe: pipe$1,
695
+ "~run"(dataset, config$1) {
696
+ for (const item of pipe$1) if (item.kind !== "metadata") {
697
+ if (dataset.issues && (item.kind === "schema" || item.kind === "transformation")) {
698
+ dataset.typed = false;
699
+ break;
700
+ }
701
+ if (!dataset.issues || !config$1.abortEarly && !config$1.abortPipeEarly) dataset = item["~run"](dataset, config$1);
702
+ }
703
+ return dataset;
704
+ }
705
+ });
706
+ }
707
+ /**
708
+ * Parses an unknown input based on a schema.
709
+ *
710
+ * @param schema The schema to be used.
711
+ * @param input The input to be parsed.
712
+ * @param config The parse configuration.
713
+ *
714
+ * @returns The parse result.
715
+ */
716
+ /* @__NO_SIDE_EFFECTS__ */
717
+ function safeParse(schema, input, config$1) {
718
+ const dataset = schema["~run"]({ value: input }, /* @__PURE__ */ getGlobalConfig(config$1));
719
+ return {
720
+ typed: dataset.typed,
721
+ success: !dataset.issues,
722
+ output: dataset.value,
723
+ issues: dataset.issues
724
+ };
725
+ }
726
+ // ../shared/src/limits.ts
727
+ /** Ranges of the speech endpoints. */
728
+ const API_LIMITS = {
729
+ /** `GET /speech?limit=`: the default and the most a caller may ask for. */
730
+ list: {
731
+ default: 1e3,
732
+ max: 1e4
733
+ },
734
+ wait: {
735
+ /** `GET /speech/wait?timeoutMs=`. */
736
+ timeoutMs: {
737
+ default: 5e3,
738
+ max: 3e5
739
+ },
740
+ /** Entries the timeout answer holds at most: the last ones seen. */
741
+ seen: 1e3,
742
+ /** Longest `regex`. */
743
+ regexLength: 500
744
+ },
745
+ /** Longest marker label (trimmed). */
746
+ markerLength: 1e3,
747
+ /** Longest session `name`, `run` or client name (trimmed). */
748
+ sessionLabelLength: 1e3,
749
+ /** `POST /input/click` and `POST /input/keys`. */
750
+ input: {
751
+ /** Largest absolute screen coordinate (physical pixels). */
752
+ coordinate: 1e5,
753
+ /** Pause between the chords of a sequence. */
754
+ delayMs: {
755
+ default: 50,
756
+ max: 1e4
757
+ },
758
+ /** Most chords in one request. */
759
+ maxKeys: 100
760
+ }
761
+ };
762
+ /** Ranges of the settings (`GET` / `PUT /config`). */
763
+ const CONFIG_LIMITS = {
764
+ port: {
765
+ min: 0,
766
+ max: 65535
767
+ },
768
+ maxLineBytes: {
769
+ min: 1024,
770
+ max: 16777216
771
+ },
772
+ maxEntries: {
773
+ min: 1,
774
+ max: 1e6
775
+ }
776
+ };
777
+ /**
778
+ * An exact npm version (`1.56.1`, `1.57.0-beta-1`): `playwright.version` ends up on an
779
+ * `npm install` command line, so nothing else may get through.
780
+ */
781
+ const EXACT_VERSION_PATTERN = /^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/;
782
+ /** A host name without port or scheme, or `*` (`http.allowedHosts`). */
783
+ const HOST_NAME_PATTERN = /^(\*|[A-Za-z0-9]([A-Za-z0-9.-]*[A-Za-z0-9])?)$/;
784
+ /** Whether `text` is a usable label: not empty after trimming, at most `max` characters trimmed. */
785
+ const isTrimmedLabel = (text, max) => {
786
+ const trimmed = text.trim();
787
+ return trimmed !== "" && trimmed.length <= max;
788
+ };
789
+ // ../shared/src/config.ts
790
+ /** A `TextDecoder` label other than UTF-16 (the framing splits the bytes on 0x0A first). */
791
+ function isSupportedEncoding(label) {
792
+ try {
793
+ return !new TextDecoder(label).encoding.startsWith("utf-16");
794
+ } catch {
795
+ return false;
796
+ }
797
+ }
798
+ const LOG_LEVELS = [
799
+ "error",
800
+ "warn",
801
+ "info",
802
+ "debug"
803
+ ];
804
+ const range = ({ min, max }) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min), /* @__PURE__ */ maxValue(max));
805
+ const port = range(CONFIG_LIMITS.port);
806
+ /** Port of a child service: `0` ("any free port") would leave the bridge no port to proxy to. */
807
+ const childPort = range({
808
+ min: 1,
809
+ max: CONFIG_LIMITS.port.max
810
+ });
811
+ const nonBlank = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ regex(/\S/), /* @__PURE__ */ description("Not empty or blank."));
812
+ const AllowedHostsSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ array(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ regex(HOST_NAME_PATTERN))), /* @__PURE__ */ description("Host names the API answers to besides IP addresses, `localhost` and the machine's name. Without port or scheme. `[\"*\"]` accepts any name. Added in API 1.5."));
813
+ const ServiceConfigSchema = /* @__PURE__ */ object({
814
+ enabled: /* @__PURE__ */ boolean(),
815
+ port: childPort,
816
+ version: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ regex(EXACT_VERSION_PATTERN))), /* @__PURE__ */ description("`null` = bundled version. Otherwise an exact version like `1.65.0`."))
817
+ });
818
+ const sections = {
819
+ tcp: {
820
+ host: nonBlank,
821
+ port,
822
+ encoding: /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ check(isSupportedEncoding), /* @__PURE__ */ description("TextDecoder label of the socket voice's code page. Not `utf-16*`: lines are split on bytes.")),
823
+ maxLineBytes: range(CONFIG_LIMITS.maxLineBytes)
824
+ },
825
+ http: {
826
+ host: nonBlank,
827
+ port,
828
+ allowedHosts: AllowedHostsSchema
829
+ },
830
+ buffer: { maxEntries: range(CONFIG_LIMITS.maxEntries) },
831
+ log: {
832
+ level: /* @__PURE__ */ picklist(LOG_LEVELS),
833
+ file: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(nonBlank), /* @__PURE__ */ description("Bridge log file, `null` = default path.")),
834
+ consoleSpeech: /* @__PURE__ */ pipe(/* @__PURE__ */ boolean(), /* @__PURE__ */ description("Also write the speech text to the console."))
835
+ }
836
+ };
837
+ sections.tcp, sections.http, sections.buffer, sections.log;
838
+ /** A section with every setting optional and no others allowed. */
839
+ const patchOf = (entries) => /* @__PURE__ */ strictObject(Object.fromEntries(Object.entries(entries).map(([key, schema]) => [key, /* @__PURE__ */ optional(schema)])));
840
+ patchOf(ServiceConfigSchema.entries);
841
+ patchOf({
842
+ enabled: /* @__PURE__ */ boolean(),
843
+ port: childPort
844
+ });
845
+ patchOf(sections.tcp), patchOf(sections.http), patchOf(sections.buffer), patchOf(sections.log);
846
+ // ../shared/src/input.ts
847
+ const { coordinate, delayMs, maxKeys } = API_LIMITS.input;
848
+ -coordinate, -coordinate;
849
+ `${maxKeys}`, delayMs.max, `${delayMs.default}`;
850
+ // ../shared/src/services.ts
851
+ /** The Playwright server (`connectOptions.wsEndpoint`): `ws://<bridge>:5151/playwright`. */
852
+ const PLAYWRIGHT_PATH = "/playwright";
853
+ // ../shared/src/session.ts
854
+ const integer$2 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
855
+ const timestamp$2 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
856
+ const label = (text) => /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ check((text) => isTrimmedLabel(text, API_LIMITS.sessionLabelLength)), /* @__PURE__ */ description(`${text} Trimmed, must not be empty, at most ${API_LIMITS.sessionLabelLength} characters.`));
857
+ const sessionEntries = {
858
+ id: /* @__PURE__ */ pipe(integer$2(1), /* @__PURE__ */ description("Increasing, restarts at 1 with the bridge.")),
859
+ name: /* @__PURE__ */ string(),
860
+ run: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Optional label that groups sessions.")),
861
+ client: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Who started it: the `X-SR-Speech-Client` header, `null` if it wasn't sent. Added in API 1.10.")),
862
+ startedAt: timestamp$2,
863
+ endedAt: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(timestamp$2), /* @__PURE__ */ description("`null` while the session is current.")),
864
+ startSeq: /* @__PURE__ */ pipe(integer$2(0), /* @__PURE__ */ description("The last `seq` given out before the session started: `since=startSeq` reads the session from its start. Added in API 1.9.")),
865
+ firstSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$2(1)), /* @__PURE__ */ description("First entry still in the buffer, `null` if none.")),
866
+ lastSeq: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$2(1)), /* @__PURE__ */ description("Last entry still in the buffer, `null` if none.")),
867
+ entries: /* @__PURE__ */ pipe(integer$2(0), /* @__PURE__ */ description("Entries of this session still in the buffer."))
868
+ };
869
+ const SessionSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ object(sessionEntries), /* @__PURE__ */ description("A session (docs/usage/speech-capture.md#sessions). Added in API 1.3."), /* @__PURE__ */ examples([{
870
+ id: 7,
871
+ name: "form › submit button is announced",
872
+ run: "nightly-42",
873
+ client: "ci-runner pid 4242",
874
+ startedAt: "2026-11-12T09:31:04.120Z",
875
+ endedAt: null,
876
+ startSeq: 339,
877
+ firstSeq: 340,
878
+ lastSeq: 342,
879
+ entries: 3
880
+ }]));
881
+ label("For example the test title."), label("Optional label that groups sessions, for example one per test run.");
882
+ const StartSessionResponseSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ object({
883
+ ...sessionEntries,
884
+ replaced: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(SessionSchema), /* @__PURE__ */ description("The session this start ended if another client had started it, `null` otherwise. Added in API 1.10."))
885
+ }), /* @__PURE__ */ description("`POST /sessions`: the new session, plus `replaced`."));
886
+ /**
887
+ * Request header naming the client (for example `host pid 1234`), so the bridge can tell when
888
+ * one client ends or replaces another one's session. Optional. API 1.10.
889
+ */
890
+ const CLIENT_HEADER = "x-sr-speech-client";
891
+ const SessionListSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ object({
892
+ sessions: /* @__PURE__ */ array(SessionSchema),
893
+ currentId: /* @__PURE__ */ nullable(integer$2(1))
894
+ }), /* @__PURE__ */ description("`GET /sessions`: the current session and the ended ones with entries in the buffer, newest first."));
895
+ // ../shared/src/speech.ts
896
+ const integer$1 = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
897
+ const timestamp$1 = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
898
+ const SpeechEntrySchema = /* @__PURE__ */ pipe(/* @__PURE__ */ object({
899
+ seq: /* @__PURE__ */ pipe(integer$1(1), /* @__PURE__ */ description("Increasing sequence number. Survives clear and keeps rising across restarts: the first entry of a bridge run gets the run's start time in milliseconds.")),
900
+ kind: /* @__PURE__ */ picklist(["speech", "marker"]),
901
+ text: /* @__PURE__ */ string(),
902
+ receivedAt: /* @__PURE__ */ pipe(timestamp$1, /* @__PURE__ */ description("When the bridge received the line (UTC).")),
903
+ source: /* @__PURE__ */ pipe(/* @__PURE__ */ picklist(["tcp", "api"]), /* @__PURE__ */ description("`tcp` for speech, `api` for markers.")),
904
+ voice: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ string()), /* @__PURE__ */ description("Header (`voice=<id>`) of the sending voice, `null` if not set or for markers.")),
905
+ connectionId: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(integer$1(1)), /* @__PURE__ */ description("TCP connection that delivered it, `null` for markers.")),
906
+ sessionId: /* @__PURE__ */ pipe(/* @__PURE__ */ optional(/* @__PURE__ */ nullable(integer$1(1))), /* @__PURE__ */ description("The session that was current, `null` outside any session. Added in API 1.3."))
907
+ }), /* @__PURE__ */ description("One recorded speech line or a marker."), /* @__PURE__ */ examples([{
908
+ seq: 42,
909
+ kind: "speech",
910
+ text: "Submit, button",
911
+ receivedAt: "2026-11-07T14:03:12.345Z",
912
+ source: "tcp",
913
+ voice: "ssc5000",
914
+ connectionId: 3,
915
+ sessionId: 7
916
+ }]));
917
+ const SpeechListSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ object({
918
+ entries: /* @__PURE__ */ array(SpeechEntrySchema),
919
+ truncated: /* @__PURE__ */ pipe(/* @__PURE__ */ boolean(), /* @__PURE__ */ description("`true` when entries after `since` were dropped because the buffer was full.")),
920
+ hasMore: /* @__PURE__ */ pipe(/* @__PURE__ */ boolean(), /* @__PURE__ */ description("`true` when more entries follow: ask again with the last entry's `seq` as `since`."))
921
+ }), /* @__PURE__ */ description("`GET /speech`: a page of entries after `since`, oldest first."));
922
+ API_LIMITS.wait.seen, `${API_LIMITS.wait.seen}`;
923
+ `${API_LIMITS.markerLength}`;
924
+ // ../shared/src/status.ts
925
+ const integer = (min) => /* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3(), /* @__PURE__ */ minValue(min));
926
+ const timestamp = /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ isoTimestamp());
927
+ const BRIDGE_STATES = [
928
+ "starting",
929
+ "ready",
930
+ "stopping"
931
+ ];
932
+ const ServiceStatusSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ object({
933
+ state: /* @__PURE__ */ pipe(/* @__PURE__ */ picklist([
934
+ "stopped",
935
+ "starting",
936
+ "running",
937
+ "crashed",
938
+ "failed"
939
+ ]), /* @__PURE__ */ description("`starting` includes the install. `crashed`: it exited and restarts after a delay. `failed`: 5 crashes in a row; restart the bridge (or change the service's settings).")),
940
+ version: /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ description("The version that runs (configured or bundled)."), /* @__PURE__ */ examples(["1.65.0"])),
941
+ port: integer(0),
942
+ restarts: /* @__PURE__ */ pipe(integer(0), /* @__PURE__ */ description("Restarts after crashes since the service was last started (bridge start or config change).")),
943
+ exitCode: /* @__PURE__ */ pipe(/* @__PURE__ */ nullable(/* @__PURE__ */ pipe(/* @__PURE__ */ number(), /* @__PURE__ */ integer$3())), /* @__PURE__ */ description("Exit code of the last unexpected exit. `null` if none, or killed by a signal."))
944
+ }), /* @__PURE__ */ description("A child service (docs/usage/operations.md#child-service-crashes)."));
945
+ const ConnectionSchema = /* @__PURE__ */ object({
946
+ id: integer(1),
947
+ voice: /* @__PURE__ */ nullable(/* @__PURE__ */ string()),
948
+ connectedAt: timestamp
949
+ });
950
+ const StatusSchema = /* @__PURE__ */ pipe(/* @__PURE__ */ object({
951
+ bridge: /* @__PURE__ */ object({
952
+ version: /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ description("Package version of the bridge."), /* @__PURE__ */ examples(["0.3.0"])),
953
+ apiVersion: /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ description("`<major>.<minor>` of this API."), /* @__PURE__ */ examples(["1.13"])),
954
+ state: /* @__PURE__ */ picklist(BRIDGE_STATES),
955
+ startedAt: /* @__PURE__ */ pipe(timestamp, /* @__PURE__ */ description("When this bridge run started. Added in API 1.4."))
956
+ }),
957
+ tcp: /* @__PURE__ */ object({
958
+ listening: /* @__PURE__ */ boolean(),
959
+ host: /* @__PURE__ */ string(),
960
+ port: integer(0),
961
+ encoding: /* @__PURE__ */ pipe(/* @__PURE__ */ string(), /* @__PURE__ */ description("Code page used to decode the socket voice.")),
962
+ connections: /* @__PURE__ */ pipe(/* @__PURE__ */ array(ConnectionSchema), /* @__PURE__ */ description("Open connections, oldest first."))
963
+ }),
964
+ buffer: /* @__PURE__ */ object({
965
+ size: integer(0),
966
+ maxEntries: integer(1),
967
+ firstSeq: /* @__PURE__ */ nullable(integer(1)),
968
+ lastSeq: /* @__PURE__ */ nullable(integer(1))
969
+ }),
970
+ playwright: ServiceStatusSchema,
971
+ mcp: ServiceStatusSchema,
972
+ session: /* @__PURE__ */ pipe(/* @__PURE__ */ object({
973
+ current: /* @__PURE__ */ nullable(SessionSchema),
974
+ count: /* @__PURE__ */ pipe(integer(0), /* @__PURE__ */ description("Number of sessions `GET /sessions` lists."))
975
+ }), /* @__PURE__ */ description("Added in API 1.3."))
976
+ }), /* @__PURE__ */ description("`GET /status`. `playwright` since API 1.1, `mcp` since 1.2, `session` since 1.3."));
977
+ // ../shared/src/text-match.ts
978
+ /**
979
+ * The `normalize` rule of the HTTP API (docs/usage/http-api.md). The bridge applies it in
980
+ * `GET /speech/wait`, the client in its own waits, so both must use this one copy. It is the only
981
+ * behaviour in this package: it belongs to the contract, not to either side.
982
+ */
983
+ /** Lower case, whitespace runs collapsed to one space, trimmed. */
984
+ function normalizeText(text) {
985
+ return text.toLowerCase().replace(/\s+/g, " ").trim();
986
+ }
987
+ /**
988
+ * Test for a substring or a regular expression. With `normalize`, the text (and a substring) go
989
+ * through {@link normalizeText} and a regular expression gets the `i` flag. `g` / `y` are dropped,
990
+ * so the test keeps no state between texts. Returns `undefined` for an empty substring (after
991
+ * normalizing); callers report that in their own way.
992
+ */
993
+ function createTextTest(match, normalize) {
994
+ const prepare = normalize ? normalizeText : (text) => text;
995
+ if (match instanceof RegExp) {
996
+ let flags = match.flags.replace(/[gy]/g, "");
997
+ if (normalize && !flags.includes("i")) flags += "i";
998
+ const pattern = new RegExp(match.source, flags);
999
+ return (text) => pattern.test(prepare(text));
1000
+ }
1001
+ const needle = prepare(match);
1002
+ if (needle === "") return void 0;
1003
+ return (text) => prepare(text).includes(needle);
1004
+ }
1005
+ // ../shared/src/validate.ts
1006
+ /**
1007
+ * Checks `value` against `schema`. Unknown keys don't fail it and are left out of the result: a
1008
+ * newer bridge of the same major version may add fields.
1009
+ */
1010
+ function checkDto(schema, value) {
1011
+ const result = /* @__PURE__ */ safeParse(schema, value);
1012
+ if (result.success) return {
1013
+ ok: true,
1014
+ value: result.output
1015
+ };
1016
+ const [issue] = result.issues;
1017
+ return {
1018
+ ok: false,
1019
+ field: /* @__PURE__ */ getDotPath(issue) ?? "(body)",
1020
+ message: issue.message
1021
+ };
1022
+ }
1023
+ /** Just enough of `GET /status` to check the API version before anything else. */
1024
+ const ApiVersionSchema = /* @__PURE__ */ object({ bridge: /* @__PURE__ */ object({ apiVersion: /* @__PURE__ */ string() }) });
1025
+ /**
1026
+ * An error body as a client must accept it: like `ErrorBodySchema`, but with any `code`, since
1027
+ * new codes may come in minor versions.
1028
+ */
1029
+ const AnyErrorBodySchema = /* @__PURE__ */ object({ error: /* @__PURE__ */ object({
1030
+ code: /* @__PURE__ */ string(),
1031
+ message: /* @__PURE__ */ string(),
1032
+ details: /* @__PURE__ */ optional(/* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ unknown()))
1033
+ }) });
1034
+ // src/adapters/out/clock/system-clock.ts
1035
+ var SystemClock = class {
1036
+ now() {
1037
+ return performance.now();
1038
+ }
1039
+ async sleep(ms, signal) {
1040
+ await setTimeout$1(ms, void 0, signal ? { signal } : void 0);
1041
+ }
1042
+ };
1043
+ // src/domain/errors.ts
1044
+ /**
1045
+ * A wait ended without a match. `entries` holds the speech seen while waiting, oldest first.
1046
+ * `truncated`: some of the speech it should have looked at was dropped because the bridge's
1047
+ * buffer was full, so the match may have been among it.
1048
+ */
1049
+ var SpeechTimeoutError = class extends Error {
1050
+ entries;
1051
+ truncated;
1052
+ name = "SpeechTimeoutError";
1053
+ constructor(message, entries, truncated = false) {
1054
+ super(truncated ? `${message}; ${TRUNCATED_HINT}` : message);
1055
+ this.entries = entries;
1056
+ this.truncated = truncated;
1057
+ }
1058
+ };
1059
+ /**
1060
+ * `getSpeech` / `getText` without `allowTruncated`: some of the speech asked for was dropped
1061
+ * because the bridge's buffer was full, so the read would be incomplete. `entries` holds what is
1062
+ * left, oldest first.
1063
+ */
1064
+ var SpeechTruncatedError = class extends Error {
1065
+ since;
1066
+ entries;
1067
+ name = "SpeechTruncatedError";
1068
+ constructor(since, entries) {
1069
+ super(`Speech after seq ${since} is incomplete: ${TRUNCATED_HINT}. Pass allowTruncated: true to read what is left.`);
1070
+ this.since = since;
1071
+ this.entries = entries;
1072
+ }
1073
+ };
1074
+ /** Why a wait or recording may have missed speech, and what to do about it. */
1075
+ const TRUNCATED_HINT = "some speech was dropped because the bridge's buffer was full (raise buffer.maxEntries)";
1076
+ /** `waitForReady` timed out: the bridge was not reachable or not `ready` in time. */
1077
+ var BridgeNotReadyError = class extends Error {
1078
+ name = "BridgeNotReadyError";
1079
+ };
1080
+ /** The bridge speaks another major version of the HTTP API (docs/usage/http-api.md#versioning). */
1081
+ var IncompatibleBridgeError = class extends Error {
1082
+ bridgeApiVersion;
1083
+ clientApiVersion;
1084
+ name = "IncompatibleBridgeError";
1085
+ constructor(bridgeApiVersion, clientApiVersion) {
1086
+ super(`The bridge speaks API ${bridgeApiVersion}, this client needs API ${clientApiVersion}. Install the bridge and the client in the same version.`);
1087
+ this.bridgeApiVersion = bridgeApiVersion;
1088
+ this.clientApiVersion = clientApiVersion;
1089
+ }
1090
+ };
1091
+ /** No connection to the bridge (wrong URL, bridge not running, network). */
1092
+ var BridgeUnreachableError = class extends Error {
1093
+ url;
1094
+ name = "BridgeUnreachableError";
1095
+ constructor(url, options) {
1096
+ const reason = describeCause(options?.cause);
1097
+ super(`The bridge at ${url} is not reachable${reason ? ` (${reason})` : ""}`, options);
1098
+ this.url = url;
1099
+ }
1100
+ };
1101
+ /**
1102
+ * `BridgeHttpError.code` when the bridge's answer doesn't match the API contract: a wrong
1103
+ * version, a proxy, a bug. Asking again won't help.
1104
+ */
1105
+ const INVALID_RESPONSE = "INVALID_RESPONSE";
1106
+ /** The bridge answered with an error (docs/usage/http-api.md#errors). */
1107
+ var BridgeHttpError = class extends Error {
1108
+ status;
1109
+ code;
1110
+ details;
1111
+ name = "BridgeHttpError";
1112
+ constructor(status, code, message, details) {
1113
+ super(`${message} (HTTP ${status}, ${code})`);
1114
+ this.status = status;
1115
+ this.code = code;
1116
+ this.details = details;
1117
+ }
1118
+ };
1119
+ function describeCause(cause) {
1120
+ if (!(cause instanceof Error)) return void 0;
1121
+ const inner = cause.cause;
1122
+ if (typeof inner === "object" && inner !== null && "code" in inner) return String(inner.code);
1123
+ return inner instanceof Error ? inner.message : cause.message;
1124
+ }
1125
+ /** The config file or a configured value is invalid. */
1126
+ var ClientConfigError = class extends Error {
1127
+ name = "ClientConfigError";
1128
+ };
1129
+ // src/domain/bridge-url.ts
1130
+ /** Bridge URL used when nothing else is configured. */
1131
+ const DEFAULT_BRIDGE_URL = "http://localhost:5151";
1132
+ /** Environment variable with the bridge URL. */
1133
+ const URL_ENV = "SR_SPEECH_URL";
1134
+ /**
1135
+ * Checks a bridge URL and returns it normalised: only `http:` / `https:`, no trailing slash, so
1136
+ * API paths can be appended directly.
1137
+ */
1138
+ function normalizeBridgeUrl(input, origin = "URL") {
1139
+ let url;
1140
+ try {
1141
+ url = new URL(input.trim());
1142
+ } catch {
1143
+ throw new ClientConfigError(`${origin} "${input}" is not a valid URL (e.g. http://my-vm:5151)`);
1144
+ }
1145
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new ClientConfigError(`${origin} "${input}" must start with http:// or https://`);
1146
+ if (url.search !== "" || url.hash !== "") throw new ClientConfigError(`${origin} "${input}" must not contain a query or fragment`);
1147
+ return url.href.replace(/\/+$/, "");
1148
+ }
1149
+ const isSet = (value) => value !== void 0 && value !== "";
1150
+ /** True if the stored value can't win, so the config file doesn't have to be read. */
1151
+ const overridesStored = (sources) => isSet(sources.explicit) || isSet(sources.env);
1152
+ /**
1153
+ * The bridge URL to use: explicit value, then `SR_SPEECH_URL`, then the config file, then
1154
+ * {@link DEFAULT_BRIDGE_URL}.
1155
+ */
1156
+ function pickBridgeUrl(sources) {
1157
+ if (isSet(sources.explicit)) return {
1158
+ value: normalizeBridgeUrl(sources.explicit),
1159
+ source: "explicit"
1160
+ };
1161
+ if (isSet(sources.env)) return {
1162
+ value: normalizeBridgeUrl(sources.env, URL_ENV),
1163
+ source: "env"
1164
+ };
1165
+ if (isSet(sources.stored)) return {
1166
+ value: sources.stored,
1167
+ source: "config"
1168
+ };
1169
+ return {
1170
+ value: DEFAULT_BRIDGE_URL,
1171
+ source: "default"
1172
+ };
1173
+ }
1174
+ // src/domain/client-config.ts
1175
+ /** Checks the parsed content of a config file. `origin` names the file in errors. */
1176
+ function parseClientConfig(raw, origin) {
1177
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new ClientConfigError(`The client config file ${origin} must contain a JSON object`);
1178
+ const { url } = raw;
1179
+ if (url === void 0) return {};
1180
+ if (typeof url !== "string") throw new ClientConfigError(`"url" in the client config file ${origin} must be a string`);
1181
+ return { url: normalizeBridgeUrl(url, `"url" in ${origin}`) };
1182
+ }
1183
+ /** Keys the client config stores, each with the check that normalises a value before saving. */
1184
+ const CONFIG_KEYS = { url: (value) => normalizeBridgeUrl(value) };
1185
+ /** Checks a key name given by a user. */
1186
+ function parseConfigKey(key) {
1187
+ if (Object.hasOwn(CONFIG_KEYS, key)) return key;
1188
+ throw new ClientConfigError(`Unknown config key "${key}". Known keys: ${Object.keys(CONFIG_KEYS).join(", ")}.`);
1189
+ }
1190
+ // src/adapters/out/fs-config/fs-client-config-store.ts
1191
+ /**
1192
+ * The client config file (docs/usage/client.md#bridge-url): JSON, one per user. Keys this version
1193
+ * doesn't know are kept when saving.
1194
+ */
1195
+ var FsClientConfigStore = class {
1196
+ location;
1197
+ constructor(location) {
1198
+ this.location = location;
1199
+ }
1200
+ async load() {
1201
+ return parseClientConfig(await this.readRaw(), this.location);
1202
+ }
1203
+ /**
1204
+ * Writes a temporary file, flushes it to disk and renames it, so a crash never leaves half a
1205
+ * file. Values already
1206
+ * in the file aren't checked, so `config set` can repair an invalid one.
1207
+ */
1208
+ async save(patch) {
1209
+ const raw = await this.readRaw();
1210
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new ClientConfigError(`The client config file ${this.location} must contain a JSON object`);
1211
+ const next = { ...raw };
1212
+ for (const [key, value] of Object.entries(patch)) if (value === void 0) delete next[key];
1213
+ else next[key] = value;
1214
+ await fs.mkdir(path.dirname(this.location), { recursive: true });
1215
+ const temporary = `${this.location}.${process.pid}.tmp`;
1216
+ try {
1217
+ const handle = await fs.open(temporary, "w");
1218
+ try {
1219
+ await handle.writeFile(`${JSON.stringify(next, null, 2)}\n`, "utf8");
1220
+ await handle.sync();
1221
+ } finally {
1222
+ await handle.close();
1223
+ }
1224
+ await fs.rename(temporary, this.location);
1225
+ } catch (error) {
1226
+ await fs.rm(temporary, { force: true });
1227
+ throw error;
1228
+ }
1229
+ }
1230
+ /** The parsed file, `{}` if it doesn't exist. */
1231
+ async readRaw() {
1232
+ let text;
1233
+ try {
1234
+ text = await fs.readFile(this.location, "utf8");
1235
+ } catch (error) {
1236
+ if (error.code === "ENOENT") return {};
1237
+ throw new ClientConfigError(`Cannot read the client config file ${this.location}: ${error.message}`, { cause: error });
1238
+ }
1239
+ try {
1240
+ return JSON.parse(text.replace(/^\uFEFF/, ""));
1241
+ } catch (error) {
1242
+ throw new ClientConfigError(`The client config file ${this.location} is not valid JSON: ${error.message}`, { cause: error });
1243
+ }
1244
+ }
1245
+ };
1246
+ // ../shared/src/platform-paths.ts
1247
+ /** The folder name under each per-user base directory. */
1248
+ const APP_DIR_NAME = "screenreader-speech-capture";
1249
+ function currentHost() {
1250
+ return {
1251
+ platform: process.platform,
1252
+ env: process.env,
1253
+ home: os.homedir()
1254
+ };
1255
+ }
1256
+ /**
1257
+ * `<base>/screenreader-speech-capture/<...segments>` for `kind`. Windows uses `%APPDATA%` /
1258
+ * `%LOCALAPPDATA%` (or their default under the home directory); Linux and macOS use the XDG
1259
+ * directories, for development.
1260
+ */
1261
+ function appDir(kind, segments = [], { platform, env, home } = currentHost()) {
1262
+ if (platform === "win32") {
1263
+ const base = kind === "config" ? env.APPDATA ?? path.win32.join(home, "AppData", "Roaming") : env.LOCALAPPDATA ?? path.win32.join(home, "AppData", "Local");
1264
+ return path.win32.join(base, APP_DIR_NAME, ...segments);
1265
+ }
1266
+ const xdg = {
1267
+ config: env.XDG_CONFIG_HOME ?? path.posix.join(home, ".config"),
1268
+ state: env.XDG_STATE_HOME ?? path.posix.join(home, ".local", "state"),
1269
+ cache: env.XDG_CACHE_HOME ?? path.posix.join(home, ".cache")
1270
+ };
1271
+ return path.posix.join(xdg[kind], APP_DIR_NAME, ...segments);
1272
+ }
1273
+ // src/adapters/out/fs-config/paths.ts
1274
+ /** Environment variable that points the client at a different config file. */
1275
+ const CONFIG_PATH_ENV = "SR_SPEECH_CLIENT_CONFIG";
1276
+ /**
1277
+ * The client's config file: `%APPDATA%\screenreader-speech-capture\client.json` on Windows,
1278
+ * `$XDG_CONFIG_HOME` (or `~/.config`) + `screenreader-speech-capture/client.json` on Linux and
1279
+ * macOS. It sits next to the bridge's `config.json` (both come from `appDir('config')` in
1280
+ * `packages/shared`) but is a separate file, so a bridge and a client on the same machine never
1281
+ * share settings. `SR_SPEECH_CLIENT_CONFIG` overrides the path.
1282
+ */
1283
+ function clientConfigFile(platform = process.platform, env = process.env, home = os.homedir()) {
1284
+ const override = env[CONFIG_PATH_ENV];
1285
+ if (override !== void 0 && override !== "") return override;
1286
+ return appDir("config", ["client.json"], {
1287
+ platform,
1288
+ env,
1289
+ home
1290
+ });
1291
+ }
1292
+ // src/domain/api-version.ts
1293
+ /** The major version of a `<major>.<minor>` API version, `undefined` if it isn't one. */
1294
+ function major(version) {
1295
+ const match = /^(\d+)\.\d+$/.exec(version);
1296
+ return match ? Number(match[1]) : void 0;
1297
+ }
1298
+ /**
1299
+ * Throws {@link IncompatibleBridgeError} unless the bridge's API has the client's major version
1300
+ * (docs/usage/http-api.md#versioning). Any minor version is accepted: the bridge and the client are
1301
+ * released together.
1302
+ */
1303
+ function checkApiVersion(bridgeApiVersion, clientApiVersion) {
1304
+ const bridge = major(bridgeApiVersion);
1305
+ if (bridge === void 0 || bridge !== major(clientApiVersion)) throw new IncompatibleBridgeError(bridgeApiVersion, clientApiVersion);
1306
+ }
1307
+ // src/adapters/out/http/sse-parser.ts
1308
+ /**
1309
+ * Parses a `text/event-stream` body, already decoded to text, into messages (the event stream
1310
+ * format of the HTML standard): lines end with LF, CRLF or CR, `:` starts a comment (the
1311
+ * bridge's ping), a blank line ends a message, and a message without `data` is skipped. A
1312
+ * message that is not ended by a blank line when the stream ends is dropped, as the standard
1313
+ * says.
1314
+ */
1315
+ async function* parseSse(chunks) {
1316
+ let rest = "";
1317
+ let first = true;
1318
+ let skipLf = false;
1319
+ let id;
1320
+ let event = "";
1321
+ let data = [];
1322
+ for await (let chunk of chunks) {
1323
+ if (first && chunk.length > 0) {
1324
+ first = false;
1325
+ if (chunk.startsWith("")) chunk = chunk.slice(1);
1326
+ }
1327
+ if (skipLf && chunk.startsWith("\n")) chunk = chunk.slice(1);
1328
+ skipLf = false;
1329
+ rest += chunk;
1330
+ let start = 0;
1331
+ for (;;) {
1332
+ const end = rest.slice(start).search(/[\r\n]/);
1333
+ if (end === -1) break;
1334
+ const at = start + end;
1335
+ const line = rest.slice(start, at);
1336
+ if (rest[at] === "\r" && rest[at + 1] === "\n") start = at + 2;
1337
+ else {
1338
+ start = at + 1;
1339
+ if (rest[at] === "\r" && start === rest.length) skipLf = true;
1340
+ }
1341
+ if (line === "") {
1342
+ if (data.length > 0) yield {
1343
+ id,
1344
+ event: event || "message",
1345
+ data: data.join("\n")
1346
+ };
1347
+ id = void 0;
1348
+ event = "";
1349
+ data = [];
1350
+ continue;
1351
+ }
1352
+ if (line.startsWith(":")) continue;
1353
+ const colon = line.indexOf(":");
1354
+ const field = colon === -1 ? line : line.slice(0, colon);
1355
+ let value = colon === -1 ? "" : line.slice(colon + 1);
1356
+ if (value.startsWith(" ")) value = value.slice(1);
1357
+ if (field === "data") data.push(value);
1358
+ else if (field === "event") event = value;
1359
+ else if (field === "id" && !value.includes("\0")) id = value;
1360
+ }
1361
+ rest = rest.slice(start);
1362
+ }
1363
+ }
1364
+ // src/adapters/out/http/fetch-bridge-api.ts
1365
+ /** A request that gets no answer in this time fails as unreachable (the bridge answers at once). */
1366
+ const REQUEST_TIMEOUT_MS = 1e4;
1367
+ /**
1368
+ * The live feed counts as dead after this long without a byte: the bridge sends a `: ping`
1369
+ * every 15 s, so this is three missed pings (a half-open connection never reports an error).
1370
+ */
1371
+ const STREAM_IDLE_MS = 45e3;
1372
+ /** {@link BridgeApi} over `fetch` (docs/usage/http-api.md). */
1373
+ var FetchBridgeApi = class {
1374
+ options;
1375
+ #baseUrl;
1376
+ constructor(options) {
1377
+ this.options = options;
1378
+ }
1379
+ async status() {
1380
+ const response = await this.request("GET", "/status");
1381
+ const body = await response.json();
1382
+ const version = checkDto(ApiVersionSchema, body);
1383
+ if (version.ok) checkApiVersion(version.value.bridge.apiVersion, API_VERSION);
1384
+ return toStatus(parseBody(StatusSchema, body, response.status, "GET /status"));
1385
+ }
1386
+ async listSpeech(query) {
1387
+ const params = new URLSearchParams({ since: String(query.since) });
1388
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
1389
+ if (query.session !== void 0) params.set("session", String(query.session));
1390
+ const page = await this.json(SpeechListSchema, "GET", `/speech?${params.toString()}`);
1391
+ return {
1392
+ entries: page.entries.map(toEntry),
1393
+ truncated: page.truncated,
1394
+ hasMore: page.hasMore
1395
+ };
1396
+ }
1397
+ async clear() {
1398
+ await this.request("DELETE", "/speech");
1399
+ }
1400
+ async mark(label) {
1401
+ const body = { label };
1402
+ return toEntry(await this.json(SpeechEntrySchema, "POST", "/markers", { body }));
1403
+ }
1404
+ async startSession(request) {
1405
+ const body = {
1406
+ name: request.name,
1407
+ ...request.run === void 0 ? {} : { run: request.run }
1408
+ };
1409
+ const started = await this.json(StartSessionResponseSchema, "POST", "/sessions", { body });
1410
+ return {
1411
+ ...toSession(started),
1412
+ replaced: started.replaced && toSession(started.replaced)
1413
+ };
1414
+ }
1415
+ async endSession() {
1416
+ await this.request("POST", "/sessions/end");
1417
+ }
1418
+ async click(request) {
1419
+ const body = {
1420
+ x: request.x,
1421
+ y: request.y,
1422
+ ...request.button === void 0 ? {} : { button: request.button }
1423
+ };
1424
+ await this.request("POST", "/input/click", { body });
1425
+ }
1426
+ async pressKeys(request) {
1427
+ const body = {
1428
+ keys: typeof request.keys === "string" ? request.keys : [...request.keys],
1429
+ ...request.delayMs === void 0 ? {} : { delayMs: request.delayMs }
1430
+ };
1431
+ await this.request("POST", "/input/keys", { body });
1432
+ }
1433
+ async listSessions() {
1434
+ const list = await this.json(SessionListSchema, "GET", "/sessions");
1435
+ return {
1436
+ sessions: list.sessions.map(toSession),
1437
+ currentId: list.currentId
1438
+ };
1439
+ }
1440
+ async *streamSpeech(options) {
1441
+ const { lastEventId, session, signal } = options;
1442
+ const controller = new AbortController();
1443
+ const close = () => controller.abort(signal.reason);
1444
+ signal.addEventListener("abort", close, { once: true });
1445
+ let watchdog;
1446
+ const watch = (ms, reason) => {
1447
+ clearTimeout(watchdog);
1448
+ watchdog = setTimeout(() => controller.abort(new Error(reason)), ms);
1449
+ };
1450
+ try {
1451
+ watch(REQUEST_TIMEOUT_MS, `no answer within ${REQUEST_TIMEOUT_MS} ms`);
1452
+ const query = session === void 0 ? "" : `?session=${session}`;
1453
+ const response = await this.request("GET", `/speech/stream${query}`, {
1454
+ headers: {
1455
+ accept: "text/event-stream",
1456
+ ...lastEventId === null ? {} : { "last-event-id": String(lastEventId) }
1457
+ },
1458
+ signal: controller.signal
1459
+ });
1460
+ if (!response.body) return;
1461
+ const text = response.body.pipeThrough(new TextDecoderStream());
1462
+ async function* watched() {
1463
+ watch(STREAM_IDLE_MS, `no data for ${STREAM_IDLE_MS} ms`);
1464
+ for await (const chunk of text) {
1465
+ watch(STREAM_IDLE_MS, `no data for ${STREAM_IDLE_MS} ms`);
1466
+ yield chunk;
1467
+ }
1468
+ }
1469
+ for await (const message of parseSse(watched())) {
1470
+ const event = toStreamEvent(message);
1471
+ if (event) yield event;
1472
+ }
1473
+ } catch (error) {
1474
+ if (signal.aborted) return;
1475
+ if (error instanceof BridgeUnreachableError || error instanceof BridgeHttpError) throw error;
1476
+ const cause = controller.signal.aborted ? controller.signal.reason : error;
1477
+ throw new BridgeUnreachableError(await this.base(), { cause });
1478
+ } finally {
1479
+ clearTimeout(watchdog);
1480
+ signal.removeEventListener("abort", close);
1481
+ controller.abort();
1482
+ }
1483
+ }
1484
+ /** The answer's JSON body, checked against `schema` (`INVALID_RESPONSE` if it doesn't match). */
1485
+ async json(schema, method, path, options) {
1486
+ const response = await this.request(method, path, options);
1487
+ return parseBody(schema, await response.json(), response.status, `${method} ${path.split("?")[0]}`);
1488
+ }
1489
+ async request(method, path, options = {}) {
1490
+ const base = await this.base();
1491
+ const { body } = options;
1492
+ const { clientName } = this.options;
1493
+ const headers = {
1494
+ ...options.headers,
1495
+ ...clientName === void 0 ? {} : { [CLIENT_HEADER]: clientName },
1496
+ ...body === void 0 ? {} : { "content-type": "application/json" }
1497
+ };
1498
+ let response;
1499
+ try {
1500
+ response = await (this.options.fetch ?? fetch)(`${base}${API_PREFIX}${path}`, {
1501
+ method,
1502
+ signal: options.signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS),
1503
+ headers,
1504
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
1505
+ });
1506
+ } catch (error) {
1507
+ throw new BridgeUnreachableError(base, { cause: error });
1508
+ }
1509
+ if (!response.ok) throw await toHttpError(response);
1510
+ return response;
1511
+ }
1512
+ base() {
1513
+ this.#baseUrl ??= this.options.baseUrl().catch((error) => {
1514
+ this.#baseUrl = void 0;
1515
+ throw error;
1516
+ });
1517
+ return this.#baseUrl;
1518
+ }
1519
+ };
1520
+ /**
1521
+ * `body` checked against the contract. A body that doesn't match fails here, at the boundary,
1522
+ * with what was wrong, instead of somewhere inside the client.
1523
+ */
1524
+ function parseBody(schema, body, status, what) {
1525
+ const checked = checkDto(schema, body);
1526
+ if (checked.ok) return checked.value;
1527
+ throw new BridgeHttpError(status, INVALID_RESPONSE, `The bridge answered ${what} with an unexpected body: ${checked.field}: ${checked.message}`);
1528
+ }
1529
+ async function toHttpError(response) {
1530
+ const body = await response.json().catch(() => void 0);
1531
+ const parsed = checkDto(AnyErrorBodySchema, body);
1532
+ if (!parsed.ok) return new BridgeHttpError(response.status, "HTTP_ERROR", response.statusText);
1533
+ const { error } = parsed.value;
1534
+ return new BridgeHttpError(response.status, error.code, error.message, error.details);
1535
+ }
1536
+ /** The feed event for one SSE message, `undefined` for events this client doesn't know. */
1537
+ function toStreamEvent({ event, data, id }) {
1538
+ switch (event) {
1539
+ case "entry": return {
1540
+ type: "entry",
1541
+ entry: toEntry(parseEvent(SpeechEntrySchema, data, event))
1542
+ };
1543
+ case "session": return {
1544
+ type: "session",
1545
+ session: toSession(parseEvent(SessionSchema, data, event))
1546
+ };
1547
+ case "position": {
1548
+ const seq = id !== void 0 && /^\d+$/.test(id) ? Number(id) : NaN;
1549
+ if (!Number.isSafeInteger(seq)) throw new BridgeHttpError(200, INVALID_RESPONSE, `the live feed's position event has no valid id (${JSON.stringify(id)})`);
1550
+ return {
1551
+ type: "position",
1552
+ seq
1553
+ };
1554
+ }
1555
+ case "clear":
1556
+ case "truncated": return { type: event };
1557
+ default: return;
1558
+ }
1559
+ }
1560
+ /** The data of an SSE event, checked against the contract like a response body. */
1561
+ function parseEvent(schema, data, event) {
1562
+ let body;
1563
+ try {
1564
+ body = JSON.parse(data);
1565
+ } catch {
1566
+ body = data;
1567
+ }
1568
+ return parseBody(schema, body, 200, `the live feed's ${event} event`);
1569
+ }
1570
+ const toEntry = (dto) => ({
1571
+ seq: dto.seq,
1572
+ kind: dto.kind,
1573
+ text: dto.text,
1574
+ receivedAt: dto.receivedAt,
1575
+ source: dto.source,
1576
+ voice: dto.voice,
1577
+ connectionId: dto.connectionId,
1578
+ sessionId: dto.sessionId ?? null
1579
+ });
1580
+ const toSession = (dto) => ({
1581
+ id: dto.id,
1582
+ name: dto.name,
1583
+ run: dto.run,
1584
+ client: dto.client,
1585
+ startedAt: dto.startedAt,
1586
+ endedAt: dto.endedAt,
1587
+ startSeq: dto.startSeq,
1588
+ firstSeq: dto.firstSeq,
1589
+ lastSeq: dto.lastSeq,
1590
+ entries: dto.entries
1591
+ });
1592
+ const toServiceStatus = (dto) => ({
1593
+ state: dto.state,
1594
+ version: dto.version,
1595
+ port: dto.port,
1596
+ restarts: dto.restarts,
1597
+ exitCode: dto.exitCode
1598
+ });
1599
+ const toStatus = ({ bridge, tcp, buffer, playwright, mcp, session }) => ({
1600
+ bridge: {
1601
+ version: bridge.version,
1602
+ apiVersion: bridge.apiVersion,
1603
+ state: bridge.state,
1604
+ startedAt: bridge.startedAt
1605
+ },
1606
+ tcp: {
1607
+ listening: tcp.listening,
1608
+ host: tcp.host,
1609
+ port: tcp.port,
1610
+ encoding: tcp.encoding,
1611
+ connections: tcp.connections.map(({ id, voice, connectedAt }) => ({
1612
+ id,
1613
+ voice,
1614
+ connectedAt
1615
+ }))
1616
+ },
1617
+ buffer: {
1618
+ size: buffer.size,
1619
+ maxEntries: buffer.maxEntries,
1620
+ firstSeq: buffer.firstSeq,
1621
+ lastSeq: buffer.lastSeq
1622
+ },
1623
+ playwright: toServiceStatus(playwright),
1624
+ mcp: toServiceStatus(mcp),
1625
+ session: {
1626
+ current: session.current === null ? null : toSession(session.current),
1627
+ count: session.count
1628
+ }
1629
+ });
1630
+ // src/application/services/client-config-service.ts
1631
+ var ClientConfigService = class {
1632
+ deps;
1633
+ constructor(deps) {
1634
+ this.deps = deps;
1635
+ }
1636
+ get location() {
1637
+ return this.deps.store.location;
1638
+ }
1639
+ async get(key, explicit = {}) {
1640
+ const k = parseConfigKey(key);
1641
+ const sources = {
1642
+ explicit: explicit[k],
1643
+ env: this.deps.envUrl
1644
+ };
1645
+ return {
1646
+ key: k,
1647
+ ...overridesStored(sources) ? pickBridgeUrl(sources) : pickBridgeUrl({
1648
+ ...sources,
1649
+ stored: (await this.deps.store.load())[k]
1650
+ })
1651
+ };
1652
+ }
1653
+ list(explicit = {}) {
1654
+ return Promise.all(Object.keys(CONFIG_KEYS).map((k) => this.get(k, explicit)));
1655
+ }
1656
+ async set(key, value) {
1657
+ const k = parseConfigKey(key);
1658
+ const normalized = CONFIG_KEYS[k](value);
1659
+ await this.deps.store.save({ [k]: normalized });
1660
+ return {
1661
+ key: k,
1662
+ value: normalized,
1663
+ ...overridesStored({ env: this.deps.envUrl }) ? { shadowedBy: "env" } : {}
1664
+ };
1665
+ }
1666
+ async unset(key) {
1667
+ const k = parseConfigKey(key);
1668
+ await this.deps.store.save({ [k]: void 0 });
1669
+ return { key: k };
1670
+ }
1671
+ };
1672
+ // src/domain/native-input.ts
1673
+ /** How far below the window's top edge the default click lands, in CSS pixels. */
1674
+ const TITLE_BAR_OFFSET = 12;
1675
+ /**
1676
+ * Where to click so the window becomes the foreground window, in physical pixels.
1677
+ *
1678
+ * Without `target`: the middle of the window's top edge, inside the title bar, which doesn't do
1679
+ * anything to the page (docs/usage/native-input.md). With `target`: the centre of the element.
1680
+ * The browser's own frame (tabs, address bar) is what the window's outer size has beyond its
1681
+ * inner size; the left, right and bottom borders are the same width, so they are split evenly.
1682
+ */
1683
+ function clickPoint(geometry, target) {
1684
+ const { screenX, screenY, outerWidth, outerHeight, innerWidth, innerHeight } = geometry;
1685
+ const scale = geometry.devicePixelRatio > 0 ? geometry.devicePixelRatio : 1;
1686
+ const border = Math.max(0, (outerWidth - innerWidth) / 2);
1687
+ const frameHeight = Math.max(0, outerHeight - innerHeight - border);
1688
+ const [x, y] = target === void 0 ? [screenX + outerWidth / 2, screenY + Math.min(TITLE_BAR_OFFSET, outerHeight / 2)] : [screenX + border + target.x + target.width / 2, screenY + frameHeight + target.y + target.height / 2];
1689
+ return {
1690
+ x: Math.round(x * scale),
1691
+ y: Math.round(y * scale)
1692
+ };
1693
+ }
1694
+ /**
1695
+ * The top-left corner of the page content, in physical pixels: where the web page starts, below
1696
+ * the browser's tabs and address bar. Lands 1 CSS pixel inside, so it hits the page and not the
1697
+ * window border.
1698
+ */
1699
+ function contentCornerPoint(geometry) {
1700
+ return clickPoint(geometry, {
1701
+ x: 1,
1702
+ y: 1,
1703
+ width: 0,
1704
+ height: 0
1705
+ });
1706
+ }
1707
+ /** The page's window geometry could not be read, or the target element isn't on screen. */
1708
+ var FocusError = class extends Error {
1709
+ name = "FocusError";
1710
+ };
1711
+ /** Script a page evaluates to report its window geometry. */
1712
+ const READ_GEOMETRY_SCRIPT = `({
1713
+ screenX: window.screenX,
1714
+ screenY: window.screenY,
1715
+ outerWidth: window.outerWidth,
1716
+ outerHeight: window.outerHeight,
1717
+ innerWidth: window.innerWidth,
1718
+ innerHeight: window.innerHeight,
1719
+ devicePixelRatio: window.devicePixelRatio,
1720
+ })`;
1721
+ const GEOMETRY_KEYS = [
1722
+ "screenX",
1723
+ "screenY",
1724
+ "outerWidth",
1725
+ "outerHeight",
1726
+ "innerWidth",
1727
+ "innerHeight",
1728
+ "devicePixelRatio"
1729
+ ];
1730
+ /** Checks what the page answered to {@link READ_GEOMETRY_SCRIPT}. */
1731
+ function parseWindowGeometry(value) {
1732
+ const record = typeof value === "object" && value !== null ? value : {};
1733
+ const numbers = GEOMETRY_KEYS.map((key) => record[key]);
1734
+ if (!numbers.every((n) => typeof n === "number" && Number.isFinite(n))) throw new FocusError(`The page did not report its window geometry: ${JSON.stringify(value)}`);
1735
+ return Object.fromEntries(GEOMETRY_KEYS.map((key, i) => [key, numbers[i]]));
1736
+ }
1737
+ // src/application/services/version-gate.ts
1738
+ /**
1739
+ * Checks once that the bridge speaks this client's API version (major). A failed check is
1740
+ * repeated on the next call. Shared by the services that talk to one bridge.
1741
+ */
1742
+ var VersionGate = class {
1743
+ api;
1744
+ apiVersion;
1745
+ #checked;
1746
+ constructor(api, apiVersion) {
1747
+ this.api = api;
1748
+ this.apiVersion = apiVersion;
1749
+ }
1750
+ /** Resolves when the bridge is compatible, rejects with `IncompatibleBridgeError` if not. */
1751
+ ensure() {
1752
+ this.#checked ??= this.api.status().then((status) => this.#check(status.bridge.apiVersion), (error) => {
1753
+ this.#checked = void 0;
1754
+ throw error;
1755
+ });
1756
+ return this.#checked;
1757
+ }
1758
+ /** A status the caller read anyway counts as the check. */
1759
+ passed(bridgeApiVersion) {
1760
+ this.#check(bridgeApiVersion);
1761
+ this.#checked = Promise.resolve();
1762
+ }
1763
+ #check(bridgeApiVersion) {
1764
+ try {
1765
+ checkApiVersion(bridgeApiVersion, this.apiVersion);
1766
+ } catch (error) {
1767
+ this.#checked = void 0;
1768
+ throw error;
1769
+ }
1770
+ }
1771
+ };
1772
+ // src/application/services/native-input-service.ts
1773
+ /** {@link NativeInput} on the bridge's native input endpoints (docs/usage/native-input.md). */
1774
+ var NativeInputService = class {
1775
+ deps;
1776
+ #gate;
1777
+ constructor(deps) {
1778
+ this.deps = deps;
1779
+ this.#gate = new VersionGate(deps.api, deps.apiVersion);
1780
+ }
1781
+ async click(point, options = {}) {
1782
+ await this.#gate.ensure();
1783
+ await this.deps.api.click({
1784
+ x: point.x,
1785
+ y: point.y,
1786
+ button: options.button
1787
+ });
1788
+ }
1789
+ async pressKeys(keys, options = {}) {
1790
+ await this.#gate.ensure();
1791
+ await this.deps.api.pressKeys({
1792
+ keys,
1793
+ delayMs: options.delayMs
1794
+ });
1795
+ }
1796
+ async setFocus(page, options = {}) {
1797
+ const geometry = parseWindowGeometry(await page.evaluate(READ_GEOMETRY_SCRIPT));
1798
+ const box = options.target === void 0 ? void 0 : await options.target.boundingBox();
1799
+ if (box === null) throw new FocusError("The target element has no bounding box: is it visible?");
1800
+ await this.click(clickPoint(geometry, box));
1801
+ }
1802
+ };
1803
+ // src/domain/speech-entry.ts
1804
+ const isSpeech = (entry) => entry.kind === "speech";
1805
+ // src/domain/text-match.ts
1806
+ /** Builds the test for one {@link SpeechMatch}. Markers never match. */
1807
+ function toMatcher(match, options = {}) {
1808
+ if (typeof match === "function") return (entry) => isSpeech(entry) && match(entry);
1809
+ const test = createTextTest(match, options.normalize ?? false);
1810
+ if (test === void 0) throw new TypeError("The text to wait for must not be empty");
1811
+ return (entry) => isSpeech(entry) && test(entry.text);
1812
+ }
1813
+ /**
1814
+ * Feeds `entries` into an ordered search for `matchers` and returns the matches found so far
1815
+ * (`found` extended). Other entries may come in between. Done when the result has
1816
+ * `matchers.length` entries.
1817
+ */
1818
+ function advanceSequence(matchers, found, entries) {
1819
+ const result = [...found];
1820
+ for (const entry of entries) {
1821
+ const next = matchers[result.length];
1822
+ if (next === void 0) break;
1823
+ if (next(entry)) result.push(entry);
1824
+ }
1825
+ return result;
1826
+ }
1827
+ // src/application/services/speech-events.ts
1828
+ /** Reconnect delays: doubling from `MIN` up to `MAX`. */
1829
+ var Backoff = class Backoff {
1830
+ static MIN = 250;
1831
+ static MAX = 5e3;
1832
+ #delay = Backoff.MIN;
1833
+ reset() {
1834
+ this.#delay = Backoff.MIN;
1835
+ }
1836
+ /** The delay to wait now; the next one is twice as long. */
1837
+ next() {
1838
+ const delay = this.#delay;
1839
+ this.#delay = Math.min(delay * 2, Backoff.MAX);
1840
+ return delay;
1841
+ }
1842
+ };
1843
+ /**
1844
+ * The live feed (`GET /api/v1/speech/stream`) as one sequence of events across connections: the
1845
+ * code path behind both `onSpeech` and the waits. Reconnects with `Last-Event-ID` and backoff, so
1846
+ * no entry is lost or repeated, also across a bridge restart (`seq` keeps rising) and when the
1847
+ * connection drops before the first entry (the bridge's `position` event is the cursor then). Ends when
1848
+ * `signal` aborts; throws errors a reconnect can't fix (an incompatible bridge, an HTTP `4xx`, an
1849
+ * invalid bridge URL).
1850
+ */
1851
+ async function* speechEvents(deps, options) {
1852
+ const { api, clock, ensureCompatible } = deps;
1853
+ const { session, signal } = options;
1854
+ const backoff = new Backoff();
1855
+ /**
1856
+ * The `seq` of the last entry seen, or the stream's `position` before the first one: a
1857
+ * reconnect asks the bridge for what came after it.
1858
+ */
1859
+ let lastEventId = options.since;
1860
+ while (!signal.aborted) {
1861
+ const connectedAt = clock.now();
1862
+ let lost;
1863
+ try {
1864
+ await ensureCompatible();
1865
+ const events = api.streamSpeech({
1866
+ lastEventId,
1867
+ signal,
1868
+ ...session === void 0 ? {} : { session }
1869
+ });
1870
+ for await (const event of events) {
1871
+ if (signal.aborted) return;
1872
+ backoff.reset();
1873
+ if (event.type === "position") {
1874
+ lastEventId = event.seq;
1875
+ continue;
1876
+ }
1877
+ if (event.type === "entry") lastEventId = event.entry.seq;
1878
+ yield event;
1879
+ }
1880
+ if (signal.aborted) return;
1881
+ lost = /* @__PURE__ */ new Error("The bridge closed the live feed");
1882
+ } catch (error) {
1883
+ if (signal.aborted) return;
1884
+ if (isFatal(error)) throw error;
1885
+ lost = error instanceof Error ? error : new Error(String(error));
1886
+ }
1887
+ options.onRetry?.(lost);
1888
+ if (clock.now() - connectedAt >= Backoff.MAX) backoff.reset();
1889
+ try {
1890
+ await clock.sleep(backoff.next(), signal);
1891
+ } catch {
1892
+ return;
1893
+ }
1894
+ }
1895
+ }
1896
+ /** Errors a reconnect can't fix. */
1897
+ function isFatal(error) {
1898
+ return error instanceof IncompatibleBridgeError || error instanceof ClientConfigError || error instanceof BridgeHttpError && (error.status >= 400 && error.status < 500 || error.code === "INVALID_RESPONSE");
1899
+ }
1900
+ // src/application/services/live-feed.ts
1901
+ /**
1902
+ * Starts the live feed (`onSpeech`): it delivers the bridge's SSE events to `listener` and the
1903
+ * `options` callbacks, and reconnects with backoff until unsubscribed or a fatal error.
1904
+ * Returns the unsubscribe function.
1905
+ */
1906
+ function startLiveFeed(deps, listener, options = {}) {
1907
+ const controller = new AbortController();
1908
+ new LiveFeed(deps, listener, options, controller.signal).run();
1909
+ return () => controller.abort();
1910
+ }
1911
+ /** One subscription: dispatches the events of {@link speechEvents} to the listener and callbacks. */
1912
+ var LiveFeed = class {
1913
+ deps;
1914
+ listener;
1915
+ options;
1916
+ signal;
1917
+ constructor(deps, listener, options, signal) {
1918
+ this.deps = deps;
1919
+ this.listener = listener;
1920
+ this.options = options;
1921
+ this.signal = signal;
1922
+ }
1923
+ /** Runs until `signal` aborts or a fatal error. Never rejects. */
1924
+ async run() {
1925
+ const { signal } = this;
1926
+ try {
1927
+ const events = speechEvents(this.deps, {
1928
+ since: this.options.since ?? null,
1929
+ signal,
1930
+ onRetry: (error) => this.#report(error, true)
1931
+ });
1932
+ for await (const event of events) this.#dispatch(event);
1933
+ } catch (error) {
1934
+ this.#report(error, false);
1935
+ }
1936
+ }
1937
+ #dispatch(event) {
1938
+ const { options } = this;
1939
+ switch (event.type) {
1940
+ case "entry": {
1941
+ const { entry } = event;
1942
+ if (options.includeMarkers || isSpeech(entry)) this.#notify(() => this.listener(entry));
1943
+ break;
1944
+ }
1945
+ case "session": {
1946
+ const { session } = event;
1947
+ this.#notify(() => options.onSession?.(session));
1948
+ break;
1949
+ }
1950
+ case "clear":
1951
+ this.#notify(() => options.onClear?.());
1952
+ break;
1953
+ case "truncated": this.#notify(() => options.onTruncated?.());
1954
+ }
1955
+ }
1956
+ /** Runs a user callback; a throw is reported and the feed goes on. */
1957
+ #notify(callback) {
1958
+ try {
1959
+ callback();
1960
+ } catch (error) {
1961
+ this.#report(error, true);
1962
+ }
1963
+ }
1964
+ #report(error, retrying) {
1965
+ if (this.signal.aborted) return;
1966
+ try {
1967
+ this.options.onError?.(toError(error), { retrying });
1968
+ } catch {}
1969
+ }
1970
+ };
1971
+ function toError(error) {
1972
+ return error instanceof Error ? error : new Error(String(error));
1973
+ }
1974
+ // src/application/services/speech-capture-service.ts
1975
+ /** Largest `limit` the bridge accepts for `GET /api/v1/speech`. */
1976
+ const MAX_PAGE = API_LIMITS.list.max;
1977
+ /** Entries a timeout error holds at most: the last ones seen, as on the bridge. */
1978
+ const MAX_SEEN = API_LIMITS.wait.seen;
1979
+ function remember(seen, entries) {
1980
+ seen.push(...entries);
1981
+ if (seen.length > MAX_SEEN) seen.splice(0, seen.length - MAX_SEEN);
1982
+ }
1983
+ const DEFAULTS = {
1984
+ timeout: 5e3,
1985
+ quietFor: 500,
1986
+ silenceTimeout: 1e4,
1987
+ readyTimeout: 12e4
1988
+ };
1989
+ /** How often `waitForReady` asks for the status. */
1990
+ const READY_POLL_MS = 500;
1991
+ var SpeechCaptureService = class {
1992
+ deps;
1993
+ /**
1994
+ * `seq` keeps rising across bridge restarts (it starts at the bridge's start time), so a cursor
1995
+ * from before a restart reads the new run from its start.
1996
+ */
1997
+ #cursor = 0;
1998
+ /**
1999
+ * Counts the explicit moves (`setCursor`, `clear`, `startSession`). A wait or recording only
2000
+ * moves the cursor if none happened since it started: the explicit move wins.
2001
+ */
2002
+ #moves = 0;
2003
+ #gate;
2004
+ constructor(deps) {
2005
+ this.deps = deps;
2006
+ this.#gate = new VersionGate(deps.api, deps.apiVersion);
2007
+ }
2008
+ cursor() {
2009
+ return this.#cursor;
2010
+ }
2011
+ setCursor(seq) {
2012
+ if (!Number.isSafeInteger(seq) || seq < 0) throw new RangeError(`The cursor must be a seq (an integer >= 0), got ${seq}`);
2013
+ this.#moveTo(seq);
2014
+ }
2015
+ /** An explicit move: sets the cursor, also backwards. */
2016
+ #moveTo(seq) {
2017
+ this.#cursor = seq;
2018
+ this.#moves++;
2019
+ }
2020
+ /**
2021
+ * Where a wait starts, taken when it is called (before any `await`): its `since` (the cursor
2022
+ * unless given) and the explicit moves so far. Call order decides, not when the wait gets to
2023
+ * read.
2024
+ */
2025
+ #start(options) {
2026
+ return {
2027
+ options: {
2028
+ ...options,
2029
+ since: options.since ?? this.#cursor
2030
+ },
2031
+ moves: this.#moves
2032
+ };
2033
+ }
2034
+ /**
2035
+ * After an operation that consumed up to `seq` and started at `moves`: only forward, so calls
2036
+ * running at the same time can't move it back, and not past an explicit move made meanwhile.
2037
+ */
2038
+ #advance(seq, moves) {
2039
+ if (moves === this.#moves && seq > this.#cursor) this.#cursor = seq;
2040
+ }
2041
+ async getSpeech(options = {}) {
2042
+ const since = options.since ?? this.#cursor;
2043
+ await this.compatible();
2044
+ const { entries, truncated } = await this.fetchSince(since, options.session);
2045
+ const wanted = options.includeMarkers ? entries : entries.filter(isSpeech);
2046
+ const result = options.limit === void 0 ? wanted : wanted.slice(0, options.limit);
2047
+ if (truncated && !options.allowTruncated) throw new SpeechTruncatedError(since, result);
2048
+ return result;
2049
+ }
2050
+ async getText(options = {}) {
2051
+ return (await this.getSpeech({
2052
+ since: options.since,
2053
+ session: options.session,
2054
+ allowTruncated: options.allowTruncated
2055
+ })).map((e) => e.text).join(options.separator ?? "\n");
2056
+ }
2057
+ async clear() {
2058
+ await this.compatible();
2059
+ await this.deps.api.clear();
2060
+ this.#moveTo(0);
2061
+ }
2062
+ async startSession(name, options = {}) {
2063
+ await this.compatible();
2064
+ const session = await this.deps.api.startSession({
2065
+ name,
2066
+ run: options.run
2067
+ });
2068
+ this.#moveTo(session.startSeq);
2069
+ return session;
2070
+ }
2071
+ async endSession() {
2072
+ await this.compatible();
2073
+ await this.deps.api.endSession();
2074
+ }
2075
+ async sessions() {
2076
+ await this.compatible();
2077
+ return this.deps.api.listSessions();
2078
+ }
2079
+ async mark(label) {
2080
+ await this.compatible();
2081
+ return this.deps.api.mark(label);
2082
+ }
2083
+ async status() {
2084
+ const status = await this.deps.api.status();
2085
+ this.#gate.passed(status.bridge.apiVersion);
2086
+ return status;
2087
+ }
2088
+ async waitForReady(options = {}) {
2089
+ const { clock } = this.deps;
2090
+ const timeout = options.timeout ?? DEFAULTS.readyTimeout;
2091
+ const deadline = clock.now() + timeout;
2092
+ let last;
2093
+ for (;;) {
2094
+ try {
2095
+ const status = await this.status();
2096
+ if (status.bridge.state === "ready") return status;
2097
+ last = `state is ${status.bridge.state}`;
2098
+ } catch (error) {
2099
+ const starting = error instanceof BridgeHttpError && error.status === 503;
2100
+ if (!(error instanceof BridgeUnreachableError) && !starting) throw error;
2101
+ last = error.message;
2102
+ }
2103
+ const left = deadline - clock.now();
2104
+ if (left <= 0) throw new BridgeNotReadyError(`The bridge was not ready within ${timeout} ms: ${last}`);
2105
+ await clock.sleep(Math.min(READY_POLL_MS, left));
2106
+ }
2107
+ }
2108
+ async waitForOutput(match, options = {}) {
2109
+ const test = toMatcher(match, options);
2110
+ const start = this.#start(options);
2111
+ await this.compatible();
2112
+ const entry = await this.search(start.options, (entries) => entries.find(test), `No speech matched ${describe(match)}`);
2113
+ this.#advance(entry.seq, start.moves);
2114
+ return entry;
2115
+ }
2116
+ async waitForSequence(matches, options = {}) {
2117
+ if (matches.length === 0) throw new TypeError("waitForSequence needs at least one match");
2118
+ const matchers = matches.map((m) => toMatcher(m, options));
2119
+ const start = this.#start(options);
2120
+ await this.compatible();
2121
+ let found = [];
2122
+ const result = await this.search(start.options, (entries) => {
2123
+ found = advanceSequence(matchers, found, entries);
2124
+ return found.length === matchers.length ? found : void 0;
2125
+ }, () => `Only ${found.length} of ${matches.length} matches occurred in order (next: ${describe(matches[found.length])})`);
2126
+ this.#advance(result.at(-1).seq, start.moves);
2127
+ return result;
2128
+ }
2129
+ async waitForSilence(options = {}) {
2130
+ const { clock } = this.deps;
2131
+ const quietFor = options.quietFor ?? DEFAULTS.quietFor;
2132
+ const timeout = options.timeout ?? DEFAULTS.silenceTimeout;
2133
+ await this.compatible();
2134
+ const start = clock.now();
2135
+ const end = await this.endSeq();
2136
+ let lastSpeech = start;
2137
+ const seen = [];
2138
+ const left = () => Math.min(lastSpeech + quietFor, start + timeout) - clock.now();
2139
+ await this.follow({ since: end }, left(), (entry, timer) => {
2140
+ if (!isSpeech(entry)) return void 0;
2141
+ remember(seen, [entry]);
2142
+ lastSpeech = clock.now();
2143
+ timer.set(left());
2144
+ });
2145
+ if (lastSpeech + quietFor <= start + timeout) return;
2146
+ throw new SpeechTimeoutError(`Speech did not pause for ${quietFor} ms within ${timeout} ms`, seen);
2147
+ }
2148
+ async record(fn, options = {}) {
2149
+ const moves = this.#moves;
2150
+ await this.compatible();
2151
+ const start = await this.endSeq();
2152
+ const result = await fn();
2153
+ await this.waitForSilence(options);
2154
+ const { entries, truncated } = await this.fetchSince(start);
2155
+ const last = entries.at(-1)?.seq;
2156
+ if (last !== void 0) this.#advance(last, moves);
2157
+ return {
2158
+ result,
2159
+ entries: entries.filter(isSpeech),
2160
+ truncated
2161
+ };
2162
+ }
2163
+ onSpeech(listener, options = {}) {
2164
+ const { api, clock } = this.deps;
2165
+ return startLiveFeed({
2166
+ api,
2167
+ clock,
2168
+ ensureCompatible: () => this.compatible()
2169
+ }, listener, options);
2170
+ }
2171
+ /** Checks the API version once. A failed check is repeated on the next call. */
2172
+ compatible() {
2173
+ return this.#gate.ensure();
2174
+ }
2175
+ /** The `seq` of the newest entry in the buffer, 0 if it is empty. */
2176
+ async endSeq() {
2177
+ return (await this.deps.api.status()).buffer.lastSeq ?? 0;
2178
+ }
2179
+ /**
2180
+ * Every entry with `seq > since` (of `session`, if given), across pages, and whether some of
2181
+ * them were already dropped from the bridge's full buffer.
2182
+ */
2183
+ async fetchSince(since, session) {
2184
+ const entries = [];
2185
+ let truncated = false;
2186
+ let from = since;
2187
+ for (;;) {
2188
+ const page = await this.deps.api.listSpeech({
2189
+ since: from,
2190
+ limit: MAX_PAGE,
2191
+ ...session === void 0 ? {} : { session }
2192
+ });
2193
+ entries.push(...page.entries);
2194
+ truncated ||= page.truncated;
2195
+ const last = page.entries.at(-1);
2196
+ if (!page.hasMore || last === void 0) return {
2197
+ entries,
2198
+ truncated
2199
+ };
2200
+ from = last.seq;
2201
+ }
2202
+ }
2203
+ /**
2204
+ * The session id a wait is limited to: `'current'` becomes the session current now, and stays
2205
+ * that one for the whole wait, even if another session starts meanwhile.
2206
+ */
2207
+ async resolveSession(ref) {
2208
+ if (ref !== "current") return ref;
2209
+ const { current } = (await this.deps.api.status()).session;
2210
+ if (!current) throw new BridgeHttpError(404, "NOT_FOUND", "No session is current");
2211
+ return current.id;
2212
+ }
2213
+ /**
2214
+ * Searches the entries after the cursor (or `options.since`) until `step` returns a result:
2215
+ * first the buffer, then the live feed. Rejects with {@link SpeechTimeoutError} (and the speech
2216
+ * seen) after `options.timeout`.
2217
+ */
2218
+ async search(options, step, failure) {
2219
+ const { clock } = this.deps;
2220
+ const timeout = options.timeout ?? DEFAULTS.timeout;
2221
+ const deadline = clock.now() + timeout;
2222
+ const since = options.since ?? this.#cursor;
2223
+ const session = await this.resolveSession(options.session);
2224
+ const seen = [];
2225
+ const consume = (entries) => {
2226
+ remember(seen, entries.filter(isSpeech));
2227
+ return step(entries);
2228
+ };
2229
+ const buffered = await this.fetchSince(since, session);
2230
+ let truncated = buffered.truncated;
2231
+ let result = consume(buffered.entries);
2232
+ const left = deadline - clock.now();
2233
+ if (result === void 0 && left > 0) {
2234
+ const from = buffered.entries.at(-1)?.seq ?? since;
2235
+ result = await this.follow({
2236
+ since: from,
2237
+ session
2238
+ }, left, (entry) => consume([entry]), () => truncated = true);
2239
+ }
2240
+ if (result !== void 0) return result;
2241
+ throw new SpeechTimeoutError(`${typeof failure === "string" ? failure : failure()} within ${timeout} ms`, seen, truncated);
2242
+ }
2243
+ /**
2244
+ * Reads the live feed from `since` and hands each entry to `onEntry` until it returns a result,
2245
+ * or the timer (first set to `ms`, `onEntry` may set it again) runs out: then `undefined`.
2246
+ * `onTruncated`: a reconnect's replay found entries already dropped from the bridge's buffer.
2247
+ */
2248
+ async follow(from, ms, onEntry, onTruncated) {
2249
+ const { api, clock } = this.deps;
2250
+ const feed = new AbortController();
2251
+ const timer = new Timer(clock, () => feed.abort());
2252
+ timer.set(ms);
2253
+ try {
2254
+ const events = speechEvents({
2255
+ api,
2256
+ clock,
2257
+ ensureCompatible: () => this.compatible()
2258
+ }, {
2259
+ since: from.since,
2260
+ session: from.session,
2261
+ signal: feed.signal
2262
+ });
2263
+ for await (const event of events) {
2264
+ if (event.type === "truncated") onTruncated?.();
2265
+ if (event.type === "entry") {
2266
+ const result = onEntry(event.entry, timer);
2267
+ if (result !== void 0) return result;
2268
+ }
2269
+ }
2270
+ return;
2271
+ } finally {
2272
+ timer.stop();
2273
+ feed.abort();
2274
+ }
2275
+ }
2276
+ };
2277
+ /** A timeout that can be set again: the last {@link set} wins. */
2278
+ var Timer = class {
2279
+ clock;
2280
+ onTimeout;
2281
+ #controller;
2282
+ constructor(clock, onTimeout) {
2283
+ this.clock = clock;
2284
+ this.onTimeout = onTimeout;
2285
+ }
2286
+ /** Calls `onTimeout` in `ms` (now if `ms <= 0`), unless set again or stopped before. */
2287
+ set(ms) {
2288
+ this.stop();
2289
+ const controller = new AbortController();
2290
+ this.#controller = controller;
2291
+ this.clock.sleep(Math.max(0, ms), controller.signal).then(this.onTimeout, () => {});
2292
+ }
2293
+ stop() {
2294
+ this.#controller?.abort();
2295
+ }
2296
+ };
2297
+ function describe(match) {
2298
+ if (typeof match === "string") return JSON.stringify(match);
2299
+ if (match instanceof RegExp) return String(match);
2300
+ return "the predicate";
2301
+ }
2302
+ // src/domain/playwright-endpoint.ts
2303
+ /**
2304
+ * The WebSocket URL of the bridge's Playwright server for a (normalized) bridge URL:
2305
+ * `http://vm:5151` -> `ws://vm:5151/playwright` (docs/usage/playwright-mcp.md).
2306
+ */
2307
+ function playwrightEndpoint(bridgeUrl) {
2308
+ const url = new URL(bridgeUrl);
2309
+ const scheme = url.protocol === "https:" ? "wss:" : "ws:";
2310
+ const base = url.pathname.replace(/\/+$/, "");
2311
+ return `${scheme}//${url.host}${base}${PLAYWRIGHT_PATH}`;
2312
+ }
2313
+ // src/main.ts
2314
+ /**
2315
+ * The client's per-user settings, stored in the config file (docs/usage/client.md#bridge-url).
2316
+ * `SR_SPEECH_URL` and `SR_SPEECH_CLIENT_CONFIG` are read from `env` once, here.
2317
+ */
2318
+ function createClientConfig(env = process.env) {
2319
+ return new ClientConfigService({
2320
+ store: new FsClientConfigStore(clientConfigFile(void 0, env)),
2321
+ envUrl: env[URL_ENV]
2322
+ });
2323
+ }
2324
+ /**
2325
+ * Talks to the bridge (docs/usage/client.md#library): `new SpeechCaptureClient()` uses the stored
2326
+ * bridge URL. The URL is resolved on the first request.
2327
+ *
2328
+ * Wraps the service instead of extending it, so the service's internals stay out of the public
2329
+ * type surface (docs/implementation/architecture.md).
2330
+ */
2331
+ var SpeechCaptureClient = class {
2332
+ #service;
2333
+ #input;
2334
+ #resolveUrl;
2335
+ constructor(options = {}) {
2336
+ const config = createClientConfig(options.env ?? process.env);
2337
+ this.#resolveUrl = async () => (await config.get("url", { url: options.baseUrl })).value;
2338
+ const api = new FetchBridgeApi({
2339
+ baseUrl: this.#resolveUrl,
2340
+ clientName: options.clientName ?? `${hostname()} pid ${process.pid}`
2341
+ });
2342
+ this.#service = new SpeechCaptureService({
2343
+ api,
2344
+ clock: new SystemClock(),
2345
+ apiVersion: API_VERSION
2346
+ });
2347
+ this.#input = new NativeInputService({
2348
+ api,
2349
+ apiVersion: API_VERSION
2350
+ });
2351
+ }
2352
+ click(point, options) {
2353
+ return this.#input.click(point, options);
2354
+ }
2355
+ pressKeys(keys, options) {
2356
+ return this.#input.pressKeys(keys, options);
2357
+ }
2358
+ setFocus(page, options) {
2359
+ return this.#input.setFocus(page, options);
2360
+ }
2361
+ /** WebSocket URL of the bridge's Playwright server, for `browserType.connect()`. */
2362
+ async playwrightEndpoint() {
2363
+ return playwrightEndpoint(await this.#resolveUrl());
2364
+ }
2365
+ getSpeech(options) {
2366
+ return this.#service.getSpeech(options);
2367
+ }
2368
+ getText(options) {
2369
+ return this.#service.getText(options);
2370
+ }
2371
+ clear() {
2372
+ return this.#service.clear();
2373
+ }
2374
+ startSession(name, options) {
2375
+ return this.#service.startSession(name, options);
2376
+ }
2377
+ endSession() {
2378
+ return this.#service.endSession();
2379
+ }
2380
+ sessions() {
2381
+ return this.#service.sessions();
2382
+ }
2383
+ mark(label) {
2384
+ return this.#service.mark(label);
2385
+ }
2386
+ status() {
2387
+ return this.#service.status();
2388
+ }
2389
+ waitForReady(options) {
2390
+ return this.#service.waitForReady(options);
2391
+ }
2392
+ waitForOutput(match, options) {
2393
+ return this.#service.waitForOutput(match, options);
2394
+ }
2395
+ waitForSequence(matches, options) {
2396
+ return this.#service.waitForSequence(matches, options);
2397
+ }
2398
+ waitForSilence(options) {
2399
+ return this.#service.waitForSilence(options);
2400
+ }
2401
+ record(fn, options) {
2402
+ return this.#service.record(fn, options);
2403
+ }
2404
+ onSpeech(listener, options) {
2405
+ return this.#service.onSpeech(listener, options);
2406
+ }
2407
+ cursor() {
2408
+ return this.#service.cursor();
2409
+ }
2410
+ setCursor(seq) {
2411
+ this.#service.setCursor(seq);
2412
+ }
2413
+ };
2414
+ export { IncompatibleBridgeError as _, READ_GEOMETRY_SCRIPT as a, normalizeText as b, CONFIG_PATH_ENV as c, URL_ENV as d, normalizeBridgeUrl as f, ClientConfigError as g, BridgeUnreachableError as h, FocusError as i, clientConfigFile as l, BridgeNotReadyError as m, createClientConfig as n, contentCornerPoint as o, BridgeHttpError as p, playwrightEndpoint as r, parseWindowGeometry as s, SpeechCaptureClient as t, DEFAULT_BRIDGE_URL as u, SpeechTimeoutError as v, SpeechTruncatedError as y };