article-voice 0.1.0 → 0.2.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/index.js CHANGED
@@ -402,17 +402,20 @@ var DetectArticle = class {
402
402
  detector;
403
403
  execute(input = {}) {
404
404
  const minWords = input.minWords ?? MinWords.of(DEFAULT_MIN_WORDS);
405
- const candidates = this.source.candidates(input.explicitId);
405
+ const target = input.explicitId === void 0 ? input.target : void 0;
406
+ const selected = target === void 0 ? void 0 : this.source.selectByCss?.(target);
407
+ const candidates = target === void 0 ? this.source.candidates(input.explicitId) : selected ? [selected] : [];
408
+ const explicitId = selected?.id ?? input.explicitId;
406
409
  const result = this.detector.detect({
407
410
  candidates,
408
411
  minWords,
409
- ...input.explicitId !== void 0 ? { explicitId: input.explicitId } : {}
412
+ ...explicitId !== void 0 ? { explicitId } : {}
410
413
  });
411
414
  if (!result.ok) {
412
415
  if (result.code === "AV_ARTICLE_NOT_FOUND") {
413
416
  throw new ResourceNotFoundError(result.code, "No se encontr\xF3 el art\xEDculo", {
414
417
  recoverable: true,
415
- details: { explicitId: input.explicitId }
418
+ details: target === void 0 ? { explicitId: input.explicitId } : { target }
416
419
  });
417
420
  }
418
421
  throw new DomainValidationError(result.code, "El art\xEDculo es demasiado corto", {
@@ -511,7 +514,10 @@ var SelectEngine = class {
511
514
  async execute(input = {}, signal) {
512
515
  const requested = (input.engine ?? EngineKind.DEFAULT).value;
513
516
  const allowFallback = (input.fallback ?? "web-speech") === "web-speech";
514
- if (requested === "moss-browser") return { kind: "moss-browser", fallback: false };
517
+ if (requested === "moss-browser") {
518
+ if (input.mossBrowserAvailable !== false) return { kind: "moss-browser", fallback: false };
519
+ return this.systemVoiceFallback(requested, "moss-browser-unavailable", allowFallback);
520
+ }
515
521
  if (requested === "moss-server") {
516
522
  if (!input.serverUrl) throw unavailable('engine="moss-server" requiere server-url');
517
523
  return { kind: "moss-server", fallback: false };
@@ -527,12 +533,19 @@ var SelectEngine = class {
527
533
  }
528
534
  reason = "server-unreachable";
529
535
  }
536
+ return this.systemVoiceFallback(
537
+ input.serverUrl ? "moss-server" : "auto",
538
+ reason,
539
+ allowFallback
540
+ );
541
+ }
542
+ async systemVoiceFallback(from, reason, allowFallback) {
530
543
  if (!allowFallback) {
531
544
  throw unavailable('Ning\xFAn motor disponible y fallback="none"', { reason });
532
545
  }
533
546
  await this.assertSystemVoice();
534
547
  this.onFallback({
535
- from: input.serverUrl ? "moss-server" : "auto",
548
+ from,
536
549
  to: "web-speech",
537
550
  reason,
538
551
  label: SYSTEM_VOICE_LABEL
@@ -1558,6 +1571,7 @@ var BaseElement = typeof HTMLElement === "undefined" ? class {
1558
1571
  var ArticleVoiceElement = class extends BaseElement {
1559
1572
  static observedAttributes = [
1560
1573
  "for",
1574
+ "target",
1561
1575
  "lang",
1562
1576
  "engine",
1563
1577
  "fallback",
@@ -1584,6 +1598,8 @@ var ArticleVoiceElement = class extends BaseElement {
1584
1598
  articleSource = EMPTY_SOURCE;
1585
1599
  createEngine;
1586
1600
  createAudioOutput;
1601
+ /** Disponibilidad del adaptador en la composición. */
1602
+ mossBrowserAvailable = true;
1587
1603
  /** Resalta el segmento en lectura; sin él (o con `no-highlight`) no se resalta nada. */
1588
1604
  highlighter;
1589
1605
  /** D�nde se recuerdan velocidad y voz; por defecto localStorage (tolerante a fallos). */
@@ -1656,6 +1672,12 @@ var ArticleVoiceElement = class extends BaseElement {
1656
1672
  set htmlFor(v) {
1657
1673
  this.#reflect("for", v);
1658
1674
  }
1675
+ get target() {
1676
+ return this.getAttribute("target");
1677
+ }
1678
+ set target(v) {
1679
+ this.#reflect("target", v);
1680
+ }
1659
1681
  get engine() {
1660
1682
  return this.getAttribute("engine") ?? "auto";
1661
1683
  }
@@ -1925,6 +1947,7 @@ var ArticleVoiceElement = class extends BaseElement {
1925
1947
  ).execute({
1926
1948
  ...engine ? { engine } : {},
1927
1949
  ...serverUrl ? { serverUrl } : {},
1950
+ mossBrowserAvailable: this.mossBrowserAvailable,
1928
1951
  fallback
1929
1952
  });
1930
1953
  if (run !== this.#run) return;
@@ -1941,9 +1964,11 @@ var ArticleVoiceElement = class extends BaseElement {
1941
1964
  const minWords = this.#option(() => MinWords.from(this.getAttribute("min-words") ?? "120"));
1942
1965
  const rate = this.#option(() => PlaybackRate.from(this.getAttribute("rate") ?? "1"));
1943
1966
  const explicitId = this.getAttribute("for") ?? void 0;
1967
+ const target = this.target;
1944
1968
  const lang = this.getAttribute("lang") || void 0;
1945
1969
  const out = new DetectArticle(this.articleSource).execute({
1946
1970
  ...explicitId ? { explicitId } : {},
1971
+ ...target !== null ? { target } : {},
1947
1972
  ...minWords ? { minWords } : {},
1948
1973
  ...rate ? { rate } : {},
1949
1974
  ...lang ? { language: lang } : {}
@@ -1960,6 +1985,7 @@ var ArticleVoiceElement = class extends BaseElement {
1960
1985
  this.#emit("article-voice:ready", { article: this.article });
1961
1986
  } catch (error) {
1962
1987
  this.#article = null;
1988
+ this.#durationMs = 0;
1963
1989
  this.#syncUi();
1964
1990
  this.#emit("article-voice:error", toErrorDetail(error));
1965
1991
  }
@@ -1988,7 +2014,7 @@ var ArticleVoiceElement = class extends BaseElement {
1988
2014
  const modelUrl = this.getAttribute("model-url");
1989
2015
  const ortWasmUrl = this.getAttribute("ort-wasm-url");
1990
2016
  const workerUrl = this.getAttribute("worker-url");
1991
- const engine = this.createEngine({
2017
+ const request = {
1992
2018
  kind: active.kind,
1993
2019
  ...serverUrl ? { serverUrl } : {},
1994
2020
  ...modelUrl ? { modelUrl } : {},
@@ -1996,13 +2022,14 @@ var ArticleVoiceElement = class extends BaseElement {
1996
2022
  ...workerUrl ? { workerUrl } : {},
1997
2023
  language: article.language.value,
1998
2024
  rate: rate.value
1999
- });
2025
+ };
2026
+ const primary = this.createEngine(request);
2027
+ const engine = active.kind === "moss-server" && this.fallback !== "none" ? this.#withSystemVoiceFallback(primary, this.createEngine, request) : primary;
2000
2028
  this.#engine = engine;
2001
2029
  await engine.prepare();
2002
- const wanted = this.#prefVoice ?? this.getAttribute("voice");
2003
2030
  const available = engine.voices();
2004
2031
  this.#syncVoices(available.map((v) => v.value));
2005
- const voice = (wanted ? available.find((v) => v.value === wanted) : void 0) ?? available[0] ?? VoiceId.of("default");
2032
+ const voice = this.#chooseNarrationVoice(available);
2006
2033
  const segments = new Segmenter().segment(
2007
2034
  article.blocks,
2008
2035
  Language.of(article.language.value).value
@@ -2024,6 +2051,66 @@ var ArticleVoiceElement = class extends BaseElement {
2024
2051
  const session = await this.#play(play, narration);
2025
2052
  this.#session = session;
2026
2053
  }
2054
+ #chooseNarrationVoice(available) {
2055
+ const wanted = this.#prefVoice ?? this.getAttribute("voice");
2056
+ return available.find((v) => v.value === wanted) ?? available[0] ?? VoiceId.of("default");
2057
+ }
2058
+ #withSystemVoiceFallback(primary, createEngine, request) {
2059
+ const active = this.#active;
2060
+ let engine = primary;
2061
+ let serverDeliveredAudio = false;
2062
+ let localVoice;
2063
+ const switchToLocal = async (signal) => {
2064
+ const local = createEngine({ ...request, kind: "web-speech" });
2065
+ try {
2066
+ await local.prepare(signal);
2067
+ if (signal?.aborted || this.#active !== active) return false;
2068
+ const voices = local.voices();
2069
+ localVoice = this.#chooseNarrationVoice(voices);
2070
+ primary.dispose();
2071
+ engine = local;
2072
+ this.#active = { kind: "web-speech", fallback: true };
2073
+ this.#syncVoices(voices.map((v) => v.value));
2074
+ this.#syncUi();
2075
+ this.#emit(FALLBACK_EVENT, {
2076
+ from: "moss-server",
2077
+ to: "web-speech",
2078
+ reason: "server-synthesis-failed",
2079
+ label: SYSTEM_VOICE_LABEL
2080
+ });
2081
+ return true;
2082
+ } finally {
2083
+ if (engine !== local) local.dispose();
2084
+ }
2085
+ };
2086
+ return {
2087
+ get kind() {
2088
+ return engine.kind;
2089
+ },
2090
+ prepare: (signal) => engine.prepare(signal),
2091
+ voices: () => engine.voices(),
2092
+ dispose: () => engine.dispose(),
2093
+ async *synthesize(text, voice, signal) {
2094
+ if (engine !== primary) {
2095
+ yield* engine.synthesize(text, localVoice ?? voice, signal);
2096
+ return;
2097
+ }
2098
+ try {
2099
+ for await (const chunk of primary.synthesize(text, voice, signal)) {
2100
+ serverDeliveredAudio = true;
2101
+ yield chunk;
2102
+ }
2103
+ return;
2104
+ } catch (error) {
2105
+ if (serverDeliveredAudio || signal?.aborted || !(error instanceof DomainError) || error.code !== "AV_SERVER_ERROR") {
2106
+ throw error;
2107
+ }
2108
+ if (!await switchToLocal(signal).catch(() => false)) throw error;
2109
+ }
2110
+ yield* engine.synthesize(text, localVoice ?? voice, signal);
2111
+ }
2112
+ };
2113
+ }
2027
2114
  async #play(play, narration) {
2028
2115
  const pending = play.execute(narration);
2029
2116
  const session = this.#registry.active;
@@ -2563,26 +2650,44 @@ var DomArticleSource = class {
2563
2650
  if (explicit && !els.includes(explicit)) els.push(explicit);
2564
2651
  }
2565
2652
  for (const el of els) {
2566
- const excluded = this.isExcludedOrInside(el);
2567
- const raw = excluded ? [] : this.collect(el);
2568
- const wordCount = raw.reduce((n, b) => n + countWords2(b.text), 0);
2569
2653
  const isExplicit = explicitId !== void 0 && el.id === explicitId;
2570
- if (wordCount === 0 && !isExplicit) continue;
2571
- const id = el.id && !this.candidateEls.has(el.id) ? el.id : `av-c${this.nextCandidate++}`;
2572
- this.candidateEls.set(id, el);
2573
- out.push({
2574
- id,
2575
- tag: el.tagName.toLowerCase(),
2576
- wordCount,
2577
- linkWordCount: raw.reduce((n, b) => n + b.linkWords, 0),
2578
- paragraphCount: raw.filter((b) => b.role === "paragraph").length,
2579
- isArticleBody: el.getAttribute("itemprop") === "articleBody",
2580
- excluded
2581
- });
2654
+ const candidate = this.describeCandidate(el, isExplicit);
2655
+ if (candidate) out.push(candidate);
2582
2656
  }
2583
2657
  return out;
2584
2658
  }
2585
- /** Extrae los bloques legibles del candidato (llamar tras `candidates()`). */
2659
+ selectByCss(selector) {
2660
+ this.candidateEls.clear();
2661
+ let el;
2662
+ try {
2663
+ el = this.doc.querySelector(selector);
2664
+ } catch (error) {
2665
+ if (!(error instanceof DOMException) || error.name !== "SyntaxError") throw error;
2666
+ throw new DomainValidationError("AV_INVALID_OPTION", "Selector CSS inv\xE1lido", {
2667
+ details: { name: "target", reason: "Selector CSS inv\xE1lido", value: selector },
2668
+ recoverable: true
2669
+ });
2670
+ }
2671
+ return el ? this.describeCandidate(el, true) : void 0;
2672
+ }
2673
+ describeCandidate(el, isExplicit) {
2674
+ const excluded = this.isExcludedOrInside(el);
2675
+ const raw = excluded ? [] : this.collect(el);
2676
+ const wordCount = raw.reduce((n, b) => n + countWords2(b.text), 0);
2677
+ if (wordCount === 0 && !isExplicit) return void 0;
2678
+ const id = el.id && !this.candidateEls.has(el.id) ? el.id : `av-c${this.nextCandidate++}`;
2679
+ this.candidateEls.set(id, el);
2680
+ return {
2681
+ id,
2682
+ tag: el.tagName.toLowerCase(),
2683
+ wordCount,
2684
+ linkWordCount: raw.reduce((n, b) => n + b.linkWords, 0),
2685
+ paragraphCount: raw.filter((b) => b.role === "paragraph").length,
2686
+ isArticleBody: el.getAttribute("itemprop") === "articleBody",
2687
+ excluded
2688
+ };
2689
+ }
2690
+ /** Extrae los bloques legibles del candidato descrito. */
2586
2691
  extract(candidateId) {
2587
2692
  const el = this.candidateEls.get(candidateId);
2588
2693
  if (!el) return void 0;
@@ -2856,23 +2961,36 @@ function isAbort(e) {
2856
2961
  var MossServerEngine = class {
2857
2962
  kind = EngineKind.of("moss-server");
2858
2963
  endpoint;
2964
+ voicesEndpoint;
2859
2965
  model;
2860
2966
  voiceIds;
2861
2967
  speed;
2862
2968
  sampleRate;
2969
+ discoverVoices;
2970
+ voicesTimeoutMs;
2863
2971
  doFetch;
2864
2972
  ready = false;
2865
2973
  lifecycle = new AbortController();
2866
2974
  constructor(options) {
2867
2975
  const base = HttpsUrl.of(options.serverUrl, "server-url").value;
2868
- this.endpoint = new URL("v1/audio/speech", base.endsWith("/") ? base : `${base}/`).href;
2976
+ const root = base.endsWith("/") ? base : `${base}/`;
2977
+ this.endpoint = new URL("v1/audio/speech", root).href;
2978
+ this.voicesEndpoint = new URL("v1/audio/voices", root).href;
2869
2979
  this.model = options.model ?? DEFAULT_MODEL;
2870
2980
  this.voiceIds = (options.voices ?? ["default"]).map((v) => VoiceId.of(v));
2871
2981
  this.speed = options.speed ?? 1;
2872
2982
  this.sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
2983
+ this.discoverVoices = options.discoverVoices ?? false;
2984
+ this.voicesTimeoutMs = options.voicesTimeoutMs ?? 1500;
2873
2985
  this.doFetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
2874
2986
  }
2875
2987
  async prepare(signal) {
2988
+ if (signal?.aborted || this.lifecycle.signal.aborted) throw aborted();
2989
+ if (this.ready) return;
2990
+ if (this.discoverVoices) {
2991
+ const found = await this.fetchVoices(signal);
2992
+ if (found.length > 0) this.voiceIds = found;
2993
+ }
2876
2994
  if (signal?.aborted || this.lifecycle.signal.aborted) throw aborted();
2877
2995
  this.ready = true;
2878
2996
  }
@@ -2947,6 +3065,34 @@ var MossServerEngine = class {
2947
3065
  this.lifecycle.signal.removeEventListener("abort", onAbort);
2948
3066
  }
2949
3067
  }
3068
+ /** Descubrimiento de voces: mejor esfuerzo; nunca lanza (un abort se trata como «sin voces»). */
3069
+ async fetchVoices(signal) {
3070
+ const ac = new AbortController();
3071
+ const timer = setTimeout(() => ac.abort(), this.voicesTimeoutMs);
3072
+ const onAbort = () => ac.abort();
3073
+ signal?.addEventListener("abort", onAbort, { once: true });
3074
+ this.lifecycle.signal.addEventListener("abort", onAbort, { once: true });
3075
+ try {
3076
+ const response = await this.doFetch(this.voicesEndpoint, {
3077
+ method: "GET",
3078
+ headers: { accept: "application/json" },
3079
+ signal: ac.signal,
3080
+ redirect: "error",
3081
+ credentials: "omit"
3082
+ });
3083
+ if (!response.ok) {
3084
+ await response.body?.cancel().catch(() => void 0);
3085
+ return [];
3086
+ }
3087
+ return parseVoices(await response.json());
3088
+ } catch {
3089
+ return [];
3090
+ } finally {
3091
+ clearTimeout(timer);
3092
+ signal?.removeEventListener("abort", onAbort);
3093
+ this.lifecycle.signal.removeEventListener("abort", onAbort);
3094
+ }
3095
+ }
2950
3096
  dispose() {
2951
3097
  this.ready = false;
2952
3098
  this.lifecycle.abort();
@@ -2974,6 +3120,24 @@ function concat(a, b) {
2974
3120
  out.set(b, a.length);
2975
3121
  return out;
2976
3122
  }
3123
+ function parseVoices(data) {
3124
+ const raw = data?.voices;
3125
+ if (!Array.isArray(raw)) return [];
3126
+ const seen = /* @__PURE__ */ new Set();
3127
+ const out = [];
3128
+ for (const item of raw) {
3129
+ const value = typeof item === "string" ? item : item?.id;
3130
+ if (typeof value !== "string") continue;
3131
+ const id = value.trim();
3132
+ if (id === "" || seen.has(id)) continue;
3133
+ try {
3134
+ out.push(VoiceId.of(id));
3135
+ seen.add(id);
3136
+ } catch {
3137
+ }
3138
+ }
3139
+ return out;
3140
+ }
2977
3141
  function pcm16ToFloat32(bytes) {
2978
3142
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2979
3143
  const out = new Float32Array(bytes.length / 2);
@@ -2990,6 +3154,15 @@ var SynthesisError = class extends DomainError {
2990
3154
  };
2991
3155
  var aborted2 = () => new AbortedError2("AV_ABORTED", "Operation aborted", { recoverable: true });
2992
3156
  var SILENCE = { samples: new Float32Array(1), sampleRate: 24e3 };
3157
+ function voicePriority(voice) {
3158
+ const enhanced = /\b(?:premium|enhanced|natural|neural)\b/i.test(
3159
+ `${voice.name} ${voice.voiceURI}`
3160
+ );
3161
+ return 2 * Number(enhanced) + Number(voice.default);
3162
+ }
3163
+ function hasLocalVoice(voices) {
3164
+ return voices.some((voice) => voice.localService);
3165
+ }
2993
3166
  function slug(voice) {
2994
3167
  const base = `${voice.name}-${voice.lang}`.toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 60);
2995
3168
  return base === "" ? "voice" : base;
@@ -3020,14 +3193,20 @@ var WebSpeechEngine = class {
3020
3193
  if (!synthesis) throw this.unavailable("Este navegador no tiene voz del sistema");
3021
3194
  if (this.ready) return;
3022
3195
  let voices = synthesis.getVoices();
3023
- if (voices.length === 0) voices = await this.waitForVoices(synthesis, signal);
3196
+ if (!hasLocalVoice(voices)) voices = await this.waitForVoices(synthesis, signal);
3024
3197
  if (signal?.aborted || this.disposed) throw aborted2();
3025
- if (voices.length === 0) throw this.unavailable("No hay voces del sistema instaladas");
3198
+ if (!hasLocalVoice(voices)) throw this.unavailable("No hay voces locales disponibles");
3026
3199
  const preferred = this.language === void 0 ? voices : voices.filter((v) => v.lang.toLowerCase().split(/[-_]/)[0] === this.language);
3200
+ const byId = /* @__PURE__ */ new Map();
3201
+ for (const v of hasLocalVoice(preferred) ? preferred : voices) {
3202
+ const base = slug(v);
3203
+ let id = base;
3204
+ for (let n = 2; byId.has(id); n++) id = `${base.slice(0, 56)}-${n}`;
3205
+ byId.set(id, v);
3206
+ }
3207
+ const local = [...byId].filter(([, voice]) => voice.localService);
3027
3208
  this.byId.clear();
3028
- for (const v of preferred.length > 0 ? preferred : voices) {
3029
- let id = slug(v);
3030
- for (let n = 2; this.byId.has(id); n++) id = `${slug(v).slice(0, 56)}-${n}`;
3209
+ for (const [id, v] of local.sort((a, b) => voicePriority(b[1]) - voicePriority(a[1]))) {
3031
3210
  this.byId.set(id, v);
3032
3211
  }
3033
3212
  this.ready = true;
@@ -3078,15 +3257,20 @@ var WebSpeechEngine = class {
3078
3257
  }
3079
3258
  waitForVoices(synthesis, signal) {
3080
3259
  return new Promise((resolve) => {
3081
- const timer = setTimeout(() => done(), this.voicesTimeoutMs);
3082
- const done = () => {
3260
+ const timer = setTimeout(() => finish(synthesis.getVoices()), this.voicesTimeoutMs);
3261
+ const onChange = () => {
3262
+ const voices = synthesis.getVoices();
3263
+ if (hasLocalVoice(voices)) finish(voices);
3264
+ };
3265
+ const onAbort = () => finish([]);
3266
+ const finish = (voices) => {
3083
3267
  clearTimeout(timer);
3084
- synthesis.removeEventListener?.("voiceschanged", done);
3085
- signal?.removeEventListener("abort", done);
3086
- resolve(synthesis.getVoices());
3268
+ synthesis.removeEventListener?.("voiceschanged", onChange);
3269
+ signal?.removeEventListener("abort", onAbort);
3270
+ resolve(voices);
3087
3271
  };
3088
- synthesis.addEventListener?.("voiceschanged", done);
3089
- signal?.addEventListener("abort", done, { once: true });
3272
+ synthesis.addEventListener?.("voiceschanged", onChange);
3273
+ signal?.addEventListener("abort", onAbort, { once: true });
3090
3274
  });
3091
3275
  }
3092
3276
  unavailable(message) {
@@ -3137,11 +3321,19 @@ function createHttpServerProbe(options = {}) {
3137
3321
  // src/compose.ts
3138
3322
  function engineFor(request) {
3139
3323
  if (request.kind === "moss-server" && request.serverUrl) {
3140
- return new MossServerEngine({ serverUrl: request.serverUrl, speed: request.rate });
3324
+ return new MossServerEngine({
3325
+ serverUrl: request.serverUrl,
3326
+ speed: request.rate,
3327
+ discoverVoices: true
3328
+ });
3329
+ }
3330
+ if (request.kind === "web-speech") {
3331
+ return new WebSpeechEngine({ language: request.language, rate: request.rate });
3141
3332
  }
3142
- return new WebSpeechEngine({ language: request.language, rate: request.rate });
3333
+ throw new ResourceNotFoundError("AV_ENGINE_UNAVAILABLE", `Motor no disponible: ${request.kind}`);
3143
3334
  }
3144
3335
  var ComposedArticleVoiceElement = class extends ArticleVoiceElement {
3336
+ mossBrowserAvailable = false;
3145
3337
  probe = createHttpServerProbe();
3146
3338
  capabilities = new BrowserDeviceCapabilities();
3147
3339
  articleSource = new DomArticleSource(document);