@speeq/core 0.3.0 → 0.5.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.
- package/dist/chunk-CELQUH6A.js +166 -0
- package/dist/chunk-CELQUH6A.js.map +1 -0
- package/dist/{chunk-JA2L35IQ.js → chunk-FRW2OUQL.js} +8 -2
- package/dist/chunk-FRW2OUQL.js.map +1 -0
- package/dist/chunk-PU7PGHHO.js +421 -0
- package/dist/chunk-PU7PGHHO.js.map +1 -0
- package/dist/errors.cjs +6 -0
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.cts +1 -1
- package/dist/errors.d.ts +1 -1
- package/dist/errors.js +1 -1
- package/dist/index-DPp4Fwdy.d.cts +236 -0
- package/dist/index-I0oTxGMf.d.ts +236 -0
- package/dist/index.cjs +365 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +176 -3
- package/dist/index.d.ts +176 -3
- package/dist/index.js +87 -4
- package/dist/index.js.map +1 -1
- package/dist/manifest.cjs +230 -0
- package/dist/manifest.cjs.map +1 -0
- package/dist/manifest.d.cts +2523 -0
- package/dist/manifest.d.ts +2523 -0
- package/dist/manifest.js +218 -0
- package/dist/manifest.js.map +1 -0
- package/dist/speech-http.cjs +346 -0
- package/dist/speech-http.cjs.map +1 -0
- package/dist/speech-http.d.cts +41 -0
- package/dist/speech-http.d.ts +41 -0
- package/dist/speech-http.js +264 -0
- package/dist/speech-http.js.map +1 -0
- package/dist/speech-provider-D0YChUSt.d.cts +103 -0
- package/dist/speech-provider-D0YChUSt.d.ts +103 -0
- package/dist/utils.cjs +237 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +2 -156
- package/dist/utils.d.ts +2 -156
- package/dist/utils.js +3 -2
- package/package.json +24 -2
- package/dist/chunk-JA2L35IQ.js.map +0 -1
- package/dist/chunk-JOTEKM5R.js +0 -318
- package/dist/chunk-JOTEKM5R.js.map +0 -1
package/dist/chunk-JOTEKM5R.js
DELETED
|
@@ -1,318 +0,0 @@
|
|
|
1
|
-
import { SpeeqError, isAbortError } from './chunk-JA2L35IQ.js';
|
|
2
|
-
|
|
3
|
-
// src/utils/async.ts
|
|
4
|
-
function combineSignals(signals, timeoutMs) {
|
|
5
|
-
const list = signals.filter((s) => s !== void 0);
|
|
6
|
-
if (timeoutMs !== void 0) list.push(AbortSignal.timeout(timeoutMs));
|
|
7
|
-
if (typeof AbortSignal.any === "function") return AbortSignal.any(list);
|
|
8
|
-
const controller = new AbortController();
|
|
9
|
-
for (const s of list) {
|
|
10
|
-
if (s.aborted) {
|
|
11
|
-
controller.abort(s.reason);
|
|
12
|
-
break;
|
|
13
|
-
}
|
|
14
|
-
s.addEventListener("abort", () => controller.abort(s.reason), { once: true });
|
|
15
|
-
}
|
|
16
|
-
return controller.signal;
|
|
17
|
-
}
|
|
18
|
-
function sleep(ms, signal) {
|
|
19
|
-
return new Promise((resolve, reject) => {
|
|
20
|
-
if (signal?.aborted) {
|
|
21
|
-
reject(signal.reason);
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
|
-
const timer = setTimeout(resolve, ms);
|
|
25
|
-
signal?.addEventListener(
|
|
26
|
-
"abort",
|
|
27
|
-
() => {
|
|
28
|
-
clearTimeout(timer);
|
|
29
|
-
reject(signal.reason);
|
|
30
|
-
},
|
|
31
|
-
{ once: true }
|
|
32
|
-
);
|
|
33
|
-
});
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
// src/utils/emitter.ts
|
|
37
|
-
var TypedEmitter = class {
|
|
38
|
-
listeners = /* @__PURE__ */ new Map();
|
|
39
|
-
/** Subscribes to `event`. Returns an unsubscribe function. */
|
|
40
|
-
on(event, listener) {
|
|
41
|
-
let set = this.listeners.get(event);
|
|
42
|
-
if (!set) {
|
|
43
|
-
set = /* @__PURE__ */ new Set();
|
|
44
|
-
this.listeners.set(event, set);
|
|
45
|
-
}
|
|
46
|
-
set.add(listener);
|
|
47
|
-
return () => this.off(event, listener);
|
|
48
|
-
}
|
|
49
|
-
/** Subscribes to the next `event` only. */
|
|
50
|
-
once(event, listener) {
|
|
51
|
-
const off = this.on(event, (payload) => {
|
|
52
|
-
off();
|
|
53
|
-
listener(payload);
|
|
54
|
-
});
|
|
55
|
-
return off;
|
|
56
|
-
}
|
|
57
|
-
/** Removes a listener. */
|
|
58
|
-
off(event, listener) {
|
|
59
|
-
this.listeners.get(event)?.delete(listener);
|
|
60
|
-
}
|
|
61
|
-
/** Calls every listener for `event` with `payload`. */
|
|
62
|
-
emit(event, payload) {
|
|
63
|
-
const set = this.listeners.get(event);
|
|
64
|
-
if (!set) return;
|
|
65
|
-
for (const listener of [...set]) {
|
|
66
|
-
try {
|
|
67
|
-
listener(payload);
|
|
68
|
-
} catch (error) {
|
|
69
|
-
console.error("[speeq] event listener threw", error);
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
}
|
|
73
|
-
/** Removes every listener. */
|
|
74
|
-
clear() {
|
|
75
|
-
this.listeners.clear();
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
|
|
79
|
-
// src/utils/ids.ts
|
|
80
|
-
function createId(prefix) {
|
|
81
|
-
return `${prefix}_${globalThis.crypto.randomUUID().replace(/-/g, "")}`;
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
// src/utils/json.ts
|
|
85
|
-
function safeJsonParse(text) {
|
|
86
|
-
try {
|
|
87
|
-
return { ok: true, value: JSON.parse(text) };
|
|
88
|
-
} catch (error) {
|
|
89
|
-
return { ok: false, error: error instanceof Error ? error.message : "Invalid JSON" };
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
function safeJsonStringify(value, space) {
|
|
93
|
-
const seen = /* @__PURE__ */ new WeakSet();
|
|
94
|
-
try {
|
|
95
|
-
const out = JSON.stringify(
|
|
96
|
-
value,
|
|
97
|
-
(_key, v) => {
|
|
98
|
-
if (typeof v === "bigint") return v.toString();
|
|
99
|
-
if (typeof v === "function" || typeof v === "symbol") return void 0;
|
|
100
|
-
if (v instanceof Error) return { name: v.name, message: v.message };
|
|
101
|
-
if (typeof v === "object" && v !== null) {
|
|
102
|
-
if (seen.has(v)) return "[Circular]";
|
|
103
|
-
seen.add(v);
|
|
104
|
-
}
|
|
105
|
-
return v;
|
|
106
|
-
},
|
|
107
|
-
space
|
|
108
|
-
);
|
|
109
|
-
return out ?? "null";
|
|
110
|
-
} catch {
|
|
111
|
-
return '"[Unserializable]"';
|
|
112
|
-
}
|
|
113
|
-
}
|
|
114
|
-
function truncate(text, maxChars) {
|
|
115
|
-
if (text.length <= maxChars) return { text, truncated: false };
|
|
116
|
-
const marker = "\u2026[truncated]";
|
|
117
|
-
const keep = Math.max(0, maxChars - marker.length);
|
|
118
|
-
return { text: text.slice(0, keep) + marker, truncated: true };
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
// src/utils/sse.ts
|
|
122
|
-
function encodeSse(event, data) {
|
|
123
|
-
const lines = data.split(/\r?\n/).map((line) => `data: ${line}`);
|
|
124
|
-
return `event: ${event}
|
|
125
|
-
${lines.join("\n")}
|
|
126
|
-
|
|
127
|
-
`;
|
|
128
|
-
}
|
|
129
|
-
var SseParser = class {
|
|
130
|
-
buffer = "";
|
|
131
|
-
event = "";
|
|
132
|
-
data = [];
|
|
133
|
-
id;
|
|
134
|
-
/** Adds a chunk and returns every message completed by it. */
|
|
135
|
-
push(chunk) {
|
|
136
|
-
this.buffer += chunk;
|
|
137
|
-
const out = [];
|
|
138
|
-
for (; ; ) {
|
|
139
|
-
const match = /\r\n|\r|\n/.exec(this.buffer);
|
|
140
|
-
if (!match) break;
|
|
141
|
-
if (match[0] === "\r" && match.index === this.buffer.length - 1) break;
|
|
142
|
-
const line = this.buffer.slice(0, match.index);
|
|
143
|
-
this.buffer = this.buffer.slice(match.index + match[0].length);
|
|
144
|
-
const message = this.processLine(line);
|
|
145
|
-
if (message) out.push(message);
|
|
146
|
-
}
|
|
147
|
-
return out;
|
|
148
|
-
}
|
|
149
|
-
/** Flushes a final message that was not followed by a blank line (end of stream). */
|
|
150
|
-
end() {
|
|
151
|
-
const out = this.buffer.length > 0 ? this.push("\n") : [];
|
|
152
|
-
const last = this.dispatch();
|
|
153
|
-
return last ? [...out, last] : out;
|
|
154
|
-
}
|
|
155
|
-
processLine(line) {
|
|
156
|
-
if (line === "") return this.dispatch();
|
|
157
|
-
if (line.startsWith(":")) return null;
|
|
158
|
-
const colon = line.indexOf(":");
|
|
159
|
-
const field = colon === -1 ? line : line.slice(0, colon);
|
|
160
|
-
let value = colon === -1 ? "" : line.slice(colon + 1);
|
|
161
|
-
if (value.startsWith(" ")) value = value.slice(1);
|
|
162
|
-
if (field === "event") this.event = value;
|
|
163
|
-
else if (field === "data") this.data.push(value);
|
|
164
|
-
else if (field === "id") this.id = value;
|
|
165
|
-
return null;
|
|
166
|
-
}
|
|
167
|
-
dispatch() {
|
|
168
|
-
if (this.data.length === 0) {
|
|
169
|
-
this.event = "";
|
|
170
|
-
return null;
|
|
171
|
-
}
|
|
172
|
-
const message = { event: this.event || "message", data: this.data.join("\n") };
|
|
173
|
-
if (this.id !== void 0) message.id = this.id;
|
|
174
|
-
this.event = "";
|
|
175
|
-
this.data = [];
|
|
176
|
-
return message;
|
|
177
|
-
}
|
|
178
|
-
};
|
|
179
|
-
|
|
180
|
-
// src/utils/provider-http.ts
|
|
181
|
-
async function* readSseData(body, signal) {
|
|
182
|
-
const reader = body.getReader();
|
|
183
|
-
const decoder = new TextDecoder();
|
|
184
|
-
const parser = new SseParser();
|
|
185
|
-
try {
|
|
186
|
-
for (; ; ) {
|
|
187
|
-
signal?.throwIfAborted();
|
|
188
|
-
const { value, done } = await reader.read();
|
|
189
|
-
const messages = done ? parser.end() : parser.push(decoder.decode(value, { stream: true }));
|
|
190
|
-
for (const m of messages) {
|
|
191
|
-
if (m.data === "[DONE]") return;
|
|
192
|
-
yield m.data;
|
|
193
|
-
}
|
|
194
|
-
if (done) return;
|
|
195
|
-
}
|
|
196
|
-
} finally {
|
|
197
|
-
reader.cancel().catch(() => void 0);
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
function parseRetryAfter(value) {
|
|
201
|
-
if (!value) return void 0;
|
|
202
|
-
const seconds = Number(value);
|
|
203
|
-
if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1e3));
|
|
204
|
-
const date = Date.parse(value);
|
|
205
|
-
return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
|
|
206
|
-
}
|
|
207
|
-
var QUOTA_RE = /rate.?limit|quota|resource.?exhausted|too many requests|tokens per (minute|day)/i;
|
|
208
|
-
function mapProviderHttpError(provider, status, bodyText, retryAfter) {
|
|
209
|
-
const details = { provider, status, body: bodyText.slice(0, 1e3) };
|
|
210
|
-
if (status === 429 || QUOTA_RE.test(bodyText)) {
|
|
211
|
-
return new SpeeqError("RATE_LIMITED", {
|
|
212
|
-
retryAfterMs: parseRetryAfter(retryAfter) ?? 5e3,
|
|
213
|
-
details
|
|
214
|
-
});
|
|
215
|
-
}
|
|
216
|
-
if (status === 401 || status === 403) {
|
|
217
|
-
return new SpeeqError("NOT_CONFIGURED", {
|
|
218
|
-
message: "The AI provider rejected the API key.",
|
|
219
|
-
details
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
return new SpeeqError("PROVIDER_ERROR", { retryable: status >= 500, details });
|
|
223
|
-
}
|
|
224
|
-
async function providerFetch(provider, fetchImpl, url, init) {
|
|
225
|
-
try {
|
|
226
|
-
return await fetchImpl(url, init);
|
|
227
|
-
} catch (error) {
|
|
228
|
-
if (isAbortError(error)) throw error;
|
|
229
|
-
throw new SpeeqError("PROVIDER_ERROR", { cause: error, details: { provider, network: true } });
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
// src/utils/redact.ts
|
|
234
|
-
var REDACTED = "[REDACTED]";
|
|
235
|
-
var DEFAULT_SECRET_KEYS = [
|
|
236
|
-
"password",
|
|
237
|
-
"passwd",
|
|
238
|
-
"secret",
|
|
239
|
-
"token",
|
|
240
|
-
"accesstoken",
|
|
241
|
-
"refreshtoken",
|
|
242
|
-
"apikey",
|
|
243
|
-
"api_key",
|
|
244
|
-
"authorization",
|
|
245
|
-
"cookie",
|
|
246
|
-
"creditcard",
|
|
247
|
-
"cardnumber",
|
|
248
|
-
"cvv",
|
|
249
|
-
"ssn"
|
|
250
|
-
];
|
|
251
|
-
function redactKeys(value, keys = DEFAULT_SECRET_KEYS) {
|
|
252
|
-
const wanted = new Set(keys.map(normalizeKey));
|
|
253
|
-
const walk = (v, depth) => {
|
|
254
|
-
if (depth > 20 || v === null || typeof v !== "object") return v;
|
|
255
|
-
if (Array.isArray(v)) return v.map((item) => walk(item, depth + 1));
|
|
256
|
-
const out = {};
|
|
257
|
-
for (const [k, inner] of Object.entries(v)) {
|
|
258
|
-
out[k] = wanted.has(normalizeKey(k)) ? REDACTED : walk(inner, depth + 1);
|
|
259
|
-
}
|
|
260
|
-
return out;
|
|
261
|
-
};
|
|
262
|
-
return walk(value, 0);
|
|
263
|
-
}
|
|
264
|
-
function normalizeKey(key) {
|
|
265
|
-
return key.toLowerCase().replace(/[-_]/g, "");
|
|
266
|
-
}
|
|
267
|
-
var EMAIL_RE = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi;
|
|
268
|
-
var LONG_NUMBER_RE = /\+?\d[\d\s-]{8,}\d/g;
|
|
269
|
-
function redactText(text) {
|
|
270
|
-
return text.replace(EMAIL_RE, REDACTED).replace(LONG_NUMBER_RE, REDACTED);
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
// src/utils/sentence-chunker.ts
|
|
274
|
-
var END_RE = /([.!?…。!?।॥]+["')\]]*)\s+/u;
|
|
275
|
-
var SentenceChunker = class {
|
|
276
|
-
buffer = "";
|
|
277
|
-
maxLength;
|
|
278
|
-
constructor(options = {}) {
|
|
279
|
-
this.maxLength = options.maxLength ?? 220;
|
|
280
|
-
}
|
|
281
|
-
/** Adds a delta and returns every sentence it completed (never empty strings). */
|
|
282
|
-
push(delta) {
|
|
283
|
-
this.buffer += delta;
|
|
284
|
-
const out = [];
|
|
285
|
-
for (let s = this.take(); s !== null; s = this.take()) {
|
|
286
|
-
if (s.length > 0) out.push(s);
|
|
287
|
-
}
|
|
288
|
-
return out;
|
|
289
|
-
}
|
|
290
|
-
/** Returns the buffered remainder (trimmed, may be empty) and resets the chunker. */
|
|
291
|
-
flush() {
|
|
292
|
-
const rest = this.buffer.trim();
|
|
293
|
-
this.buffer = "";
|
|
294
|
-
return rest;
|
|
295
|
-
}
|
|
296
|
-
take() {
|
|
297
|
-
const match = END_RE.exec(this.buffer);
|
|
298
|
-
const endIdx = match ? match.index + (match[1]?.length ?? 0) : -1;
|
|
299
|
-
const newline = this.buffer.indexOf("\n");
|
|
300
|
-
const candidates = [endIdx, newline].filter((i) => i >= 0);
|
|
301
|
-
if (candidates.length > 0) return this.cut(Math.min(...candidates));
|
|
302
|
-
if (this.buffer.length > this.maxLength) {
|
|
303
|
-
const window = this.buffer.slice(0, this.maxLength);
|
|
304
|
-
const soft = Math.max(window.lastIndexOf(", "), window.lastIndexOf(" "));
|
|
305
|
-
return this.cut(soft > this.maxLength / 3 ? soft + 1 : this.maxLength);
|
|
306
|
-
}
|
|
307
|
-
return null;
|
|
308
|
-
}
|
|
309
|
-
cut(at) {
|
|
310
|
-
const sentence = this.buffer.slice(0, at).trim();
|
|
311
|
-
this.buffer = this.buffer.slice(at).replace(/^\s+/, "");
|
|
312
|
-
return sentence;
|
|
313
|
-
}
|
|
314
|
-
};
|
|
315
|
-
|
|
316
|
-
export { DEFAULT_SECRET_KEYS, REDACTED, SentenceChunker, SseParser, TypedEmitter, combineSignals, createId, encodeSse, mapProviderHttpError, parseRetryAfter, providerFetch, readSseData, redactKeys, redactText, safeJsonParse, safeJsonStringify, sleep, truncate };
|
|
317
|
-
//# sourceMappingURL=chunk-JOTEKM5R.js.map
|
|
318
|
-
//# sourceMappingURL=chunk-JOTEKM5R.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/async.ts","../src/utils/emitter.ts","../src/utils/ids.ts","../src/utils/json.ts","../src/utils/sse.ts","../src/utils/provider-http.ts","../src/utils/redact.ts","../src/utils/sentence-chunker.ts"],"names":[],"mappings":";;;AAIO,SAAS,cAAA,CACd,SACA,SAAA,EACa;AACb,EAAA,MAAM,OAAO,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,KAAwB,MAAM,MAAS,CAAA;AACpE,EAAA,IAAI,cAAc,MAAA,EAAW,IAAA,CAAK,KAAK,WAAA,CAAY,OAAA,CAAQ,SAAS,CAAC,CAAA;AACrE,EAAA,IAAI,OAAO,WAAA,CAAY,GAAA,KAAQ,YAAY,OAAO,WAAA,CAAY,IAAI,IAAI,CAAA;AACtE,EAAA,MAAM,UAAA,GAAa,IAAI,eAAA,EAAgB;AACvC,EAAA,KAAA,MAAW,KAAK,IAAA,EAAM;AACpB,IAAA,IAAI,EAAE,OAAA,EAAS;AACb,MAAA,UAAA,CAAW,KAAA,CAAM,EAAE,MAAM,CAAA;AACzB,MAAA;AAAA,IACF;AACA,IAAA,CAAA,CAAE,gBAAA,CAAiB,OAAA,EAAS,MAAM,UAAA,CAAW,KAAA,CAAM,CAAA,CAAE,MAAM,CAAA,EAAG,EAAE,IAAA,EAAM,IAAA,EAAM,CAAA;AAAA,EAC9E;AACA,EAAA,OAAO,UAAA,CAAW,MAAA;AACpB;AAGO,SAAS,KAAA,CAAM,IAAY,MAAA,EAAqC;AACrE,EAAA,OAAO,IAAI,OAAA,CAAQ,CAAC,OAAA,EAAS,MAAA,KAAW;AACtC,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,MAAA,CAAO,OAAO,MAAM,CAAA;AACpB,MAAA;AAAA,IACF;AACA,IAAA,MAAM,KAAA,GAAQ,UAAA,CAAW,OAAA,EAAS,EAAE,CAAA;AACpC,IAAA,MAAA,EAAQ,gBAAA;AAAA,MACN,OAAA;AAAA,MAC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a,CAAC,MAAA,EAAQ,OAAO,EAAE,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,IAAK,CAAC,CAAA;AACzD,IAAA,IAAI,UAAA,CAAW,MAAA,GAAS,CAAA,EAAG,OAAO,IAAA,CAAK,IAAI,IAAA,CAAK,GAAA,CAAI,GAAG,UAAU,CAAC,CAAA;AAElE,IAAA,IAAI,IAAA,CAAK,MAAA,CAAO,MAAA,GAAS,IAAA,CAAK,SAAA,EAAW;AACvC,MAAA,MAAM,SAAS,IAAA,CAAK,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,KAAK,SAAS,CAAA;AAClD,MAAA,MAAM,IAAA,GAAO,IAAA,CAAK,GAAA,CAAI,MAAA,CAAO,WAAA,CAAY,IAAI,CAAA,EAAG,MAAA,CAAO,WAAA,CAAY,GAAG,CAAC,CAAA;AACvE,MAAA,OAAO,IAAA,CAAK,IAAI,IAAA,GAAO,IAAA,CAAK,YAAY,CAAA,GAAI,IAAA,GAAO,CAAA,GAAI,IAAA,CAAK,SAAS,CAAA;AAAA,IACvE;AACA,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EAEQ,IAAI,EAAA,EAAoB;AAC9B,IAAA,MAAM,WAAW,IAAA,CAAK,MAAA,CAAO,MAAM,CAAA,EAAG,EAAE,EAAE,IAAA,EAAK;AAC/C,IAAA,IAAA,CAAK,MAAA,GAAS,KAAK,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA,CAAE,OAAA,CAAQ,QAAQ,EAAE,CAAA;AACtD,IAAA,OAAO,QAAA;AAAA,EACT;AACF","file":"chunk-JOTEKM5R.js","sourcesContent":["/**\n * Returns an `AbortSignal` that aborts when any input signal aborts, or after `timeoutMs`.\n * It uses `AbortSignal.any` / `AbortSignal.timeout` when available, with a manual fallback.\n */\nexport function combineSignals(\n signals: ReadonlyArray<AbortSignal | undefined>,\n timeoutMs?: number,\n): AbortSignal {\n const list = signals.filter((s): s is AbortSignal => s !== undefined);\n if (timeoutMs !== undefined) list.push(AbortSignal.timeout(timeoutMs));\n if (typeof AbortSignal.any === \"function\") return AbortSignal.any(list);\n const controller = new AbortController();\n for (const s of list) {\n if (s.aborted) {\n controller.abort(s.reason);\n break;\n }\n s.addEventListener(\"abort\", () => controller.abort(s.reason), { once: true });\n }\n return controller.signal;\n}\n\n/** Resolves after `ms` milliseconds, or rejects early when `signal` aborts. */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(timer);\n reject(signal.reason);\n },\n { once: true },\n );\n });\n}\n","/** A listener for event `K` of an event map `E`. */\nexport type Listener<E, K extends keyof E> = (payload: E[K]) => void;\n\n/**\n * A tiny, typed event emitter. A listener that throws never breaks other listeners or the\n * emitter (the error is reported with `console.error`).\n *\n * @example\n * const em = new TypedEmitter<{ state: \"idle\" | \"busy\" }>();\n * const off = em.on(\"state\", (s) => console.log(s));\n * em.emit(\"state\", \"busy\");\n * off();\n */\nexport class TypedEmitter<E extends Record<string, unknown>> {\n private readonly listeners = new Map<keyof E, Set<(payload: never) => void>>();\n\n /** Subscribes to `event`. Returns an unsubscribe function. */\n on<K extends keyof E>(event: K, listener: Listener<E, K>): () => void {\n let set = this.listeners.get(event);\n if (!set) {\n set = new Set();\n this.listeners.set(event, set);\n }\n set.add(listener as (payload: never) => void);\n return () => this.off(event, listener);\n }\n\n /** Subscribes to the next `event` only. */\n once<K extends keyof E>(event: K, listener: Listener<E, K>): () => void {\n const off = this.on(event, (payload) => {\n off();\n listener(payload);\n });\n return off;\n }\n\n /** Removes a listener. */\n off<K extends keyof E>(event: K, listener: Listener<E, K>): void {\n this.listeners.get(event)?.delete(listener as (payload: never) => void);\n }\n\n /** Calls every listener for `event` with `payload`. */\n emit<K extends keyof E>(event: K, payload: E[K]): void {\n const set = this.listeners.get(event);\n if (!set) return;\n for (const listener of [...set]) {\n try {\n (listener as Listener<E, K>)(payload);\n } catch (error) {\n console.error(\"[speeq] event listener threw\", error);\n }\n }\n }\n\n /** Removes every listener. */\n clear(): void {\n this.listeners.clear();\n }\n}\n","/**\n * Returns a random, URL-safe id such as `ses_3f9a…`. It uses `crypto.randomUUID()`, which is\n * available in browsers, Node 20+ and edge runtimes. Ids never encode user data.\n *\n * @param prefix - A short readable prefix such as `ses`, `evt` or `turn`.\n */\nexport function createId(prefix: string): string {\n return `${prefix}_${globalThis.crypto.randomUUID().replace(/-/g, \"\")}`;\n}\n","/** Result of {@link safeJsonParse}. */\nexport type SafeJsonResult<T = unknown> = { ok: true; value: T } | { ok: false; error: string };\n\n/** Parses JSON without throwing. */\nexport function safeJsonParse<T = unknown>(text: string): SafeJsonResult<T> {\n try {\n return { ok: true, value: JSON.parse(text) as T };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error.message : \"Invalid JSON\" };\n }\n}\n\n/**\n * Stringifies any value without throwing: handles cycles (`\"[Circular]\"`), `bigint`, `Error`,\n * `undefined` at the top level and functions. Use it for tool output before sending it to a model.\n */\nexport function safeJsonStringify(value: unknown, space?: number): string {\n const seen = new WeakSet<object>();\n try {\n const out = JSON.stringify(\n value,\n (_key, v: unknown) => {\n if (typeof v === \"bigint\") return v.toString();\n if (typeof v === \"function\" || typeof v === \"symbol\") return undefined;\n if (v instanceof Error) return { name: v.name, message: v.message };\n if (typeof v === \"object\" && v !== null) {\n if (seen.has(v)) return \"[Circular]\";\n seen.add(v);\n }\n return v;\n },\n space,\n );\n return out ?? \"null\";\n } catch {\n return '\"[Unserializable]\"';\n }\n}\n\n/** Result of {@link truncate}. */\nexport interface TruncateResult {\n text: string;\n truncated: boolean;\n}\n\n/** Cuts `text` to at most `maxChars` characters and marks whether it was cut. */\nexport function truncate(text: string, maxChars: number): TruncateResult {\n if (text.length <= maxChars) return { text, truncated: false };\n const marker = \"…[truncated]\";\n const keep = Math.max(0, maxChars - marker.length);\n return { text: text.slice(0, keep) + marker, truncated: true };\n}\n","/** One parsed Server-Sent Event. */\nexport interface SseMessage {\n /** The `event:` field, or `\"message\"` when absent. */\n event: string;\n /** The joined `data:` lines. */\n data: string;\n id?: string;\n}\n\n/** Encodes one SSE message (`event:` + `data:` lines + blank line). */\nexport function encodeSse(event: string, data: string): string {\n const lines = data.split(/\\r?\\n/).map((line) => `data: ${line}`);\n return `event: ${event}\\n${lines.join(\"\\n\")}\\n\\n`;\n}\n\n/**\n * Incremental SSE parser that follows the WHATWG event-stream rules. Feed it decoded text chunks\n * in any split (mid-line, mid-field, CRLF across chunks) and it returns complete messages.\n */\nexport class SseParser {\n private buffer = \"\";\n private event = \"\";\n private data: string[] = [];\n private id: string | undefined;\n\n /** Adds a chunk and returns every message completed by it. */\n push(chunk: string): SseMessage[] {\n this.buffer += chunk;\n const out: SseMessage[] = [];\n for (;;) {\n const match = /\\r\\n|\\r|\\n/.exec(this.buffer);\n if (!match) break;\n // A lone trailing \"\\r\" may be the first half of \"\\r\\n\": wait for more input.\n if (match[0] === \"\\r\" && match.index === this.buffer.length - 1) break;\n const line = this.buffer.slice(0, match.index);\n this.buffer = this.buffer.slice(match.index + match[0].length);\n const message = this.processLine(line);\n if (message) out.push(message);\n }\n return out;\n }\n\n /** Flushes a final message that was not followed by a blank line (end of stream). */\n end(): SseMessage[] {\n const out = this.buffer.length > 0 ? this.push(\"\\n\") : [];\n const last = this.dispatch();\n return last ? [...out, last] : out;\n }\n\n private processLine(line: string): SseMessage | null {\n if (line === \"\") return this.dispatch();\n if (line.startsWith(\":\")) return null;\n const colon = line.indexOf(\":\");\n const field = colon === -1 ? line : line.slice(0, colon);\n let value = colon === -1 ? \"\" : line.slice(colon + 1);\n if (value.startsWith(\" \")) value = value.slice(1);\n if (field === \"event\") this.event = value;\n else if (field === \"data\") this.data.push(value);\n else if (field === \"id\") this.id = value;\n return null;\n }\n\n private dispatch(): SseMessage | null {\n if (this.data.length === 0) {\n this.event = \"\";\n return null;\n }\n const message: SseMessage = { event: this.event || \"message\", data: this.data.join(\"\\n\") };\n if (this.id !== undefined) message.id = this.id;\n this.event = \"\";\n this.data = [];\n return message;\n }\n}\n","import { isAbortError, SpeeqError } from \"../errors.js\";\nimport { SseParser } from \"./sse.js\";\n\n/**\n * Reads the `data:` payloads of an SSE response body. For LLM adapters: stops at `[DONE]`\n * and honors `signal`.\n */\nexport async function* readSseData(\n body: ReadableStream<Uint8Array>,\n signal?: AbortSignal,\n): AsyncGenerator<string> {\n const reader = body.getReader();\n const decoder = new TextDecoder();\n const parser = new SseParser();\n try {\n for (;;) {\n signal?.throwIfAborted();\n const { value, done } = await reader.read();\n const messages = done ? parser.end() : parser.push(decoder.decode(value, { stream: true }));\n for (const m of messages) {\n if (m.data === \"[DONE]\") return;\n yield m.data;\n }\n if (done) return;\n }\n } finally {\n reader.cancel().catch(() => undefined);\n }\n}\n\n/** Parses a `Retry-After` header (seconds or HTTP date) into milliseconds. */\nexport function parseRetryAfter(value: string | null | undefined): number | undefined {\n if (!value) return undefined;\n const seconds = Number(value);\n if (Number.isFinite(seconds)) return Math.max(0, Math.round(seconds * 1000));\n const date = Date.parse(value);\n return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());\n}\n\nconst QUOTA_RE = /rate.?limit|quota|resource.?exhausted|too many requests|tokens per (minute|day)/i;\n\n/**\n * Maps an HTTP error from an LLM provider to a {@link SpeeqError}:\n * 429 and quota or rate-limit bodies → `RATE_LIMITED` (with a retry hint), 401/403 →\n * `NOT_CONFIGURED` (bad API key), anything else → `PROVIDER_ERROR`. The provider's raw message\n * is kept in `details` for server logs, never in the public message.\n */\nexport function mapProviderHttpError(\n provider: string,\n status: number,\n bodyText: string,\n retryAfter?: string | null,\n): SpeeqError {\n const details = { provider, status, body: bodyText.slice(0, 1000) };\n if (status === 429 || QUOTA_RE.test(bodyText)) {\n return new SpeeqError(\"RATE_LIMITED\", {\n retryAfterMs: parseRetryAfter(retryAfter) ?? 5000,\n details,\n });\n }\n if (status === 401 || status === 403) {\n return new SpeeqError(\"NOT_CONFIGURED\", {\n message: \"The AI provider rejected the API key.\",\n details,\n });\n }\n return new SpeeqError(\"PROVIDER_ERROR\", { retryable: status >= 500, details });\n}\n\n/** Wraps `fetch` so network failures become `PROVIDER_ERROR` and aborts are rethrown as-is. */\nexport async function providerFetch(\n provider: string,\n fetchImpl: typeof fetch,\n url: string,\n init: RequestInit,\n): Promise<Response> {\n try {\n return await fetchImpl(url, init);\n } catch (error) {\n if (isAbortError(error)) throw error;\n throw new SpeeqError(\"PROVIDER_ERROR\", { cause: error, details: { provider, network: true } });\n }\n}\n","/** The placeholder written in place of redacted values. */\nexport const REDACTED = \"[REDACTED]\";\n\n/** Keys that are redacted by default by {@link redactKeys}. Matching ignores case. */\nexport const DEFAULT_SECRET_KEYS: readonly string[] = [\n \"password\",\n \"passwd\",\n \"secret\",\n \"token\",\n \"accesstoken\",\n \"refreshtoken\",\n \"apikey\",\n \"api_key\",\n \"authorization\",\n \"cookie\",\n \"creditcard\",\n \"cardnumber\",\n \"cvv\",\n \"ssn\",\n];\n\n/**\n * Returns a deep copy of `value` with the values of matching keys replaced by `[REDACTED]`.\n * Matching ignores case and also strips `-` / `_`, so `api-key` matches `apikey`.\n */\nexport function redactKeys<T>(value: T, keys: readonly string[] = DEFAULT_SECRET_KEYS): T {\n const wanted = new Set(keys.map(normalizeKey));\n const walk = (v: unknown, depth: number): unknown => {\n if (depth > 20 || v === null || typeof v !== \"object\") return v;\n if (Array.isArray(v)) return v.map((item) => walk(item, depth + 1));\n const out: Record<string, unknown> = {};\n for (const [k, inner] of Object.entries(v)) {\n out[k] = wanted.has(normalizeKey(k)) ? REDACTED : walk(inner, depth + 1);\n }\n return out;\n };\n return walk(value, 0) as T;\n}\n\nfunction normalizeKey(key: string): string {\n return key.toLowerCase().replace(/[-_]/g, \"\");\n}\n\nconst EMAIL_RE = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}/gi;\n// 10+ digit sequences, optionally with +, spaces or dashes (phone numbers, card numbers).\nconst LONG_NUMBER_RE = /\\+?\\d[\\d\\s-]{8,}\\d/g;\n\n/** Replaces email addresses and long digit sequences (phones, cards) in free text. */\nexport function redactText(text: string): string {\n return text.replace(EMAIL_RE, REDACTED).replace(LONG_NUMBER_RE, REDACTED);\n}\n","/** Options for {@link SentenceChunker}. */\nexport interface SentenceChunkerOptions {\n /** Force a split (at the last comma or space) once a sentence grows past this length. */\n maxLength?: number;\n}\n\n// Sentence enders: Latin . ! ?, ellipsis, CJK 。!? and Devanagari danda । ॥ (used in Hindi),\n// optionally followed by closing quotes/brackets, and then whitespace.\nconst END_RE = /([.!?…。!?।॥]+[\"')\\]]*)\\s+/u;\n\n/**\n * Splits streamed text deltas into whole sentences, so text-to-speech can start speaking the\n * first sentence while the rest is still generating.\n *\n * A sentence ends at end-punctuation followed by whitespace, or at a newline. Punctuation at the\n * very end of the buffer waits for more input, so `3.` + `5` stays `3.5`. Overlong text is split\n * at the last comma or space before `maxLength`.\n *\n * @example\n * const c = new SentenceChunker();\n * c.push(\"Hello the\"); // []\n * c.push(\"re. How are\"); // [\"Hello there.\"]\n * c.flush(); // \"How are\"\n */\nexport class SentenceChunker {\n private buffer = \"\";\n private readonly maxLength: number;\n\n constructor(options: SentenceChunkerOptions = {}) {\n this.maxLength = options.maxLength ?? 220;\n }\n\n /** Adds a delta and returns every sentence it completed (never empty strings). */\n push(delta: string): string[] {\n this.buffer += delta;\n const out: string[] = [];\n for (let s = this.take(); s !== null; s = this.take()) {\n if (s.length > 0) out.push(s);\n }\n return out;\n }\n\n /** Returns the buffered remainder (trimmed, may be empty) and resets the chunker. */\n flush(): string {\n const rest = this.buffer.trim();\n this.buffer = \"\";\n return rest;\n }\n\n private take(): string | null {\n const match = END_RE.exec(this.buffer);\n const endIdx = match ? match.index + (match[1]?.length ?? 0) : -1;\n const newline = this.buffer.indexOf(\"\\n\");\n const candidates = [endIdx, newline].filter((i) => i >= 0);\n if (candidates.length > 0) return this.cut(Math.min(...candidates));\n\n if (this.buffer.length > this.maxLength) {\n const window = this.buffer.slice(0, this.maxLength);\n const soft = Math.max(window.lastIndexOf(\", \"), window.lastIndexOf(\" \"));\n return this.cut(soft > this.maxLength / 3 ? soft + 1 : this.maxLength);\n }\n return null;\n }\n\n private cut(at: number): string {\n const sentence = this.buffer.slice(0, at).trim();\n this.buffer = this.buffer.slice(at).replace(/^\\s+/, \"\");\n return sentence;\n }\n}\n"]}
|