@pie-qti/player-elements 0.1.22 → 0.1.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/ar-SA-BDmOol_3.js +854 -0
  2. package/dist/ar-SA-BDmOol_3.js.map +1 -0
  3. package/dist/{define-Bkc2UFCK.js → define-D7_K0JFy.js} +4057 -2664
  4. package/dist/define-D7_K0JFy.js.map +1 -0
  5. package/dist/dist-BRTWr852.js +5809 -0
  6. package/dist/dist-BRTWr852.js.map +1 -0
  7. package/dist/{dist-CPyrAOfS.js → dist-BaQdJU08.js} +210 -130
  8. package/dist/dist-BaQdJU08.js.map +1 -0
  9. package/dist/{dist-C0bIgnik.js → dist-DwvskOs6.js} +4 -4
  10. package/dist/{dist-C0bIgnik.js.map → dist-DwvskOs6.js.map} +1 -1
  11. package/dist/{dist-_mWRIrTg.js → dist-ffJZTPTU.js} +2440 -2658
  12. package/dist/dist-ffJZTPTU.js.map +1 -0
  13. package/dist/{element-BrpUrZI4.js → element-DSCNeDLu.js} +2 -2
  14. package/dist/{element-BrpUrZI4.js.map → element-DSCNeDLu.js.map} +1 -1
  15. package/dist/{element-class-DWoLXp_r-ms67Krq-.js → element-class-DQy2cIPM-CldZrSRR.js} +3717 -3464
  16. package/dist/element-class-DQy2cIPM-CldZrSRR.js.map +1 -0
  17. package/dist/elements/BaseSvelteMountElement.d.ts +1 -0
  18. package/dist/elements/QtiAssessmentPlayerElement.d.ts +1 -0
  19. package/dist/elements.js +3 -3
  20. package/dist/es-ES-C98YtDtb.js +802 -0
  21. package/dist/es-ES-C98YtDtb.js.map +1 -0
  22. package/dist/fr-FR-CrmmiRPf.js +802 -0
  23. package/dist/fr-FR-CrmmiRPf.js.map +1 -0
  24. package/dist/index.js +2 -2
  25. package/dist/item-toolbar-element-BW9Y_n5x.js +1990 -0
  26. package/dist/item-toolbar-element-BW9Y_n5x.js.map +1 -0
  27. package/dist/{tag-names-DV56RHJk.js → language-tags-DVlRltrl.js} +25 -22
  28. package/dist/language-tags-DVlRltrl.js.map +1 -0
  29. package/dist/nl-NL-BeQBX6yq.js +505 -0
  30. package/dist/nl-NL-BeQBX6yq.js.map +1 -0
  31. package/dist/nl-NL-CAR7pgVz.js +802 -0
  32. package/dist/nl-NL-CAR7pgVz.js.map +1 -0
  33. package/dist/pie-assessment-toolkit-element-CpiB3twr.js +8573 -0
  34. package/dist/pie-assessment-toolkit-element-CpiB3twr.js.map +1 -0
  35. package/dist/pie-tool-calculator-BiWMTJe7.js +2992 -0
  36. package/dist/pie-tool-calculator-BiWMTJe7.js.map +1 -0
  37. package/dist/provider-Y5PhmTAu.js +58 -0
  38. package/dist/provider-Y5PhmTAu.js.map +1 -0
  39. package/dist/register-players.js +1 -1
  40. package/dist/register.js +7285 -9569
  41. package/dist/register.js.map +1 -1
  42. package/dist/{resolveItems-XtUnsftV.js → resolveItems-D8DJkv-4.js} +2 -2
  43. package/dist/{resolveItems-XtUnsftV.js.map → resolveItems-D8DJkv-4.js.map} +1 -1
  44. package/dist/ro-RO-DTZbhL0e.js +802 -0
  45. package/dist/ro-RO-DTZbhL0e.js.map +1 -0
  46. package/dist/root-DSkIM1v3.js +47 -0
  47. package/dist/root-DSkIM1v3.js.map +1 -0
  48. package/dist/th-TH-aqlT_oK3.js +802 -0
  49. package/dist/th-TH-aqlT_oK3.js.map +1 -0
  50. package/dist/tool-tts-inline-B71NTBbb.js +4435 -0
  51. package/dist/tool-tts-inline-B71NTBbb.js.map +1 -0
  52. package/dist/zh-CN-DCqaRRhU.js +802 -0
  53. package/dist/zh-CN-DCqaRRhU.js.map +1 -0
  54. package/package.json +8 -8
  55. package/dist/define-Bkc2UFCK.js.map +0 -1
  56. package/dist/dist-CPyrAOfS.js.map +0 -1
  57. package/dist/dist-DU1nH3y8.js +0 -1247
  58. package/dist/dist-DU1nH3y8.js.map +0 -1
  59. package/dist/dist-_mWRIrTg.js.map +0 -1
  60. package/dist/element-class-DWoLXp_r-ms67Krq-.js.map +0 -1
  61. package/dist/item-toolbar-element-DFppTi_H.js +0 -6015
  62. package/dist/item-toolbar-element-DFppTi_H.js.map +0 -1
  63. package/dist/pie-assessment-toolkit-element-DlSFT_I2.js +0 -28479
  64. package/dist/pie-assessment-toolkit-element-DlSFT_I2.js.map +0 -1
  65. package/dist/pie-tool-calculator-BGp3etqJ.js +0 -2226
  66. package/dist/pie-tool-calculator-BGp3etqJ.js.map +0 -1
  67. package/dist/root-DBWhDxjY.js +0 -98
  68. package/dist/root-DBWhDxjY.js.map +0 -1
  69. package/dist/tag-names-DV56RHJk.js.map +0 -1
  70. package/dist/tool-tts-inline-DVUYjVnD.js +0 -2574
  71. package/dist/tool-tts-inline-DVUYjVnD.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dist-ffJZTPTU.js","names":["log","segmentTextToSentences","TOKEN_PATTERN","NUMERIC_WORDS","normalizedTokenValue","findTokenAtOffset","normalizeBoundaryWord","mapRawOffsetToSpokenOffset","normalizeBoundaryWord","resolveMatchedTargetForBoundary","normalizeLocale","isPlainRecord","normalizeLocale","segmentTextToSentences","segmentTextToSentences"],"sources":["../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/context/assessment-toolkit-context.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/context/runtime-context-consumer.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/catalog-owner.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/runtime/tool-host-contract.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/SSMLExtractor.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/AccessibilityCatalogResolver.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/ElementToolStateStore.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/RangeSerializer.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/HighlightCoordinator.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/utils/logger.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/I18nService.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tool-config-defaults.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tools-config-normalizer.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/ToolRegistry.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tool-request.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/framework-error.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tool-config-validation.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/pnp-standard-features.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/catalog-media.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/spoken-audio-cards.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/ToolCoordinator.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/framework-error-bus.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/text-segmentation.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/browser-provider.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/text-processing.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/ssml/spoken-text.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/catalog-span-alignment.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/math-alignment/mathml-tokenizer.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/math-alignment/range-resolver.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/math-alignment/sequence-aligner.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/math-alignment/speech-tokenizer.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/math-alignment/index.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/mathml-sanitization.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/math-aware-text-processing.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/math-speech.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/generated-speech/assemble-plan.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/generated-speech/math-speech-cache.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/highlight-pipeline/boundary-normalizer.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/highlight-pipeline/highlight-policy.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/highlight-pipeline/rendered-math-target-resolver.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/highlight-pipeline/math-semantic-resolver.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/highlight-pipeline/visible-map-range.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/highlight-pipeline/prose-boundary-resolver.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/highlight-pipeline/create-highlight-plan.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/highlight-pipeline/normalize-speech-chunks.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/highlight-pipeline/readable-region.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/generated-speech/dom/build-dom-plan.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts/generated-speech/dom/to-chunk-inputs.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts-control-events.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/TTSService.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tts-runtime-config.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tool-providers/ToolProviderRegistry.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/policy/core/feature-decision.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/policy/core/provenance.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/policy/core/compose-decision.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/policy/core/pnp-policy-inputs.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/policy/sources/PnpPolicySource.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/policy/core/ToolPolicyEngine.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/ToolkitCoordinator.js","../../../node_modules/.bun/@pie-players+pie-assessment-toolkit@0.3.68+0f70b067cf29f19a/node_modules/@pie-players/pie-assessment-toolkit/dist/services/tool-instance-id.js"],"sourcesContent":["import { createContext } from \"@pie-players/pie-context\";\nexport const assessmentToolkitRuntimeContext = createContext(Symbol.for(\"pie.assessmentToolkit.runtimeContext\"));\nexport const assessmentToolkitHostRuntimeContext = createContext(Symbol.for(\"pie.assessmentToolkit.hostRuntimeContext\"));\nexport const assessmentToolkitShellContext = createContext(Symbol.for(\"pie.assessmentToolkit.shellContext\"));\nexport const assessmentToolkitRegionScopeContext = createContext(Symbol.for(\"pie.assessmentToolkit.regionScopeContext\"));\n","import { ContextConsumer } from \"@pie-players/pie-context\";\nimport { assessmentToolkitHostRuntimeContext, assessmentToolkitRegionScopeContext, assessmentToolkitShellContext, assessmentToolkitRuntimeContext, } from \"./assessment-toolkit-context.js\";\nfunction connectConsumerWithProviderRetry(host, context, onValue) {\n let hasValue = false;\n const consumer = new ContextConsumer(host, {\n context,\n subscribe: true,\n onValue: (value) => {\n hasValue = true;\n onValue(value);\n },\n });\n consumer.connect();\n const onContextProvider = (event) => {\n if (event.context !== context)\n return;\n consumer.requestValue();\n };\n host.addEventListener(\"context-provider\", onContextProvider);\n let attempts = 0;\n const maxAttempts = 200;\n const retryTimer = globalThis.setInterval(() => {\n if (hasValue || attempts >= maxAttempts) {\n globalThis.clearInterval(retryTimer);\n return;\n }\n attempts += 1;\n consumer.requestValue();\n }, 50);\n return () => {\n globalThis.clearInterval(retryTimer);\n host.removeEventListener(\"context-provider\", onContextProvider);\n consumer.disconnect();\n };\n}\n/**\n * Connect a DOM host element to the shared assessment toolkit runtime context.\n * Returns a cleanup function that disconnects the underlying consumer.\n */\nexport function connectAssessmentToolkitRuntimeContext(host, onValue) {\n return connectConsumerWithProviderRetry(host, assessmentToolkitRuntimeContext, onValue);\n}\nexport function connectAssessmentToolkitHostRuntimeContext(host, onValue) {\n return connectConsumerWithProviderRetry(host, assessmentToolkitHostRuntimeContext, onValue);\n}\nexport function connectAssessmentToolkitShellContext(host, onValue) {\n return connectConsumerWithProviderRetry(host, assessmentToolkitShellContext, onValue);\n}\nexport function connectAssessmentToolkitRegionScopeContext(host, onValue) {\n return connectConsumerWithProviderRetry(host, assessmentToolkitRegionScopeContext, onValue);\n}\n","/**\n * Identity and traversal rules for one mounted accessibility-catalog owner.\n *\n * The resolver is the public lifecycle boundary. This supporting module keeps\n * its owner identity and direct-lookup helper separate from the runtime event\n * adapter, while keeping the entity walk private to the resolver package.\n */\nconst hasCatalogs = (catalogs) => Array.isArray(catalogs) && catalogs.length > 0;\n/**\n * Build the lookup context for a direct resolver client such as inline TTS.\n *\n * Owner registration uses the same function, so direct readers cannot drift\n * from the context the resolver files the entity under.\n */\nexport function catalogOwnerContextFor(owner) {\n if (owner.kind === \"passage\") {\n return {\n ownerKind: \"passage\",\n assessmentId: owner.assessmentId,\n sectionId: owner.sectionId,\n passageId: owner.canonicalItemId || owner.itemId,\n };\n }\n return {\n ownerKind: \"itemModel\",\n assessmentId: owner.assessmentId,\n sectionId: owner.sectionId,\n itemId: owner.itemId,\n canonicalItemId: owner.canonicalItemId || owner.itemId,\n };\n}\n/**\n * Collect every catalog group carried by one owner in registration-precedence\n * order. This is deliberately not exported from the package root: callers\n * register the owner once through `AccessibilityCatalogResolver.registerOwner`.\n */\nexport function collectOwnerCatalogRegistrations(entity, owner) {\n if (!entity)\n return [];\n const context = catalogOwnerContextFor(owner);\n const registrations = [];\n if (hasCatalogs(entity.accessibilityCatalogs)) {\n registrations.push({ context, catalogs: entity.accessibilityCatalogs });\n }\n if (hasCatalogs(entity.config?.extractedCatalogs)) {\n registrations.push({\n context,\n catalogs: entity.config.extractedCatalogs,\n });\n }\n if (owner.kind === \"passage\")\n return registrations;\n if (context.ownerKind !== \"itemModel\")\n return registrations;\n for (const model of entity.config?.models ?? []) {\n if (!hasCatalogs(model.accessibilityCatalogs))\n continue;\n registrations.push({\n context: { ...context, modelId: model.id },\n catalogs: model.accessibilityCatalogs,\n });\n }\n return registrations;\n}\n","import { connectAssessmentToolkitRegionScopeContext, connectAssessmentToolkitRuntimeContext, connectAssessmentToolkitShellContext, } from \"../context/runtime-context-consumer.js\";\nconst CROSS_BOUNDARY_EVENT_INIT = {\n bubbles: true,\n composed: true,\n cancelable: false,\n};\n/**\n * Contract helper for all toolkit/tool events that must cross custom-element boundaries.\n */\nexport function createCrossBoundaryEvent(name, detail, init = {}) {\n return new CustomEvent(name, {\n detail,\n ...CROSS_BOUNDARY_EVENT_INIT,\n ...init,\n });\n}\n/**\n * Dispatches a cross-boundary event with toolkit defaults.\n */\nexport function dispatchCrossBoundaryEvent(target, name, detail, init = {}) {\n return target.dispatchEvent(createCrossBoundaryEvent(name, detail, init));\n}\n/**\n * Shared runtime-context connection contract for tools and shells.\n * Uses retry + provider announcements so late providers are tolerated.\n */\nexport function connectToolRuntimeContext(host, onValue) {\n return connectAssessmentToolkitRuntimeContext(host, onValue);\n}\n/**\n * Shared shell-context connection contract for tools needing item/passage scope.\n */\nexport function connectToolShellContext(host, onValue) {\n return connectAssessmentToolkitShellContext(host, onValue);\n}\n/**\n * Shared region-scope context contract for tools targeting content subregions.\n */\nexport function connectToolRegionScopeContext(host, onValue) {\n return connectAssessmentToolkitRegionScopeContext(host, onValue);\n}\n/**\n * Guard utility: narrows unknown context payloads when needed by callers.\n */\nexport function isContextValueDefined(value) {\n return value !== null && value !== undefined;\n}\n","/**\n * SSMLExtractor\n *\n * Service for extracting embedded SSML from PIE item content and converting\n * it into QTI 3.0 accessibility catalogs.\n *\n * Authors can embed <speak> SSML tags directly in content for convenience.\n * The extractor automatically:\n * 1. Parses markup and finds all <speak> elements\n * 2. Extracts SSML content with language metadata\n * 3. Generates accessibility catalogs with unique IDs\n * 4. Cleans visual markup (removes SSML, adds data-catalog-idref)\n *\n * This enables proper pronunciation, emphasis, and pacing for TTS without\n * requiring authors to maintain separate catalog files.\n *\n * Part of PIE Assessment Toolkit.\n */\n/**\n * Allow-listed SSML elements (from the SSML 1.1 spec subset we forward to\n * TTS providers). Anything outside this list is unwrapped during\n * sanitization so we never leak author-supplied scripts, iframes, or\n * arbitrary HTML into the TTS pipeline.\n */\nconst SSML_ALLOWED_TAGS = new Set([\n \"speak\",\n \"break\",\n \"prosody\",\n \"emphasis\",\n \"say-as\",\n \"sub\",\n \"mark\",\n \"phoneme\",\n \"lang\",\n \"p\",\n \"s\",\n \"voice\",\n \"audio\",\n \"lexicon\",\n]);\n/**\n * Allow-listed attributes across SSML elements. Attribute allow-listing is\n * global (not per-tag) because the union is small and consistent across\n * providers.\n */\n/**\n * Tags whose content must be dropped entirely (rather than unwrapped to\n * preserve phrasing text). These are dangerous containers whose text\n * payload could be re-interpreted downstream.\n */\nconst SSML_DROP_FULLY_TAGS = new Set([\n \"script\",\n \"style\",\n \"iframe\",\n \"object\",\n \"embed\",\n \"foreignobject\",\n \"noscript\",\n \"template\",\n]);\nconst SSML_ALLOWED_ATTRS = new Set([\n \"alphabet\",\n \"ph\",\n \"time\",\n \"strength\",\n \"rate\",\n \"pitch\",\n \"volume\",\n \"name\",\n \"interpret-as\",\n \"format\",\n \"detail\",\n \"language\",\n \"xml:lang\",\n \"lang\",\n \"gender\",\n \"src\",\n]);\n/**\n * SSML elements that are empty in practice (no child content). Authors\n * typically write them as self-closing (`<break time=\"200ms\"/>`). HTML's\n * parser does NOT recognize them as void elements and silently drops the\n * `/`, then nests every subsequent sibling as a child — producing\n * malformed SSML like `<break>…rest of paragraph…</break>` when\n * round-tripped. Pre-processing self-closing forms to explicit\n * open+close pairs before HTML parsing avoids the reflow, and the\n * serializer re-emits them as self-closing so providers see valid SSML.\n *\n * `audio` is intentionally excluded — SSML <audio> may carry fallback\n * children (the spec's \"alternate content\"), so treating it as void\n * would lose author intent.\n */\nconst SSML_VOID_TAGS = new Set([\"break\", \"mark\", \"lexicon\"]);\n/**\n * Normalize self-closing forms of SSML void elements to explicit\n * open+close pairs BEFORE handing the string to an HTML parser. The\n * HTML5 parser ignores the `/` on non-void tags, so `<break/>` becomes\n * a plain `<break>` open tag that swallows every following sibling.\n * Rewriting to `<break></break>` preserves the empty-element shape\n * across the HTML round-trip.\n */\nfunction expandSelfClosingVoidTags(input) {\n let next = input;\n for (const tag of SSML_VOID_TAGS) {\n const selfClosing = new RegExp(`<${tag}\\\\b([^>/]*?)\\\\s*/>`, \"gi\");\n next = next.replace(selfClosing, (_match, attrs) => {\n const attrText = attrs ? attrs.replace(/\\s+$/, \"\") : \"\";\n return `<${tag}${attrText}></${tag}>`;\n });\n }\n return next;\n}\n/**\n * Hosts that must never appear inside an SSML `<audio src>` because they\n * would cause the server-side TTS provider to fetch a private / metadata\n * endpoint on behalf of the request. Mirrors the SchoolCity provider's\n * defense-in-depth check; the SSML-side block is cheap and belt-and-braces.\n */\nconst SSML_PRIVATE_AUDIO_HOSTS = [\n /^localhost$/i,\n /^127(?:\\.\\d{1,3}){3}$/,\n /^0(?:\\.\\d{1,3}){3}$/,\n /^10(?:\\.\\d{1,3}){3}$/,\n /^192\\.168(?:\\.\\d{1,3}){2}$/,\n /^172\\.(?:1[6-9]|2\\d|3[01])(?:\\.\\d{1,3}){2}$/,\n /^169\\.254(?:\\.\\d{1,3}){2}$/,\n /^::1$/,\n /^fe80:/i,\n /^fc00:/i,\n /^fd[0-9a-f]{2}:/i,\n /^metadata\\.google\\.internal$/i,\n /^metadata\\.azure\\.internal$/i,\n /^metadata\\.packet\\.net$/i,\n];\nfunction isSafeSsmlAudioSrc(raw) {\n if (typeof raw !== \"string\" || raw.length === 0)\n return false;\n let parsed;\n try {\n parsed = new URL(raw);\n }\n catch {\n return false;\n }\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return false;\n }\n const hostname = parsed.hostname.replace(/^\\[|\\]$/g, \"\").replace(/\\.$/, \"\");\n return !SSML_PRIVATE_AUDIO_HOSTS.some((pattern) => pattern.test(hostname));\n}\n/**\n * Sanitize an SSML subtree in place: remove disallowed attributes and\n * replace disallowed elements with their text content (so phrasing order\n * is preserved but no scripts / iframes / unknown tags survive).\n */\nexport function sanitizeSsmlElement(element) {\n // Walk children snapshot first because we may replace nodes as we go.\n const children = Array.from(element.children);\n for (const child of children) {\n const tagName = child.tagName.toLowerCase();\n if (SSML_DROP_FULLY_TAGS.has(tagName)) {\n child.remove();\n continue;\n }\n sanitizeSsmlElement(child);\n if (!SSML_ALLOWED_TAGS.has(tagName)) {\n const textNode = element.ownerDocument.createTextNode(child.textContent ?? \"\");\n child.replaceWith(textNode);\n }\n }\n // Strip disallowed attributes on the surviving node.\n const attrNames = Array.from(element.attributes).map((attr) => attr.name);\n for (const attrName of attrNames) {\n if (!SSML_ALLOWED_ATTRS.has(attrName.toLowerCase())) {\n element.removeAttribute(attrName);\n }\n }\n // Belt-and-braces: even though `src` is allow-listed, SSML `<audio>`\n // sends its URL to a server-side TTS provider that will dereference\n // it. Refuse non-http(s) schemes and private / cloud-metadata hosts\n // at the SSML boundary so we never forward an SSRF primitive.\n if (element.tagName.toLowerCase() === \"audio\") {\n const src = element.getAttribute(\"src\");\n if (src !== null && !isSafeSsmlAudioSrc(src)) {\n element.removeAttribute(\"src\");\n }\n }\n}\n/**\n * Serialize a sanitized `<speak>` element back to a minimal SSML string.\n * Uses a manual walker instead of `outerHTML` so that any namespace\n * quirks (e.g. `xmlns` attributes added by the HTML parser) are\n * normalised and disallowed descendants cannot reappear through quirks\n * in the serializer.\n */\nexport function serializeSsmlElement(element) {\n const tagName = element.tagName.toLowerCase();\n const attrs = Array.from(element.attributes)\n .filter((attr) => SSML_ALLOWED_ATTRS.has(attr.name.toLowerCase()))\n .map((attr) => ` ${attr.name}=\"${escapeXmlAttr(attr.value)}\"`)\n .join(\"\");\n // SSML void elements (e.g. <break>, <mark>) must be emitted as\n // self-closing so providers like AWS Polly accept them. Emitting\n // `<break></break>` parses fine on the SSML side but is wasteful;\n // emitting `<break>` (open without close) is invalid SSML.\n if (SSML_VOID_TAGS.has(tagName)) {\n return `<${tagName}${attrs}/>`;\n }\n const childPieces = [];\n for (const node of Array.from(element.childNodes)) {\n if (node.nodeType === 3 /* text */) {\n childPieces.push(escapeXmlText(node.nodeValue ?? \"\"));\n }\n else if (node.nodeType === 1 /* element */) {\n const childElement = node;\n const childTag = childElement.tagName.toLowerCase();\n if (SSML_DROP_FULLY_TAGS.has(childTag)) {\n continue;\n }\n if (SSML_ALLOWED_TAGS.has(childTag)) {\n childPieces.push(serializeSsmlElement(childElement));\n }\n else {\n childPieces.push(escapeXmlText(childElement.textContent ?? \"\"));\n }\n }\n }\n return `<${tagName}${attrs}>${childPieces.join(\"\")}</${tagName}>`;\n}\nexport function sanitizeSsmlString(input) {\n const trimmed = String(input || \"\").trim();\n if (!trimmed || !trimmed.includes(\"<\"))\n return input;\n if (typeof DOMParser === \"undefined\")\n return input;\n const parser = new DOMParser();\n const doc = parser.parseFromString(expandSelfClosingVoidTags(trimmed), \"text/html\");\n const speakElement = doc.querySelector(\"speak\");\n if (speakElement) {\n sanitizeSsmlElement(speakElement);\n return serializeSsmlElement(speakElement);\n }\n const wrapper = doc.createElement(\"speak\");\n for (const node of Array.from(doc.body.childNodes)) {\n wrapper.appendChild(node);\n }\n sanitizeSsmlElement(wrapper);\n return Array.from(wrapper.childNodes)\n .map((node) => {\n if (node.nodeType === 3 /* text */) {\n return escapeXmlText(node.nodeValue ?? \"\");\n }\n if (node.nodeType === 1 /* element */) {\n const child = node;\n if (SSML_ALLOWED_TAGS.has(child.tagName.toLowerCase())) {\n return serializeSsmlElement(child);\n }\n return escapeXmlText(child.textContent ?? \"\");\n }\n return \"\";\n })\n .join(\"\");\n}\nfunction escapeXmlText(value) {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\");\n}\nfunction escapeXmlAttr(value) {\n return value\n .replace(/&/g, \"&amp;\")\n .replace(/</g, \"&lt;\")\n .replace(/>/g, \"&gt;\")\n .replace(/\"/g, \"&quot;\");\n}\n/**\n * SSMLExtractor Service\n *\n * Extracts embedded SSML from PIE content and generates accessibility catalogs.\n */\nexport class SSMLExtractor {\n catalogCounter = 0;\n /**\n * Extract SSML from entire item config (markup + models)\n *\n * @param config Item configuration with potential embedded SSML\n * @returns Extracted catalogs and cleaned config\n */\n extractFromItemConfig(config) {\n const allCatalogs = [];\n // Shallow clone of config + a fresh models array. The per-model/choice\n // objects are replaced (not mutated in place) by the `.map` below, so the\n // caller's original config and its models are never mutated.\n const cleanedConfig = {\n ...config,\n models: config.models ? [...config.models] : [],\n };\n // 1. Extract from top-level markup (passages)\n if (config.markup) {\n const markupResult = this.extractFromMarkup(config.markup, \"markup\");\n allCatalogs.push(...markupResult.catalogs);\n cleanedConfig.markup = markupResult.cleanedMarkup;\n }\n // 2. Extract from models (prompts, choices, etc.)\n if (config.models && config.models.length > 0) {\n cleanedConfig.models = config.models.map((model) => {\n const cleanedModel = { ...model };\n const modelCatalogs = [];\n // Extract from prompt\n if (model.prompt && typeof model.prompt === \"string\") {\n const promptResult = this.extractFromMarkup(model.prompt, `prompt-${model.id}`);\n modelCatalogs.push(...promptResult.catalogs);\n cleanedModel.prompt = promptResult.cleanedMarkup;\n }\n // Extract from choices\n if (model.choices && Array.isArray(model.choices)) {\n cleanedModel.choices = model.choices.map((choice) => {\n if (choice.label && typeof choice.label === \"string\") {\n const choiceResult = this.extractFromMarkup(choice.label, `choice-${model.id}-${choice.value}`);\n modelCatalogs.push(...choiceResult.catalogs);\n return {\n ...choice,\n label: choiceResult.cleanedMarkup,\n };\n }\n return choice;\n });\n }\n allCatalogs.push(...modelCatalogs);\n return cleanedModel;\n });\n }\n return {\n catalogs: allCatalogs,\n cleanedConfig,\n };\n }\n /**\n * Extract SSML from markup string\n *\n * @param markup HTML markup potentially containing <speak> elements\n * @param idPrefix Prefix for generating catalog IDs\n * @returns Extracted catalogs and cleaned markup\n */\n extractFromMarkup(markup, idPrefix) {\n if (!markup || markup.trim() === \"\") {\n return { catalogs: [], cleanedMarkup: markup };\n }\n // Check if running in browser environment\n if (typeof window === \"undefined\" || typeof DOMParser === \"undefined\") {\n console.warn(\"[SSMLExtractor] DOMParser not available (SSR?), skipping extraction\");\n return { catalogs: [], cleanedMarkup: markup };\n }\n const catalogs = [];\n try {\n const parser = new DOMParser();\n const doc = parser.parseFromString(expandSelfClosingVoidTags(markup), \"text/html\");\n // Find all <speak> elements\n const speakElements = Array.from(doc.querySelectorAll(\"speak\"));\n if (speakElements.length === 0) {\n // No SSML found, return original markup\n return { catalogs: [], cleanedMarkup: markup };\n }\n // Process each <speak> element\n for (const speakEl of speakElements) {\n try {\n // Generate unique catalog ID\n const catalogId = this.generateCatalogId(idPrefix);\n // Sanitize before serializing so the SSML forwarded to the TTS\n // provider only contains spec-allowed tags/attributes. This\n // closes an author-content -> TTS-server pipeline that would\n // otherwise accept arbitrary HTML.\n sanitizeSsmlElement(speakEl);\n const ssmlContent = serializeSsmlElement(speakEl);\n // Extract language (check both xml:lang and lang attributes)\n const language = speakEl.getAttribute(\"xml:lang\") ||\n speakEl.getAttribute(\"lang\") ||\n \"en-US\";\n // The docking node is the element the author already wrote around\n // the visible content this SSML speaks. Nothing is synthesized to\n // stand in for it: a `<speak>` with no element around it has no\n // content node to be an alternate *for*, and inventing one would\n // mean inventing visible content too.\n const wrapper = speakEl.parentElement && speakEl.parentElement.tagName !== \"BODY\"\n ? speakEl.parentElement\n : null;\n // Visible content never keeps the SSML, docked or not.\n speakEl.remove();\n // Tag the docking node with the QTI-style catalog reference so the\n // runtime can resolve this region's spoken content. Same attribute\n // authored content uses (`data-catalog-idref`) — one canonical name,\n // which is also why an existing value is never replaced: the\n // reference names a whole card array, so overwriting it to win the\n // spoken type would take that node's braille, simplified-language and\n // sign-language cards down with it.\n //\n // Either way the catalog is still emitted, so a consumer resolving\n // through the item's catalog set finds it. What an undocked catalog\n // loses is DOM lookup, which is how TTS resolves — a content problem\n // only the author can fix, so say so rather than failing silently.\n const existingIdRef = wrapper?.getAttribute(\"data-catalog-idref\");\n if (!wrapper) {\n console.warn(`[SSMLExtractor] \"${idPrefix}\" has a <speak> with no element around it, so catalog \"${catalogId}\" has no content node to dock to and TTS will not find it. Wrap the visible content this SSML speaks in an element.`);\n }\n else if (existingIdRef) {\n console.warn(`[SSMLExtractor] \"${idPrefix}\" has an inline <speak> inside a node already docked to catalog \"${existingIdRef}\"; keeping the existing reference, so catalog \"${catalogId}\" is not reachable from this node. Give the <speak> its own wrapper element, or author the SSML as a \"spoken\" card on \"${existingIdRef}\".`);\n }\n else {\n wrapper.setAttribute(\"data-catalog-idref\", catalogId);\n }\n // Create catalog entry\n catalogs.push({\n identifier: catalogId,\n cards: [\n {\n catalog: \"spoken\",\n language,\n content: ssmlContent,\n },\n ],\n });\n }\n catch (error) {\n console.error(\"[SSMLExtractor] Error processing <speak> element:\", error);\n // Continue with other elements\n }\n }\n // Return cleaned markup\n const cleanedMarkup = doc.body.innerHTML;\n return { catalogs, cleanedMarkup };\n }\n catch (error) {\n console.error(\"[SSMLExtractor] Error parsing markup:\", error);\n // Return original markup if parsing fails\n return { catalogs: [], cleanedMarkup: markup };\n }\n }\n /**\n * Generate unique catalog ID\n *\n * @param prefix Context prefix (e.g., 'prompt-q1', 'choice-q1-a')\n * @returns Unique catalog ID (e.g., 'auto-prompt-q1-0')\n */\n generateCatalogId(prefix) {\n const id = `auto-${prefix}-${this.catalogCounter}`;\n this.catalogCounter++;\n return id;\n }\n /**\n * Reset counter (useful for testing or new extraction contexts)\n */\n reset() {\n this.catalogCounter = 0;\n }\n}\n","import { languageTagLookupSequence, normalizeLanguageTag, } from \"@pie-players/pie-players-shared/i18n/language-tags\";\nimport { catalogOwnerContextFor, collectOwnerCatalogRegistrations, } from \"./catalog-owner.js\";\nimport { sanitizeSsmlString } from \"./SSMLExtractor.js\";\n/**\n * The catalog types PIE names, plus the rule for the ones it does not.\n *\n * The type above stays open on purpose: QTI treats the support vocabulary as\n * extensible, and closing it here would reject content PIE has no reason to\n * reject and could not usefully validate anyway, since catalogs arrive as\n * authored JSON rather than through this type. Keeping it open cost something\n * though — the named literals were documentation only, so a card written\n * `\"spokn\"` was a perfectly valid `CatalogType` that no reader would ever ask\n * for, and it failed by being invisible rather than by failing. That is what\n * `isKnownCatalogType` and the warnings below are for: the openness stays, the\n * silence does not.\n */\nexport const KNOWN_CATALOG_TYPES = new Set([\n \"spoken\",\n \"sign-language\",\n \"transcript\",\n \"braille\",\n \"tactile\",\n \"simplified-language\",\n \"audio-description\",\n \"extended-description\",\n]);\n/**\n * QTI reserves an `ext:` prefix for vendor extensions, and pairs such a card\n * with a standard one on the same node in its own examples. A prefixed token is\n * therefore a deliberate extension rather than a typo, and passes without\n * comment even though PIE ships no consumer for it.\n */\nconst EXTENSION_TYPE_PREFIX = \"ext:\";\nexport function isKnownCatalogType(type) {\n if (KNOWN_CATALOG_TYPES.has(type))\n return true;\n return (type.startsWith(EXTENSION_TYPE_PREFIX) &&\n type.length > EXTENSION_TYPE_PREFIX.length);\n}\n// One report per distinct token per side, because the interesting information is\n// \"this token is not a thing\", and repeating it per card or per lookup would bury\n// it under itself.\nconst reportedUnknownTypes = new Set();\nfunction cloneAndFreezeCatalogValue(value, seen = new Set()) {\n if (value === null ||\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\" ||\n typeof value === \"undefined\") {\n return value;\n }\n if (typeof value !== \"object\") {\n throw new TypeError(\"catalog cards must contain JSON-compatible values\");\n }\n if (seen.has(value)) {\n throw new TypeError(\"catalog cards must not contain cycles\");\n }\n seen.add(value);\n try {\n if (Array.isArray(value)) {\n return Object.freeze(value.map((entry) => cloneAndFreezeCatalogValue(entry, seen)));\n }\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) {\n throw new TypeError(\"catalog cards must contain only plain objects and arrays\");\n }\n const cloned = {};\n for (const [key, entry] of Object.entries(value)) {\n cloned[key] = cloneAndFreezeCatalogValue(entry, seen);\n }\n return Object.freeze(cloned);\n }\n finally {\n seen.delete(value);\n }\n}\nfunction reportUnknownCatalogType(type, side, where) {\n const key = `${side}|${type}`;\n if (reportedUnknownTypes.has(key))\n return;\n reportedUnknownTypes.add(key);\n const known = `${Array.from(KNOWN_CATALOG_TYPES).join(\", \")}, or an \"${EXTENSION_TYPE_PREFIX}\" prefixed vendor extension`;\n if (side === \"card\") {\n console.warn(`[AccessibilityCatalogResolver] catalog \"${where}\" has a card of unknown type \"${type}\"; it is stored but no reader asks for that type, so the alternate will never be shown. Expected one of: ${known}.`);\n return;\n }\n console.warn(`[AccessibilityCatalogResolver] lookup for unknown catalog type \"${type}\" on \"${where}\" cannot match any card. Expected one of: ${known}.`);\n}\nexport const catalogCardForm = (card) => card.payload !== undefined ? \"payload\" : \"content\";\n/**\n * Accessibility Catalog Resolver Service\n *\n * Manages QTI 3.0 accessibility catalogs at both assessment and item levels.\n * Provides lookup and resolution services for alternative content representations.\n *\n * @example\n * ```typescript\n * // Initialize with assessment-level catalogs\n * const resolver = new AccessibilityCatalogResolver(assessment.accessibilityCatalogs);\n *\n * // Add item-level catalogs when rendering item\n * resolver.addItemCatalogs(item.accessibilityCatalogs);\n *\n * // Resolve catalog by identifier\n * const spokenContent = resolver.getAlternative('intro-passage', {\n * type: 'spoken',\n * language: 'en-US'\n * });\n *\n * // Check if catalog exists\n * if (resolver.hasCatalog('math-problem-1')) {\n * const braille = resolver.getAlternative('math-problem-1', { type: 'braille' });\n * }\n * ```\n */\nexport class AccessibilityCatalogResolver {\n assessmentCatalogs = new Map();\n itemCatalogs = new Map();\n scopedCatalogs = new Map();\n // Matches the language the extractor tags cards with and the TTSService\n // passes on lookup (\"en-US\"), so the default-language fallback rung in\n // findMatchingCard is actually reachable for the common case.\n defaultLanguage = \"en-US\";\n // Egress sanitization cache. Catalogs are sanitized at registration, but that\n // is a no-op when indexing runs without a DOM (SSR). Sanitizing again as\n // spoken content leaves the resolver guarantees no raw author SSML reaches a\n // provider regardless of where indexing happened; the cache keeps it to one\n // pass per unique string (sanitizeSsmlString is idempotent).\n sanitizedSpokenCache = new Map();\n catalogChangeListeners = new Set();\n reportedSnapshotProblems = new Set();\n constructor(assessmentCatalogs, defaultLanguage = \"en-US\") {\n this.defaultLanguage = defaultLanguage;\n this.indexCatalogs(assessmentCatalogs ?? [], \"assessment\");\n }\n /**\n * Set the default language for fallback resolution\n */\n setDefaultLanguage(language) {\n this.defaultLanguage = language;\n }\n /**\n * Subscribe to catalog registrations and removals.\n *\n * Readers that render a catalog — as opposed to TTS, which resolves by DOM\n * lookup at the moment it speaks — have to compute \"is there a card for this\n * item\" before the catalogs exist: registration is driven by an item shell's\n * mount event, so a card that renders alongside the item legitimately looks\n * too early. Without a signal the only options are polling on a deadline (no\n * budget is right: too short strands the accommodation, too long is a visible\n * delay) or missing the content silently.\n *\n * Same contract as `ToolPolicyEngine.onPolicyChange`, deliberately: a listener\n * plus an unsubscribe, an event that names the `reason` and carries no\n * resolved state, and subscriber errors swallowed so one bad listener cannot\n * break registration. Listeners re-query rather than consuming a payload,\n * which is what keeps the resolver free of assumptions about who is reading.\n *\n * Fires after the mutation, so a listener that re-queries sees the new state.\n *\n * @returns Unsubscribe function\n */\n onCatalogsChange(listener) {\n this.catalogChangeListeners.add(listener);\n return () => {\n this.catalogChangeListeners.delete(listener);\n };\n }\n emitCatalogsChange(event) {\n // Iterated over a copy: a listener that unsubscribes itself (or another)\n // while handling the event must not make the loop skip its neighbours.\n for (const listener of Array.from(this.catalogChangeListeners)) {\n try {\n listener(event);\n }\n catch {\n // Subscriber errors must not break registration. Hosts that want\n // error telemetry should wrap their listener.\n }\n }\n }\n /**\n * Get the default language\n */\n getDefaultLanguage() {\n return this.defaultLanguage;\n }\n /**\n * Index catalogs into the appropriate map\n */\n indexCatalogs(catalogs, source) {\n const targetMap = source === \"assessment\" ? this.assessmentCatalogs : this.itemCatalogs;\n for (const catalog of this.sanitizeCatalogs(catalogs)) {\n if (targetMap.has(catalog.identifier)) {\n console.warn(`[AccessibilityCatalogResolver] Duplicate ${source} catalog \"${catalog.identifier}\" ignored`);\n continue;\n }\n targetMap.set(catalog.identifier, catalog);\n }\n }\n insertScopedCatalogs(context, catalogs) {\n if (!catalogs || catalogs.length === 0)\n return null;\n const key = this.getOwnerKey(context);\n const existing = this.scopedCatalogs.get(key);\n const scoped = existing?.catalogs ?? new Map();\n const insertedIds = [];\n for (const catalog of this.sanitizeCatalogs(catalogs)) {\n if (scoped.has(catalog.identifier)) {\n console.warn(`[AccessibilityCatalogResolver] Duplicate scoped catalog \"${catalog.identifier}\" ignored for ${key}`);\n continue;\n }\n scoped.set(catalog.identifier, catalog);\n insertedIds.push(catalog.identifier);\n }\n if (!existing && insertedIds.length > 0) {\n this.scopedCatalogs.set(key, {\n context: { ...context },\n catalogs: scoped,\n });\n }\n return { key, context: { ...context }, catalogs: scoped, insertedIds };\n }\n removeScopedInsertion(insertion) {\n const current = this.scopedCatalogs.get(insertion.key);\n if (current?.catalogs !== insertion.catalogs)\n return false;\n let removed = false;\n for (const insertedId of insertion.insertedIds) {\n removed = current.catalogs.delete(insertedId) || removed;\n }\n if (current.catalogs.size === 0) {\n this.scopedCatalogs.delete(insertion.key);\n }\n return removed;\n }\n registerCatalogs(context, catalogs) {\n const insertion = this.insertScopedCatalogs(context, catalogs);\n // Only when something was actually inserted: an all-duplicates call changes\n // nothing, and waking every reader to re-resolve for that would make the\n // signal untrustworthy.\n if (insertion && insertion.insertedIds.length > 0) {\n this.emitCatalogsChange({ reason: \"scoped-registered\", context });\n }\n let active = true;\n return () => {\n if (!active)\n return;\n active = false;\n if (insertion && this.removeScopedInsertion(insertion)) {\n this.emitCatalogsChange({ reason: \"scoped-removed\", context });\n }\n };\n }\n /**\n * Register every catalog carried by one mounted item or passage as one\n * owner-level transaction.\n *\n * The resolver owns the entity walk and emits one post-mutation signal, so a\n * reader never observes only the root or only the model half of an owner.\n */\n registerOwner(registration) {\n const { owner, entity } = registration;\n const context = catalogOwnerContextFor(owner);\n const insertions = [];\n let registrations = [];\n try {\n registrations = collectOwnerCatalogRegistrations(entity, owner);\n }\n catch (error) {\n console.warn(\"[AccessibilityCatalogResolver] A mounted content owner could not be traversed for catalogs; the primary content remains available.\", error);\n }\n for (const entry of registrations) {\n try {\n const insertion = this.insertScopedCatalogs(entry.context, entry.catalogs);\n if (insertion)\n insertions.push(insertion);\n }\n catch (error) {\n console.warn(\"[AccessibilityCatalogResolver] Invalid catalogs on a mounted content owner were ignored; the primary content and other valid catalogs remain available.\", error);\n }\n }\n const changed = insertions.some((insertion) => insertion.insertedIds.length > 0);\n if (changed) {\n this.emitCatalogsChange({ reason: \"scoped-registered\", context });\n }\n let active = true;\n return () => {\n if (!active)\n return;\n active = false;\n let removed = false;\n for (const insertion of insertions) {\n removed = this.removeScopedInsertion(insertion) || removed;\n }\n if (removed) {\n this.emitCatalogsChange({ reason: \"scoped-removed\", context });\n }\n };\n }\n /** Bind catalog reads and change observation to one content owner. */\n forOwner(context) {\n const ownerContext = { ...context };\n return Object.freeze({\n snapshot: () => this.createOwnerSnapshot(ownerContext),\n onChange: (listener) => this.onCatalogsChange((event) => {\n if (this.catalogChangeAffectsOwner(event, ownerContext))\n listener();\n }),\n });\n }\n /**\n * Add item-level catalogs (called when rendering a new item)\n */\n addItemCatalogs(catalogs) {\n if (!catalogs || catalogs.length === 0)\n return;\n this.indexCatalogs(catalogs, \"item\");\n this.emitCatalogsChange({ reason: \"item-added\" });\n }\n /**\n * Clear item-level catalogs (called when leaving an item)\n */\n clearItemCatalogs() {\n if (this.itemCatalogs.size === 0)\n return;\n this.itemCatalogs.clear();\n this.emitCatalogsChange({ reason: \"item-cleared\" });\n }\n /**\n * Check if a catalog exists (checks both assessment and item levels)\n */\n hasCatalog(catalogId) {\n return (this.itemCatalogs.has(catalogId) ||\n this.assessmentCatalogs.has(catalogId) ||\n Array.from(this.scopedCatalogs.values()).some((owner) => owner.catalogs.has(catalogId)));\n }\n /**\n * Get alternative content for a catalog identifier\n *\n * Priority: Item-level catalogs take precedence over assessment-level\n */\n getAlternative(catalogId, options) {\n // A typo on this side is as silent as one on a card: the lookup simply finds\n // nothing and the caller reads that as \"no alternate authored\".\n if (!isKnownCatalogType(options.type)) {\n reportUnknownCatalogType(options.type, \"lookup\", catalogId);\n }\n const scopedCatalog = options.context\n ? this.scopedCatalogs\n .get(this.getOwnerKey(options.context))\n ?.catalogs.get(catalogId)\n : null;\n if (scopedCatalog) {\n const card = this.findMatchingCard(scopedCatalog, options);\n if (card)\n return this.resolveCard(catalogId, card, \"item\");\n }\n if (options.context) {\n const candidates = this.findScopedCandidates(catalogId, options.context);\n if (candidates.length === 1) {\n const card = this.findMatchingCard(candidates[0], options);\n if (card)\n return this.resolveCard(catalogId, card, \"item\");\n }\n else if (candidates.length > 1) {\n console.warn(`[AccessibilityCatalogResolver] Ambiguous scoped catalog \"${catalogId}\" for owner context`, options.context);\n return null;\n }\n }\n // Check item-level first (higher precedence)\n const itemCatalog = this.itemCatalogs.get(catalogId);\n if (itemCatalog) {\n const card = this.findMatchingCard(itemCatalog, options);\n if (card)\n return this.resolveCard(catalogId, card, \"item\");\n }\n // Fallback to assessment-level\n const assessmentCatalog = this.assessmentCatalogs.get(catalogId);\n if (assessmentCatalog) {\n const card = this.findMatchingCard(assessmentCatalog, options);\n if (card)\n return this.resolveCard(catalogId, card, \"assessment\");\n }\n return null;\n }\n resolveCard(catalogId, card, source) {\n return {\n catalogId,\n type: card.catalog,\n language: card.language,\n content: card.catalog === \"spoken\" && card.content !== undefined\n ? this.ensureSpokenSanitized(card.content)\n : card.content,\n payload: card.payload,\n source,\n };\n }\n ensureSpokenSanitized(content) {\n const cached = this.sanitizedSpokenCache.get(content);\n if (cached !== undefined)\n return cached;\n const sanitized = sanitizeSsmlString(content);\n this.sanitizedSpokenCache.set(content, sanitized);\n return sanitized;\n }\n getOwnerKey(context) {\n return [\n context.ownerKind,\n context.assessmentId || \"\",\n context.sectionId || \"\",\n context.canonicalItemId || \"\",\n context.itemId || \"\",\n context.passageId || \"\",\n context.modelId || \"\",\n ].join(\"|\");\n }\n // Flattened [id, catalog] pairs for every context-scoped owner. The primary\n // runtime path registers catalogs as scoped, so enumeration APIs must include\n // these or they silently under-report what TTS content exists.\n scopedCatalogEntries() {\n const entries = [];\n for (const owner of this.scopedCatalogs.values()) {\n for (const entry of owner.catalogs.entries()) {\n entries.push(entry);\n }\n }\n return entries;\n }\n findScopedCandidates(catalogId, context) {\n return Array.from(this.scopedCatalogs.values())\n .filter((owner) => this.isCompatibleOwnerContext(owner.context, context))\n .map((owner) => owner.catalogs.get(catalogId))\n .filter((catalog) => Boolean(catalog));\n }\n isCompatibleOwnerContext(registered, lookup) {\n if (registered.ownerKind !== lookup.ownerKind)\n return false;\n if (lookup.assessmentId &&\n registered.assessmentId !== lookup.assessmentId) {\n return false;\n }\n if (lookup.sectionId && registered.sectionId !== lookup.sectionId) {\n return false;\n }\n if (lookup.canonicalItemId &&\n registered.canonicalItemId !== lookup.canonicalItemId) {\n return false;\n }\n if (lookup.itemId && registered.itemId !== lookup.itemId) {\n return false;\n }\n if (lookup.passageId && registered.passageId !== lookup.passageId) {\n return false;\n }\n if (lookup.modelId && registered.modelId !== lookup.modelId) {\n return false;\n }\n return true;\n }\n ownerScopedCatalogEntries(context) {\n const entries = [];\n const exact = this.scopedCatalogs.get(this.getOwnerKey(context));\n if (exact)\n entries.push(...exact.catalogs.entries());\n for (const owner of this.scopedCatalogs.values()) {\n if (owner === exact)\n continue;\n if (!this.isCompatibleOwnerContext(owner.context, context))\n continue;\n entries.push(...owner.catalogs.entries());\n }\n return entries;\n }\n createOwnerSnapshot(context) {\n const cards = [];\n const entries = this.ownerScopedCatalogEntries(context);\n if (context.ownerKind === \"global\") {\n entries.push(...this.assessmentCatalogs.entries());\n }\n for (const [catalogId, catalog] of entries) {\n for (const card of catalog.cards) {\n try {\n cards.push(Object.freeze({\n catalogId,\n card: cloneAndFreezeCatalogValue(card),\n }));\n }\n catch (error) {\n const key = `${this.getOwnerKey(context)}\\u0000${catalogId}`;\n if (!this.reportedSnapshotProblems.has(key)) {\n this.reportedSnapshotProblems.add(key);\n console.warn(`[AccessibilityCatalogResolver] Catalog \"${catalogId}\" contains a card that cannot be exposed in an owner snapshot; that card was ignored.`, error);\n }\n }\n }\n }\n return Object.freeze({ cards: Object.freeze(cards) });\n }\n catalogChangeAffectsOwner(event, context) {\n if (!event.context)\n return false;\n if (this.isCompatibleOwnerContext(event.context, context))\n return true;\n // `registerOwner` emits once at the entity root after registering root and\n // model catalogs transactionally. A model-bound reader belongs to that same\n // owner family and must observe the root event too.\n if (context.ownerKind === \"itemModel\" &&\n context.modelId &&\n event.context.ownerKind === \"itemModel\" &&\n !event.context.modelId) {\n return this.isCompatibleOwnerContext({ ...event.context, modelId: context.modelId }, context);\n }\n return false;\n }\n // The single funnel every registration path runs through — the constructor and\n // `addItemCatalogs` by way of `indexCatalogs`, and `registerCatalogs`\n // directly — which is why the unknown-type report lives here rather than at\n // each entry point.\n sanitizeCatalogs(catalogs) {\n return catalogs.map((catalog) => ({\n ...catalog,\n cards: catalog.cards.map((card) => {\n if (!isKnownCatalogType(card.catalog)) {\n reportUnknownCatalogType(card.catalog, \"card\", catalog.identifier);\n }\n return {\n ...card,\n content: card.catalog === \"spoken\" && card.content !== undefined\n ? sanitizeSsmlString(card.content)\n : card.content,\n };\n }),\n }));\n }\n /**\n * Find a matching catalog card based on lookup options\n */\n findMatchingCard(catalog, options) {\n const { type, language, useFallback = true, form } = options;\n // Language rungs, most specific first: the requested language, then the\n // default language, then any.\n //\n // Each requested tag expands into its RFC 4647 lookup sequence, so `es-MX`\n // tries `es-mx` and then `es` before falling through to the default. Matching\n // was `===`, which made a POSIX `es_ES` card — what the Learnosity transform\n // emits — unreachable for an `es-ES` request except through the final\n // no-constraint rung, i.e. by accident.\n const languageRungs = [];\n const pushLookupRungs = (tag) => {\n for (const step of languageTagLookupSequence(tag)) {\n languageRungs.push((card) => normalizeLanguageTag(card.language) === step);\n }\n };\n if (language) {\n pushLookupRungs(language);\n }\n if (useFallback) {\n pushLookupRungs(this.defaultLanguage);\n languageRungs.push(() => true);\n }\n for (const matchesLanguage of languageRungs) {\n const candidates = catalog.cards.filter((card) => card.catalog === type && matchesLanguage(card));\n if (candidates.length === 0)\n continue;\n // Form is preferred inside a language rung and never across them: a\n // recording in the requested language beats a script in that language,\n // but a script in the requested language beats a recording in another\n // one. Getting this backwards would answer a Spanish lookup with English\n // audio, which is worse than answering it with Spanish text.\n if (form) {\n const preferred = candidates.find((card) => catalogCardForm(card) === form);\n if (preferred)\n return preferred;\n }\n // No preference expressed, or the preferred form is absent: first match,\n // which is what every caller got before form preference existed.\n return candidates[0];\n }\n return null;\n }\n /**\n * Get all available alternatives for a catalog identifier\n *\n * Every card goes through `resolveCard`, the same projection `getAlternative`\n * uses, so enumeration cannot describe a card differently from the resolution\n * that renders it. It was hand-rolled here once and drifted immediately: the\n * `signLanguage` alias was folded in on the resolution path only, so a card\n * that arrived under the alias rendered correctly and was still reported as\n * carrying no payload by anything asking what alternates exist.\n */\n getAllAlternatives(catalogId) {\n const results = [];\n // Type, language *and* form: one catalog identifier legitimately carries\n // several cards of the same type in different languages, and also a script\n // and a recording of the same type in the *same* language. Keying on type\n // and language alone dropped the second of those on the floor, so anything\n // asking what alternates exist under-reported them.\n const claimed = new Set();\n const add = (card, source) => {\n // The language part is normalized, so a POSIX `es_ES` card and a BCP-47\n // `es-ES` card collapse to one entry here exactly as they now collapse on\n // the resolution path. Keying on the raw string would report two\n // alternates where resolution can only ever return one.\n const key = `${card.catalog}|${normalizeLanguageTag(card.language)}|${catalogCardForm(card)}`;\n if (claimed.has(key))\n return;\n claimed.add(key);\n results.push(this.resolveCard(catalogId, card, source));\n };\n // Item-level first, which is also the precedence `getAlternative` applies.\n const itemCatalog = this.itemCatalogs.get(catalogId);\n if (itemCatalog) {\n for (const card of itemCatalog.cards)\n add(card, \"item\");\n }\n const assessmentCatalog = this.assessmentCatalogs.get(catalogId);\n if (assessmentCatalog) {\n for (const card of assessmentCatalog.cards)\n add(card, \"assessment\");\n }\n // Scoped (context-registered) alternatives resolve as \"item\" in\n // `getAlternative`, so report them the same way here.\n for (const [id, catalog] of this.scopedCatalogEntries()) {\n if (id !== catalogId)\n continue;\n for (const card of catalog.cards)\n add(card, \"item\");\n }\n return results;\n }\n /**\n * Get all catalog identifiers available (both assessment and item)\n */\n getAllCatalogIds() {\n const scopedIds = this.scopedCatalogEntries().map(([id]) => id);\n return Array.from(new Set([\n ...this.itemCatalogs.keys(),\n ...this.assessmentCatalogs.keys(),\n ...scopedIds,\n ]));\n }\n /**\n * Get statistics about available catalogs\n */\n getStatistics() {\n const allTypes = new Set();\n const allLanguages = new Set();\n // Collect from assessment catalogs\n for (const catalog of this.assessmentCatalogs.values()) {\n for (const card of catalog.cards) {\n allTypes.add(card.catalog);\n if (card.language)\n allLanguages.add(card.language);\n }\n }\n // Collect from item catalogs\n for (const catalog of this.itemCatalogs.values()) {\n for (const card of catalog.cards) {\n allTypes.add(card.catalog);\n if (card.language)\n allLanguages.add(card.language);\n }\n }\n for (const owner of this.scopedCatalogs.values()) {\n for (const catalog of owner.catalogs.values()) {\n for (const card of catalog.cards) {\n allTypes.add(card.catalog);\n if (card.language)\n allLanguages.add(card.language);\n }\n }\n }\n return {\n totalCatalogs: this.assessmentCatalogs.size +\n this.itemCatalogs.size +\n Array.from(this.scopedCatalogs.values()).reduce((total, owner) => total + owner.catalogs.size, 0),\n assessmentCatalogs: this.assessmentCatalogs.size,\n itemCatalogs: this.itemCatalogs.size +\n Array.from(this.scopedCatalogs.values()).reduce((total, owner) => total + owner.catalogs.size, 0),\n availableTypes: allTypes,\n availableLanguages: allLanguages,\n };\n }\n /**\n * Check if a specific catalog type is available for a given catalog ID\n */\n hasAlternativeType(catalogId, type) {\n const alternatives = this.getAllAlternatives(catalogId);\n return alternatives.some((alt) => alt.type === type);\n }\n /**\n * Get all catalog IDs that have a specific type of alternative\n */\n getCatalogsByType(type) {\n const catalogIds = new Set();\n for (const [id, catalog] of this.assessmentCatalogs.entries()) {\n if (catalog.cards.some((card) => card.catalog === type)) {\n catalogIds.add(id);\n }\n }\n for (const [id, catalog] of this.itemCatalogs.entries()) {\n if (catalog.cards.some((card) => card.catalog === type)) {\n catalogIds.add(id);\n }\n }\n for (const [id, catalog] of this.scopedCatalogEntries()) {\n if (catalog.cards.some((card) => card.catalog === type)) {\n catalogIds.add(id);\n }\n }\n return Array.from(catalogIds);\n }\n /**\n * Reset all catalogs (both assessment and item)\n */\n reset() {\n this.assessmentCatalogs.clear();\n this.itemCatalogs.clear();\n this.scopedCatalogs.clear();\n this.sanitizedSpokenCache.clear();\n this.reportedSnapshotProblems.clear();\n }\n /**\n * Destroy and cleanup\n */\n destroy() {\n this.reset();\n }\n}\n","/**\n * ElementToolStateStore - Manages element-level ephemeral tool state\n *\n * Provides centralized storage for UI tool state (answer eliminations, flags, etc.)\n * that should NOT be sent to the server for scoring. Each element is uniquely identified\n * across the entire assessment using composite keys.\n *\n * Key features:\n * - Element-level granularity (not item-level)\n * - Composite keys for global uniqueness: `assessmentId:sectionId:itemId:elementId`\n * - Cross-section state persistence\n * - Reactive subscriptions\n * - Optional persistence callback integration\n * - Generic solution for any tool\n */\nexport class ElementToolStateStore {\n elementStates = new Map();\n listeners = new Set();\n onStateChange = null;\n /**\n * Generates a globally unique element ID by combining assessment, section, item, and element IDs.\n * Format: `${assessmentId}:${sectionId}:${itemId}:${elementId}`\n *\n * @example\n * getGlobalElementId('demo-assessment', 'section-1', 'q1', 'mc1')\n * // Returns: \"demo-assessment:section-1:q1:mc1\"\n */\n getGlobalElementId(assessmentId, sectionId, itemId, elementId) {\n return `${assessmentId}:${sectionId}:${itemId}:${elementId}`;\n }\n /**\n * Parses a global element ID into its component parts.\n *\n * @example\n * parseGlobalElementId('demo-assessment:section-1:q1:mc1')\n * // Returns: { assessmentId: 'demo-assessment', sectionId: 'section-1', itemId: 'q1', elementId: 'mc1' }\n */\n parseGlobalElementId(globalElementId) {\n const parts = globalElementId.split(\":\");\n if (parts.length !== 4)\n return null;\n return {\n assessmentId: parts[0],\n sectionId: parts[1],\n itemId: parts[2],\n elementId: parts[3],\n };\n }\n /**\n * Sets tool state for a specific element.\n * Notifies all subscribers and triggers persistence callback.\n *\n * @param globalElementId Composite key identifying the element\n * @param toolId Tool identifier (e.g., 'answerEliminator', 'flagging')\n * @param state Tool-specific state object\n */\n setState(globalElementId, toolId, state) {\n let elementState = this.elementStates.get(globalElementId);\n if (!elementState) {\n elementState = new Map();\n this.elementStates.set(globalElementId, elementState);\n }\n elementState.set(toolId, state);\n this._notifyListeners();\n this._notifyStateChange();\n }\n /**\n * Gets tool state for a specific element.\n *\n * @param globalElementId Composite key identifying the element\n * @param toolId Tool identifier\n * @returns Tool state or undefined if not found\n */\n getState(globalElementId, toolId) {\n return this.elementStates.get(globalElementId)?.get(toolId);\n }\n /**\n * Gets all tool states for a specific element.\n *\n * @param globalElementId Composite key identifying the element\n * @returns Object with tool states keyed by toolId\n */\n getElementState(globalElementId) {\n const elementState = this.elementStates.get(globalElementId);\n if (!elementState)\n return {};\n return Object.fromEntries(elementState.entries());\n }\n /**\n * Gets all tool states for all elements.\n * Used for persistence and debugging.\n *\n * @returns Nested object: { globalElementId: { toolId: state } }\n */\n getAllState() {\n const result = {};\n for (const [globalElementId, toolStates] of this.elementStates.entries()) {\n result[globalElementId] = Object.fromEntries(toolStates.entries());\n }\n return result;\n }\n /**\n * Subscribes to state changes.\n * Callback is invoked whenever any element's tool state changes.\n *\n * @param callback Function to call on state changes\n * @returns Unsubscribe function\n */\n subscribe(callback) {\n this.listeners.add(callback);\n return () => this.listeners.delete(callback);\n }\n _notifyListeners() {\n for (const listener of this.listeners) {\n listener(this.elementStates);\n }\n }\n /**\n * Sets a callback to be invoked on state changes for persistence integration.\n * Used by demo/app layer to persist tool state to localStorage or server.\n *\n * @param callback Function to call with serialized state on changes\n */\n setOnStateChange(callback) {\n this.onStateChange = callback;\n }\n _notifyStateChange() {\n if (this.onStateChange) {\n this.onStateChange(this.getAllState());\n }\n }\n /**\n * Loads tool state from serialized format.\n * Used to restore state from localStorage or server.\n *\n * @param state Serialized state object\n */\n loadState(state) {\n this.elementStates.clear();\n for (const [globalElementId, toolStates] of Object.entries(state)) {\n const elementState = new Map(Object.entries(toolStates));\n this.elementStates.set(globalElementId, elementState);\n }\n this._notifyListeners();\n }\n /**\n * Clears all tool state for a specific element.\n *\n * @param globalElementId Composite key identifying the element\n */\n clearElement(globalElementId) {\n this.elementStates.delete(globalElementId);\n this._notifyListeners();\n this._notifyStateChange();\n }\n /**\n * Clears state for a specific tool across all elements.\n * Useful when disabling a tool globally.\n *\n * @param toolId Tool identifier\n */\n clearTool(toolId) {\n for (const elementState of this.elementStates.values()) {\n elementState.delete(toolId);\n }\n this._notifyListeners();\n this._notifyStateChange();\n }\n /**\n * Clears all tool state for a specific section.\n * Useful when unmounting/disposing a section.\n *\n * @param assessmentId Assessment identifier\n * @param sectionId Section identifier\n */\n clearSection(assessmentId, sectionId) {\n const prefix = `${assessmentId}:${sectionId}:`;\n const keysToDelete = [];\n for (const key of this.elementStates.keys()) {\n if (key.startsWith(prefix)) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n this.elementStates.delete(key);\n }\n this._notifyListeners();\n this._notifyStateChange();\n }\n /**\n * Clears all tool state.\n * Useful when switching between assessments or demos.\n */\n clearAll() {\n this.elementStates.clear();\n this._notifyListeners();\n this._notifyStateChange();\n }\n}\n","/**\n * RangeSerializer - Serialize and deserialize DOM Range objects\n *\n * Provides utilities for storing and restoring text ranges across sessions.\n * Used by both TTS (for timing data) and annotations (for persistence).\n *\n * Uses CSS selector paths and node indices for robust serialization that\n * survives content changes when possible.\n */\n/**\n * RangeSerializer - Serialize and deserialize Range objects.\n */\nexport class RangeSerializer {\n /**\n * Serialize a Range to storable format.\n *\n * @param range - Range to serialize\n * @param root - Root element (typically document.body or content container)\n * @returns Serialized range data\n *\n * @example\n * ```typescript\n * const serializer = new RangeSerializer();\n * const range = window.getSelection()!.getRangeAt(0);\n * const serialized = serializer.serialize(range, document.body);\n * localStorage.setItem('savedRange', JSON.stringify(serialized));\n * ```\n */\n serialize(range, root) {\n return {\n startContainer: this.getNodePath(range.startContainer, root),\n startOffset: range.startOffset,\n endContainer: this.getNodePath(range.endContainer, root),\n endOffset: range.endOffset,\n text: range.toString(),\n };\n }\n /**\n * Deserialize range from storage.\n *\n * @param data - Serialized range data\n * @param root - Root element (same as used in serialize)\n * @returns Range object, or null if content changed\n *\n * @example\n * ```typescript\n * const serializer = new RangeSerializer();\n * const data = JSON.parse(localStorage.getItem('savedRange')!);\n * const range = serializer.deserialize(data, document.body);\n * if (range) {\n * // Range successfully restored\n * } else {\n * // Content changed, range invalid\n * }\n * ```\n */\n deserialize(data, root) {\n const startNode = this.findNodeByPath(data.startContainer, root);\n const endNode = this.findNodeByPath(data.endContainer, root);\n if (!startNode || !endNode) {\n return null;\n }\n try {\n const range = new Range();\n range.setStart(startNode, data.startOffset);\n range.setEnd(endNode, data.endOffset);\n // Validate text hasn't changed\n if (range.toString() === data.text) {\n return range;\n }\n // Text changed, range is invalid\n return null;\n }\n catch (error) {\n // Range construction failed (offsets invalid, etc.)\n console.warn(\"Failed to deserialize range:\", error);\n return null;\n }\n }\n /**\n * Get a unique path to a node from root.\n *\n * Uses a hybrid approach:\n * - For element nodes: CSS selector path\n * - For text nodes: parent selector + text node index\n *\n * @param node - Node to get path for\n * @param root - Root element\n * @returns Path string\n */\n getNodePath(node, root) {\n if (node === root) {\n return \"\";\n }\n // Handle text nodes\n if (node.nodeType === Node.TEXT_NODE) {\n const parent = node.parentElement;\n if (!parent) {\n throw new Error(\"Text node has no parent\");\n }\n // Get index of this text node among its siblings\n const textNodes = Array.from(parent.childNodes).filter((n) => n.nodeType === Node.TEXT_NODE);\n const index = textNodes.indexOf(node);\n const parentPath = this.getElementPath(parent, root);\n return `${parentPath}::text[${index}]`;\n }\n // Handle element nodes\n if (node.nodeType === Node.ELEMENT_NODE) {\n return this.getElementPath(node, root);\n }\n throw new Error(`Unsupported node type: ${node.nodeType}`);\n }\n /**\n * Get CSS selector path to an element.\n *\n * @param element - Element to get path for\n * @param root - Root element\n * @returns CSS selector path\n */\n getElementPath(element, root) {\n if (element === root) {\n return \"\";\n }\n const path = [];\n let current = element;\n while (current && current !== root) {\n // Use ID if available (more stable)\n if (current.id) {\n path.unshift(`#${current.id}`);\n break;\n }\n // Otherwise use tag + nth-of-type\n const parent = current.parentElement;\n if (!parent)\n break;\n const siblings = Array.from(parent.children).filter((el) => el.tagName === current.tagName);\n const index = siblings.indexOf(current);\n const selector = siblings.length > 1\n ? `${current.tagName.toLowerCase()}:nth-of-type(${index + 1})`\n : current.tagName.toLowerCase();\n path.unshift(selector);\n current = parent;\n }\n return path.join(\" > \");\n }\n /**\n * Find a node by its path from root.\n *\n * @param path - Path string from getNodePath\n * @param root - Root element\n * @returns Node, or null if not found\n */\n findNodeByPath(path, root) {\n if (path === \"\") {\n return root;\n }\n // Handle text node paths\n if (path.includes(\"::text[\")) {\n const [elementPath, textPart] = path.split(\"::text[\");\n const textIndex = Number.parseInt(textPart.replace(\"]\", \"\"), 10);\n // Find parent element\n const parent = elementPath ? root.querySelector(elementPath) : root;\n if (!parent)\n return null;\n // Find text node by index\n const textNodes = Array.from(parent.childNodes).filter((n) => n.nodeType === Node.TEXT_NODE);\n return textNodes[textIndex] || null;\n }\n // Handle element paths\n try {\n return root.querySelector(path);\n }\n catch (error) {\n console.warn(\"Invalid selector path:\", path, error);\n return null;\n }\n }\n /**\n * Batch serialize multiple ranges.\n *\n * @param ranges - Ranges to serialize\n * @param root - Root element\n * @returns Array of serialized ranges\n */\n serializeMany(ranges, root) {\n return ranges.map((range) => this.serialize(range, root));\n }\n /**\n * Batch deserialize multiple ranges.\n *\n * @param data - Array of serialized ranges\n * @param root - Root element\n * @returns Array of ranges (nulls for invalid ranges)\n */\n deserializeMany(data, root) {\n return data.map((item) => this.deserialize(item, root));\n }\n}\n","/**\n * HighlightCoordinator\n *\n * Manages separate highlight layers for TTS (temporary) and annotations (persistent).\n * Uses CSS Custom Highlight API - zero DOM mutation, preserves accessibility.\n *\n * Features:\n * - Separate layers prevent TTS clearing from removing student annotations\n * - CSS Custom Highlight API (no DOM mutation)\n * - Full accessibility support (screen readers see original text)\n * - Configurable colors and styles\n * - Annotation persistence via RangeSerializer\n *\n * Part of PIE Assessment Toolkit.\n *\n * Browser Support:\n * - Chrome/Edge 105+\n * - Safari 17.2+\n * - Firefox: Behind flag (not recommended for production)\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/CSS_Custom_Highlight_API\n */\nimport { RangeSerializer } from \"./RangeSerializer.js\";\n/**\n * Highlight types\n */\nexport var HighlightType;\n(function (HighlightType) {\n HighlightType[\"TTS_WORD\"] = \"tts-word\";\n HighlightType[\"TTS_SENTENCE\"] = \"tts-sentence\";\n HighlightType[\"ANNOTATION\"] = \"annotation\";\n})(HighlightType || (HighlightType = {}));\n/**\n * Highlight colors for annotations\n */\nexport var HighlightColor;\n(function (HighlightColor) {\n HighlightColor[\"YELLOW\"] = \"yellow\";\n HighlightColor[\"GREEN\"] = \"green\";\n HighlightColor[\"BLUE\"] = \"blue\";\n HighlightColor[\"PINK\"] = \"pink\";\n HighlightColor[\"ORANGE\"] = \"orange\";\n HighlightColor[\"UNDERLINE\"] = \"underline\";\n})(HighlightColor || (HighlightColor = {}));\nexport class HighlightCoordinator {\n config;\n ttsWordHighlight = null;\n ttsSentenceHighlight = null;\n ttsWordElementHighlights = new Set();\n ttsSentenceElementHighlights = new Set();\n annotations = new Map();\n // Shared highlights per color (one Highlight object per color, contains all ranges)\n colorHighlights = new Map();\n nextAnnotationId = 1;\n supported = false;\n rangeSerializer;\n themeObserver = null;\n explicitTTSColorOverride = null;\n constructor(config = {}) {\n this.config = config;\n this.rangeSerializer = new RangeSerializer();\n // SSR guard\n if (typeof CSS === \"undefined\" || !(\"highlights\" in CSS)) {\n console.warn(\"CSS Custom Highlight API not supported (SSR or unsupported browser)\");\n return;\n }\n this.supported = true;\n this.initializeHighlights();\n this.registerStyles();\n this.applyAdaptiveTTSStyle();\n this.setupThemeObservation();\n }\n setupThemeObservation() {\n if (typeof document === \"undefined\")\n return;\n if (typeof MutationObserver === \"undefined\")\n return;\n const refresh = () => this.applyAdaptiveTTSStyle();\n this.themeObserver = new MutationObserver(refresh);\n this.themeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: [\"style\", \"data-theme\", \"data-color-scheme\", \"class\"],\n });\n for (const host of document.querySelectorAll(\"pie-theme\")) {\n this.themeObserver.observe(host, {\n attributes: true,\n attributeFilter: [\n \"theme\",\n \"scheme\",\n \"provider\",\n \"variables\",\n \"style\",\n \"data-theme\",\n \"data-color-scheme\",\n ],\n });\n }\n }\n parseColor(input) {\n if (!input)\n return null;\n const value = input.trim();\n if (!value)\n return null;\n const hexMatch = /^#([a-f\\d]{3}|[a-f\\d]{6})$/i.exec(value);\n if (hexMatch) {\n const hex = hexMatch[1];\n if (hex.length === 3) {\n return [\n parseInt(hex[0] + hex[0], 16),\n parseInt(hex[1] + hex[1], 16),\n parseInt(hex[2] + hex[2], 16),\n ];\n }\n return [\n parseInt(hex.slice(0, 2), 16),\n parseInt(hex.slice(2, 4), 16),\n parseInt(hex.slice(4, 6), 16),\n ];\n }\n const rgbMatch = /^rgba?\\((.+)\\)$/i.exec(value);\n if (rgbMatch) {\n const normalized = rgbMatch[1].replace(/\\//g, \",\");\n const parts = normalized\n .split(/[,\\s]+/)\n .map((part) => part.trim())\n .filter(Boolean);\n const r = Number(parts[0]);\n const g = Number(parts[1]);\n const b = Number(parts[2]);\n if (Number.isFinite(r) && Number.isFinite(g) && Number.isFinite(b)) {\n return [r, g, b];\n }\n }\n // Browser parser fallback (covers formats like oklch()).\n if (typeof document !== \"undefined\") {\n const parserEl = document.createElement(\"span\");\n parserEl.style.color = value;\n if (typeof parserEl.style.color === \"string\" && parserEl.style.color) {\n document.body?.appendChild(parserEl);\n const resolved = typeof getComputedStyle === \"function\"\n ? getComputedStyle(parserEl).color\n : \"\";\n parserEl.remove();\n const normalizedResolved = resolved.trim();\n // Guard against recursive loops when computed style returns the same\n // unresolved function syntax (observed with certain color formats).\n if (normalizedResolved && normalizedResolved !== value) {\n return this.parseColor(resolved);\n }\n }\n }\n return null;\n }\n relativeLuminance([r, g, b]) {\n const toLinear = (channel) => {\n const n = channel / 255;\n return n <= 0.03928 ? n / 12.92 : ((n + 0.055) / 1.055) ** 2.4;\n };\n const lr = toLinear(r);\n const lg = toLinear(g);\n const lb = toLinear(b);\n return 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;\n }\n contrastRatio(a, b) {\n const la = this.relativeLuminance(a);\n const lb = this.relativeLuminance(b);\n const lighter = Math.max(la, lb);\n const darker = Math.min(la, lb);\n return (lighter + 0.05) / (darker + 0.05);\n }\n blend(fg, bg, alpha) {\n return [\n Math.round(fg[0] * alpha + bg[0] * (1 - alpha)),\n Math.round(fg[1] * alpha + bg[1] * (1 - alpha)),\n Math.round(fg[2] * alpha + bg[2] * (1 - alpha)),\n ];\n }\n resolveAdaptiveTTSStyle(sourceEl) {\n const fallbackMissing = [255, 235, 59];\n const fallbackText = [17, 24, 39];\n const fallbackBackground = [255, 255, 255];\n const target = sourceEl ||\n (typeof document !== \"undefined\" ? document.documentElement : null);\n const computed = target && typeof getComputedStyle === \"function\"\n ? getComputedStyle(target)\n : null;\n const background = this.parseColor(computed?.getPropertyValue(\"--pie-background\") ||\n computed?.backgroundColor) || fallbackBackground;\n const text = this.parseColor(computed?.getPropertyValue(\"--pie-text\")) || fallbackText;\n const accent = this.explicitTTSColorOverride\n ? this.parseColor(this.explicitTTSColorOverride.color) || fallbackMissing\n : this.parseColor(computed?.getPropertyValue(\"--pie-missing\")) ||\n fallbackMissing;\n const opacityCandidates = this.explicitTTSColorOverride\n ? [Math.max(0.3, Math.min(0.95, this.explicitTTSColorOverride.opacity))]\n : [0.8, 0.72, 0.68, 0.62, 0.56, 0.5];\n let selectedOpacity = opacityCandidates[opacityCandidates.length - 1];\n let bestScore = -Infinity;\n for (const opacity of opacityCandidates) {\n const blended = this.blend(accent, background, opacity);\n const backgroundDelta = this.contrastRatio(blended, background);\n const textContrast = this.contrastRatio(blended, text);\n const score = backgroundDelta * 1.2 + textContrast * 0.8;\n if (backgroundDelta >= 1.25 && textContrast >= 2.4) {\n selectedOpacity = opacity;\n break;\n }\n if (score > bestScore) {\n bestScore = score;\n selectedOpacity = opacity;\n }\n }\n const sentenceOpacity = Math.max(0.24, Math.min(0.85, selectedOpacity * 0.55));\n const underlineOpacity = Math.max(0.55, Math.min(0.95, selectedOpacity + 0.2));\n const shadowOpacity = Math.max(0.22, Math.min(0.6, selectedOpacity * 0.45));\n const underlineColor = text;\n const underlineBlend = this.blend(underlineColor, background, underlineOpacity);\n const underlineDelta = this.contrastRatio(underlineBlend, background);\n const fallbackUnderline = this.relativeLuminance(background) > 0.45 ? [0, 0, 0] : [255, 255, 255];\n const finalUnderline = underlineDelta >= 1.35 ? underlineColor : fallbackUnderline;\n const wordHighlight = `rgba(${accent[0]}, ${accent[1]}, ${accent[2]}, ${selectedOpacity})`;\n const sentenceHighlight = `rgba(${accent[0]}, ${accent[1]}, ${accent[2]}, ${sentenceOpacity})`;\n const wordUnderline = `rgba(${finalUnderline[0]}, ${finalUnderline[1]}, ${finalUnderline[2]}, ${underlineOpacity})`;\n const wordShadow = `rgba(${finalUnderline[0]}, ${finalUnderline[1]}, ${finalUnderline[2]}, ${shadowOpacity})`;\n return {\n wordHighlight,\n sentenceHighlight,\n wordUnderline,\n wordShadow,\n };\n }\n applyAdaptiveTTSStyle(sourceEl) {\n if (typeof document === \"undefined\")\n return;\n const vars = this.resolveAdaptiveTTSStyle(sourceEl);\n document.documentElement.style.setProperty(\"--pie-tts-word-highlight\", vars.wordHighlight);\n document.documentElement.style.setProperty(\"--pie-tts-sentence-highlight\", vars.sentenceHighlight);\n document.documentElement.style.setProperty(\"--pie-tts-line-highlight\", vars.sentenceHighlight);\n document.documentElement.style.setProperty(\"--pie-tts-word-underline\", vars.wordUnderline);\n document.documentElement.style.setProperty(\"--pie-tts-word-shadow\", vars.wordShadow);\n }\n /**\n * Initialize CSS Custom Highlights\n */\n initializeHighlights() {\n if (!this.supported)\n return;\n // Create highlight registries for TTS\n this.ttsWordHighlight = new Highlight();\n this.ttsSentenceHighlight = new Highlight();\n // Register TTS highlights with CSS\n CSS.highlights.set(\"tts-word\", this.ttsWordHighlight);\n CSS.highlights.set(\"tts-sentence\", this.ttsSentenceHighlight);\n // Create shared highlights for each annotation color\n for (const color of Object.values(HighlightColor)) {\n const highlight = new Highlight();\n this.colorHighlights.set(color, highlight);\n CSS.highlights.set(`annotation-${color}`, highlight);\n }\n }\n /**\n * Register CSS styles for highlights\n */\n registerStyles() {\n if (!this.supported)\n return;\n if (typeof document === \"undefined\")\n return; // SSR guard\n // Check if styles already exist\n if (document.getElementById(\"pie-highlight-styles\"))\n return;\n const style = document.createElement(\"style\");\n style.id = \"pie-highlight-styles\";\n style.textContent = `\n /* TTS highlights - temporary */\n ::highlight(tts-word) {\n background-color: var(--pie-tts-word-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 68%, transparent));\n text-decoration: underline 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));\n text-underline-offset: 2px;\n text-shadow: 0 0 1px var(--pie-tts-word-shadow, color-mix(in srgb, var(--pie-text, #111827) 35%, transparent));\n color: inherit;\n }\n\n /* tts-sentence registry id: coarse read-along band (visual line boxes in layout) */\n ::highlight(tts-sentence) {\n background-color: var(--pie-tts-line-highlight, var(--pie-tts-sentence-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 38%, transparent)));\n color: inherit;\n }\n\n [data-pie-tts-sentence-element=\"true\"] {\n background-color: var(--pie-tts-line-highlight, var(--pie-tts-sentence-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 38%, transparent)));\n border-radius: 0.12em;\n box-decoration-break: clone;\n -webkit-box-decoration-break: clone;\n }\n\n [data-pie-tts-word-element=\"true\"] {\n background-color: var(--pie-tts-word-highlight, color-mix(in srgb, var(--pie-missing, #ffeb3b) 68%, transparent));\n text-decoration: underline 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));\n text-underline-offset: 2px;\n text-shadow: 0 0 1px var(--pie-tts-word-shadow, color-mix(in srgb, var(--pie-text, #111827) 35%, transparent));\n border-bottom: 2px solid var(--pie-tts-word-underline, color-mix(in srgb, var(--pie-text, #111827) 70%, transparent));\n padding-bottom: 1px;\n border-radius: 0.12em;\n box-decoration-break: clone;\n -webkit-box-decoration-break: clone;\n }\n\n /* Annotation highlights - persistent */\n ::highlight(annotation-yellow) {\n background-color: var(--pie-annotation-yellow-highlight, rgba(253, 233, 149, 0.5));\n color: inherit;\n }\n\n ::highlight(annotation-green) {\n background-color: var(--pie-annotation-green-highlight, rgba(166, 225, 197, 0.5));\n color: inherit;\n }\n\n ::highlight(annotation-blue) {\n background-color: var(--pie-annotation-blue-highlight, rgba(167, 224, 246, 0.5));\n color: inherit;\n }\n\n ::highlight(annotation-pink) {\n background-color: var(--pie-annotation-pink-highlight, rgba(255, 159, 174, 0.5));\n color: inherit;\n }\n\n ::highlight(annotation-orange) {\n background-color: var(--pie-annotation-orange-highlight, rgba(255, 165, 0, 0.5));\n color: inherit;\n }\n\n /* The base light/dark pair is fixed: #4221d5 on light, #9c89ec on dark.\n One value cannot serve both -- #4221d5 is 2.41:1 on black and #9c89ec is\n 2.85:1 on white -- so neither of those two consults the theme accent,\n which is chosen against one background and illegible on the other.\n\n Each state has its own token so overriding one never silently moves the\n other, and so either can beat a host-set pie-primary: a var() fallback\n can never override a value the host actually set. */\n ::highlight(annotation-underline) {\n background-color: transparent;\n text-decoration: underline 2px solid var(--pie-annotation-underline, #4221d5);\n text-underline-offset: 2px;\n color: inherit;\n }\n\n /* The blocks below cover annotation swatches, print, and reduced motion.\n They deliberately do NOT retune the TTS layers: applyAdaptiveTTSStyle()\n writes the pie-tts custom properties inline on documentElement on every\n paint and on theme change, so a media query that only varies a var()\n fallback for those can never take effect. Annotation colours have no such\n adaptive path -- they are fixed swatches a student chose -- so a media\n query is the only way to adjust them, and each keeps its var() so a host\n override still wins.\n\n The names above are spelled without their leading dashes on purpose.\n check-theme-tokens scans comments, and its token pattern stops at the\n first non-alphanumeric character, so writing the wildcard form reads as\n consumption of a shorter token that is not in the registry and fails the\n check. Spell property names in full, or omit the dashes. */\n\n @media (prefers-color-scheme: dark) {\n ::highlight(annotation-yellow) {\n background-color: var(--pie-annotation-yellow-highlight, rgba(139, 117, 0, 0.6));\n }\n ::highlight(annotation-green) {\n background-color: var(--pie-annotation-green-highlight, rgba(45, 92, 63, 0.6));\n }\n ::highlight(annotation-blue) {\n background-color: var(--pie-annotation-blue-highlight, rgba(0, 102, 170, 0.6));\n }\n ::highlight(annotation-pink) {\n background-color: var(--pie-annotation-pink-highlight, rgba(139, 51, 74, 0.6));\n }\n ::highlight(annotation-orange) {\n background-color: var(--pie-annotation-orange-highlight, rgba(154, 99, 0, 0.6));\n }\n ::highlight(annotation-underline) {\n text-decoration-color: var(--pie-annotation-underline-dark, #9c89ec);\n }\n }\n\n /* The media query above reports the OS preference, which is only a guess\n at what the page is actually showing. An app that declares a theme has\n the final say, so the rules below override it. pie-theme always stamps\n data-theme on documentElement (scope=\"document\") or on its own host, and\n resolves to a dark palette only for the literal value \"dark\" -- every\n other value, including DaisyUI theme ids, maps to a light base.\n\n The three cases are mutually exclusive, so they never fight each other.\n All carry attribute selectors, which outrank the bare ::highlight() rules\n above -- including the one inside the media query, since a media query\n adds no specificity -- whatever the source order. */\n [data-theme=\"light\"] ::highlight(annotation-underline) {\n text-decoration-color: var(--pie-annotation-underline, #4221d5);\n }\n\n [data-theme=\"dark\"] ::highlight(annotation-underline) {\n text-decoration-color: var(--pie-annotation-underline-dark, #9c89ec);\n }\n\n /* A host or DaisyUI palette: follow its accent so the mark belongs to that\n theme, falling back to the light default when it declares none. */\n [data-theme]:not([data-theme=\"light\"]):not([data-theme=\"dark\"]) ::highlight(annotation-underline) {\n text-decoration-color: var(--pie-annotation-underline, var(--pie-primary, #4221d5));\n }\n\n /* WCAG 2.2 SC 1.4.11 non-text contrast: a highlight is the only indication\n that text is annotated, so the swatches saturate and the underline\n thickens when the user asks for more contrast.\n\n The value is \"more\", not \"high\". The stylesheet this was recovered from\n used prefers-contrast: high, which is not a valid value for the feature\n -- the keywords are no-preference, more, less, custom. An invalid query\n evaluates to \"not all\", so that block could never have matched in any\n browser even had the file been loaded. Verified with matchMedia under\n emulation: \"high\" stays false where \"more\" flips true. */\n @media (prefers-contrast: more) {\n ::highlight(annotation-yellow) {\n background-color: var(--pie-annotation-yellow-highlight, rgba(255, 255, 0, 0.7));\n }\n ::highlight(annotation-green) {\n background-color: var(--pie-annotation-green-highlight, rgba(0, 255, 127, 0.7));\n }\n ::highlight(annotation-blue) {\n background-color: var(--pie-annotation-blue-highlight, rgba(0, 191, 255, 0.7));\n }\n ::highlight(annotation-pink) {\n background-color: var(--pie-annotation-pink-highlight, rgba(255, 105, 180, 0.7));\n }\n ::highlight(annotation-orange) {\n background-color: var(--pie-annotation-orange-highlight, rgba(255, 165, 0, 0.85));\n }\n ::highlight(annotation-underline) {\n text-decoration-thickness: 3px;\n }\n }\n\n @media print {\n /* TTS highlighting is a transient read-along cue, not content. */\n ::highlight(tts-word),\n ::highlight(tts-sentence),\n [data-pie-tts-word-element=\"true\"],\n [data-pie-tts-sentence-element=\"true\"] {\n background-color: transparent;\n text-decoration: none;\n text-shadow: none;\n border-bottom: none;\n }\n\n /* Annotations are student work and must survive printing, but a fill\n that reads fine on screen can print as an illegible wash, so each\n becomes an underline that keeps its colour coding. */\n ::highlight(annotation-yellow),\n ::highlight(annotation-green),\n ::highlight(annotation-blue),\n ::highlight(annotation-pink),\n ::highlight(annotation-orange) {\n background-color: transparent;\n border-bottom: 2px solid currentColor;\n }\n ::highlight(annotation-yellow) { border-bottom-color: #ffeb3b; }\n ::highlight(annotation-green) { border-bottom-color: #a6e1c5; }\n ::highlight(annotation-blue) { border-bottom-color: #a7e0f6; }\n ::highlight(annotation-pink) { border-bottom-color: #ff9fae; }\n ::highlight(annotation-orange) { border-bottom-color: #ffa500; }\n ::highlight(annotation-underline) {\n text-decoration-color: #000;\n border-bottom: none;\n }\n }\n\n /* text-shadow is a direct property rather than a var(), so unlike the\n other TTS rules this one is not overridden by the adaptive path. */\n @media (prefers-reduced-motion: reduce) {\n ::highlight(tts-word),\n [data-pie-tts-word-element=\"true\"] {\n text-shadow: none;\n }\n }\n `;\n document.head.appendChild(style);\n }\n /**\n * Highlight a word for TTS (temporary)\n *\n * @param textNode Text node containing the word\n * @param startOffset Start position in text node\n * @param endOffset End position in text node\n */\n highlightTTSWord(textNode, startOffset, endOffset) {\n if (!this.ttsWordHighlight)\n return;\n this.applyAdaptiveTTSStyle(textNode.parentElement);\n // Clear previous word highlight\n this.clearTTSWord();\n // Create range for word\n const range = document.createRange();\n range.setStart(textNode, startOffset);\n range.setEnd(textNode, endOffset);\n // Add to highlight\n this.ttsWordHighlight.add(range);\n }\n /**\n * Highlight a single element as the active TTS word (temporary).\n *\n * Unlike {@link highlightTTSWord} (which paints a CSS range over a text node)\n * this marks the element itself via `data-pie-tts-word-element`. It is used\n * for atomic targets that have no direct text node to range over — most\n * notably MathJax CHTML tokens (e.g. `<mjx-mi><mjx-c/></mjx-mi>`, whose glyph\n * lives in a font-driven pseudo-element a CSS range cannot paint) and\n * whole-expression fallbacks.\n *\n * The supplied element is painted exactly; we deliberately do NOT walk up to\n * a containing `<math>` / `<mjx-container>`. That escalation is what made\n * MathJax-rendered math highlight as a full block while native MathML tracked\n * per-token: a resolved single token must paint as a token, and only a\n * genuine expression fallback (where the element already is the container)\n * should paint the whole expression.\n */\n highlightTTSWordElement(element) {\n if (!this.ttsWordHighlight)\n return;\n this.applyAdaptiveTTSStyle(element);\n // Clear previous word highlight (CSS range and any element attributes)\n this.clearTTSWord();\n element.setAttribute(\"data-pie-tts-word-element\", \"true\");\n this.ttsWordElementHighlights.add(element);\n }\n /**\n * Highlight the coarse TTS read-along band (temporary).\n * Usually one Range per visual line; CSS layer `tts-sentence` for compatibility.\n *\n * @param ranges Line (or sentence) ranges to paint with `--pie-tts-line-highlight`\n */\n highlightTTSSentence(ranges) {\n if (!this.ttsSentenceHighlight)\n return;\n const source = ranges[0]?.startContainer;\n const sourceElement = source?.nodeType === Node.ELEMENT_NODE\n ? source\n : source?.parentElement;\n this.applyAdaptiveTTSStyle(sourceElement);\n // Clear previous sentence highlight\n this.clearTTSSentence();\n // Add all ranges\n for (const range of ranges) {\n this.ttsSentenceHighlight.add(range);\n }\n this.highlightTTSElementFallbacks(ranges);\n }\n /**\n * Highlight sentence/block elements for TTS (background layer).\n *\n * @param elements Visible elements to paint with `--pie-tts-line-highlight`\n */\n highlightTTSSentenceElements(elements) {\n if (!this.ttsSentenceHighlight)\n return;\n this.applyAdaptiveTTSStyle(elements[0] || null);\n this.clearTTSSentence();\n for (const element of elements) {\n element.setAttribute(\"data-pie-tts-sentence-element\", \"true\");\n this.ttsSentenceElementHighlights.add(element);\n }\n }\n // The read-along (sentence) band legitimately covers whole equations and\n // replaced elements, so it escalates to them.\n static SENTENCE_FALLBACK_SELECTOR = \"math, mjx-container, svg, img, canvas, [role='img']\";\n // The word layer must NOT escalate a multi-node range to the enclosing\n // `<math>` / `<mjx-container>`: that is what made an equation flash as a\n // whole block whenever a spoken word's visible range crossed several math\n // glyph nodes. Math is tracked per token (or held / region) by the highlight\n // pipeline instead. Replaced elements (svg/img/canvas) still need the element\n // fallback because a CSS range cannot paint them.\n static WORD_FALLBACK_SELECTOR = \"svg, img, canvas, [role='img']\";\n highlightTTSElementFallbacks(ranges) {\n if (typeof Element === \"undefined\")\n return;\n this.highlightElementFallbacks(ranges, \"data-pie-tts-sentence-element\", this.ttsSentenceElementHighlights, HighlightCoordinator.SENTENCE_FALLBACK_SELECTOR);\n }\n highlightTTSWordElementFallbacks(ranges) {\n if (typeof Element === \"undefined\")\n return;\n this.highlightElementFallbacks(ranges, \"data-pie-tts-word-element\", this.ttsWordElementHighlights, HighlightCoordinator.WORD_FALLBACK_SELECTOR);\n }\n highlightElementFallbacks(ranges, attributeName, trackedElements, selector) {\n for (const range of ranges) {\n const root = range.commonAncestorContainer.nodeType === Node.ELEMENT_NODE\n ? range.commonAncestorContainer\n : range.commonAncestorContainer.parentElement;\n if (!root)\n continue;\n const candidates = [];\n const rangeStartElement = range.startContainer.nodeType === Node.ELEMENT_NODE\n ? range.startContainer\n : range.startContainer.parentElement;\n const rangeEndElement = range.endContainer.nodeType === Node.ELEMENT_NODE\n ? range.endContainer\n : range.endContainer.parentElement;\n for (const element of [rangeStartElement, rangeEndElement]) {\n let current = element;\n while (current) {\n if (current.matches?.(selector))\n candidates.push(current);\n current = current.parentElement;\n }\n }\n if (root.matches?.(selector)) {\n candidates.push(root);\n }\n candidates.push(...Array.from(root.querySelectorAll(selector)));\n for (const element of new Set(candidates)) {\n try {\n if (!range.intersectsNode(element) &&\n !element.contains(rangeStartElement) &&\n !element.contains(rangeEndElement)) {\n continue;\n }\n }\n catch {\n continue;\n }\n element.setAttribute(attributeName, \"true\");\n trackedElements.add(element);\n }\n }\n }\n /**\n * Clear TTS word highlight\n */\n clearTTSWord() {\n if (!this.ttsWordHighlight)\n return;\n this.ttsWordHighlight.clear();\n for (const element of this.ttsWordElementHighlights) {\n element.removeAttribute(\"data-pie-tts-word-element\");\n }\n this.ttsWordElementHighlights.clear();\n }\n /**\n * Clear TTS sentence highlight\n */\n clearTTSSentence() {\n if (!this.ttsSentenceHighlight)\n return;\n this.ttsSentenceHighlight.clear();\n for (const element of this.ttsSentenceElementHighlights) {\n element.removeAttribute(\"data-pie-tts-sentence-element\");\n }\n this.ttsSentenceElementHighlights.clear();\n }\n /**\n * Clear all TTS highlights\n */\n clearTTS() {\n this.clearTTSWord();\n this.clearTTSSentence();\n }\n /**\n * Add an annotation highlight (persistent)\n *\n * @param range Text range to annotate\n * @param color Highlight color\n * @returns Annotation ID for later removal\n */\n addAnnotation(range, color = HighlightColor.YELLOW) {\n const id = `annotation-${this.nextAnnotationId++}`;\n // Clone the range to store\n const clonedRange = range.cloneRange();\n // Store annotation data\n const annotation = {\n id,\n range: clonedRange,\n type: HighlightType.ANNOTATION,\n color,\n timestamp: Date.now(),\n };\n this.annotations.set(id, annotation);\n // Add the SAME range object to the shared color highlight\n // This ensures we can later delete it by reference\n const colorHighlight = this.colorHighlights.get(color);\n if (colorHighlight) {\n colorHighlight.add(clonedRange);\n }\n return id;\n }\n /**\n * Remove an annotation\n *\n * @param id Annotation ID\n */\n removeAnnotation(id) {\n const annotation = this.annotations.get(id);\n if (!annotation) {\n console.warn(`[HighlightCoordinator] Annotation ${id} not found`);\n return;\n }\n console.log(`[HighlightCoordinator] Removing annotation ${id} (color: ${annotation.color})`);\n // Remove range from the shared color highlight\n const colorHighlight = this.colorHighlights.get(annotation.color);\n if (colorHighlight) {\n const deleted = colorHighlight.delete(annotation.range);\n console.log(`[HighlightCoordinator] Highlight.delete() returned:`, deleted);\n }\n // Clean up\n this.annotations.delete(id);\n console.log(`[HighlightCoordinator] Annotation ${id} removed from map. Remaining:`, this.annotations.size);\n }\n /**\n * Remove all annotations\n */\n clearAnnotations() {\n // Clear all color highlights\n for (const colorHighlight of this.colorHighlights.values()) {\n colorHighlight.clear();\n }\n // Clear annotation data\n this.annotations.clear();\n }\n /**\n * Get all annotations\n */\n getAnnotations() {\n return Array.from(this.annotations.values());\n }\n /**\n * Get annotation by ID\n */\n getAnnotation(id) {\n return this.annotations.get(id) ?? null;\n }\n /**\n * Change annotation color\n *\n * @param id Annotation ID\n * @param newColor New color\n */\n changeAnnotationColor(id, newColor) {\n const annotation = this.annotations.get(id);\n if (!annotation)\n return;\n const oldColor = annotation.color;\n if (oldColor === newColor)\n return;\n // Remove from old color highlight\n const oldColorHighlight = this.colorHighlights.get(oldColor);\n if (oldColorHighlight) {\n oldColorHighlight.delete(annotation.range);\n }\n // Update color\n annotation.color = newColor;\n // Add to new color highlight\n const newColorHighlight = this.colorHighlights.get(newColor);\n if (newColorHighlight) {\n newColorHighlight.add(annotation.range);\n }\n }\n /**\n * Export annotations as serializable data for persistence.\n * Uses RangeSerializer for robust DOM range serialization.\n *\n * @param root Root element for serialization (typically document.body or content container)\n * @returns Array of serialized annotations\n */\n exportAnnotations(root = document.body) {\n return this.getAnnotations().map((annotation) => ({\n ...this.rangeSerializer.serialize(annotation.range, root),\n id: annotation.id,\n color: annotation.color,\n timestamp: annotation.timestamp,\n }));\n }\n /**\n * Import annotations from serialized data.\n * Restores annotations after page navigation or refresh.\n *\n * @param data Array of serialized annotations\n * @param root Root element for deserialization (same as used in export)\n * @returns Number of successfully restored annotations\n */\n importAnnotations(data, root = document.body) {\n let restored = 0;\n for (const item of data) {\n const range = this.rangeSerializer.deserialize(item, root);\n if (range) {\n this.addAnnotation(range, item.color);\n restored++;\n }\n }\n return restored;\n }\n // ============================================================================\n // HighlightCoordinatorApi interface implementation\n // ============================================================================\n /**\n * Highlight a text range (interface method)\n *\n * Generic method that adapts to the specific highlight type.\n * For more control, use the specific methods like highlightTTSWord().\n */\n highlightRange(range, type, color = HighlightColor.YELLOW) {\n if (!this.supported)\n return;\n switch (type) {\n case HighlightType.TTS_WORD:\n case HighlightType.TTS_SENTENCE: {\n // For TTS, add to appropriate highlight\n const highlight = type === HighlightType.TTS_WORD\n ? this.ttsWordHighlight\n : this.ttsSentenceHighlight;\n if (highlight) {\n highlight.clear();\n highlight.add(range);\n if (type === HighlightType.TTS_WORD) {\n for (const element of this.ttsWordElementHighlights) {\n element.removeAttribute(\"data-pie-tts-word-element\");\n }\n this.ttsWordElementHighlights.clear();\n this.highlightTTSWordElementFallbacks([range]);\n }\n }\n break;\n }\n case HighlightType.ANNOTATION:\n // For annotations, use the existing method\n this.addAnnotation(range, color);\n break;\n }\n }\n /**\n * Clear highlights of a specific type (interface method)\n */\n clearHighlights(type) {\n if (!this.supported)\n return;\n switch (type) {\n case HighlightType.TTS_WORD:\n this.clearTTSWord();\n break;\n case HighlightType.TTS_SENTENCE:\n this.clearTTSSentence();\n break;\n case HighlightType.ANNOTATION:\n this.clearAnnotations();\n break;\n }\n }\n /**\n * Clear all highlights (interface method)\n */\n clearAll() {\n if (!this.supported)\n return;\n this.clearTTS();\n this.clearAnnotations();\n }\n /**\n * Check if CSS Highlight API is supported (interface method)\n */\n isSupported() {\n return this.supported;\n }\n /**\n * Update TTS highlight style dynamically\n *\n * @param color CSS color value (e.g., '#ffeb3b')\n * @param opacity Opacity value (0.0 to 1.0)\n */\n updateTTSHighlightStyle(color, opacity) {\n if (!this.supported)\n return;\n if (typeof document === \"undefined\")\n return;\n const styleEl = document.getElementById(\"pie-highlight-styles\");\n if (!styleEl)\n return;\n // Convert hex to rgba\n const hexToRgb = (hex) => {\n const result = /^#?([a-f\\d]{2})([a-f\\d]{2})([a-f\\d]{2})$/i.exec(hex);\n return result\n ? {\n r: parseInt(result[1], 16),\n g: parseInt(result[2], 16),\n b: parseInt(result[3], 16),\n }\n : null;\n };\n const rgb = hexToRgb(color);\n if (!rgb)\n return;\n this.explicitTTSColorOverride = {\n color: `rgb(${rgb.r}, ${rgb.g}, ${rgb.b})`,\n opacity: Math.max(0.2, Math.min(0.95, opacity)),\n };\n this.applyAdaptiveTTSStyle();\n }\n /**\n * Cleanup - remove all highlights\n */\n destroy() {\n if (!this.supported)\n return;\n this.clearTTS();\n this.clearAnnotations();\n // Remove style element\n if (typeof document !== \"undefined\") {\n const styleEl = document.getElementById(\"pie-highlight-styles\");\n if (styleEl) {\n styleEl.remove();\n }\n }\n this.themeObserver?.disconnect();\n this.themeObserver = null;\n }\n}\n","/**\n * Minimal logger helper (replacement for PIEOneer’s internal debug logger).\n * We intentionally keep this lightweight and browser-safe.\n */\nexport function createLogger(namespace) {\n return (...args) => {\n // eslint-disable-next-line no-console\n console.debug(`[${namespace}]`, ...args);\n };\n}\n","/**\n * I18nService\n *\n * The toolkit's view of the shared i18n provider: a delegating wrapper over\n * `SimpleI18n` from `players-shared` that adds toolkit-scoped logging and wires\n * the lazy catalog loaders.\n *\n * It was once a near-verbatim second copy of that class — same fields, same\n * lookup, same plural selection. Duplicate implementations of one contract drift\n * silently, because nothing fails when only one of them is fixed. Keep this a\n * wrapper.\n *\n * Part of PIE Assessment Toolkit.\n */\nimport { createPieI18n } from \"@pie-players/pie-players-shared/i18n\";\nimport { createLogger } from \"../utils/logger.js\";\nconst log = createLogger(\"I18nService\");\n/**\n * Toolkit-scoped i18n service.\n *\n * Serves every locale this repository ships, English resident and the rest\n * lazily loaded.\n */\nexport class I18nService {\n i18n;\n constructor(config = {}) {\n this.i18n = createPieI18n(config);\n log(\"I18nService created\", {\n locale: this.i18n.getLocale(),\n fallbackLocale: config.fallbackLocale ?? \"en-US\",\n });\n }\n /**\n * Set the locale, loading its catalog first.\n *\n * Never falls back to the browser locale: a rendered-string change reaches a\n * host's live delivery on their next install with no build signal on their\n * side, so the locale has to be something the host asked for.\n */\n async initialize(config) {\n log(`Initializing with locale: ${config.locale ?? this.i18n.getLocale()}`);\n await this.i18n.initialize(config);\n }\n t(key, values) {\n return this.i18n.t(key, values);\n }\n plural(key, options) {\n return this.i18n.plural(key, options);\n }\n getLocale() {\n return this.i18n.getLocale();\n }\n async setLocale(locale) {\n log(`Setting locale to: ${locale}`);\n await this.i18n.setLocale(locale);\n }\n getDirection() {\n return this.i18n.getDirection();\n }\n getAvailableLocales() {\n return this.i18n.getAvailableLocales();\n }\n isLocaleLoaded(locale) {\n return this.i18n.isLocaleLoaded(locale);\n }\n subscribe(listener) {\n return this.i18n.subscribe(listener);\n }\n hasKey(key) {\n return this.i18n.hasKey(key);\n }\n addCustomMessages(locale, messages) {\n this.i18n.addCustomMessages(locale, messages);\n }\n withLocale(locale) {\n return this.i18n.withLocale(locale);\n }\n formatNumber(value, options) {\n return this.i18n.formatNumber?.(value, options) ?? String(value);\n }\n formatDate(date, options) {\n return this.i18n.formatDate?.(date, options) ?? date.toISOString();\n }\n}\n","/**\n * Placement defaults this package can hold.\n *\n * Only the empty one. `PACKAGED_TOOL_PLACEMENT` and\n * `SECTION_PLAYER_PREFERRED_TOOL_PLACEMENT` name capabilities, so they moved to\n * the composition layer (`@pie-players/pie-default-tool-loaders`).\n */\nexport const DEFAULT_TOOL_PLACEMENT = {\n assessment: [],\n section: [],\n item: [],\n passage: [],\n rubric: [],\n element: [],\n};\n","import { DEFAULT_TOOL_PLACEMENT } from \"./tool-config-defaults.js\";\nconst DEFAULT_PLACEMENT = {\n section: [...DEFAULT_TOOL_PLACEMENT.section],\n item: [...DEFAULT_TOOL_PLACEMENT.item],\n passage: [...DEFAULT_TOOL_PLACEMENT.passage],\n};\nfunction isPlainObject(value) {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\nfunction assertStringArray(value, fieldPath) {\n if (value == null)\n return [];\n if (!Array.isArray(value)) {\n throw new Error(`Invalid tools config at \"${fieldPath}\": expected an array of tool ids.`);\n }\n const invalidEntry = value.find((entry) => typeof entry !== \"string\");\n if (invalidEntry !== undefined) {\n throw new Error(`Invalid tools config at \"${fieldPath}\": all entries must be strings.`);\n }\n return value;\n}\nfunction assertPlacementConfig(value) {\n if (value == null)\n return undefined;\n if (!isPlainObject(value)) {\n throw new Error('Invalid tools config at \"placement\": expected an object with section/item/passage arrays.');\n }\n return value;\n}\nfunction assertPolicyConfig(value) {\n if (value == null)\n return undefined;\n if (!isPlainObject(value)) {\n throw new Error('Invalid tools config at \"policy\": expected an object with allowed/blocked arrays.');\n }\n return value;\n}\nfunction assertProviderConfig(providerId, value) {\n if (value == null)\n return undefined;\n if (!isPlainObject(value)) {\n throw new Error(`Invalid tools config at \"providers.${providerId}\": expected an object.`);\n }\n const config = value;\n const isTTSRuntimeProviderId = (provider) => provider === \"polly\" || provider === \"google\" || provider === \"custom\";\n if (\"enabled\" in config &&\n config.enabled !== undefined &&\n typeof config.enabled !== \"boolean\") {\n throw new Error(`Invalid tools config at \"providers.${providerId}.enabled\": expected a boolean.`);\n }\n if (\"settings\" in config &&\n config.settings !== undefined &&\n !isPlainObject(config.settings)) {\n throw new Error(`Invalid tools config at \"providers.${providerId}.settings\": expected an object.`);\n }\n if (\"provider\" in config &&\n config.provider !== undefined &&\n !isPlainObject(config.provider) &&\n !(providerId === \"textToSpeech\" && isTTSRuntimeProviderId(config.provider))) {\n throw new Error(`Invalid tools config at \"providers.${providerId}.provider\": expected an object.`);\n }\n return config;\n}\nfunction assertProvidersConfig(value) {\n if (value == null)\n return {};\n if (!isPlainObject(value)) {\n throw new Error('Invalid tools config at \"providers\": expected an object keyed by tool id.');\n }\n const normalized = {};\n for (const [providerId, providerConfig] of Object.entries(value)) {\n normalized[providerId] = assertProviderConfig(providerId, providerConfig);\n }\n return normalized;\n}\nexport function normalizeToolAlias(toolId) {\n const trimmed = toolId.trim();\n if (!trimmed)\n return \"\";\n return trimmed;\n}\nexport function normalizeToolList(toolIds) {\n if (!toolIds || toolIds.length === 0)\n return [];\n const deduped = new Set();\n for (const rawToolId of toolIds) {\n if (typeof rawToolId !== \"string\") {\n throw new Error(\"Invalid tools config: tool list entries must be strings.\");\n }\n const normalized = normalizeToolAlias(rawToolId);\n if (!normalized)\n continue;\n deduped.add(normalized);\n }\n return Array.from(deduped);\n}\nexport function parseToolList(input) {\n if (!input)\n return [];\n return normalizeToolList(input\n .split(\",\")\n .map((entry) => entry.trim())\n .filter(Boolean));\n}\nfunction assertPnpEnforcement(value, fieldPath) {\n if (value == null)\n return undefined;\n if (value === \"on\" || value === \"off\")\n return value;\n throw new Error(`Invalid tools config at \"${fieldPath}\": expected \"on\" or \"off\", got ${JSON.stringify(value)}.`);\n}\nexport function normalizeToolsConfig(input) {\n if (input != null && !isPlainObject(input)) {\n throw new Error('Invalid tools config: expected an object with \"policy\", \"placement\", and \"providers\".');\n }\n const policy = assertPolicyConfig(input?.policy);\n const placement = assertPlacementConfig(input?.placement);\n const providers = assertProvidersConfig(input?.providers);\n const pnpEnforcement = assertPnpEnforcement(input?.pnpEnforcement, \"pnpEnforcement\");\n const config = {\n policy: {\n allowed: normalizeToolList(assertStringArray(policy?.allowed, \"policy.allowed\")),\n blocked: normalizeToolList(assertStringArray(policy?.blocked, \"policy.blocked\")),\n },\n placement: {\n section: normalizeToolList(assertStringArray(placement?.section, \"placement.section\")).length\n ? normalizeToolList(assertStringArray(placement?.section, \"placement.section\"))\n : [...DEFAULT_PLACEMENT.section],\n item: normalizeToolList(assertStringArray(placement?.item, \"placement.item\")).length\n ? normalizeToolList(assertStringArray(placement?.item, \"placement.item\"))\n : [...DEFAULT_PLACEMENT.item],\n passage: normalizeToolList(assertStringArray(placement?.passage, \"placement.passage\")).length\n ? normalizeToolList(assertStringArray(placement?.passage, \"placement.passage\"))\n : [...DEFAULT_PLACEMENT.passage],\n },\n providers,\n };\n if (pnpEnforcement) {\n config.pnpEnforcement = pnpEnforcement;\n }\n return config;\n}\n","/**\n * Tool Registry\n *\n * Central registry for all assessment tools. Manages tool metadata, visibility logic,\n * and button/instance creation. Supports dynamic registration and override by integrators.\n */\nimport { dynamicMessageKey } from \"@pie-players/pie-players-shared/i18n/provider\";\nimport { normalizeToolAlias } from \"./tools-config-normalizer.js\";\n/**\n * A registration's display name in the interface locale.\n *\n * Precedence: the resolved `nameKey`, then `name`. A key that does not resolve\n * falls back to `name` rather than rendering the key, so a catalog gap degrades\n * to English instead of to `tools.something.name` on a toolbar button.\n *\n * Both display resolvers live here so the toolbars, the settings panels and the\n * PNP debugger cannot each invent their own precedence.\n */\nexport function resolveToolRegistrationName(registration, i18n) {\n return resolveKeyedString(registration.name, registration.nameKey, i18n);\n}\n/** A registration's description in the interface locale. See the name resolver. */\nexport function resolveToolRegistrationDescription(registration, i18n) {\n return resolveKeyedString(registration.description, registration.descriptionKey, i18n);\n}\nfunction resolveKeyedString(source, key, i18n) {\n if (!key || !i18n)\n return source;\n // A registration may be host-authored against a host catalog, so the key is\n // not drawn from PIE's `MessageKey` union and has to be asserted.\n const messageKey = dynamicMessageKey(key);\n if (i18n.hasKey)\n return i18n.hasKey(messageKey) ? i18n.t(messageKey) : source;\n // A provider without `hasKey` still signals a miss by returning the key.\n const resolved = i18n.t(messageKey);\n return resolved === key ? source : resolved;\n}\nconst VALID_TOOL_LEVELS = [\n \"assessment\",\n \"section\",\n \"item\",\n \"passage\",\n \"rubric\",\n \"element\",\n];\nfunction assertNonEmptyString(value, fieldName) {\n if (typeof value !== \"string\" || value.trim().length === 0) {\n throw new Error(`Invalid tool registration: \"${fieldName}\" must be a non-empty string.`);\n }\n}\n// Defence-in-depth: reject obvious XSS payloads in tool-registered icon\n// markup at registration time. Runtime rendering still runs each icon\n// through DOMPurify (see `ToolIcon.svelte`), but surfacing the problem\n// early produces a clearer error for tool authors than \"the icon silently\n// disappeared after sanitization\".\nconst SCRIPTABLE_ICON_PATTERNS = [\n { pattern: /<script\\b/i, reason: \"contains a <script> tag\" },\n {\n pattern: /\\son[a-z]+\\s*=/i,\n reason: \"contains an inline event handler (on*=) attribute\",\n },\n { pattern: /javascript:/i, reason: \"contains a javascript: URL\" },\n {\n pattern: /<foreignObject\\b/i,\n reason: \"contains a <foreignObject> element\",\n },\n];\nfunction assertIconStringIsSafe(toolId, icon, fieldName) {\n const trimmed = icon.trimStart();\n const looksLikeSvg = trimmed.toLowerCase().startsWith(\"<svg\");\n const looksLikeUrl = /^https?:/i.test(trimmed);\n const looksLikeDataUrl = /^data:/i.test(trimmed);\n if (looksLikeDataUrl) {\n throw new Error(`Invalid tool registration \"${toolId}\": \"${fieldName}\" may not be a data: URL.`);\n }\n if (!looksLikeSvg && !looksLikeUrl)\n return;\n for (const { pattern, reason } of SCRIPTABLE_ICON_PATTERNS) {\n if (pattern.test(icon)) {\n throw new Error(`Invalid tool registration \"${toolId}\": \"${fieldName}\" ${reason}. Inline SVG icons must not include scriptable content.`);\n }\n }\n}\nfunction assertToolRegistrationShape(registration) {\n assertNonEmptyString(registration.toolId, \"toolId\");\n assertNonEmptyString(registration.name, \"name\");\n assertNonEmptyString(registration.description, \"description\");\n // A region capability renders into a host surface and has no toolbar button,\n // so it needs neither an icon nor `renderToolbar`. Both stay required for the\n // activations that do render a button, so no existing registration is relaxed.\n const isRegion = registration.activation === \"region\";\n if (!isRegion || registration.icon !== undefined) {\n if (typeof registration.icon !== \"string\" &&\n typeof registration.icon !== \"function\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"icon\" must be a string or function.`);\n }\n }\n if (typeof registration.icon === \"string\") {\n assertIconStringIsSafe(registration.toolId, registration.icon, \"icon\");\n }\n if (!Array.isArray(registration.supportedLevels) ||\n registration.supportedLevels.length === 0) {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"supportedLevels\" must be a non-empty array.`);\n }\n const invalidLevel = registration.supportedLevels.find((level) => !VALID_TOOL_LEVELS.includes(level));\n if (invalidLevel) {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": unsupported level \"${invalidLevel}\".`);\n }\n if (registration.activation !== undefined &&\n registration.activation !== \"toolbar-toggle\" &&\n registration.activation !== \"selection-gateway\" &&\n registration.activation !== \"region\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": unsupported activation \"${String(registration.activation)}\".`);\n }\n if (registration.surfaces !== undefined &&\n (!Array.isArray(registration.surfaces) ||\n registration.surfaces.some((surface) => typeof surface !== \"string\" || surface.trim().length === 0))) {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"surfaces\" must be an array of non-empty strings.`);\n }\n if (isRegion && !registration.surfaces?.length) {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": region tools must declare at least one host surface in \"surfaces\".`);\n }\n if (isRegion && typeof registration.renderSurface !== \"function\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": region tools must implement \"renderSurface\".`);\n }\n if (registration.resolvesWithoutGrant !== undefined &&\n typeof registration.resolvesWithoutGrant !== \"boolean\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"resolvesWithoutGrant\" must be a boolean.`);\n }\n if (registration.resolvesWithoutGrant &&\n !registration.requiresAuthoredContent) {\n // The flag only decides whether content is consulted without a grant, so on a\n // capability with no content dependency it reads as \"granted to everyone\" and\n // does nothing at all.\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"resolvesWithoutGrant\" requires \"requiresAuthoredContent\".`);\n }\n if (registration.renderSurface !== undefined &&\n typeof registration.renderSurface !== \"function\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"renderSurface\" must be a function.`);\n }\n if (registration.renderSurface && !registration.surfaces?.length) {\n // A surface renderer nothing can find is a registration that silently does\n // not render, which is the failure mode this mechanism exists to remove.\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"renderSurface\" requires at least one entry in \"surfaces\".`);\n }\n if (registration.singletonScope !== undefined &&\n registration.singletonScope !== \"section\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": unsupported singletonScope \"${String(registration.singletonScope)}\".`);\n }\n if (registration.activation === \"selection-gateway\" &&\n registration.singletonScope !== \"section\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": selection-gateway tools must declare singletonScope \"section\".`);\n }\n if (registration.pnpSupportIds !== undefined &&\n (!Array.isArray(registration.pnpSupportIds) ||\n registration.pnpSupportIds.some((pnpId) => typeof pnpId !== \"string\" || pnpId.trim().length === 0))) {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"pnpSupportIds\" must be an array of non-empty strings.`);\n }\n if (registration.activation !== \"region\" &&\n typeof registration.isVisibleInContext !== \"function\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"isVisibleInContext\" must be a function.`);\n }\n if (registration.isVisibleInContext !== undefined &&\n typeof registration.isVisibleInContext !== \"function\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"isVisibleInContext\" must be a function when present.`);\n }\n if (registration.requiresAuthoredContent !== undefined) {\n if (typeof registration.requiresAuthoredContent !== \"object\" ||\n registration.requiresAuthoredContent === null ||\n typeof registration.requiresAuthoredContent.resolve !== \"function\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"requiresAuthoredContent\" must be an object with a \"resolve\" function.`);\n }\n if (!registration.pnpSupportIds?.length) {\n // A content dependency's second job is keeping the capability out of a\n // wholesale grant, and a host filters that by support id. Declaring one\n // with no id to filter on would silently drop that guarantee.\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"requiresAuthoredContent\" requires at least one entry in \"pnpSupportIds\", which is what a host filters a default grant list on.`);\n }\n }\n if (registration.renderToolbar !== undefined) {\n if (typeof registration.renderToolbar !== \"function\") {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"renderToolbar\" must be a function.`);\n }\n }\n else if (!isRegion) {\n throw new Error(`Invalid tool registration \"${registration.toolId}\": \"renderToolbar\" must be a function.`);\n }\n}\n/**\n * Tool Registry\n *\n * Manages tool registrations and provides query/lookup functionality\n */\nexport class ToolRegistry {\n tools = new Map();\n pnpIndex = new Map(); // pnpSupportId → Set<toolId>\n componentOverrides = {};\n moduleLoaders = new Map();\n loadedToolModules = new Set();\n moduleLoadPromises = new Map();\n changeListeners = new Set();\n emitChange(event) {\n for (const listener of this.changeListeners) {\n try {\n listener(event);\n }\n catch (error) {\n console.warn(\"[ToolRegistry] change listener failed:\", error);\n }\n }\n }\n /**\n * Observe successful registry mutations. Delivery is synchronous, listener\n * failures are isolated, and the returned unsubscribe is idempotent.\n */\n onRegistryChange(listener) {\n this.changeListeners.add(listener);\n let subscribed = true;\n return () => {\n if (!subscribed)\n return;\n subscribed = false;\n this.changeListeners.delete(listener);\n };\n }\n /**\n * Normalize a single tool alias to canonical toolId.\n */\n normalizeToolId(toolId) {\n return normalizeToolAlias(toolId);\n }\n /**\n * Normalize a list of tool aliases to canonical toolIds.\n */\n normalizeToolIds(toolIds) {\n return toolIds.map((toolId) => this.normalizeToolId(toolId));\n }\n /**\n * Register a tool\n *\n * @param registration - Tool registration\n * @throws Error if toolId is already registered\n */\n register(registration) {\n assertToolRegistrationShape(registration);\n if (this.tools.has(registration.toolId)) {\n throw new Error(`Tool '${registration.toolId}' is already registered`);\n }\n this.tools.set(registration.toolId, registration);\n // Index PNP support IDs\n if (registration.pnpSupportIds) {\n for (const pnpId of registration.pnpSupportIds) {\n if (!this.pnpIndex.has(pnpId)) {\n this.pnpIndex.set(pnpId, new Set());\n }\n this.pnpIndex.get(pnpId).add(registration.toolId);\n }\n }\n this.emitChange({ kind: \"register\", toolIds: [registration.toolId] });\n }\n /**\n * Override an existing tool registration\n *\n * @param registration - New tool registration (must have existing toolId)\n */\n override(registration) {\n assertToolRegistrationShape(registration);\n if (!this.tools.has(registration.toolId)) {\n throw new Error(`Cannot override non-existent tool '${registration.toolId}'`);\n }\n // Remove old PNP index entries\n const oldReg = this.tools.get(registration.toolId);\n if (oldReg.pnpSupportIds) {\n for (const pnpId of oldReg.pnpSupportIds) {\n this.pnpIndex.get(pnpId)?.delete(registration.toolId);\n }\n }\n // Add new registration\n this.tools.set(registration.toolId, registration);\n // Re-index PNP support IDs\n if (registration.pnpSupportIds) {\n for (const pnpId of registration.pnpSupportIds) {\n if (!this.pnpIndex.has(pnpId)) {\n this.pnpIndex.set(pnpId, new Set());\n }\n this.pnpIndex.get(pnpId).add(registration.toolId);\n }\n }\n this.emitChange({ kind: \"override\", toolIds: [registration.toolId] });\n }\n /**\n * Unregister a tool\n *\n * @param toolId - Tool ID to remove\n */\n unregister(toolId) {\n const reg = this.tools.get(toolId);\n if (!reg)\n return;\n // Remove PNP index entries\n if (reg.pnpSupportIds) {\n for (const pnpId of reg.pnpSupportIds) {\n this.pnpIndex.get(pnpId)?.delete(toolId);\n }\n }\n this.tools.delete(toolId);\n this.emitChange({ kind: \"unregister\", toolIds: [toolId] });\n }\n /**\n * Get a tool registration by ID\n *\n * @param toolId - Tool ID\n * @returns Tool registration or undefined\n */\n get(toolId) {\n return this.tools.get(toolId);\n }\n /**\n * Check if a tool is registered\n *\n * @param toolId - Tool ID\n * @returns true if registered\n */\n has(toolId) {\n return this.tools.has(toolId);\n }\n /**\n * Get all registered tool IDs\n *\n * @returns Array of tool IDs\n */\n getAllToolIds() {\n return Array.from(this.tools.keys());\n }\n /**\n * Get all tool registrations\n *\n * @returns Array of tool registrations\n */\n getAllTools() {\n return Array.from(this.tools.values());\n }\n /**\n * Find tool IDs that support a given PNP support ID\n *\n * @param pnpSupportId - PNP support ID (e.g., 'calculator')\n * @returns Set of tool IDs that support this PNP ID\n */\n getToolsByPNPSupport(pnpSupportId) {\n return this.pnpIndex.get(pnpSupportId) || new Set();\n }\n /**\n * Get tools that support a specific level\n *\n * @param level - Tool level (assessment, section, item, passage, element)\n * @returns Array of tool registrations that support this level\n */\n getToolsByLevel(level) {\n return this.getAllTools().filter((tool) => tool.supportedLevels.includes(level));\n }\n /**\n * Resolve tool activation, defaulting to toolbar-toggle.\n */\n getToolActivation(toolId) {\n return this.get(toolId)?.activation || \"toolbar-toggle\";\n }\n /**\n * Resolve singleton scope for a tool when present.\n */\n getToolSingletonScope(toolId) {\n return this.get(toolId)?.singletonScope || null;\n }\n /**\n * Registrations that can fill a named host surface.\n *\n * The discovery call a renderer makes instead of naming a capability. Order\n * follows registration order, so a host mounting several capabilities into one\n * surface gets a stable sequence without core deciding a precedence it has no\n * basis for.\n */\n getToolsBySurface(surface) {\n if (!surface)\n return [];\n return this.getAllTools().filter((tool) => typeof tool.renderSurface === \"function\" &&\n tool.surfaces?.includes(surface));\n }\n /**\n * Support ids belonging to capabilities that need authored content.\n *\n * What a host filters a default grant list on, in place of the compile-time\n * exclusion array this replaced: granting one of these wholesale grants an\n * accommodation to learners with no documented need for it.\n */\n getContentDependentSupportIds() {\n const ids = new Set();\n for (const tool of this.getAllTools()) {\n if (!tool.requiresAuthoredContent)\n continue;\n for (const supportId of tool.pnpSupportIds || [])\n ids.add(supportId);\n }\n return [...ids].sort();\n }\n /**\n * Filter tool IDs by activation type.\n */\n filterToolIdsByActivation(toolIds, activation) {\n return toolIds.filter((toolId) => this.getToolActivation(toolId) === activation);\n }\n /**\n * Filter tools by visibility in a given context\n *\n * Pass 2 of the two-pass model: Given a list of allowed tool IDs (from Pass 1),\n * ask each tool if it's relevant in this context.\n *\n * @param allowedToolIds - Tool IDs that passed Pass 1 (orchestrator approval)\n * @param context - Context to evaluate\n * @returns Array of visible tool registrations\n */\n filterVisibleInContext(allowedToolIds, context) {\n const visible = [];\n for (const toolId of allowedToolIds) {\n const tool = this.get(toolId);\n if (!tool) {\n console.warn(`Tool '${toolId}' is allowed but not registered`);\n continue;\n }\n // Check if tool supports this level\n if (!tool.supportedLevels.includes(context.level)) {\n continue;\n }\n // Pass 2: Ask tool if it's relevant. A region capability declares no\n // answer and has no toolbar presence, so it is never visible here.\n try {\n if (tool.isVisibleInContext?.(context)) {\n visible.push(tool);\n }\n }\n catch (error) {\n console.error(`Error evaluating visibility for tool '${toolId}':`, error);\n }\n }\n return visible;\n }\n /**\n * Get tool metadata for building UIs\n * Useful for building PNP configuration interfaces\n *\n * @returns Array of tool metadata (id, name, description, pnpSupportIds)\n */\n getToolMetadata() {\n return this.getAllTools().map((tool) => ({\n toolId: tool.toolId,\n name: tool.name,\n description: tool.description,\n pnpSupportIds: tool.pnpSupportIds || [],\n supportedLevels: tool.supportedLevels,\n activation: tool.activation || \"toolbar-toggle\",\n singletonScope: tool.singletonScope || null,\n surfaces: tool.surfaces || [],\n requiresAuthoredContent: Boolean(tool.requiresAuthoredContent),\n contentDependencyDescription: tool.requiresAuthoredContent?.description ?? null,\n }));\n }\n /**\n * Generate PNP support IDs from enabled tools\n * Useful for creating PNP profiles\n *\n * @param enabledToolIds - Tool IDs to enable\n * @returns Array of unique PNP support IDs\n */\n generatePNPSupportsFromTools(enabledToolIds) {\n const pnpSupports = new Set();\n for (const toolId of enabledToolIds) {\n const tool = this.get(toolId);\n if (tool?.pnpSupportIds) {\n for (const pnpId of tool.pnpSupportIds) {\n pnpSupports.add(pnpId);\n }\n }\n }\n return Array.from(pnpSupports);\n }\n /**\n * Clear all registrations (useful for testing)\n */\n clear() {\n const toolIds = this.getAllToolIds();\n if (toolIds.length === 0)\n return;\n this.tools.clear();\n this.pnpIndex.clear();\n this.emitChange({ kind: \"clear\", toolIds });\n }\n /**\n * Configure global component overrides used by tool instance creation.\n */\n setComponentOverrides(overrides) {\n if (this.componentOverrides === overrides)\n return;\n this.componentOverrides = overrides;\n this.emitChange({ kind: \"component-overrides\", toolIds: [] });\n }\n /**\n * Register lazy module loaders by toolId.\n * Toolbars call ensureToolModuleLoaded(toolId) before instance creation.\n */\n setToolModuleLoaders(loaders) {\n const entries = Object.entries(loaders).filter((entry) => entry[1] !== undefined);\n for (const [toolId, loader] of entries) {\n assertNonEmptyString(toolId, \"tool module loader id\");\n if (typeof loader !== \"function\") {\n throw new Error(`Invalid tool module loader for \"${toolId}\": expected a function.`);\n }\n }\n const changedToolIds = [];\n for (const [toolId, loader] of entries) {\n if (this.moduleLoaders.get(toolId) === loader)\n continue;\n this.moduleLoaders.set(toolId, loader);\n changedToolIds.push(toolId);\n }\n if (changedToolIds.length > 0) {\n this.emitChange({ kind: \"module-loaders\", toolIds: changedToolIds });\n }\n }\n /**\n * Ensure tool module side-effects are loaded exactly once.\n * Safe to call repeatedly; concurrent callers share the same promise.\n */\n async ensureToolModuleLoaded(toolId) {\n if (this.loadedToolModules.has(toolId))\n return;\n const existingPromise = this.moduleLoadPromises.get(toolId);\n if (existingPromise) {\n await existingPromise;\n return;\n }\n const loader = this.moduleLoaders.get(toolId);\n if (!loader)\n return;\n const loadPromise = (async () => {\n await loader();\n this.loadedToolModules.add(toolId);\n })();\n this.moduleLoadPromises.set(toolId, loadPromise);\n try {\n await loadPromise;\n }\n finally {\n this.moduleLoadPromises.delete(toolId);\n }\n }\n /**\n * Ensure a set of tool modules are loaded.\n */\n async ensureToolModulesLoaded(toolIds) {\n await Promise.all(toolIds.map((toolId) => this.ensureToolModuleLoaded(toolId)));\n }\n /**\n * Whether a tool module has already been loaded.\n */\n isToolModuleLoaded(toolId) {\n return this.loadedToolModules.has(toolId);\n }\n /**\n * Render a tool for toolbar use with component overrides attached.\n */\n renderForToolbar(toolId, context, toolbarContext) {\n const tool = this.get(toolId);\n if (!tool) {\n throw new Error(`Tool '${toolId}' is not registered`);\n }\n if (typeof tool.renderToolbar !== \"function\") {\n // Naming the activation rather than \"renderToolbar is not a function\":\n // the caller's mistake is asking a surface capability for a toolbar\n // button, and it is fixed by placement config, not by the registration.\n throw new Error(`Tool '${toolId}' has activation \"${tool.activation || \"toolbar-toggle\"}\" and renders into a host surface, not a toolbar. Remove it from toolbar placement.`);\n }\n const mergedContext = {\n ...toolbarContext,\n componentOverrides: {\n ...(this.componentOverrides || {}),\n ...(toolbarContext.componentOverrides || {}),\n },\n };\n return tool.renderToolbar(context, mergedContext);\n }\n /**\n * Render a capability into a host surface, with component overrides attached.\n *\n * The surface counterpart of {@link renderForToolbar}, and it exists for the\n * same reason: the registry owns the component-override map, so a host calling\n * `registration.renderSurface(...)` directly would resolve element tags against\n * nothing and fail on every packaged capability. Overrides passed in the\n * context still win, matching the toolbar path's precedence.\n */\n renderForSurface(toolId, context) {\n const tool = this.get(toolId);\n if (!tool) {\n throw new Error(`Tool '${toolId}' is not registered`);\n }\n if (typeof tool.renderSurface !== \"function\") {\n throw new Error(`Tool '${toolId}' does not render into a host surface. Surface capabilities declare \"surfaces\" and implement \"renderSurface\".`);\n }\n return tool.renderSurface({\n ...context,\n componentOverrides: {\n ...(this.componentOverrides || {}),\n ...(context.componentOverrides || {}),\n },\n });\n }\n}\n","/**\n * Tool open requests.\n *\n * A surface that acts on the learner's current selection has to hand that selection\n * to a tool it does not mount. The annotation strip is the case PIE ships: it is a\n * section-scoped singleton in its own shadow root, and the tool it opens is mounted\n * by a toolbar under a scoped instance id the strip cannot construct.\n *\n * Resolution is a claim, not a broadcast. Each toolbar registers as the target for its\n * placement level, and a request reaches exactly one: the first target that currently\n * hosts the tool, preferring section scope. A broadcast would open a panel in every\n * toolbar whose scope contains the selection, which in a section player is the item\n * card's toolbar and the section's both.\n *\n * `params` reaches the tool through the same seam a host-registered context resolver\n * feeds, so receiving a request costs a tool nothing: whatever already reads\n * `getToolRenderParams` sees it.\n *\n * Core names no capability. The requester supplies the tool id, which is why the\n * pairing of a selection action to a dictionary lives in the composition layer.\n */\n/** Level a request resolves against when the requester names none. */\nexport const DEFAULT_TOOL_REQUEST_LEVEL = \"section\";\n/**\n * Registry of the toolbars a request can reach.\n *\n * Insertion order is the tie-break within a level, so a target registered while an\n * earlier one is still mounted does not displace it.\n */\nexport class ToolRequestRegistry {\n targets = new Set();\n changeListeners = new Set();\n registerTarget(target) {\n this.targets.add(target);\n this.notifyChange();\n return () => {\n if (!this.targets.delete(target))\n return;\n this.notifyChange();\n };\n }\n /**\n * Whether a request for this tool would reach a toolbar.\n *\n * A surface asks before offering the affordance: a button that silently does\n * nothing is worse than an absent one, and availability moves with policy —\n * hence {@link onTargetsChange}.\n */\n canRequest(toolId, level) {\n return this.findTarget(toolId, level) !== null;\n }\n /** Returns whether a target claimed the request. */\n request(request) {\n const target = this.findTarget(request.toolId, request.level);\n if (!target)\n return false;\n try {\n target.open(request.toolId, request.params);\n }\n catch (error) {\n console.error(`[ToolRequestRegistry] Target failed to open \"${request.toolId}\":`, error);\n return false;\n }\n return true;\n }\n /**\n * Fires when a toolbar registers or unregisters.\n *\n * Not when a registered toolbar's own visible set changes: `hostsTool` is read\n * live, so a caller re-asking `canRequest` gets the current answer. A surface\n * that needs to notice a policy change should also follow the policy signal it\n * already has.\n */\n onTargetsChange(listener) {\n this.changeListeners.add(listener);\n return () => {\n this.changeListeners.delete(listener);\n };\n }\n /**\n * An explicit level is a constraint; the default is a preference.\n *\n * Falling back off `\"section\"` is what lets a host place a tool at item scope only\n * and still have a section-scoped gateway reach it. Requesting a level explicitly\n * does not fall back, because a requester that named one meant it.\n */\n findTarget(toolId, level) {\n const preferred = this.findTargetAtLevel(toolId, level ?? DEFAULT_TOOL_REQUEST_LEVEL);\n if (preferred || level !== undefined)\n return preferred;\n for (const target of this.targets) {\n if (target.level === DEFAULT_TOOL_REQUEST_LEVEL)\n continue;\n if (this.hostsTool(target, toolId))\n return target;\n }\n return null;\n }\n findTargetAtLevel(toolId, level) {\n for (const target of this.targets) {\n if (target.level !== level)\n continue;\n if (this.hostsTool(target, toolId))\n return target;\n }\n return null;\n }\n hostsTool(target, toolId) {\n try {\n return target.hostsTool(toolId) === true;\n }\n catch (error) {\n console.warn(`[ToolRequestRegistry] Target at level \"${target.level}\" failed the host check for \"${toolId}\":`, error);\n return false;\n }\n }\n notifyChange() {\n for (const listener of this.changeListeners) {\n try {\n listener();\n }\n catch (error) {\n console.warn(\"[ToolRequestRegistry] Target change listener threw:\", error);\n }\n }\n }\n}\n","export function toFrameworkErrorModel(args) {\n return {\n kind: args.kind,\n severity: args.severity ?? \"error\",\n source: args.source,\n message: args.message,\n details: [...(args.details || [])],\n recoverable: args.recoverable === true,\n cause: args.cause,\n };\n}\nexport function frameworkErrorFromUnknown(args) {\n const message = args.error instanceof Error && args.error.message.trim().length > 0\n ? args.error.message\n : String(args.error || \"Unknown framework error\");\n return toFrameworkErrorModel({\n kind: args.kind,\n source: args.source,\n message,\n recoverable: args.recoverable,\n cause: args.error,\n });\n}\nconst COORDINATOR_PHASE_TO_KIND = {\n \"coordinator-ready\": \"coordinator-init\",\n \"state-load\": \"tool-state-load\",\n \"state-save\": \"tool-state-save\",\n \"provider-register\": \"provider-register\",\n \"provider-init\": \"provider-init\",\n \"tts-init\": \"tts-init\",\n \"section-controller-init\": \"section-controller-init\",\n \"section-controller-dispose\": \"section-controller-dispose\",\n};\n/**\n * Build a {@link FrameworkErrorModel} from a coordinator-side error +\n * context pair.\n *\n * Maps `context.phase` to the canonical {@link FrameworkErrorKind} and\n * synthesizes a `source` from `context.providerId` when present\n * (`pie-toolkit-coordinator/<providerId>`); falls back to a phase-tagged\n * source (`pie-toolkit-coordinator:<phase>`) otherwise. Forwards the\n * original `error` as `cause` so hosts that care about the underlying\n * `Error` keep getting it.\n *\n * Recoverable defaults to `false` (most coordinator-phase failures are\n * not auto-recovered today). Override with `recoverable: true` for the\n * phases where the coordinator continues operating after the failure.\n */\nexport function frameworkErrorFromCoordinatorContext(args) {\n const kind = COORDINATOR_PHASE_TO_KIND[args.context.phase];\n const source = args.context.providerId\n ? `pie-toolkit-coordinator/${args.context.providerId}`\n : `pie-toolkit-coordinator:${args.context.phase}`;\n return frameworkErrorFromUnknown({\n kind,\n source,\n error: args.error,\n recoverable: args.recoverable,\n });\n}\nexport function frameworkErrorFromToolConfigDiagnostics(args) {\n const details = args.diagnostics.map((diagnostic) => `${diagnostic.path}: ${diagnostic.message}`);\n const message = details.length > 0\n ? \"Invalid tools config.\"\n : \"Invalid tools config (no diagnostics details were provided).\";\n return toFrameworkErrorModel({\n kind: \"tool-config\",\n source: args.source,\n message,\n details,\n recoverable: args.recoverable,\n });\n}\nexport function formatFrameworkErrorForConsole(error) {\n const prefix = `[pie-framework:${error.kind}:${error.source}]`;\n if (error.details.length === 0)\n return `${prefix} ${error.message}`;\n return `${prefix} ${error.message}\\n- ${error.details.join(\"\\n- \")}`;\n}\n","import { normalizeToolsConfig, } from \"./tools-config-normalizer.js\";\nimport { frameworkErrorFromToolConfigDiagnostics, frameworkErrorFromUnknown, } from \"./framework-error.js\";\nexport function frameworkErrorFromToolConfigValidation(args) {\n if (Array.isArray(args.diagnostics) && args.diagnostics.length > 0) {\n return frameworkErrorFromToolConfigDiagnostics({\n source: args.source,\n diagnostics: args.diagnostics,\n recoverable: args.recoverable,\n });\n }\n return frameworkErrorFromUnknown({\n kind: \"tool-config\",\n source: args.source,\n error: args.error ?? new Error(\"Invalid tools config\"),\n recoverable: args.recoverable,\n });\n}\nconst DEFAULT_STRICTNESS = \"error\";\nexport function normalizeToolConfigStrictness(value) {\n if (value === \"off\" || value === \"warn\" || value === \"error\") {\n return value;\n }\n return DEFAULT_STRICTNESS;\n}\nfunction createDiagnostic(diagnostic) {\n return diagnostic;\n}\nfunction getRegistryToolMap(toolRegistry) {\n if (!toolRegistry)\n return new Map();\n return new Map(toolRegistry\n .getAllTools()\n .slice()\n .sort((left, right) => left.toolId.localeCompare(right.toolId))\n .map((tool) => [tool.toolId, tool]));\n}\nfunction sanitizeProviderConfig(providerId, providerConfig, tool, diagnostics) {\n if (!providerConfig || !tool?.provider?.sanitizeConfig)\n return providerConfig;\n try {\n const sanitized = tool.provider.sanitizeConfig(providerConfig);\n if (!sanitized ||\n typeof sanitized !== \"object\" ||\n Array.isArray(sanitized)) {\n diagnostics.push(createDiagnostic({\n code: \"tools.providerSanitizeFailed\",\n severity: \"error\",\n path: `providers.${providerId}`,\n message: `Provider sanitizer for \"${providerId}\" must return an object.`,\n providerId,\n toolId: providerId,\n }));\n return providerConfig;\n }\n return sanitized;\n }\n catch (error) {\n diagnostics.push(createDiagnostic({\n code: \"tools.providerSanitizeFailed\",\n severity: \"error\",\n path: `providers.${providerId}`,\n message: `Provider sanitizer failed for \"${providerId}\": ${error instanceof Error ? error.message : String(error)}`,\n providerId,\n toolId: providerId,\n }));\n return providerConfig;\n }\n}\nfunction validateProviderConfig(providerId, providerConfig, tool, diagnostics) {\n if (!providerConfig || !tool?.provider?.validateConfig)\n return;\n try {\n const providerDiagnostics = tool.provider.validateConfig(providerConfig);\n if (!Array.isArray(providerDiagnostics)) {\n diagnostics.push(createDiagnostic({\n code: \"tools.invalidProviderValidation\",\n severity: \"error\",\n path: `providers.${providerId}`,\n message: `Provider validator for \"${providerId}\" must return an array.`,\n providerId,\n toolId: providerId,\n }));\n return;\n }\n for (const diagnostic of providerDiagnostics) {\n diagnostics.push({\n ...diagnostic,\n path: diagnostic.path || `providers.${providerId}`,\n providerId: diagnostic.providerId || providerId,\n toolId: diagnostic.toolId || providerId,\n });\n }\n }\n catch (error) {\n diagnostics.push(createDiagnostic({\n code: \"tools.providerValidateFailed\",\n severity: \"error\",\n path: `providers.${providerId}`,\n message: `Provider validator failed for \"${providerId}\": ${error instanceof Error ? error.message : String(error)}`,\n providerId,\n toolId: providerId,\n }));\n }\n}\nfunction collectPlacementDiagnostics(config, toolMap, diagnostics) {\n if (toolMap.size === 0)\n return;\n const levelOrder = [\"section\", \"item\", \"passage\"];\n for (const level of levelOrder) {\n for (const toolId of config.placement[level]) {\n const tool = toolMap.get(toolId);\n if (!tool) {\n diagnostics.push(createDiagnostic({\n code: \"tools.unknownToolId\",\n severity: \"error\",\n path: `placement.${level}`,\n message: `Unknown tool id \"${toolId}\" in placement.${level}.`,\n toolId,\n }));\n continue;\n }\n if (tool.activation === \"region\") {\n // A region capability has no toolbar button, so placing it names a\n // surface that will never render it. Reported at the placement rather\n // than at render time, where the symptom is an absent accommodation and\n // no error.\n diagnostics.push(createDiagnostic({\n code: \"tools.unplaceableActivation\",\n severity: \"error\",\n path: `placement.${level}`,\n message: `Tool \"${toolId}\" renders into a host surface (activation \"region\") and cannot be placed on the ${level} toolbar. Remove it from placement.${level}; its availability comes from policy plus its content dependency.`,\n toolId,\n }));\n continue;\n }\n const supportsLevel = tool.supportedLevels.includes(level);\n // Leniency policy: section-capable tools are tolerated in item placement.\n // This avoids strict failures for common host config patterns while still\n // enforcing upward-invalid placements (for example item-only -> section).\n const allowSectionToolInItemPlacement = level === \"item\" && tool.supportedLevels.includes(\"section\");\n if (!supportsLevel && !allowSectionToolInItemPlacement) {\n diagnostics.push(createDiagnostic({\n code: \"tools.unsupportedLevel\",\n severity: \"error\",\n path: `placement.${level}`,\n message: `Tool \"${toolId}\" does not support level \"${level}\".`,\n toolId,\n }));\n }\n }\n }\n}\nfunction collectPolicyDiagnostics(config, toolMap, diagnostics) {\n if (toolMap.size === 0)\n return;\n for (const toolId of config.policy.allowed || []) {\n if (toolMap.has(toolId))\n continue;\n diagnostics.push(createDiagnostic({\n code: \"tools.unknownToolId\",\n severity: \"error\",\n path: \"policy.allowed\",\n message: `Unknown tool id \"${toolId}\" in policy.allowed.`,\n toolId,\n }));\n }\n for (const toolId of config.policy.blocked || []) {\n if (toolMap.has(toolId))\n continue;\n diagnostics.push(createDiagnostic({\n code: \"tools.unknownToolId\",\n severity: \"error\",\n path: \"policy.blocked\",\n message: `Unknown tool id \"${toolId}\" in policy.blocked.`,\n toolId,\n }));\n }\n}\nfunction collectProviderKeyDiagnostics(config, toolMap, hasRemovedTtsKey, diagnostics) {\n if (hasRemovedTtsKey) {\n diagnostics.push(createDiagnostic({\n code: \"tools.removedProviderKey\",\n severity: \"error\",\n path: \"providers.tts\",\n message: `Provider key \"tts\" is no longer supported. Use \"providers.textToSpeech\".`,\n providerId: \"tts\",\n toolId: \"textToSpeech\",\n }));\n }\n for (const providerId of Object.keys(config.providers).sort()) {\n if (toolMap.size === 0 || toolMap.has(providerId))\n continue;\n diagnostics.push(createDiagnostic({\n code: \"tools.unknownProviderKey\",\n severity: \"error\",\n path: `providers.${providerId}`,\n message: `Unknown provider key \"${providerId}\".`,\n providerId,\n toolId: providerId,\n }));\n }\n}\nfunction emitWarnings(diagnostics, source) {\n if (diagnostics.length === 0)\n return;\n for (const diagnostic of diagnostics) {\n const prefix = `[tool-config-validation:${source}]`;\n console.warn(`${prefix} ${diagnostic.path} - ${diagnostic.message}`);\n }\n}\nfunction throwValidationError(diagnostics, source) {\n const formatted = diagnostics\n .map((diagnostic) => `- ${diagnostic.path}: ${diagnostic.message}`)\n .join(\"\\n\");\n throw new Error(`[tool-config-validation:${source}] Invalid tools config:\\n${formatted}`);\n}\nexport function normalizeAndValidateToolsConfig(input, options = {}) {\n const strictness = normalizeToolConfigStrictness(options.strictness);\n const source = options.source ?? \"tools\";\n const registryTools = getRegistryToolMap(options.toolRegistry);\n const normalized = normalizeToolsConfig(input);\n const diagnostics = [];\n // Tool-id and provider checks need a registry to check against, and every\n // collector below returns early without one. Say so: this package no longer\n // falls back to a packaged registry, so a caller that used to get id\n // validation for free now gets none, and a silent downgrade from \"your ids are\n // valid\" to \"nobody looked\" is the kind of change that surfaces as a typo\n // reaching a learner.\n const hasConfiguredTools = Object.values(normalized.placement).some((ids) => ids.length > 0) ||\n Object.keys(normalized.providers).length > 0 ||\n (normalized.policy.allowed?.length ?? 0) > 0 ||\n (normalized.policy.blocked?.length ?? 0) > 0;\n if (registryTools.size === 0 && hasConfiguredTools) {\n diagnostics.push(createDiagnostic({\n code: \"tools.registryUnavailable\",\n severity: \"warning\",\n path: \"tools\",\n message: 'No tool registry was supplied, so tool ids, placement levels and provider config were not validated. Pass `toolRegistry` — for the packaged capability set, `createPackagedToolRegistry()` from \"@pie-players/pie-default-tool-loaders\".',\n }));\n }\n const hasRemovedTtsKey = Object.hasOwn(normalized.providers, \"tts\");\n const nextProviders = {\n ...(normalized.providers || {}),\n };\n for (const providerId of Object.keys(nextProviders).sort()) {\n if (providerId === \"tts\") {\n delete nextProviders.tts;\n continue;\n }\n const tool = registryTools.get(providerId);\n nextProviders[providerId] = sanitizeProviderConfig(providerId, nextProviders[providerId], tool, diagnostics);\n validateProviderConfig(providerId, nextProviders[providerId], tool, diagnostics);\n }\n const nextConfig = {\n ...normalized,\n providers: nextProviders,\n };\n collectPlacementDiagnostics(nextConfig, registryTools, diagnostics);\n collectPolicyDiagnostics(nextConfig, registryTools, diagnostics);\n collectProviderKeyDiagnostics(nextConfig, registryTools, hasRemovedTtsKey, diagnostics);\n if (hasRemovedTtsKey) {\n throwValidationError(diagnostics.filter((entry) => entry.code === \"tools.removedProviderKey\"), source);\n }\n if (strictness === \"warn\") {\n emitWarnings(diagnostics, source);\n }\n // Severity decides what `strictness: \"error\"` rejects. Every diagnostic this\n // function raised was `\"error\"` until `tools.registryUnavailable`, which\n // reports that validation could not run rather than that the config is wrong —\n // throwing on it would turn \"no registry supplied\" from a host's existing,\n // working setup into a construction failure.\n const blocking = diagnostics.filter((entry) => entry.severity === \"error\");\n if (strictness === \"error\" && blocking.length > 0) {\n throwValidationError(blocking, source);\n }\n if (strictness === \"error\" && blocking.length === 0) {\n emitWarnings(diagnostics, source);\n }\n return {\n config: nextConfig,\n diagnostics,\n };\n}\n","/**\n * QTI 3.0 / IMS Access for All (AfA) 3.0 Standard Access Features\n *\n * This file contains standardized accessibility feature identifiers from:\n * - IMS Global Access for All (AfA) 3.0 specification\n * - QTI 3.0 Personal Needs and Preferences (PNP)\n * - Schema.org accessibility features vocabulary\n * - WCAG 2.x accessibility guidelines\n *\n * These are the officially recognized values for QTI 3.0's accessibilityInfo.accessFeature\n * and can be used as a reference for PNP profile configuration and tool mapping.\n *\n * References:\n * - IMS AfA 3.0: https://www.imsglobal.org/spec/afa/v3p0\n * - QTI 3.0: https://www.imsglobal.org/spec/qti/v3p0\n * - Schema.org: https://schema.org/accessibilityFeature\n */\n/**\n * Standard QTI 3.0 accessibility features organized by category\n */\nexport const QTI_STANDARD_ACCESS_FEATURES = {\n /**\n * Visual accessibility features\n * For students with low vision, color blindness, or visual processing needs\n */\n visual: {\n // Magnification and zoom\n magnification: \"magnification\",\n screenMagnifier: \"screenMagnifier\",\n zoomable: \"zoomable\",\n // Color and contrast\n highContrastDisplay: \"highContrastDisplay\",\n highContrastAudio: \"highContrastAudio\",\n colorContrast: \"colorContrast\",\n invertColors: \"invertColors\",\n // Display customization\n displayTransformability: \"displayTransformability\",\n largePrint: \"largePrint\",\n fontEnlargement: \"fontEnlargement\",\n resizeText: \"resizeText\",\n // Visual alternatives\n alternativeText: \"alternativeText\",\n longDescription: \"longDescription\",\n describedMath: \"describedMath\",\n tactileGraphic: \"tactileGraphic\",\n tactileObject: \"tactileObject\",\n },\n /**\n * Auditory accessibility features\n * For students who are deaf, hard of hearing, or benefit from audio\n */\n auditory: {\n // Audio output\n audioDescription: \"audioDescription\",\n textToSpeech: \"textToSpeech\",\n readAloud: \"readAloud\",\n humanVoice: \"humanVoice\",\n syntheticVoice: \"syntheticVoice\",\n // Speech control\n speechRate: \"speechRate\",\n speechVolume: \"speechVolume\",\n voicePitch: \"voicePitch\",\n // Visual alternatives for audio\n captions: \"captions\",\n closedCaptions: \"closedCaptions\",\n openCaptions: \"openCaptions\",\n transcript: \"transcript\",\n signLanguage: \"signLanguage\",\n subtitles: \"subtitles\",\n // Audio adjustments\n audioControl: \"audioControl\",\n noBackgroundAudio: \"noBackgroundAudio\",\n },\n /**\n * Motor/physical accessibility features\n * For students with limited mobility or motor control\n */\n motor: {\n // Input alternatives\n keyboardControl: \"keyboardControl\",\n mouseControl: \"mouseControl\",\n touchControl: \"touchControl\",\n voiceControl: \"voiceControl\",\n switchControl: \"switchControl\",\n eyeGazeControl: \"eyeGazeControl\",\n // Keyboard features\n singleSwitchAccess: \"singleSwitchAccess\",\n stickyKeys: \"stickyKeys\",\n keyboardShortcuts: \"keyboardShortcuts\",\n // Timing\n timingControl: \"timingControl\",\n unlimitedTime: \"unlimitedTime\",\n extendedTime: \"extendedTime\",\n pauseControl: \"pauseControl\",\n },\n /**\n * Cognitive/learning accessibility features\n * For students with learning disabilities, ADHD, autism, etc.\n */\n cognitive: {\n // Content simplification\n simplifiedLanguage: \"simplifiedLanguage\",\n reducedComplexity: \"reducedComplexity\",\n structuralNavigation: \"structuralNavigation\",\n tableOfContents: \"tableOfContents\",\n // Focus and attention\n reducedDistraction: \"reducedDistraction\",\n noFlashing: \"noFlashing\",\n pauseAnimation: \"pauseAnimation\",\n // Organization and support\n annotations: \"annotations\",\n bookmarking: \"bookmarking\",\n highlighting: \"highlighting\",\n guidedNavigation: \"guidedNavigation\",\n // Tools\n calculator: \"calculator\",\n thesaurus: \"thesaurus\",\n spellingAssistance: \"spellingAssistance\",\n grammarAssistance: \"grammarAssistance\",\n },\n /**\n * Reading support features\n * For students with dyslexia or reading challenges\n */\n reading: {\n // Text presentation\n lineSpacing: \"lineSpacing\",\n wordSpacing: \"wordSpacing\",\n letterSpacing: \"letterSpacing\",\n fontFamily: \"fontFamily\",\n readingMask: \"readingMask\",\n readingGuide: \"readingGuide\",\n readingRuler: \"readingRuler\",\n // Highlighting and emphasis\n wordHighlighting: \"wordHighlighting\",\n lineHighlighting: \"lineHighlighting\",\n focusIndicator: \"focusIndicator\",\n // Content support\n printableResource: \"printableResource\",\n braille: \"braille\",\n nemeth: \"nemeth\",\n refreshableBraille: \"refreshableBraille\",\n },\n /**\n * Navigation features\n * For efficient content navigation\n */\n navigation: {\n // Structure\n index: \"index\",\n pageNavigation: \"pageNavigation\",\n skipContent: \"skipContent\",\n breadcrumbs: \"breadcrumbs\",\n // Search\n searchable: \"searchable\",\n fullTextSearch: \"fullTextSearch\",\n },\n /**\n * Linguistic features\n * For language support\n */\n linguistic: {\n // Languages\n multilingualText: \"multilingualText\",\n translatedText: \"translatedText\",\n glossary: \"glossary\",\n // Sign language\n signLanguageInterpretation: \"signLanguageInterpretation\",\n visualLanguage: \"visualLanguage\",\n },\n /**\n * Assessment-specific features\n * Features specific to test-taking environments\n */\n assessment: {\n // Tools\n protractor: \"protractor\",\n ruler: \"ruler\",\n graph: \"graph\",\n graphingCalculator: \"graphingCalculator\",\n periodicTable: \"periodicTable\",\n formulaSheet: \"formulaSheet\",\n // Answer support\n answerMasking: \"answerMasking\",\n answerEliminator: \"answerEliminator\",\n strikethrough: \"strikethrough\",\n // Item features\n itemGlossary: \"itemGlossary\",\n tutorialAvailable: \"tutorialAvailable\",\n },\n};\n/**\n * Flat list of all standard access features for validation\n */\nexport const ALL_STANDARD_ACCESS_FEATURES = Object.values(QTI_STANDARD_ACCESS_FEATURES).flatMap((category) => Object.values(category));\n/**\n * Example PNP configurations for common accessibility needs\n * These are NOT official profiles but illustrative examples showing\n * how standard features can be combined for different student needs.\n */\nexport const EXAMPLE_PNP_CONFIGURATIONS = {\n /**\n * Example: Student with low vision\n */\n lowVision: {\n label: \"Example: Low Vision Support\",\n features: [\n \"magnification\",\n \"screenMagnifier\",\n \"highContrastDisplay\",\n \"colorContrast\",\n \"fontEnlargement\",\n \"textToSpeech\",\n \"alternativeText\",\n \"describedMath\",\n ],\n },\n /**\n * Example: Student who is blind\n */\n blind: {\n label: \"Example: Blind Student Support\",\n features: [\n \"textToSpeech\",\n \"screenReader\",\n \"alternativeText\",\n \"longDescription\",\n \"describedMath\",\n \"braille\",\n \"refreshableBraille\",\n \"keyboardControl\",\n \"structuralNavigation\",\n ],\n },\n /**\n * Example: Student who is deaf or hard of hearing\n */\n deafHardOfHearing: {\n label: \"Example: Deaf/Hard of Hearing Support\",\n features: [\n \"captions\",\n \"closedCaptions\",\n \"signLanguage\",\n \"transcript\",\n \"visualLanguage\",\n \"noBackgroundAudio\",\n ],\n },\n /**\n * Example: Student with dyslexia\n */\n dyslexia: {\n label: \"Example: Dyslexia Support\",\n features: [\n \"textToSpeech\",\n \"readAloud\",\n \"highlighting\",\n \"wordHighlighting\",\n \"lineHighlighting\",\n \"readingMask\",\n \"readingGuide\",\n \"fontFamily\",\n \"lineSpacing\",\n \"wordSpacing\",\n \"simplifiedLanguage\",\n ],\n },\n /**\n * Example: Student with ADHD\n */\n adhd: {\n label: \"Example: ADHD Support\",\n features: [\n \"reducedDistraction\",\n \"noFlashing\",\n \"pauseAnimation\",\n \"timingControl\",\n \"extendedTime\",\n \"highlighting\",\n \"annotations\",\n \"guidedNavigation\",\n \"structuralNavigation\",\n ],\n },\n /**\n * Example: Student with motor limitations\n */\n motorLimitations: {\n label: \"Example: Motor Limitations Support\",\n features: [\n \"keyboardControl\",\n \"stickyKeys\",\n \"keyboardShortcuts\",\n \"voiceControl\",\n \"switchControl\",\n \"timingControl\",\n \"extendedTime\",\n \"unlimitedTime\",\n ],\n },\n /**\n * Example: English language learner\n */\n englishLearner: {\n label: \"Example: English Language Learner Support\",\n features: [\n \"textToSpeech\",\n \"translatedText\",\n \"glossary\",\n \"simplifiedLanguage\",\n \"readAloud\",\n \"highlighting\",\n ],\n },\n};\n/**\n * Helper to validate if a feature ID is a standard QTI 3.0 feature\n */\nexport function isStandardAccessFeature(featureId) {\n return ALL_STANDARD_ACCESS_FEATURES.includes(featureId);\n}\n/**\n * Helper to get category for a feature\n */\nexport function getFeatureCategory(featureId) {\n for (const [category, features] of Object.entries(QTI_STANDARD_ACCESS_FEATURES)) {\n if (Object.values(features).includes(featureId)) {\n return category;\n }\n }\n return null;\n}\n/**\n * Helper to get all features in a category\n */\nexport function getFeaturesInCategory(category) {\n return Object.values(QTI_STANDARD_ACCESS_FEATURES[category]);\n}\n","/**\n * Validation primitives shared by every catalog card whose payload references\n * media.\n *\n * Extracted from `sign-language-cards.ts` when `spoken` cards gained a recorded\n * audio form: both card types take authored, wire-facing URLs and hand them to a\n * media element in the learner's browser, so both need the same scheme\n * allow-list and the same \"treat as absent, never as partially valid\" posture.\n * Two copies of a URL allow-list is one copy that gets a fix and one that does\n * not.\n *\n * Part of PIE Assessment Toolkit.\n */\n/**\n * Media source URLs are handed to a media element in the learner's browser. Only\n * schemes such an element can actually fetch are allowed; anything else is\n * dropped so an authored `javascript:` / `file:` URL cannot ride into the DOM.\n * Relative and protocol-relative URLs are allowed — host content is commonly\n * served from the same origin as the player.\n */\nconst DISALLOWED_SRC_SCHEME = /^[a-z][a-z0-9+.-]*:/i;\nconst ALLOWED_SRC_SCHEMES = new Set([\"http:\", \"https:\", \"data:\", \"blob:\"]);\n/**\n * The only `MediaAssetRef.version` this build renders.\n *\n * `media-asset-contract.md` requires unknown-version rejection for runtime\n * rendering: bumping to `2` obliges every consumer to accept both for as long as\n * any producer emits `1`, so a card claiming a version this build does not\n * implement must not be rendered on a guess at which fields still mean what they\n * did.\n */\nexport const SUPPORTED_MEDIA_ASSET_VERSION = 1;\n/**\n * Whether a media reference claims a version this build cannot render.\n *\n * An absent `version` is accepted rather than rejected — the same posture the\n * rest of this module takes toward absent fields, and the one `media.kind` and\n * `matchesRequestedSignLanguage` already take: only a positive claim of\n * something else is refused. Producers predate the field, and treating its\n * absence as a rejection would drop cards that are otherwise wholly valid.\n */\nexport function isUnsupportedMediaAssetVersion(version) {\n return version !== undefined && version !== SUPPORTED_MEDIA_ASSET_VERSION;\n}\nexport function isSafeMediaSrc(raw) {\n if (typeof raw !== \"string\")\n return false;\n const src = raw.trim();\n if (!src)\n return false;\n // Relative (\"/video.mp4\", \"video.mp4\") and protocol-relative (\"//cdn/x.mp4\")\n // forms carry no scheme to check and inherit the document's.\n if (src.startsWith(\"//\") || !DISALLOWED_SRC_SCHEME.test(src))\n return true;\n const scheme = src.slice(0, src.indexOf(\":\") + 1).toLowerCase();\n return ALLOWED_SRC_SCHEMES.has(scheme);\n}\nexport function normalizeMediaSources(raw) {\n if (!Array.isArray(raw))\n return [];\n const sources = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\")\n continue;\n const candidate = entry;\n if (!isSafeMediaSrc(candidate.src))\n continue;\n const source = { src: candidate.src.trim() };\n if (typeof candidate.type === \"string\" && candidate.type.trim()) {\n source.type = candidate.type.trim();\n }\n if (Number.isFinite(candidate.width))\n source.width = candidate.width;\n if (Number.isFinite(candidate.height))\n source.height = candidate.height;\n // Deduplicated by `src`, because the signing region renders `<source>`\n // elements in an `{#each}` keyed on exactly that: an authored card listing\n // one URL twice — the same file under two MIME types is the plausible way —\n // would otherwise throw Svelte's duplicate-key error and take the whole\n // region down rather than degrade. The first entry wins, so authored order\n // still decides which encoding the browser is offered first.\n if (sources.some((existing) => existing.src === source.src))\n continue;\n sources.push(source);\n }\n return sources;\n}\nexport function normalizeMediaFragment(raw) {\n if (!raw || typeof raw !== \"object\")\n return undefined;\n const candidate = raw;\n const start = Number(candidate.startSeconds);\n if (!Number.isFinite(start) || start < 0)\n return undefined;\n const end = Number(candidate.endSeconds);\n // An end at or before the start would produce a zero/negative slice; treat\n // it as \"no end\" rather than a range that can never play.\n if (!Number.isFinite(end) || end <= start)\n return { startSeconds: start };\n return { startSeconds: start, endSeconds: end };\n}\nexport function trimmedOrUndefined(value) {\n if (typeof value !== \"string\")\n return undefined;\n const trimmed = value.trim();\n return trimmed || undefined;\n}\n/**\n * Apply a fragment range to a source URL as a Media Fragments URI, so one\n * recording can serve several content nodes.\n *\n * The URI is a hint only: browsers honour both bounds inconsistently, so the\n * caller enforces the range itself — seek forward to the start once metadata is\n * available, and stop at the end. `SignLanguageMediaRegion` and\n * `TTSService.playRecordedAudio` are the two shipped consumers that do so.\n */\n/**\n * How often the end bound is re-checked while a slice is playing. `timeupdate`\n * alone fires about four times a second, which is loose enough to leak a sliver\n * of the next node's recording.\n */\nconst END_CHECK_INTERVAL_MS = 100;\n/** `HTMLMediaElement.HAVE_METADATA`, which not every DOM implementation exposes. */\nconst HAVE_METADATA = 1;\n/**\n * Hold a media element to one fragment's range, and return the disposer.\n *\n * The `#t=` URI `applyMediaFragment` writes is a hint browsers honour at neither\n * bound reliably, so every consumer that means \"play only this slice\" enforces it\n * here instead of reimplementing the pair. Both shipped consumers do —\n * `SignLanguageMediaRegion` pausing at the end, `TTSService.playRecordedAudio`\n * ending the clip so the chunk sequence advances — which is why the end action is\n * the caller's and only the arithmetic is shared.\n *\n * The start seek is forward only: a browser that did honour the URI has already\n * positioned past the start, and seeking back would replay audio the learner has\n * heard. `onReachedEnd` may fire more than once and must tolerate it; polling\n * stops while the element is paused, so an element left sitting past its end bound\n * goes quiet rather than being told repeatedly.\n */\nexport function enforceMediaFragment(element, fragment, onReachedEnd) {\n if (!fragment)\n return () => { };\n const { startSeconds, endSeconds } = fragment;\n let seekToStart;\n if (startSeconds > 0) {\n seekToStart = () => {\n if (element.currentTime < startSeconds) {\n element.currentTime = startSeconds;\n }\n };\n // Seeking before metadata is available only sets the default start\n // position, so wait for it unless it already landed.\n if (element.readyState >= HAVE_METADATA)\n seekToStart();\n else\n element.addEventListener(\"loadedmetadata\", seekToStart);\n }\n let checkEnd;\n let endPoll;\n if (endSeconds !== undefined) {\n checkEnd = () => {\n if (element.currentTime >= endSeconds)\n onReachedEnd();\n };\n element.addEventListener(\"timeupdate\", checkEnd);\n endPoll = setInterval(() => {\n if (!element.paused)\n checkEnd?.();\n }, END_CHECK_INTERVAL_MS);\n }\n return () => {\n if (seekToStart)\n element.removeEventListener(\"loadedmetadata\", seekToStart);\n if (checkEnd)\n element.removeEventListener(\"timeupdate\", checkEnd);\n if (endPoll !== undefined)\n clearInterval(endPoll);\n };\n}\nexport function applyMediaFragment(src, fragment) {\n if (!fragment)\n return src;\n // Never stack a second fragment onto a URL that already carries one — the\n // authored value wins.\n if (src.includes(\"#\"))\n return src;\n const end = fragment.endSeconds !== undefined ? `,${fragment.endSeconds}` : \"\";\n return `${src}#t=${fragment.startSeconds}${end}`;\n}\n","/**\n * Recorded audio as a `spoken` catalog card.\n *\n * QTI 3 treats a recording and synthesized speech as the *same* support — both\n * are `spoken`, and a card carries recorded audio through `qti-file-href` plus a\n * MIME type — so this is not a new accommodation but the other form the existing\n * one can take. Some programs prefer a human voice to synthesis; PIE's `spoken`\n * card was string-only, so it had no way to say \"play this file for this node\".\n *\n * A node commonly carries both forms in the same language: the reading script\n * *and* a recording of it. That is APIP's pattern and what QTI's migration\n * guidance preserves, because the script is both the source the audio was\n * generated from and the fallback for when the audio will not play. Resolution\n * chooses between them with `CatalogLookupOptions.form`; playback treats the\n * script as the recording's fallback.\n *\n * Validation posture matches sign-language cards: \"treat as absent, never as\n * partially valid\". A malformed payload must not produce a silent player that\n * looks like read-aloud is working.\n *\n * Part of PIE Assessment Toolkit.\n */\nimport { isUnsupportedMediaAssetVersion, normalizeMediaFragment, normalizeMediaSources, trimmedOrUndefined, } from \"./catalog-media.js\";\n/** Catalog type token for spoken alternates. Matches QTI 3's `support` value. */\nexport const SPOKEN_CATALOG_TYPE = \"spoken\";\n/**\n * Validate a `spoken` card's payload into something playable, or `null`.\n *\n * Silent when the card simply is not a recording — a card carrying `content` is\n * a reading script, which is the overwhelmingly common case and not a fault.\n * Loud when a card looks like it meant to be a recording and cannot be played,\n * because that failure is otherwise invisible to everyone but the learner who\n * needed it.\n */\nexport function resolveSpokenAudioMedia(card) {\n if (!card)\n return null;\n const payload = card.payload;\n if (!payload || typeof payload !== \"object\") {\n // A script card, not a broken audio card. Resolution asks for the payload\n // form as a *preference*, so getting a `content` card back here is normal.\n return null;\n }\n const media = payload.media;\n if (!media || typeof media !== \"object\") {\n console.warn(\"[spoken-audio] card carries a `payload` with no `media`; recorded speech needs `media.sources`, so this card is ignored and read-aloud falls back to the script or generated speech\");\n return null;\n }\n if (isUnsupportedMediaAssetVersion(media.version)) {\n console.warn(`[spoken-audio] card's media declares version ${String(media.version)}, which this build does not render; the card is ignored and read-aloud falls back to the script or generated speech`);\n return null;\n }\n // A signing video filed under `spoken` is a mis-authored card, not an audio\n // track to guess at. Refusing it keeps the two card types from quietly\n // swapping roles.\n if (media.kind !== undefined && media.kind !== \"audio\") {\n console.warn(`[spoken-audio] card's media is kind \"${media.kind}\", not \"audio\"; a spoken card carries recorded speech, so this card is ignored`);\n return null;\n }\n const sources = normalizeMediaSources(media.sources);\n if (sources.length === 0) {\n console.warn(\"[spoken-audio] card's `media.sources` yielded no usable URL; read-aloud falls back to the script or generated speech\");\n return null;\n }\n return {\n sources,\n fragment: normalizeMediaFragment(payload.fragment),\n label: trimmedOrUndefined(media.label),\n };\n}\n","/**\n * ToolCoordinator\n *\n * Manages z-index layering and visibility for floating tools.\n * Prevents conflicts between calculator, ruler, protractor, etc.\n *\n * Features:\n * - Centralized z-index management with defined layers\n * - Tool visibility state tracking\n * - Bring-to-front on interaction\n * - Framework-agnostic (works with any DOM element)\n *\n * Part of PIE Assessment Toolkit.\n */\nimport { createLogger } from \"../utils/logger.js\";\nconst log = createLogger(\"ToolCoordinator\");\n/**\n * Z-index layers for assessment components\n */\nexport var ZIndexLayer;\n(function (ZIndexLayer) {\n ZIndexLayer[ZIndexLayer[\"BASE\"] = 0] = \"BASE\";\n ZIndexLayer[ZIndexLayer[\"TOOL\"] = 1000] = \"TOOL\";\n ZIndexLayer[ZIndexLayer[\"MODAL\"] = 2000] = \"MODAL\";\n ZIndexLayer[ZIndexLayer[\"CONTROL\"] = 3000] = \"CONTROL\";\n ZIndexLayer[ZIndexLayer[\"HIGHLIGHT\"] = 4000] = \"HIGHLIGHT\";\n})(ZIndexLayer || (ZIndexLayer = {}));\nexport class ToolCoordinator {\n config;\n tools = new Map();\n layerCounters = new Map();\n listeners = new Set();\n /**\n * Activation (on/off) state keyed by tool id, kept independent of the\n * element registration lifecycle. A tool's DOM element can be unregistered\n * and re-registered as the item re-renders (e.g. a model change re-mounts\n * the toolbar overlay); when that happens the on/off state must survive so\n * that only an explicit toggle — the toolbar button — turns a tool off.\n * Cleared on genuine teardown via {@link releaseTool}.\n */\n visibilityState = new Map();\n constructor(config = {}) {\n this.config = config;\n // Initialize layer counters\n this.layerCounters.set(ZIndexLayer.BASE, 0);\n this.layerCounters.set(ZIndexLayer.TOOL, 0);\n this.layerCounters.set(ZIndexLayer.MODAL, 0);\n this.layerCounters.set(ZIndexLayer.CONTROL, 0);\n this.layerCounters.set(ZIndexLayer.HIGHLIGHT, 0);\n }\n /**\n * Subscribe to tool state changes\n * Returns unsubscribe function\n */\n subscribe(listener) {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n /**\n * Notify all listeners of state change\n */\n notifyListeners() {\n this.listeners.forEach((listener) => listener());\n }\n /**\n * Register a tool with the coordinator\n *\n * @param id Unique tool identifier\n * @param name Display name\n * @param element DOM element for the tool (optional)\n * @param layer Z-index layer (defaults to MODAL)\n */\n registerTool(id, name, element, layer = ZIndexLayer.MODAL) {\n log(\"registerTool called:\", { id, name, hasElement: !!element, layer });\n if (this.tools.has(id)) {\n log(`Tool ${id} is already registered`);\n return;\n }\n // Restore prior on/off state. A re-registration (e.g. after an item\n // re-render unmounts and re-mounts the tool element) must preserve the\n // tool's activation state so only an explicit toggle can turn it off.\n const isVisible = this.visibilityState.get(id) ?? false;\n // If no element provided, create a placeholder registration\n if (!element) {\n this.tools.set(id, {\n id,\n name,\n element: null,\n layer,\n isVisible,\n baseZIndex: layer,\n });\n log(\"Tool registered without element:\", id);\n return;\n }\n // Calculate base z-index for this layer\n const baseZIndex = layer + this.getNextLayerOffset(layer);\n // Apply z-index\n element.style.zIndex = String(baseZIndex);\n // Reflect restored visibility onto the freshly registered element.\n element.style.display = isVisible ? \"\" : \"none\";\n // Create and store event handler to enable proper cleanup\n const mouseDownHandler = () => this.bringToFront(element);\n element.addEventListener(\"mousedown\", mouseDownHandler);\n // Register tool with handler reference\n this.tools.set(id, {\n id,\n name,\n element,\n layer,\n isVisible,\n baseZIndex,\n mouseDownHandler,\n });\n if (isVisible) {\n this.bringToFront(element);\n }\n log(\"Tool registered with element:\", id);\n }\n /**\n * Unregister a tool\n *\n * Detaches the element binding (listeners, registration) but intentionally\n * preserves the tool's activation state in {@link visibilityState}, so a\n * subsequent re-registration of the same id (e.g. after an item re-render)\n * restores whether the tool was on or off. Use {@link releaseTool} to also\n * discard the activation state on genuine teardown.\n *\n * @param id Tool identifier\n */\n unregisterTool(id) {\n const tool = this.tools.get(id);\n if (!tool)\n return;\n // Remove event listeners using stored handler reference\n if (tool.element && tool.mouseDownHandler) {\n tool.element.removeEventListener(\"mousedown\", tool.mouseDownHandler);\n }\n this.tools.delete(id);\n }\n /**\n * Fully release a tool: unregister its element binding AND discard its\n * preserved activation state. Call this on genuine teardown (e.g. leaving\n * the item/section that owns the tool) rather than {@link unregisterTool},\n * which keeps the on/off state alive across element re-registration.\n *\n * @param id Tool identifier\n */\n releaseTool(id) {\n this.unregisterTool(id);\n this.visibilityState.delete(id);\n }\n /**\n * Show a tool\n *\n * @param id Tool identifier\n */\n showTool(id) {\n const tool = this.tools.get(id);\n if (!tool) {\n log(`Tool ${id} not found`);\n return;\n }\n if (tool.element) {\n tool.element.style.display = \"\";\n this.bringToFront(tool.element);\n }\n tool.isVisible = true;\n this.visibilityState.set(id, true);\n this.notifyListeners();\n }\n /**\n * Hide a tool\n *\n * @param id Tool identifier\n */\n hideTool(id) {\n const tool = this.tools.get(id);\n if (!tool) {\n log(`Tool ${id} not found`);\n return;\n }\n if (tool.element) {\n tool.element.style.display = \"none\";\n }\n tool.isVisible = false;\n this.visibilityState.set(id, false);\n this.notifyListeners();\n }\n /**\n * Toggle tool visibility\n *\n * @param id Tool identifier\n */\n toggleTool(id) {\n log(\"toggleTool called for:\", id);\n const tool = this.tools.get(id);\n if (!tool) {\n log(`Tool ${id} not found. Registered tools:`, Array.from(this.tools.keys()));\n return;\n }\n log(\"Tool found, current visibility:\", tool.isVisible);\n if (tool.isVisible) {\n this.hideTool(id);\n }\n else {\n this.showTool(id);\n }\n }\n /**\n * Check if tool is visible\n *\n * @param id Tool identifier\n * @returns true if tool is visible\n */\n isToolVisible(id) {\n const tool = this.tools.get(id);\n if (tool)\n return tool.isVisible;\n // No live element registration (e.g. mid re-render, between unmount and\n // re-mount): fall back to the preserved activation state so the tool\n // doesn't read as \"off\" during the gap.\n return this.visibilityState.get(id) ?? false;\n }\n /**\n * Bring element to front of its layer\n *\n * @param element DOM element to bring forward\n */\n bringToFront(element) {\n // Find tool registration\n const tool = Array.from(this.tools.values()).find((t) => t.element === element);\n if (!tool)\n return;\n // Calculate new z-index (highest in layer + 1)\n const maxZIndexInLayer = this.getMaxZIndexInLayer(tool.layer);\n const newZIndex = Math.max(maxZIndexInLayer + 1, tool.layer + 1);\n // Update z-index\n element.style.zIndex = String(newZIndex);\n tool.baseZIndex = newZIndex;\n }\n /**\n * Get all registered tool IDs\n */\n getRegisteredTools() {\n return Array.from(this.tools.keys());\n }\n /**\n * Get tool element by ID\n */\n getToolElement(id) {\n return this.tools.get(id)?.element ?? null;\n }\n /**\n * Get next offset within a layer\n */\n getNextLayerOffset(layer) {\n const current = this.layerCounters.get(layer) ?? 0;\n this.layerCounters.set(layer, current + 1);\n return current;\n }\n /**\n * Get maximum z-index currently in use in a layer\n */\n getMaxZIndexInLayer(layer) {\n let max = layer;\n for (const tool of this.tools.values()) {\n if (tool.layer === layer) {\n max = Math.max(max, tool.baseZIndex);\n }\n }\n return max;\n }\n /**\n * Reset all tools to their base z-indices\n */\n resetZIndices() {\n for (const tool of this.tools.values()) {\n if (tool.element) {\n tool.element.style.zIndex = String(tool.baseZIndex);\n }\n }\n }\n /**\n * Update tool element reference\n *\n * @param id Tool identifier\n * @param element New DOM element\n */\n updateToolElement(id, element) {\n const tool = this.tools.get(id);\n if (!tool) {\n log(`Tool ${id} not found`);\n return;\n }\n // Remove old event listener using stored handler reference\n if (tool.element && tool.mouseDownHandler) {\n tool.element.removeEventListener(\"mousedown\", tool.mouseDownHandler);\n }\n // Create new handler and add listener\n const mouseDownHandler = () => this.bringToFront(element);\n element.addEventListener(\"mousedown\", mouseDownHandler);\n // Update element and handler reference\n tool.element = element;\n tool.mouseDownHandler = mouseDownHandler;\n // Apply z-index to new element\n element.style.zIndex = String(tool.baseZIndex);\n if (tool.isVisible) {\n element.style.display = \"\";\n }\n else {\n element.style.display = \"none\";\n }\n }\n /**\n * Hide all tools\n */\n hideAllTools() {\n for (const id of this.tools.keys()) {\n this.hideTool(id);\n }\n this.notifyListeners();\n }\n /**\n * Get tool state (interface method)\n *\n * @param id Tool identifier\n * @returns Tool state or undefined\n */\n getToolState(id) {\n const tool = this.tools.get(id);\n if (!tool)\n return undefined;\n return {\n id: tool.id,\n name: tool.name,\n isVisible: tool.isVisible,\n element: tool.element ?? null,\n layer: tool.layer,\n };\n }\n /**\n * Get all visible tools (interface method)\n *\n * @returns Array of visible tool states\n */\n getVisibleTools() {\n return Array.from(this.tools.values())\n .filter((tool) => tool.isVisible)\n .map((tool) => ({\n id: tool.id,\n name: tool.name,\n isVisible: tool.isVisible,\n element: tool.element ?? null,\n layer: tool.layer,\n }));\n }\n}\n","/**\n * Package-internal multi-subscriber framework-error bus.\n *\n * **Design contract.**\n *\n * - **Synchronous fan-out.** `reportFrameworkError(model)` calls every\n * subscribed listener in registration order before returning. There is\n * no buffering, no microtask deferral, no replay of past errors.\n * - **Listener isolation.** A listener that throws is caught and\n * `console.warn`-logged; the throw does not interrupt fan-out to the\n * remaining listeners.\n * - **Snapshot iteration.** The fan-out iterates over a snapshot of the\n * listener set so that a listener that subscribes / unsubscribes\n * during its own delivery does not mutate the in-flight iteration.\n * - **Idempotent unsubscribe.** Calling the returned disposer twice is\n * a no-op; the listener is removed on the first call.\n * - **No replay.** Late subscribers do not see errors emitted before\n * they subscribed. Hosts that need an \"error already happened\" signal\n * should subscribe at construction time. The toolkit CE does this\n * before constructing the coordinator so the `coordinator-init`\n * failure path emits through the same bus.\n *\n * **Why not a public class.** This bus is constructed inside the toolkit\n * CE (`PieAssessmentToolkit.svelte`) and passed into\n * `ToolkitCoordinator`. Hosts subscribe via\n * `ToolkitCoordinatorApi.subscribeFrameworkErrors`, never via the bus\n * class itself. Keeping the class package-internal lets us iterate on\n * its shape without a public-API change.\n */\nexport class FrameworkErrorBus {\n listeners = new Set();\n subscribeFrameworkErrors(listener) {\n this.listeners.add(listener);\n let attached = true;\n return () => {\n if (!attached)\n return;\n attached = false;\n this.listeners.delete(listener);\n };\n }\n reportFrameworkError(model) {\n const snapshot = Array.from(this.listeners);\n for (const listener of snapshot) {\n try {\n listener(model);\n }\n catch (error) {\n console.warn(\"[FrameworkErrorBus] listener failed:\", error);\n }\n }\n }\n /**\n * Detach all listeners. Used by the toolkit CE on disconnect.\n */\n dispose() {\n this.listeners.clear();\n }\n /**\n * Test-only inspection. Not part of the public contract.\n *\n * @internal\n */\n getListenerCount() {\n return this.listeners.size;\n }\n}\n","export const segmentSentences = (text, options) => {\n const useSentenceSegmenter = options?.useSentenceSegmenter !== false;\n try {\n if (!useSentenceSegmenter) {\n throw new Error(\"Segmenter disabled by policy\");\n }\n const Segmenter = globalThis.Intl?.Segmenter;\n if (typeof Segmenter === \"function\") {\n const segmenter = new Segmenter(options?.locale, {\n granularity: \"sentence\",\n });\n const parsed = Array.from(segmenter.segment(text))\n .map((segment) => ({\n text: segment.segment,\n offset: segment.index,\n }))\n .filter((segment) => segment.text.trim().length > 0);\n if (parsed.length > 0)\n return parsed;\n }\n }\n catch {\n // Fall through to regex segmentation.\n }\n const sentenceRegex = /[^.!?]+(?:[.!?]+|$)/g;\n const raw = text.match(sentenceRegex) || [text];\n const parsed = [];\n let processed = 0;\n for (const sentence of raw) {\n const offset = text.indexOf(sentence, processed);\n if (offset === -1)\n continue;\n parsed.push({ text: sentence, offset });\n processed = offset + sentence.length;\n }\n return parsed.length > 0 ? parsed : [{ text, offset: 0 }];\n};\n","/**\n * Browser TTS Provider\n *\n * Text-to-speech provider using the browser's Web Speech API.\n * Works in all modern browsers that support SpeechSynthesis.\n *\n * Part of PIE Assessment Toolkit.\n */\nimport { segmentSentences as segmentTextToSentences } from \"./text-segmentation.js\";\nconst NATIVE_START_TIMEOUT_MS = 5_000;\nconst VOICE_INVENTORY_TIMEOUT_MS = 2_000;\nconst normalizeLanguageCode = (value) => String(value || \"\")\n .trim()\n .toLowerCase();\nconst browserLanguage = () => {\n const navigatorLanguage = typeof navigator !== \"undefined\"\n ? navigator.language || navigator.languages?.[0]\n : \"\";\n return normalizeLanguageCode(navigatorLanguage || \"en-US\");\n};\nconst findBrowserVoice = (voices, preferredVoice) => {\n if (preferredVoice) {\n return (voices.find((voice) => voice.voiceURI === preferredVoice) ||\n voices.find((voice) => voice.name === preferredVoice) ||\n null);\n }\n const language = browserLanguage();\n const languagePrefix = language.split(\"-\")[0] || \"en\";\n const matchesLanguage = (voice) => {\n const voiceLanguage = normalizeLanguageCode(voice.lang);\n return (voiceLanguage === language ||\n voiceLanguage.startsWith(`${languagePrefix}-`));\n };\n const ranked = [\n (voice) => voice.localService && matchesLanguage(voice),\n (voice) => voice.default && matchesLanguage(voice),\n (voice) => matchesLanguage(voice),\n (voice) => voice.localService,\n (voice) => voice.default,\n ];\n for (const predicate of ranked) {\n const voice = voices.find(predicate);\n if (voice)\n return voice;\n }\n return voices[0] || null;\n};\nconst shouldAssignBrowserVoice = (voice) => !voice.default;\n/**\n * Browser TTS Provider\n *\n * Stateless factory for creating browser-based TTS implementations.\n */\nexport class BrowserTTSProvider {\n providerId = \"browser\";\n providerName = \"Browser Speech Synthesis\";\n version = \"1.0.0\";\n async initialize(config) {\n // SSR guard\n if (typeof window === \"undefined\") {\n throw new Error(\"BrowserTTSProvider requires browser environment\");\n }\n // Check browser support\n if (!(\"speechSynthesis\" in window)) {\n throw new Error(\"Browser does not support Speech Synthesis API\");\n }\n return new BrowserTTSProviderImpl(config);\n }\n supportsFeature(feature) {\n // Browser supports all TTS features\n return true;\n }\n getCapabilities() {\n return {\n supportsPause: true,\n supportsResume: true,\n supportsWordBoundary: true,\n supportsVoiceSelection: true,\n supportsRateControl: true,\n supportsPitchControl: true,\n // The Web Speech API voices plain text only; SSML tags are read aloud.\n supportsSSML: false,\n };\n }\n destroy() {\n // No cleanup needed for browser provider\n }\n}\n/**\n * Browser TTS Provider Implementation\n *\n * Handles actual speech synthesis using the Web Speech API.\n */\nclass BrowserTTSProviderImpl {\n utterance = null;\n config = null;\n _isPlaying = false;\n _isPaused = false;\n speakRunId = 0;\n settlePendingVoiceWait = null;\n settlePendingChunk = null;\n onPlaybackStart = undefined;\n constructor(config) {\n this.config = config;\n }\n waitForBrowserVoices(runId, configuredVoice) {\n return new Promise((resolve, reject) => {\n const synth = speechSynthesis;\n const canUseEventTarget = typeof synth.addEventListener === \"function\" &&\n typeof synth.removeEventListener === \"function\";\n const previousHandler = canUseEventTarget ? null : synth.onvoiceschanged;\n let settled = false;\n let timeout = null;\n let pendingSettlement = null;\n const cleanup = () => {\n if (timeout !== null) {\n clearTimeout(timeout);\n timeout = null;\n }\n if (canUseEventTarget) {\n synth.removeEventListener(\"voiceschanged\", onVoicesChanged);\n }\n else if (synth.onvoiceschanged === propertyHandler) {\n synth.onvoiceschanged = previousHandler;\n }\n if (pendingSettlement &&\n this.settlePendingVoiceWait === pendingSettlement) {\n this.settlePendingVoiceWait = null;\n }\n };\n const finish = (voicesAvailable, error) => {\n if (settled)\n return;\n settled = true;\n cleanup();\n if (error) {\n reject(error);\n }\n else {\n resolve(voicesAvailable);\n }\n };\n const inspectVoiceInventory = () => {\n if (runId !== this.speakRunId) {\n finish(false);\n return;\n }\n if (synth.getVoices().length > 0)\n finish(true);\n };\n const onVoicesChanged = () => inspectVoiceInventory();\n const propertyHandler = (event) => {\n try {\n previousHandler?.call(synth, event);\n }\n finally {\n inspectVoiceInventory();\n }\n };\n pendingSettlement = () => finish(false);\n this.settlePendingVoiceWait = pendingSettlement;\n timeout = setTimeout(() => finish(false, new Error(`Configured browser voice \"${configuredVoice}\" could not be resolved because the browser did not publish its voice inventory within ${VOICE_INVENTORY_TIMEOUT_MS / 1_000} seconds.`)), VOICE_INVENTORY_TIMEOUT_MS);\n if (canUseEventTarget) {\n synth.addEventListener(\"voiceschanged\", onVoicesChanged);\n }\n else {\n synth.onvoiceschanged = propertyHandler;\n }\n // Close the getVoices()/listener-registration race without polling.\n inspectVoiceInventory();\n });\n }\n async resolveBrowserVoice(runId) {\n const configuredVoice = typeof this.config?.voice === \"string\" ? this.config.voice.trim() : \"\";\n let voices = speechSynthesis.getVoices();\n if (configuredVoice && voices.length === 0) {\n const voicesAvailable = await this.waitForBrowserVoices(runId, configuredVoice);\n if (!voicesAvailable || runId !== this.speakRunId) {\n return { shouldContinue: false, voice: null };\n }\n voices = speechSynthesis.getVoices();\n }\n if (runId !== this.speakRunId) {\n return { shouldContinue: false, voice: null };\n }\n const voice = findBrowserVoice(voices, configuredVoice || undefined);\n if (configuredVoice && !voice) {\n throw new Error(`Configured browser voice \"${configuredVoice}\" is unavailable. Select a voice exposed by this browser using its voiceURI or name.`);\n }\n return { shouldContinue: true, voice };\n }\n async speak(text) {\n if (!this.config) {\n throw new Error(\"TTS not initialized\");\n }\n // Invalidate any in-flight run and cancel current utterance.\n this.stop();\n const runId = this.speakRunId;\n const voiceResolution = await this.resolveBrowserVoice(runId);\n if (!voiceResolution.shouldContinue)\n return;\n const chunks = this.splitIntoChunks(text);\n for (const chunk of chunks) {\n if (runId !== this.speakRunId) {\n break;\n }\n const shouldContinue = await this.speakChunk(chunk.text, chunk.offset, runId, voiceResolution.voice);\n if (!shouldContinue) {\n break;\n }\n }\n }\n async speakSegments(segments) {\n if (!this.config) {\n throw new Error(\"TTS not initialized\");\n }\n this.stop();\n const runId = this.speakRunId;\n const voiceResolution = await this.resolveBrowserVoice(runId);\n if (!voiceResolution.shouldContinue)\n return;\n for (const segment of segments) {\n if (runId !== this.speakRunId)\n break;\n const chunks = this.splitIntoChunks(segment.text);\n for (const chunk of chunks) {\n if (runId !== this.speakRunId)\n break;\n const shouldContinue = await this.speakChunk(chunk.text, segment.startOffset + chunk.offset, runId, voiceResolution.voice);\n if (!shouldContinue)\n break;\n }\n const pauseMsAfter = Math.max(0, Number(segment.pauseMsAfter || 0));\n if (pauseMsAfter > 0 && runId === this.speakRunId) {\n const shouldContinue = await this.waitForPause(pauseMsAfter, runId);\n if (!shouldContinue)\n break;\n }\n }\n }\n async waitForPause(pauseMs, runId) {\n await new Promise((resolve) => setTimeout(resolve, pauseMs));\n return runId === this.speakRunId;\n }\n splitIntoChunks(text) {\n const MAX_CHUNK_LENGTH = 260;\n if (text.length <= MAX_CHUNK_LENGTH) {\n return [{ text, offset: 0 }];\n }\n const sentences = this.segmentSentences(text);\n const chunks = [];\n let currentText = \"\";\n let currentOffset = 0;\n for (const sentence of sentences) {\n const trimmed = sentence.text.trim();\n if (!trimmed)\n continue;\n const firstNonWhitespace = sentence.text.search(/\\S/);\n const trimmedStart = sentence.offset + (firstNonWhitespace === -1 ? 0 : firstNonWhitespace);\n if (!currentText) {\n currentText = trimmed;\n currentOffset = trimmedStart;\n continue;\n }\n const candidate = `${currentText} ${trimmed}`;\n if (candidate.length <= MAX_CHUNK_LENGTH) {\n currentText = candidate;\n }\n else {\n chunks.push({ text: currentText, offset: currentOffset });\n currentText = trimmed;\n currentOffset = trimmedStart;\n }\n }\n if (currentText) {\n chunks.push({ text: currentText, offset: currentOffset });\n }\n return chunks.length ? chunks : [{ text, offset: 0 }];\n }\n getHighlightMode() {\n const providerOptions = (this.config?.providerOptions || {});\n return providerOptions.highlightMode === \"word\" ? \"word\" : \"sentence\";\n }\n getSegmentationPolicy() {\n const providerOptions = (this.config?.providerOptions || {});\n const segmenter = (providerOptions.segmenter || {});\n const mode = segmenter.mode;\n const useSegmenter = mode !== \"regexOnly\";\n const locale = typeof segmenter.locale === \"string\" && segmenter.locale.trim().length > 0\n ? segmenter.locale\n : typeof providerOptions.locale === \"string\" &&\n providerOptions.locale.trim().length > 0\n ? providerOptions.locale\n : undefined;\n return {\n useSentenceSegmenter: useSegmenter,\n useWordSegmenter: useSegmenter,\n locale,\n };\n }\n segmentSentences(text) {\n const policy = this.getSegmentationPolicy();\n return segmentTextToSentences(text, {\n locale: policy.locale,\n useSentenceSegmenter: policy.useSentenceSegmenter,\n });\n }\n inferWordLength(text, index) {\n const safeIndex = Math.max(0, Math.min(index, Math.max(0, text.length - 1)));\n const slice = text.slice(safeIndex);\n const match = slice.match(/^\\s*([^\\s]+)/);\n return match?.[1]?.length || 1;\n }\n async speakChunk(chunkText, chunkOffset, runId, voice) {\n return new Promise((resolve, reject) => {\n if (runId !== this.speakRunId) {\n resolve(false);\n return;\n }\n const utterance = new SpeechSynthesisUtterance(chunkText);\n this.utterance = utterance;\n // Apply config\n if (voice && shouldAssignBrowserVoice(voice))\n utterance.voice = voice;\n if (this.config?.rate)\n utterance.rate = this.config.rate;\n if (this.config?.pitch)\n utterance.pitch = this.config.pitch;\n let didStart = false;\n let settled = false;\n let startTimeout = null;\n let pendingSettlement = null;\n const clearOwnedUtterance = () => {\n if (this.utterance === utterance) {\n this.utterance = null;\n }\n };\n const clearStartTimeout = () => {\n if (startTimeout !== null) {\n clearTimeout(startTimeout);\n startTimeout = null;\n }\n };\n const detachHandlers = () => {\n utterance.onstart = null;\n utterance.onend = null;\n utterance.onerror = null;\n utterance.onpause = null;\n utterance.onresume = null;\n utterance.onboundary = null;\n };\n const settle = (shouldContinue, error) => {\n if (settled)\n return;\n settled = true;\n clearStartTimeout();\n detachHandlers();\n clearOwnedUtterance();\n if (pendingSettlement &&\n this.settlePendingChunk === pendingSettlement) {\n this.settlePendingChunk = null;\n }\n if (runId === this.speakRunId) {\n this._isPlaying = false;\n this._isPaused = false;\n }\n if (error) {\n reject(error);\n }\n else {\n resolve(shouldContinue);\n }\n };\n const browserEngineStartError = (reason) => new Error(reason === \"ended\"\n ? \"Browser speech synthesis ended before audio started. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.\"\n : `Browser speech synthesis did not start within ${NATIVE_START_TIMEOUT_MS / 1_000} seconds. The browser speech engine may be unavailable or stuck; try another voice or restart the browser.`);\n pendingSettlement = () => settle(false);\n this.settlePendingChunk = pendingSettlement;\n utterance.onstart = () => {\n if (runId !== this.speakRunId) {\n settle(false);\n return;\n }\n didStart = true;\n clearStartTimeout();\n this._isPlaying = true;\n this._isPaused = false;\n try {\n this.onPlaybackStart?.();\n }\n catch (error) {\n console.error(\"Browser TTS playback-start callback failed\", error);\n }\n };\n utterance.onend = () => {\n if (runId !== this.speakRunId) {\n settle(false);\n return;\n }\n if (!didStart) {\n settle(false, browserEngineStartError(\"ended\"));\n return;\n }\n settle(true);\n };\n utterance.onerror = (event) => {\n if (runId !== this.speakRunId) {\n settle(false);\n return;\n }\n if (event.error === \"interrupted\" || event.error === \"canceled\") {\n settle(false);\n return;\n }\n settle(false, new Error(`Speech synthesis error: ${event.error}`));\n };\n utterance.onpause = () => {\n if (runId !== this.speakRunId)\n return;\n this._isPaused = true;\n };\n utterance.onresume = () => {\n if (runId !== this.speakRunId)\n return;\n this._isPaused = false;\n };\n utterance.onboundary = (event) => {\n if (runId !== this.speakRunId)\n return;\n console.log(\"[BrowserProvider] Boundary event:\", event.name, \"charIndex:\", event.charIndex, \"charLength:\", event.charLength);\n if (event.name !== \"word\" || !this.onWordBoundary)\n return;\n if (this.getHighlightMode() === \"sentence\") {\n return;\n }\n const charIndex = Math.max(0, Math.min(event.charIndex, Math.max(0, chunkText.length - 1)));\n const reportedLength = Number(event.charLength || 0);\n const inferredLength = this.inferWordLength(chunkText, charIndex);\n const wordLength = Number.isFinite(reportedLength) &&\n reportedLength > 0 &&\n reportedLength <= 80 &&\n charIndex + reportedLength <= chunkText.length\n ? reportedLength\n : inferredLength;\n const word = chunkText\n .substring(charIndex, Math.min(chunkText.length, charIndex + wordLength))\n .trim();\n const absoluteBoundaryStart = chunkOffset + charIndex;\n console.log(\"[BrowserProvider] Calling onWordBoundary with word:\", word, \"at position:\", absoluteBoundaryStart);\n this.onWordBoundary(word, absoluteBoundaryStart, wordLength);\n };\n startTimeout = setTimeout(() => {\n if (settled || didStart || runId !== this.speakRunId)\n return;\n settle(false, browserEngineStartError(\"timedOut\"));\n speechSynthesis.cancel();\n }, NATIVE_START_TIMEOUT_MS);\n try {\n speechSynthesis.speak(utterance);\n }\n catch (error) {\n settle(false, error instanceof Error\n ? error\n : new Error(\"Browser speech synthesis failed to queue speech\"));\n }\n });\n }\n pause() {\n if (this._isPlaying && !this._isPaused) {\n speechSynthesis.pause();\n }\n }\n resume() {\n if (this._isPlaying && this._isPaused) {\n speechSynthesis.resume();\n }\n }\n stop() {\n const utterance = this.utterance;\n const shouldCancel = this._isPlaying || utterance !== null;\n this.speakRunId += 1;\n this.settlePendingVoiceWait?.();\n this.settlePendingChunk?.();\n if (shouldCancel) {\n speechSynthesis.cancel();\n }\n this.utterance = null;\n this._isPlaying = false;\n this._isPaused = false;\n }\n isPlaying() {\n return this._isPlaying && !this._isPaused;\n }\n isPaused() {\n return this._isPaused;\n }\n /**\n * Update settings dynamically (rate, pitch, voice)\n * Changes take effect on the next speak() call\n */\n updateSettings(settings) {\n if (!this.config) {\n this.config = {};\n }\n // Update config with new settings\n if (settings.rate !== undefined) {\n this.config.rate = settings.rate;\n }\n if (settings.pitch !== undefined) {\n this.config.pitch = settings.pitch;\n }\n if (settings.voice !== undefined) {\n this.config.voice = settings.voice;\n }\n if (settings.providerOptions !== undefined) {\n this.config.providerOptions = {\n ...(this.config.providerOptions || {}),\n ...(settings.providerOptions || {}),\n };\n }\n }\n onWordBoundary;\n}\n","export const normalizeTextForSpeech = (text) => text.trim().replace(/\\s+/g, \" \");\n// Single source of truth for aligning spoken text to visible / math text.\n// Letters are matched with `\\p{L}` so the tokenizer is Unicode-aware — accented\n// Latin (\"café\") and non-Latin scripts stay one token instead of being split\n// or dropped, which is what previously limited word-level highlight alignment\n// to ASCII. Numbers cover integers and decimals; the trailing class lists the\n// math glyphs a TTS engine may surface as a single visible token. A fresh\n// RegExp is returned each call because the global flag carries mutable\n// `lastIndex` state that must not be shared across call sites.\nexport const createSpeechAlignmentTokenPattern = () => /[\\p{L}]+|\\d+(?:\\.\\d+)?|[±√=+\\-*/()²³^×÷≤≥≠≈<>|%°'′\\u2062]/gu;\nexport const isElementHiddenForTTS = (element) => {\n if (element.hidden)\n return true;\n if (element.tagName?.toLowerCase() === \"mjx-assistive-mml\")\n return true;\n if (element.getAttribute(\"aria-hidden\") === \"true\")\n return true;\n if (element.hasAttribute(\"inert\"))\n return true;\n const classList = element.classList;\n if (classList?.contains(\"sr-only\") ||\n classList?.contains(\"pie-sr-only\") ||\n classList?.contains(\"visually-hidden\")) {\n return true;\n }\n if (typeof window !== \"undefined\") {\n const style = window.getComputedStyle(element);\n if (style.display === \"none\" || style.visibility === \"hidden\") {\n return true;\n }\n const width = Number.parseFloat(style.width || \"0\");\n const height = Number.parseFloat(style.height || \"0\");\n const isTiny = Number.isFinite(width) &&\n Number.isFinite(height) &&\n width <= 1 &&\n height <= 1;\n const isOffscreenClip = style.clipPath.includes(\"inset(50%\") ||\n style.clipPath.includes(\"inset(100%\") ||\n style.clip.includes(\"rect(0px, 0px, 0px, 0px)\") ||\n style.clip.includes(\"rect(0 0 0 0)\");\n if ((style.position === \"absolute\" || style.position === \"fixed\") &&\n isTiny &&\n (style.overflow === \"hidden\" || isOffscreenClip)) {\n return true;\n }\n if (style.opacity === \"0\" && isTiny) {\n return true;\n }\n }\n return false;\n};\nexport const isNodeHiddenForTTS = (node, root) => {\n let current = node.nodeType === 1\n ? node\n : node.parentElement;\n while (current) {\n if (isElementHiddenForTTS(current))\n return true;\n if (root && current === root)\n break;\n current = current.parentElement;\n }\n return false;\n};\n/**\n * Marks content that must be shown but never spoken — items where reading *is*\n * the construct, such as decoding and spelling, where speaking the node hands\n * over the answer.\n *\n * Not a PNP field: `prohibitedSupports` is the learner declining a support, while\n * this is the item saying \"not here, for anyone\", so it overrides an entitlement\n * rather than yielding to it.\n *\n * Shape follows QTI 3's `data-qti-suppress-tts` — an attribute on the content\n * element, single-valued, vocabulary below. Element placement is what makes it\n * work on undocked nodes and enforceable in the selection read-aloud path, which\n * consults no catalog. The name follows PIE's `data-tts-*` family, and PIE reads\n * only this spelling; importers map QTI's.\n */\nexport const TTS_SUPPRESS_ATTRIBUTE = \"data-tts-suppress\";\nconst SUPPRESSES_COMPUTER_READ_ALOUD = new Set([\"computer-read-aloud\", \"all\"]);\n// `screen-reader` is in the vocabulary but is not ours: it asks the delivery\n// engine to hide the node from assistive technology, which is the host's job\n// (and is what `aria-hidden` above already covers on the way in). A node marked\n// only `screen-reader` is still legitimately machine-read aloud.\nconst SUPPRESS_VALUES = new Set([\n ...SUPPRESSES_COMPUTER_READ_ALOUD,\n \"screen-reader\",\n]);\nconst warnedSuppressValues = new Set();\n/**\n * Whether this element forbids machine read-aloud of itself and its subtree.\n *\n * Unrecognized and empty values suppress rather than pass through, and say so once\n * per distinct value: a typo that fell through would speak a word the item was\n * measuring, invalidating the score with no visible symptom, whereas\n * over-suppressing only withholds speech an author had already marked as withheld.\n */\nexport const isElementSuppressedForTTS = (element) => {\n const raw = element.getAttribute?.(TTS_SUPPRESS_ATTRIBUTE);\n if (raw === null || raw === undefined)\n return false;\n const value = raw.trim().toLowerCase();\n if (SUPPRESSES_COMPUTER_READ_ALOUD.has(value))\n return true;\n if (SUPPRESS_VALUES.has(value))\n return false;\n if (!warnedSuppressValues.has(value)) {\n warnedSuppressValues.add(value);\n console.warn(`[tts] ${TTS_SUPPRESS_ATTRIBUTE}=\"${raw}\" is not one of ${Array.from(SUPPRESS_VALUES).join(\", \")}; suppressing read-aloud for this content anyway, because a suppression attribute that fails open would leak the answer to items where reading is the construct. Correct the value to silence this.`);\n }\n return true;\n};\nexport const isNodeSuppressedForTTS = (node, root) => {\n let current = node.nodeType === 1\n ? node\n : node.parentElement;\n while (current) {\n if (isElementSuppressedForTTS(current))\n return true;\n if (root && current === root)\n break;\n current = current.parentElement;\n }\n return false;\n};\n/**\n * The predicate every speech-producing path filters on: hidden *or* suppressed.\n *\n * Kept distinct from `isNodeHiddenForTTS`, which stays a question about\n * visibility — suppressed content is visible on purpose, and the highlight\n * geometry resolvers that ask \"can the candidate see this\" must keep getting\n * the visibility answer rather than this one.\n */\nexport const isNodeExcludedFromSpeech = (node, root) => isNodeHiddenForTTS(node, root) || isNodeSuppressedForTTS(node);\n/**\n * Text of a range with the parts that must not be spoken removed.\n *\n * `Range.toString()` is not usable for speech: it is pure character extraction\n * and honours no DOM filter at all, so it happily returns suppressed — and\n * hidden — text. The selection read-aloud path is a text-in path rather than a\n * DOM walk, which makes this the only place its content can be filtered.\n *\n * `filtered` reports whether anything was dropped, so a caller can tell \"the\n * candidate selected nothing speakable\" apart from \"the candidate selected\n * nothing\".\n */\nexport const collectRangeTextForSpeech = (range, root) => {\n if (typeof document === \"undefined\" ||\n typeof document.createTreeWalker !==\n \"function\" ||\n typeof NodeFilter === \"undefined\" ||\n typeof range.intersectsNode !== \"function\") {\n // Degraded, and deliberately not silent about the difference: callers still\n // enforce whole-selection suppression from the range's common ancestor, so\n // the construct guard holds even here. What is lost is per-node filtering\n // of a selection that only partly overlaps suppressed content.\n return { text: range.toString(), filtered: false };\n }\n const parts = [];\n let filtered = false;\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n let current = walker.nextNode();\n while (current) {\n const textNode = current;\n if (range.intersectsNode(textNode)) {\n if (isNodeExcludedFromSpeech(textNode, root)) {\n filtered = true;\n }\n else {\n const raw = textNode.textContent || \"\";\n const start = textNode === range.startContainer ? range.startOffset : 0;\n const end = textNode === range.endContainer ? range.endOffset : raw.length;\n parts.push(raw.slice(start, end));\n }\n }\n current = walker.nextNode();\n }\n return { text: parts.join(\"\"), filtered };\n};\nexport const shouldInsertWordBoundarySpace = (previousChar, nextChar, options) => {\n if (!previousChar || !nextChar)\n return false;\n if (/\\s/.test(previousChar) || /\\s/.test(nextChar))\n return false;\n const mode = options?.boundarySpacingMode ?? \"segmenterPreferred\";\n if (mode === \"none\")\n return false;\n if (mode === \"segmenterPreferred\") {\n try {\n const Segmenter = globalThis.Intl?.Segmenter;\n if (typeof Segmenter === \"function\") {\n const segmenter = new Segmenter(options?.locale, {\n granularity: \"word\",\n });\n const segments = Array.from(segmenter.segment(`${previousChar}${nextChar}`));\n const wordLikeCount = segments.filter((segment) => segment.isWordLike !== false &&\n segment.segment.trim().length > 0).length;\n if (wordLikeCount >= 2)\n return true;\n }\n }\n catch {\n // Fall back to alnum heuristics below.\n }\n }\n const prevIsAlnum = /[A-Za-z0-9]/.test(previousChar);\n const nextIsAlnum = /[A-Za-z0-9]/.test(nextChar);\n return prevIsAlnum && nextIsAlnum;\n};\nexport const collectVisibleTextAndMap = (element, options) => {\n const map = new Map();\n if (typeof document === \"undefined\" ||\n typeof document.createTreeWalker !==\n \"function\" ||\n typeof NodeFilter === \"undefined\") {\n return { text: \"\", map };\n }\n const outChars = [];\n let outPos = 0;\n let inLeadingWhitespace = true;\n let lastCharWasWhitespace = false;\n let lastMapped = null;\n let previousVisibleChar = null;\n const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);\n let current = walker.nextNode();\n while (current) {\n const textNode = current;\n const parent = textNode.parentElement;\n if (parent && !isNodeExcludedFromSpeech(textNode, element)) {\n const raw = textNode.textContent || \"\";\n const firstVisibleMatch = raw.match(/\\S/);\n const firstVisibleChar = firstVisibleMatch ? firstVisibleMatch[0] : null;\n if (!inLeadingWhitespace &&\n !lastCharWasWhitespace &&\n shouldInsertWordBoundarySpace(previousVisibleChar, firstVisibleChar, options)) {\n outChars.push(\" \");\n if (lastMapped) {\n map.set(outPos, lastMapped);\n }\n outPos++;\n lastCharWasWhitespace = true;\n }\n for (let i = 0; i < raw.length; i++) {\n const ch = raw[i];\n const isWhitespace = /\\s/.test(ch);\n if (inLeadingWhitespace) {\n if (!isWhitespace) {\n inLeadingWhitespace = false;\n outChars.push(ch);\n map.set(outPos, { node: textNode, offset: i });\n lastMapped = { node: textNode, offset: i };\n outPos++;\n lastCharWasWhitespace = false;\n previousVisibleChar = ch;\n }\n }\n else if (isWhitespace) {\n if (!lastCharWasWhitespace) {\n outChars.push(\" \");\n map.set(outPos, { node: textNode, offset: i });\n lastMapped = { node: textNode, offset: i };\n outPos++;\n }\n lastCharWasWhitespace = true;\n }\n else {\n outChars.push(ch);\n map.set(outPos, { node: textNode, offset: i });\n lastMapped = { node: textNode, offset: i };\n outPos++;\n lastCharWasWhitespace = false;\n previousVisibleChar = ch;\n }\n }\n }\n current = walker.nextNode();\n }\n const text = outChars.join(\"\").trimEnd();\n while (map.has(text.length)) {\n map.delete(text.length);\n }\n return { text, map };\n};\nexport const extractVisibleText = (element, options) => collectVisibleTextAndMap(element, options).text;\n","import { normalizeTextForSpeech } from \"../text-processing.js\";\nconst STRUCTURAL_SSML_TAGS = new Set([\n \"speak\",\n \"p\",\n \"s\",\n \"emphasis\",\n \"prosody\",\n \"say-as\",\n \"voice\",\n \"lang\",\n]);\nconst UNSUPPORTED_SEMANTIC_SSML_TAGS = new Set([\"audio\", \"phoneme\"]);\nconst decodeXmlEntities = (value) => value\n .replace(/&quot;/g, '\"')\n .replace(/&apos;/g, \"'\")\n .replace(/&lt;/g, \"<\")\n .replace(/&gt;/g, \">\")\n .replace(/&nbsp;/g, \"\\u00a0\")\n .replace(/&#160;/g, \"\\u00a0\")\n .replace(/&amp;/g, \"&\");\nconst appendSourceText = (chars, value, rawOffset) => {\n for (let i = 0; i < value.length; i++) {\n chars.push({\n char: value[i],\n rawOffset: rawOffset === null ? null : rawOffset + i,\n });\n }\n};\nconst appendDecodedXmlEntity = (chars, source, rawOffset) => {\n const match = source\n .slice(rawOffset)\n .match(/^&(quot|apos|lt|gt|nbsp|amp|#160);/i);\n if (!match)\n return 0;\n appendSourceText(chars, decodeXmlEntities(match[0]), rawOffset);\n return match[0].length;\n};\nconst appendSpace = (chars) => {\n chars.push({ char: \" \", rawOffset: null });\n};\nconst normalizeSourceChars = (chars) => {\n const rawToSpokenOffsetMap = new Map();\n const out = [];\n let lastWasWhitespace = true;\n for (const sourceChar of chars) {\n const isWhitespace = /\\s/.test(sourceChar.char);\n if (isWhitespace) {\n if (!lastWasWhitespace && out.length > 0) {\n out.push(\" \");\n if (sourceChar.rawOffset !== null) {\n rawToSpokenOffsetMap.set(sourceChar.rawOffset, out.length - 1);\n }\n }\n lastWasWhitespace = true;\n continue;\n }\n out.push(sourceChar.char);\n if (sourceChar.rawOffset !== null) {\n rawToSpokenOffsetMap.set(sourceChar.rawOffset, out.length - 1);\n }\n lastWasWhitespace = false;\n }\n while (out.length > 0 && out[out.length - 1] === \" \") {\n out.pop();\n }\n // Drop any raw→spoken entries that now point past the trimmed end; otherwise\n // a boundary at a trailing space would map to an out-of-range spoken offset.\n for (const [rawOffset, spokenOffset] of rawToSpokenOffsetMap) {\n if (spokenOffset >= out.length)\n rawToSpokenOffsetMap.delete(rawOffset);\n }\n return { text: out.join(\"\"), rawToSpokenOffsetMap };\n};\nconst getTagName = (tagSource) => {\n const match = tagSource.match(/^<\\/?\\s*([A-Za-z0-9:-]+)/);\n return match?.[1]?.toLowerCase() || \"\";\n};\nconst getAttribute = (tagSource, name) => {\n const pattern = new RegExp(`${name}\\\\s*=\\\\s*(\"([^\"]*)\"|'([^']*)')`, \"i\");\n const match = tagSource.match(pattern);\n return decodeXmlEntities(match?.[2] ?? match?.[3] ?? \"\") || null;\n};\nexport const extractSpokenText = (speechText) => {\n const sourceChars = [];\n let unsupportedSemantic = false;\n let hasMarkup = false;\n let index = 0;\n while (index < speechText.length) {\n const char = speechText[index];\n if (char !== \"<\") {\n if (char === \"&\") {\n const consumed = appendDecodedXmlEntity(sourceChars, speechText, index);\n if (consumed > 0) {\n index += consumed;\n continue;\n }\n }\n appendSourceText(sourceChars, char, index);\n index++;\n continue;\n }\n const closeIndex = speechText.indexOf(\">\", index + 1);\n if (closeIndex < 0) {\n appendSourceText(sourceChars, char, index);\n index++;\n continue;\n }\n hasMarkup = true;\n const tagSource = speechText.slice(index, closeIndex + 1);\n const tagName = getTagName(tagSource);\n const isClosing = /^<\\s*\\//.test(tagSource);\n const isSelfClosing = /\\/\\s*>$/.test(tagSource);\n if (!isClosing && tagName === \"sub\") {\n const alias = getAttribute(tagSource, \"alias\");\n if (!alias) {\n unsupportedSemantic = true;\n index = closeIndex + 1;\n continue;\n }\n appendSourceText(sourceChars, alias, null);\n const closingSub = speechText\n .toLowerCase()\n .indexOf(\"</sub>\", closeIndex + 1);\n index = closingSub >= 0 ? closingSub + \"</sub>\".length : closeIndex + 1;\n continue;\n }\n if (!isClosing && tagName === \"break\") {\n appendSpace(sourceChars);\n index = closeIndex + 1;\n continue;\n }\n if (!isClosing && UNSUPPORTED_SEMANTIC_SSML_TAGS.has(tagName)) {\n unsupportedSemantic = true;\n if (isSelfClosing) {\n index = closeIndex + 1;\n continue;\n }\n }\n if (tagName &&\n !STRUCTURAL_SSML_TAGS.has(tagName) &&\n !UNSUPPORTED_SEMANTIC_SSML_TAGS.has(tagName) &&\n tagName !== \"break\" &&\n tagName !== \"sub\") {\n unsupportedSemantic = true;\n }\n if (!isClosing && (tagName === \"p\" || tagName === \"s\")) {\n appendSpace(sourceChars);\n }\n index = closeIndex + 1;\n }\n const normalized = normalizeSourceChars(sourceChars);\n return {\n spokenText: normalizeTextForSpeech(normalized.text),\n rawToSpokenOffsetMap: normalized.rawToSpokenOffsetMap,\n unsupportedSemantic,\n hasMarkup,\n };\n};\n","import { extractSpokenText } from \"./ssml/spoken-text.js\";\nimport { createSpeechAlignmentTokenPattern, normalizeTextForSpeech, } from \"./text-processing.js\";\n// Shared Unicode-aware tokenizer (see `createSpeechAlignmentTokenPattern`), so\n// accented Latin and non-Latin words tokenize the same way here as in the math\n// speech tokenizer. LIMITATION (i18n): the phrase table below is still English,\n// so multi-word operator phrases (\"plus or minus\", \"divided by\") only align for\n// English speech; other locales degrade to coarse region highlighting. A fresh\n// pattern per call because of the global flag's mutable `lastIndex`.\nconst TOKEN_PATTERN = createSpeechAlignmentTokenPattern();\nconst NUMERIC_WORDS = new Map([\n [\"zero\", \"0\"],\n [\"one\", \"1\"],\n [\"two\", \"2\"],\n [\"three\", \"3\"],\n [\"four\", \"4\"],\n [\"five\", \"5\"],\n [\"six\", \"6\"],\n [\"seven\", \"7\"],\n [\"eight\", \"8\"],\n [\"nine\", \"9\"],\n [\"ten\", \"10\"],\n]);\nconst SPOKEN_PHRASE_TARGETS = [\n { phrase: [\"plus\", \"or\", \"minus\"], visible: \"±\", score: 8 },\n { phrase: [\"square\", \"root\"], visible: \"√\", score: 8 },\n { phrase: [\"divided\", \"by\"], visible: \"/\", score: 7 },\n { phrase: [\"all\", \"over\"], visible: \"/\", score: 7 },\n { phrase: [\"equals\"], visible: \"=\", score: 7 },\n { phrase: [\"equal\"], visible: \"=\", score: 7 },\n { phrase: [\"times\"], visible: \"\\u2062\", score: 7 },\n { phrase: [\"multiplied\", \"by\"], visible: \"\\u2062\", score: 7 },\n { phrase: [\"over\"], visible: \"/\", score: 6 },\n { phrase: [\"squared\"], visible: \"²\", score: 6 },\n { phrase: [\"squared\"], visible: \"2\", score: 4 },\n { phrase: [\"negative\"], visible: \"-\", score: 5 },\n { phrase: [\"minus\"], visible: \"-\", score: 5 },\n { phrase: [\"plus\"], visible: \"+\", score: 5 },\n];\nconst tokenize = (text) => {\n const tokens = [];\n for (const match of text.matchAll(TOKEN_PATTERN)) {\n const value = match[0];\n const start = match.index ?? 0;\n tokens.push({\n text: value,\n normalized: value.toLowerCase(),\n start,\n end: start + value.length,\n });\n }\n return tokens;\n};\nconst normalizedTokenValue = (token) => NUMERIC_WORDS.get(token.normalized) || token.normalized;\nconst createCandidates = (spokenTokens, visibleTokens) => {\n const candidates = [];\n for (let spokenIndex = 0; spokenIndex < spokenTokens.length; spokenIndex++) {\n for (let visibleIndex = 0; visibleIndex < visibleTokens.length; visibleIndex++) {\n const spokenValue = normalizedTokenValue(spokenTokens[spokenIndex]);\n const visibleValue = normalizedTokenValue(visibleTokens[visibleIndex]);\n if (spokenValue === visibleValue) {\n candidates.push({\n spokenStartToken: spokenIndex,\n spokenEndToken: spokenIndex + 1,\n visibleToken: visibleIndex,\n score: 10,\n });\n }\n }\n for (const phraseTarget of SPOKEN_PHRASE_TARGETS) {\n const phraseTokens = spokenTokens.slice(spokenIndex, spokenIndex + phraseTarget.phrase.length);\n if (phraseTokens.length !== phraseTarget.phrase.length)\n continue;\n if (!phraseTokens.every((token, tokenIndex) => token.normalized === phraseTarget.phrase[tokenIndex])) {\n continue;\n }\n for (let visibleIndex = 0; visibleIndex < visibleTokens.length; visibleIndex++) {\n if (visibleTokens[visibleIndex].normalized !== phraseTarget.visible) {\n continue;\n }\n candidates.push({\n spokenStartToken: spokenIndex,\n spokenEndToken: spokenIndex + phraseTarget.phrase.length,\n visibleToken: visibleIndex,\n score: phraseTarget.score,\n });\n }\n }\n }\n return candidates;\n};\nconst computeAnchors = (spokenTokens, visibleTokens) => {\n const candidates = createCandidates(spokenTokens, visibleTokens).sort((left, right) => spokenTokens[left.spokenStartToken].start -\n spokenTokens[right.spokenStartToken].start ||\n visibleTokens[left.visibleToken].start -\n visibleTokens[right.visibleToken].start);\n const bestScore = new Array(candidates.length).fill(0);\n const previous = new Array(candidates.length).fill(-1);\n for (let i = 0; i < candidates.length; i++) {\n const candidate = candidates[i];\n bestScore[i] = candidate.score;\n for (let j = 0; j < i; j++) {\n const prior = candidates[j];\n if (prior.spokenEndToken <= candidate.spokenStartToken &&\n prior.visibleToken < candidate.visibleToken) {\n const spokenGap = candidate.spokenStartToken - prior.spokenEndToken;\n const visibleGap = candidate.visibleToken - prior.visibleToken - 1;\n const gapPenalty = Math.max(0, Math.abs(spokenGap - visibleGap) - 2);\n const score = bestScore[j] + candidate.score - gapPenalty;\n if (score > bestScore[i]) {\n bestScore[i] = score;\n previous[i] = j;\n }\n }\n }\n }\n let bestIndex = -1;\n for (let i = 0; i < bestScore.length; i++) {\n if (bestIndex < 0 || bestScore[i] > bestScore[bestIndex]) {\n bestIndex = i;\n }\n }\n if (bestIndex < 0)\n return [];\n const chosen = [];\n let current = bestIndex;\n while (current >= 0) {\n chosen.unshift(candidates[current]);\n current = previous[current];\n }\n return chosen.map((candidate) => {\n const firstSpoken = spokenTokens[candidate.spokenStartToken];\n const lastSpoken = spokenTokens[candidate.spokenEndToken - 1];\n const visible = visibleTokens[candidate.visibleToken];\n return {\n spokenStart: firstSpoken.start,\n spokenEnd: lastSpoken.end,\n visibleStart: visible.start,\n visibleEnd: visible.end,\n score: candidate.score,\n };\n });\n};\nconst scoreConfidence = (anchors, spokenTokens, visibleTokens) => {\n if (anchors.length === 0)\n return 0;\n const tokenCoverage = anchors.length /\n Math.max(1, Math.min(spokenTokens.length, visibleTokens.length));\n const averageScore = anchors.reduce((total, anchor) => total + anchor.score, 0) /\n anchors.length /\n 10;\n return Math.min(1, tokenCoverage * averageScore);\n};\nexport const createCatalogSpanAlignment = (args) => {\n const extracted = extractSpokenText(args.speechText);\n const visibleText = normalizeTextForSpeech(args.visibleText);\n const spokenText = extracted.spokenText;\n const spokenTokens = tokenize(spokenText);\n const visibleTokens = tokenize(visibleText);\n const anchors = extracted.unsupportedSemantic\n ? []\n : computeAnchors(spokenTokens, visibleTokens);\n const confidence = scoreConfidence(anchors, spokenTokens, visibleTokens);\n const isExact = spokenText === visibleText && spokenText.length > 0;\n const hasShortSingleExactAnchor = anchors.length === 1 &&\n anchors[0].score === 10 &&\n spokenTokens.length <= 2 &&\n visibleTokens.length <= 2;\n const playbackMode = extracted.unsupportedSemantic\n ? \"region-fallback\"\n : isExact\n ? \"exact-word\"\n : anchors.length >= 2 || hasShortSingleExactAnchor\n ? confidence >= 0.12\n ? \"anchor-span\"\n : \"region-fallback\"\n : \"region-fallback\";\n const boundaryOffsetMode = extracted.unsupportedSemantic\n ? \"unsupported\"\n : extracted.hasMarkup\n ? \"raw-ssml\"\n : \"plain-spoken-text\";\n return {\n speechText: args.speechText,\n spokenText,\n visibleText,\n playbackMode,\n boundaryOffsetMode,\n anchors,\n confidence,\n spokenTokens,\n visibleTokens,\n rawToSpokenOffsetMap: extracted.rawToSpokenOffsetMap,\n };\n};\nconst findTokenAtOffset = (tokens, offset) => tokens.find((token) => token.start <= offset && offset < token.end) || null;\nconst normalizeBoundaryWord = (word) => {\n if (!word)\n return null;\n if (/^<[^>]+>$/.test(word.trim()))\n return null;\n const token = tokenize(word)[0];\n if (!token)\n return null;\n return NUMERIC_WORDS.get(token.normalized) || token.normalized;\n};\nconst candidateMatchesBoundaryWord = (alignment, candidate, boundaryWord) => {\n const normalizedBoundary = normalizeBoundaryWord(boundaryWord);\n if (!candidate || !normalizedBoundary)\n return false;\n const token = findTokenAtOffset(alignment.spokenTokens, candidate.start);\n if (!token)\n return false;\n return normalizedTokenValue(token) === normalizedBoundary;\n};\nconst mapRawOffsetToSpokenOffset = (alignment, position) => {\n const direct = alignment.rawToSpokenOffsetMap.get(position);\n if (direct !== undefined)\n return direct;\n for (let offset = position; offset < alignment.speechText.length; offset++) {\n const mapped = alignment.rawToSpokenOffsetMap.get(offset);\n if (mapped !== undefined)\n return mapped;\n if (alignment.speechText[offset] === \">\")\n break;\n }\n return null;\n};\nconst resolveRawBoundaryOffset = (alignment, position, safeLength) => {\n const mappedStart = mapRawOffsetToSpokenOffset(alignment, position);\n if (mappedStart === null)\n return null;\n const mappedEnd = mapRawOffsetToSpokenOffset(alignment, Math.max(position, position + safeLength - 1));\n const token = findTokenAtOffset(alignment.spokenTokens, mappedStart);\n const mappedLength = mappedEnd !== null && mappedEnd >= mappedStart\n ? mappedEnd - mappedStart + 1\n : token\n ? token.end - mappedStart\n : safeLength;\n return { start: mappedStart, length: Math.max(1, mappedLength) };\n};\nconst resolvePlainBoundaryOffset = (alignment, position, safeLength) => {\n if (position < 0 || position >= alignment.spokenText.length)\n return null;\n const token = findTokenAtOffset(alignment.spokenTokens, position);\n if (!token)\n return null;\n return {\n start: position,\n length: Math.min(safeLength, token.end - position),\n };\n};\nexport const resolveSpokenBoundaryOffset = (alignment, position, length = 1, boundaryWord) => {\n if (alignment.boundaryOffsetMode === \"unsupported\" ||\n !Number.isFinite(position)) {\n return null;\n }\n const safeLength = Math.max(1, Number.isFinite(length) ? length : 1);\n if (boundaryWord && /^<[^>]+>$/.test(boundaryWord.trim()))\n return null;\n if (alignment.boundaryOffsetMode === \"raw-ssml\") {\n const rawCandidate = resolveRawBoundaryOffset(alignment, position, safeLength);\n const plainCandidate = resolvePlainBoundaryOffset(alignment, position, safeLength);\n if (boundaryWord) {\n if (candidateMatchesBoundaryWord(alignment, rawCandidate, boundaryWord)) {\n return rawCandidate;\n }\n if (candidateMatchesBoundaryWord(alignment, plainCandidate, boundaryWord)) {\n return plainCandidate;\n }\n if (normalizeBoundaryWord(boundaryWord))\n return null;\n }\n return rawCandidate || plainCandidate;\n }\n return (resolvePlainBoundaryOffset(alignment, position, safeLength) ||\n resolveRawBoundaryOffset(alignment, position, safeLength));\n};\nexport const resolveVisibleSpanForBoundary = (alignment, spokenOffset) => {\n if (alignment.playbackMode === \"region-fallback\")\n return null;\n const exactAnchor = alignment.anchors.find((anchor) => anchor.spokenStart <= spokenOffset && spokenOffset < anchor.spokenEnd);\n if (exactAnchor) {\n return { start: exactAnchor.visibleStart, end: exactAnchor.visibleEnd };\n }\n let previous = null;\n let next = null;\n for (const anchor of alignment.anchors) {\n if (anchor.spokenEnd <= spokenOffset) {\n previous = anchor;\n continue;\n }\n if (anchor.spokenStart > spokenOffset) {\n next = anchor;\n break;\n }\n }\n if (previous && next) {\n return {\n start: Math.min(previous.visibleStart, next.visibleStart),\n end: Math.max(previous.visibleEnd, next.visibleEnd),\n };\n }\n return null;\n};\n","const OPERATOR_ALIASES = new Map([\n [\"+\", [\"plus\"]],\n [\"-\", [\"minus\", \"negative\"]],\n [\"−\", [\"minus\", \"negative\"]],\n [\"×\", [\"times\", \"multiplied by\"]],\n [\"÷\", [\"divided by\"]],\n [\"=\", [\"equals\", \"equal to\"]],\n [\"≠\", [\"is not equal to\", \"not equal to\"]],\n [\"≈\", [\"approximately equals\"]],\n [\"≤\", [\"less than or equal to\"]],\n [\"≥\", [\"greater than or equal to\"]],\n [\"<\", [\"less than\"]],\n [\">\", [\"greater than\"]],\n [\"∠\", [\"angle\"]],\n [\"△\", [\"triangle\"]],\n [\"□\", [\"box\"]],\n [\"○\", [\"circle\"]],\n [\"°\", [\"degrees\", \"degree\"]],\n [\"%\", [\"percent\"]],\n [\"'\", [\"prime\"]],\n [\"′\", [\"prime\"]],\n [\"•\", [\"times\"]],\n [\"·\", [\"times\"]],\n [\"\\u2062\", [\"times\", \"multiplied by\"]],\n]);\n// Invisible operators (no glyph). A TTS engine usually does not voice them, so\n// they are tokenized as OPTIONAL — they only consume a spoken token when one\n// happens to match (e.g. an invisible-times read aloud as \"times\"). Marking\n// them required would force a coarse fallback for any function call (sin, f(x))\n// or implicit product.\nconst INVISIBLE_OPERATOR_ROLES = new Map([\n [\"\\u2061\", \"function-application\"],\n [\"\\u2062\", \"implicit-multiply\"],\n [\"\\u2063\", \"invisible-separator\"],\n [\"\\u2064\", \"invisible-plus\"],\n]);\n// Exponents a TTS engine reliably reads as a single power word. Other exponents\n// (variables, 4 and up, nested) are voiced in ways we cannot anchor, so they\n// recurse and let the all-or-nothing cover check fall back to the expression.\nconst SUPERSCRIPT_ALIASES = new Map([\n [\"2\", [\"squared\"]],\n [\"3\", [\"cubed\"]],\n]);\n// 2D / scripted containers we do not attempt to track per token. Each becomes a\n// single opaque, unmatchable structure token so any expression containing one\n// degrades to a coarse whole-expression highlight rather than risking a\n// misaligned per-glyph highlight from flattened inner tokens.\nconst OPAQUE_STRUCTURE_ROLES = new Map([\n [\"msqrt\", \"radical\"],\n [\"mroot\", \"radical\"],\n [\"msub\", \"subscript\"],\n [\"msubsup\", \"subsupscript\"],\n [\"munder\", \"underscript\"],\n [\"mover\", \"overscript\"],\n [\"munderover\", \"underoverscript\"],\n [\"mmultiscripts\", \"multiscript\"],\n [\"menclose\", \"enclosure\"],\n]);\nconst normalizeWhitespace = (value) => value.replace(/\\s+/g, \" \").trim();\nconst localNameOf = (element) => (element.localName || element.tagName || \"\").toLowerCase();\nconst isElement = (node) => node.nodeType === Node.ELEMENT_NODE;\nconst elementChildren = (element) => Array.from(element.childNodes).filter(isElement);\nconst textContentOf = (element) => normalizeWhitespace(element.textContent || \"\");\nconst elementTarget = (element, quality) => ({\n type: \"element-range\",\n quality,\n element,\n});\nconst tokenKindFor = (tagName) => {\n switch (tagName) {\n case \"mi\":\n return \"identifier\";\n case \"mn\":\n return \"number\";\n case \"mo\":\n return \"operator\";\n case \"mtext\":\n case \"ms\":\n return \"text\";\n case \"mspace\":\n return \"space\";\n default:\n return \"unknown\";\n }\n};\nconst normalizeToken = (text, kind) => {\n if (kind === \"operator\") {\n if (text === \"−\")\n return \"-\";\n return text;\n }\n return text.toLowerCase();\n};\nconst aliasesFor = (text, kind, role) => {\n if (role === \"fraction\")\n return [\"over\", \"divided by\"];\n if (role === \"superscript\")\n return SUPERSCRIPT_ALIASES.get(text) ?? [];\n if (text === \"|\")\n return [\"absolute value\"];\n if (kind === \"operator\")\n return OPERATOR_ALIASES.get(text) || [];\n return [];\n};\nconst createToken = (args) => {\n const normalized = args.normalized ?? normalizeToken(args.text, args.kind || \"unknown\");\n return {\n id: `math-token-${args.state.nextId++}`,\n kind: args.kind,\n role: args.role,\n text: args.text,\n normalized,\n spokenAliases: aliasesFor(args.text, args.kind, args.role),\n sourceElement: args.sourceElement,\n path: args.path,\n target: args.target || elementTarget(args.sourceElement, \"element-range\"),\n optional: args.optional,\n };\n};\nconst pushToken = (state, token, collection = \"tokens\") => {\n state[collection].push(token);\n};\nconst visitChildren = (element, state, path) => {\n elementChildren(element).forEach((child, index) => visitElement(child, state, `${path}/${localNameOf(child)}[${index}]`));\n};\nconst visitFraction = (element, state, path) => {\n const children = elementChildren(element);\n if (children[0])\n visitElement(children[0], state, `${path}/numerator`);\n pushToken(state, createToken({\n state,\n kind: \"structure\",\n role: \"fraction\",\n text: \"/\",\n sourceElement: element,\n path,\n target: elementTarget(element, \"element-range\"),\n }));\n if (children[1])\n visitElement(children[1], state, `${path}/denominator`);\n};\nconst visitFenced = (element, state, path) => {\n const open = element.getAttribute(\"open\") || \"(\";\n const close = element.getAttribute(\"close\") || \")\";\n pushToken(state, createToken({\n state,\n kind: \"operator\",\n role: open === \"|\" ? \"absolute-value-fence\" : \"open-fence\",\n text: open,\n sourceElement: element,\n path: `${path}/open`,\n target: elementTarget(element, \"element-range\"),\n }));\n visitChildren(element, state, path);\n pushToken(state, createToken({\n state,\n kind: \"operator\",\n role: close === \"|\" ? \"absolute-value-fence\" : \"close-fence\",\n text: close,\n sourceElement: element,\n path: `${path}/close`,\n target: elementTarget(element, \"element-range\"),\n }));\n};\nconst visitSuperscript = (element, state, path) => {\n const children = elementChildren(element);\n if (children[0])\n visitElement(children[0], state, `${path}/base`);\n const exponent = children[1];\n if (!exponent)\n return;\n const exponentText = textContentOf(exponent);\n if (SUPERSCRIPT_ALIASES.has(exponentText)) {\n // One token aliased to the power word (\"squared\" / \"cubed\"), targeting the\n // whole superscript so the spoken power word highlights the base-and-\n // exponent unit.\n pushToken(state, createToken({\n state,\n kind: \"structure\",\n role: \"superscript\",\n text: exponentText,\n normalized: exponentText,\n sourceElement: exponent,\n path: `${path}/exponent`,\n target: elementTarget(element, \"element-range\"),\n }));\n return;\n }\n visitElement(exponent, state, `${path}/exponent`);\n};\nconst visitOpaqueStructure = (element, state, path, role) => {\n // A single required, unmatchable token. The NUL-prefixed normalized value can\n // never equal a spoken token, so the cover check always falls back to the\n // whole-expression target when this structure is present — no per-glyph\n // guessing inside fractions-under-radicals, subscripts, accents, etc.\n pushToken(state, createToken({\n state,\n kind: \"structure\",\n role,\n text: textContentOf(element) || role,\n normalized: `\\u0000${role}`,\n sourceElement: element,\n path,\n target: elementTarget(element, \"element-range\"),\n }));\n};\nconst visitTable = (element, state, path) => {\n let rowNumber = 0;\n for (const child of elementChildren(element)) {\n if (localNameOf(child) === \"mtr\" || localNameOf(child) === \"mlabeledtr\") {\n rowNumber++;\n pushToken(state, createToken({\n state,\n kind: \"layout\",\n role: \"table-row\",\n text: `row-${rowNumber}`,\n normalized: `row-${rowNumber}`,\n sourceElement: child,\n path: `${path}/row[${rowNumber}]`,\n target: elementTarget(child, \"region-fallback\"),\n }), \"layoutTargets\");\n }\n visitElement(child, state, `${path}/${localNameOf(child)}[${rowNumber}]`);\n }\n};\nconst visitTokenElement = (element, state, path) => {\n const text = textContentOf(element);\n if (!text)\n return;\n const kind = tokenKindFor(localNameOf(element));\n const invisibleRole = kind === \"operator\" ? INVISIBLE_OPERATOR_ROLES.get(text) : undefined;\n const role = invisibleRole ??\n (kind === \"operator\" && (text === \"(\" || text === \")\")\n ? \"grouping-fence\"\n : kind);\n pushToken(state, createToken({\n state,\n kind,\n role,\n text,\n sourceElement: element,\n path,\n target: invisibleRole && element.parentElement\n ? elementTarget(element.parentElement, \"region-fallback\")\n : undefined,\n optional: Boolean(invisibleRole) || role === \"grouping-fence\",\n }));\n};\nconst visitElement = (element, state, path) => {\n const tagName = localNameOf(element);\n switch (tagName) {\n case \"annotation\":\n case \"annotation-xml\":\n return;\n case \"semantics\": {\n const presentation = elementChildren(element).find((child) => {\n const childName = localNameOf(child);\n return childName !== \"annotation\" && childName !== \"annotation-xml\";\n });\n if (presentation)\n visitElement(presentation, state, `${path}/presentation`);\n return;\n }\n case \"mi\":\n case \"mn\":\n case \"mo\":\n case \"mtext\":\n case \"ms\":\n case \"mspace\":\n visitTokenElement(element, state, path);\n return;\n case \"mfrac\":\n visitFraction(element, state, path);\n return;\n case \"msup\":\n visitSuperscript(element, state, path);\n return;\n case \"mfenced\":\n visitFenced(element, state, path);\n return;\n case \"mtable\":\n visitTable(element, state, path);\n return;\n case \"mphantom\":\n // Invisible spacing content — must not become spoken tokens.\n return;\n case \"maction\": {\n // Only the shown alternative (first child) is rendered/spoken.\n const shown = elementChildren(element)[0];\n if (shown)\n visitElement(shown, state, `${path}/action`);\n return;\n }\n default: {\n const opaqueRole = OPAQUE_STRUCTURE_ROLES.get(tagName);\n if (opaqueRole) {\n visitOpaqueStructure(element, state, path, opaqueRole);\n return;\n }\n visitChildren(element, state, path);\n }\n }\n};\nexport const tokenizeMathML = (mathElement) => {\n const state = {\n tokens: [],\n layoutTargets: [],\n nextId: 0,\n };\n visitElement(mathElement, state, \"/math\");\n return {\n tokens: state.tokens,\n layoutTargets: state.layoutTargets,\n expressionTarget: elementTarget(mathElement, \"region-fallback\"),\n };\n};\n","export const resolveHighlightTargetForBoundary = (args) => {\n if (!args.boundary)\n return args.alignment.fallbackTarget;\n const segment = args.alignment.segments.find((candidate) => candidate.speechTokenIds.includes(args.boundary.token.id));\n return segment?.target || args.alignment.fallbackTarget;\n};\nexport const resolveMatchedHighlightTargetForBoundary = (args) => {\n if (!args.boundary)\n return null;\n const segment = args.alignment.segments.find((candidate) => candidate.speechTokenIds.includes(args.boundary.token.id));\n return segment?.target || null;\n};\n","const MIN_EXACT_WORD_CONFIDENCE = 0.95;\n// Candidate spoken forms for a math token: its own normalized value plus every\n// spoken alias, each split into the sequence of words a TTS engine emits (e.g.\n// \"÷\" → [\"divided\", \"by\"], \"≤\" → [\"less\", \"than\", \"or\", \"equal\", \"to\"]). This is\n// what lets multi-word operator names match — a single speech token can never\n// equal \"divided by\". Speech tokens are already number-word normalized by the\n// speech tokenizer (two → 2), so no numeric mapping is repeated here.\nconst candidatePhrasesFor = (math) => {\n const phrases = [];\n const seen = new Set();\n const add = (value) => {\n const words = value.toLowerCase().trim().split(/\\s+/).filter(Boolean);\n if (words.length === 0)\n return;\n const key = words.join(\" \");\n if (seen.has(key))\n return;\n seen.add(key);\n phrases.push(words);\n };\n add(math.normalized);\n for (const alias of math.spokenAliases)\n add(alias);\n return phrases;\n};\n// Length (in speech tokens) of the longest candidate phrase that matches the\n// run of speech tokens starting at `startIndex`, or 0 if none match. Longest\n// match wins so a multi-word alias is preferred over a coincidental one-word\n// prefix.\nconst matchPhraseLengthAt = (speechTokens, startIndex, phrases) => {\n let best = 0;\n for (const phrase of phrases) {\n if (phrase.length <= best)\n continue;\n let matched = true;\n for (let i = 0; i < phrase.length; i++) {\n const token = speechTokens[startIndex + i];\n if (!token || token.normalized.toLowerCase() !== phrase[i]) {\n matched = false;\n break;\n }\n }\n if (matched)\n best = phrase.length;\n }\n return best;\n};\n// Greedy forward (monotonic) pass: each math token consumes the next run of\n// speech tokens that spells one of its candidate phrases. Optional math tokens\n// (invisible operators, grouping fences) are consumed only when present.\n// Unmatched speech tokens are skipped, which the perfect-cover check below then\n// treats as a miss.\nconst computeMonotonicMatches = (speechTokens, mathTokens) => {\n const matches = [];\n let speechIndex = 0;\n for (const math of mathTokens) {\n const phrases = candidatePhrasesFor(math);\n if (math.optional) {\n const consumed = matchPhraseLengthAt(speechTokens, speechIndex, phrases);\n if (consumed > 0) {\n matches.push({\n speechTokens: speechTokens.slice(speechIndex, speechIndex + consumed),\n math,\n });\n speechIndex += consumed;\n }\n continue;\n }\n while (speechIndex < speechTokens.length) {\n const consumed = matchPhraseLengthAt(speechTokens, speechIndex, phrases);\n if (consumed > 0) {\n matches.push({\n speechTokens: speechTokens.slice(speechIndex, speechIndex + consumed),\n math,\n });\n speechIndex += consumed;\n break;\n }\n speechIndex++;\n }\n }\n return matches;\n};\n// Word-level highlighting is all-or-nothing: it is emitted only when every\n// required math token AND every spoken token is accounted for. Anything less\n// falls back to a coarse whole-expression highlight, because \"false positives\n// are worse than coarse highlighting\" — a partial alignment risks underlining\n// the wrong glyph.\nconst isPerfectCover = (matches, speechTokens, mathTokens) => {\n const requiredTokenCount = mathTokens.filter((token) => !token.optional).length;\n const requiredMatched = matches.filter((match) => !match.math.optional).length;\n const consumedSpeech = matches.reduce((total, match) => total + match.speechTokens.length, 0);\n return (requiredTokenCount > 0 &&\n requiredMatched === requiredTokenCount &&\n consumedSpeech === speechTokens.length);\n};\nconst createSegments = (matches) => matches.map(({ speechTokens, math }) => ({\n // Every spoken word that spells this math token maps back to it, so a\n // boundary on any of those words (\"divided\" or \"by\") resolves to the\n // same glyph.\n speechTokenIds: speechTokens.map((token) => token.id),\n mathTokenIds: [math.id],\n score: 1,\n confidence: 1,\n target: math.target,\n}));\nexport const alignSpeechToMath = (args) => {\n const minConfidence = args.minExactWordConfidence ?? MIN_EXACT_WORD_CONFIDENCE;\n const matches = computeMonotonicMatches(args.speech.tokens, args.math.tokens);\n const confidence = isPerfectCover(matches, args.speech.tokens, args.math.tokens)\n ? 1\n : 0;\n return {\n segments: confidence >= minConfidence ? createSegments(matches) : [],\n confidence,\n fallbackTarget: args.math.expressionTarget,\n };\n};\n","import { extractSpokenText } from \"../ssml/spoken-text.js\";\nimport { createSpeechAlignmentTokenPattern } from \"../text-processing.js\";\n// Shared Unicode-aware tokenizer, identical to the catalog span aligner's, so\n// spoken text tokenizes the same way on both paths (see\n// `createSpeechAlignmentTokenPattern`).\nconst TOKEN_PATTERN = createSpeechAlignmentTokenPattern();\nconst NUMERIC_WORDS = new Map([\n [\"zero\", \"0\"],\n [\"one\", \"1\"],\n [\"two\", \"2\"],\n [\"three\", \"3\"],\n [\"four\", \"4\"],\n [\"five\", \"5\"],\n [\"six\", \"6\"],\n [\"seven\", \"7\"],\n [\"eight\", \"8\"],\n [\"nine\", \"9\"],\n [\"ten\", \"10\"],\n]);\nconst normalizedTokenValue = (value) => {\n const normalized = value.toLowerCase();\n return NUMERIC_WORDS.get(normalized) || normalized;\n};\nconst tokenizeSpokenText = (spokenText) => {\n const tokens = [];\n for (const match of spokenText.matchAll(TOKEN_PATTERN)) {\n const text = match[0];\n const start = match.index ?? 0;\n tokens.push({\n id: `speech-token-${tokens.length}`,\n text,\n normalized: normalizedTokenValue(text),\n start,\n end: start + text.length,\n sourceStart: start,\n sourceEnd: start + text.length,\n coordinateSystem: \"normalized-speech\",\n });\n }\n return tokens;\n};\nexport const tokenizeSpeechSource = (args) => {\n const extracted = extractSpokenText(args.speechText);\n return {\n speechText: args.speechText,\n spokenText: extracted.spokenText,\n tokens: tokenizeSpokenText(extracted.spokenText),\n rawToSpokenOffsetMap: extracted.rawToSpokenOffsetMap,\n boundaryOffsetSpace: extracted.unsupportedSemantic\n ? \"unsupported\"\n : extracted.hasMarkup\n ? \"raw-ssml\"\n : \"plain-spoken-text\",\n unsupportedSemantic: extracted.unsupportedSemantic,\n hasMarkup: extracted.hasMarkup,\n };\n};\nconst normalizeBoundaryWord = (word) => {\n if (!word)\n return null;\n if (/^<[^>]+>$/.test(word.trim()))\n return null;\n const match = word.match(TOKEN_PATTERN);\n if (!match?.[0])\n return null;\n return normalizedTokenValue(match[0]);\n};\nconst findTokenAtOffset = (tokens, offset) => tokens.find((token) => token.start <= offset && offset < token.end) || null;\nconst mapRawOffsetToSpokenOffset = (tokenization, position) => {\n const direct = tokenization.rawToSpokenOffsetMap.get(position);\n if (direct !== undefined)\n return direct;\n for (let offset = position; offset < tokenization.speechText.length; offset++) {\n const mapped = tokenization.rawToSpokenOffsetMap.get(offset);\n if (mapped !== undefined)\n return mapped;\n if (tokenization.speechText[offset] === \">\")\n break;\n }\n return null;\n};\nconst candidateForOffset = (tokenization, offset, length) => {\n if (offset === null)\n return null;\n const token = findTokenAtOffset(tokenization.tokens, offset);\n if (!token)\n return null;\n return {\n token,\n start: offset,\n length: Math.max(1, Math.min(length, token.end - offset)),\n confidence: 0.75,\n };\n};\nconst candidateMatchesWord = (candidate, boundaryWord) => {\n const normalizedBoundary = normalizeBoundaryWord(boundaryWord);\n return Boolean(candidate &&\n normalizedBoundary &&\n candidate.token.normalized === normalizedBoundary);\n};\nexport const resolveBoundaryToSpeechToken = (args) => {\n if (args.tokenization.boundaryOffsetSpace === \"unsupported\" ||\n !Number.isFinite(args.position) ||\n (args.boundaryWord && /^<[^>]+>$/.test(args.boundaryWord.trim()))) {\n return null;\n }\n const safeLength = Math.max(1, Number.isFinite(args.length) ? args.length : 1);\n const rawCandidate = candidateForOffset(args.tokenization, mapRawOffsetToSpokenOffset(args.tokenization, args.position), safeLength);\n const plainCandidate = candidateForOffset(args.tokenization, args.position >= 0 && args.position < args.tokenization.spokenText.length\n ? args.position\n : null, safeLength);\n if (candidateMatchesWord(rawCandidate, args.boundaryWord)) {\n return { ...rawCandidate, confidence: 1 };\n }\n if (candidateMatchesWord(plainCandidate, args.boundaryWord)) {\n return { ...plainCandidate, confidence: 1 };\n }\n if (args.boundaryWord && normalizeBoundaryWord(args.boundaryWord)) {\n return null;\n }\n return args.tokenization.boundaryOffsetSpace === \"raw-ssml\"\n ? rawCandidate || plainCandidate\n : plainCandidate || rawCandidate;\n};\nexport const resolveSpokenOffsetToSpeechToken = (args) => {\n if (args.tokenization.boundaryOffsetSpace === \"unsupported\" ||\n !Number.isFinite(args.position) ||\n (args.boundaryWord && /^<[^>]+>$/.test(args.boundaryWord.trim()))) {\n return null;\n }\n const safeLength = Math.max(1, Number.isFinite(args.length) ? args.length : 1);\n const spokenCandidate = candidateForOffset(args.tokenization, args.position >= 0 && args.position < args.tokenization.spokenText.length\n ? args.position\n : null, safeLength);\n if (candidateMatchesWord(spokenCandidate, args.boundaryWord)) {\n return { ...spokenCandidate, confidence: 1 };\n }\n if (args.boundaryWord && normalizeBoundaryWord(args.boundaryWord)) {\n return null;\n }\n return spokenCandidate;\n};\n","import { tokenizeMathML } from \"./mathml-tokenizer.js\";\nimport { resolveMatchedHighlightTargetForBoundary as resolveMatchedTargetForBoundary, resolveHighlightTargetForBoundary as resolveTargetForBoundary, } from \"./range-resolver.js\";\nimport { alignSpeechToMath } from \"./sequence-aligner.js\";\nimport { resolveBoundaryToSpeechToken, resolveSpokenOffsetToSpeechToken, tokenizeSpeechSource, } from \"./speech-tokenizer.js\";\nexport const createMathAwareAlignment = (args) => {\n const speech = tokenizeSpeechSource({ speechText: args.speechText });\n const math = tokenizeMathML(args.mathElement);\n return {\n speech,\n math,\n result: alignSpeechToMath({ speech, math }),\n };\n};\nexport const resolveHighlightTargetForBoundary = (alignment, args) => {\n const boundary = resolveBoundaryToSpeechToken({\n tokenization: alignment.speech,\n position: args.position,\n length: args.length,\n boundaryWord: args.boundaryWord,\n });\n return resolveTargetForBoundary({\n alignment: alignment.result,\n boundary,\n });\n};\nexport const resolveMatchedHighlightTargetForBoundary = (alignment, args) => {\n const boundary = resolveBoundaryToSpeechToken({\n tokenization: alignment.speech,\n position: args.position,\n length: args.length,\n boundaryWord: args.boundaryWord,\n });\n return resolveMatchedTargetForBoundary({\n alignment: alignment.result,\n boundary,\n });\n};\nexport const resolveMatchedHighlightTargetForSpokenBoundary = (alignment, args) => {\n const boundary = resolveSpokenOffsetToSpeechToken({\n tokenization: alignment.speech,\n position: args.position,\n length: args.length,\n boundaryWord: args.boundaryWord,\n });\n return resolveMatchedTargetForBoundary({\n alignment: alignment.result,\n boundary,\n });\n};\nexport const resolveUniqueMathTargetForBoundaryWord = (alignment, args) => {\n if (!args.boundaryWord || /^<[^>]+>$/.test(args.boundaryWord.trim())) {\n return null;\n }\n const boundaryToken = tokenizeSpeechSource({\n speechText: args.boundaryWord,\n }).tokens[0];\n if (!boundaryToken)\n return null;\n const matches = alignment.math.tokens.filter((token) => {\n const normalized = boundaryToken.normalized.toLowerCase();\n return (token.normalized.toLowerCase() === normalized ||\n token.spokenAliases.some((alias) => alias.toLowerCase() === normalized));\n });\n return matches.length === 1 ? matches[0].target : null;\n};\n","const MATHML_NAMESPACE = \"http://www.w3.org/1998/Math/MathML\";\nconst ALLOWED_MATHML_ELEMENTS = new Set([\n \"math\",\n \"maction\",\n \"menclose\",\n \"merror\",\n \"mfenced\",\n \"mfrac\",\n \"mi\",\n \"mmultiscripts\",\n \"mn\",\n \"mo\",\n \"mover\",\n \"mpadded\",\n \"mphantom\",\n \"mprescripts\",\n \"mroot\",\n \"mrow\",\n \"ms\",\n \"mspace\",\n \"msqrt\",\n \"mstyle\",\n \"msub\",\n \"msubsup\",\n \"msup\",\n \"mtable\",\n \"mtd\",\n \"mtext\",\n \"mtr\",\n \"munder\",\n \"munderover\",\n \"none\",\n \"semantics\",\n \"annotation\",\n \"annotation-xml\",\n]);\nconst ALLOWED_ATTRIBUTES = new Set([\n \"accent\",\n \"accentunder\",\n \"align\",\n \"bevelled\",\n \"class\",\n \"close\",\n \"columnalign\",\n \"columnlines\",\n \"columnspacing\",\n \"columnspan\",\n \"denomalign\",\n \"depth\",\n \"dir\",\n \"display\",\n \"encoding\",\n \"fence\",\n \"height\",\n \"href\",\n \"id\",\n \"largeop\",\n \"length\",\n \"linethickness\",\n \"lspace\",\n \"mathbackground\",\n \"mathcolor\",\n \"mathsize\",\n \"mathvariant\",\n \"maxsize\",\n \"minsize\",\n \"movablelimits\",\n \"notation\",\n \"numalign\",\n \"open\",\n \"rowalign\",\n \"rowlines\",\n \"rowspacing\",\n \"rowspan\",\n \"rspace\",\n \"scriptlevel\",\n \"scriptminsize\",\n \"scriptsizemultiplier\",\n \"selection\",\n \"separator\",\n \"separators\",\n \"stretchy\",\n \"subscriptshift\",\n \"supscriptshift\",\n \"symmetric\",\n \"width\",\n \"xmlns\",\n \"xml:lang\",\n]);\nconst escapeText = (value) => value.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\nconst escapeAttribute = (value) => escapeText(value).replace(/\"/g, \"&quot;\");\nconst isUnsafeAttribute = (name, value) => {\n const lowerName = name.toLowerCase();\n const lowerValue = value.trim().toLowerCase();\n if (lowerName.startsWith(\"on\"))\n return true;\n if (!ALLOWED_ATTRIBUTES.has(lowerName))\n return true;\n if (lowerValue.includes(\"javascript:\"))\n return true;\n if (lowerValue.includes(\"data:text/html\"))\n return true;\n return false;\n};\nconst isAllowedMathElement = (element) => {\n const localName = element.localName.toLowerCase();\n if (!ALLOWED_MATHML_ELEMENTS.has(localName))\n return false;\n const namespace = element.namespaceURI;\n return (!namespace ||\n namespace === MATHML_NAMESPACE ||\n namespace === \"http://www.w3.org/1999/xhtml\");\n};\nconst serializeMathNode = (node) => {\n if (node.nodeType === Node.TEXT_NODE) {\n return escapeText(node.textContent || \"\");\n }\n if (node.nodeType === Node.COMMENT_NODE) {\n return \"\";\n }\n if (node.nodeType !== Node.ELEMENT_NODE) {\n return null;\n }\n const element = node;\n if (!isAllowedMathElement(element))\n return null;\n const tagName = element.localName.toLowerCase();\n const attrs = [];\n for (const attr of Array.from(element.attributes)) {\n const name = attr.name.toLowerCase();\n if (isUnsafeAttribute(name, attr.value))\n continue;\n if (name === \"xmlns\" && attr.value !== MATHML_NAMESPACE)\n return null;\n attrs.push(`${name}=\"${escapeAttribute(attr.value)}\"`);\n }\n if (tagName === \"math\" && !attrs.some((attr) => attr.startsWith(\"xmlns=\"))) {\n attrs.unshift(`xmlns=\"${MATHML_NAMESPACE}\"`);\n }\n const children = [];\n for (const child of Array.from(element.childNodes)) {\n const serialized = serializeMathNode(child);\n if (serialized === null)\n return null;\n children.push(serialized);\n }\n const attrText = attrs.length > 0 ? ` ${attrs.join(\" \")}` : \"\";\n return `<${tagName}${attrText}>${children.join(\"\")}</${tagName}>`;\n};\nconst parseMathML = (input) => {\n if (typeof DOMParser !== \"undefined\") {\n return new DOMParser().parseFromString(input, \"application/xml\");\n }\n return null;\n};\nexport const canonicalizeMathML = (input) => {\n const trimmed = String(input || \"\").trim();\n if (!trimmed)\n return null;\n const parsed = parseMathML(trimmed);\n if (!parsed)\n return null;\n if (parsed.getElementsByTagName(\"parsererror\").length > 0)\n return null;\n const root = parsed.documentElement;\n if (!root || root.localName.toLowerCase() !== \"math\")\n return null;\n return serializeMathNode(root);\n};\n","import { canonicalizeMathML } from \"./mathml-sanitization.js\";\nimport { collectVisibleTextAndMap, isNodeExcludedFromSpeech, normalizeTextForSpeech, shouldInsertWordBoundarySpace, } from \"./text-processing.js\";\nconst createAccumulator = (options) => ({\n chars: [],\n map: new Map(),\n position: 0,\n inLeadingWhitespace: true,\n lastCharWasWhitespace: false,\n lastMapped: null,\n options,\n});\nconst isMathJaxElement = (element) => element.classList?.contains(\"MathJax\") ||\n element.tagName?.toLowerCase() === \"mjx-container\";\nconst isAssistiveMathElement = (element) => element.tagName?.toLowerCase() === \"mjx-assistive-mml\";\nconst isAnnotationElement = (element) => {\n const tagName = element.tagName?.toLowerCase();\n return tagName === \"annotation\" || tagName === \"annotation-xml\";\n};\nconst getDataMathML = (element) => {\n const value = element.getAttribute(\"data-mathml\");\n return value && value.trim() ? value : null;\n};\nconst findAssistiveMathML = (element) => {\n const assistive = element.querySelector(\"mjx-assistive-mml math\");\n return assistive?.outerHTML || null;\n};\nconst findCanonicalMathML = (element) => {\n if (element.tagName.toLowerCase() === \"math\") {\n return canonicalizeMathML(element.outerHTML);\n }\n const dataMath = getDataMathML(element);\n if (dataMath) {\n const canonical = canonicalizeMathML(dataMath);\n if (canonical)\n return canonical;\n }\n if (isMathJaxElement(element)) {\n const assistive = findAssistiveMathML(element);\n if (assistive) {\n const canonical = canonicalizeMathML(assistive);\n if (canonical)\n return canonical;\n }\n }\n return null;\n};\nconst isMathContainer = (element) => Boolean(findCanonicalMathML(element));\nconst TEXT_CHUNK_SOURCE_TAGS = new Set([\n \"P\",\n \"H1\",\n \"H2\",\n \"H3\",\n \"H4\",\n \"H5\",\n \"H6\",\n \"LI\",\n \"TD\",\n \"TH\",\n \"DD\",\n \"DT\",\n \"FIGCAPTION\",\n \"LABEL\",\n \"BUTTON\",\n]);\nconst TEXT_CHUNK_SOURCE_ROLES = new Set([\n \"heading\",\n \"listitem\",\n \"option\",\n \"radio\",\n \"row\",\n \"cell\",\n \"columnheader\",\n \"rowheader\",\n]);\nconst resolveTextChunkSourceElement = (textNode, root) => {\n let current = textNode.parentElement;\n let best = null;\n while (current && current !== root) {\n const role = (current.getAttribute(\"role\") || \"\").toLowerCase();\n const tagName = current.tagName.toUpperCase();\n if (TEXT_CHUNK_SOURCE_TAGS.has(tagName) ||\n TEXT_CHUNK_SOURCE_ROLES.has(role)) {\n best = current;\n break;\n }\n current = current.parentElement;\n }\n return best || root;\n};\nconst hasMathCandidate = (element) => Boolean(typeof element.querySelector === \"function\" &&\n element.querySelector(\"math, [data-mathml], .MathJax, mjx-container, mjx-assistive-mml\")) ||\n element.tagName?.toLowerCase() === \"math\" ||\n element.hasAttribute?.(\"data-mathml\") ||\n isMathJaxElement(element);\nconst appendCharacter = (acc, character, mapping) => {\n if (/[.,;:!?]/.test(character) &&\n acc.chars.length > 0 &&\n acc.chars[acc.chars.length - 1] === \" \") {\n acc.chars.pop();\n acc.position--;\n acc.map.delete(acc.position);\n }\n acc.chars.push(character);\n if (mapping) {\n acc.map.set(acc.position, mapping);\n acc.lastMapped = mapping;\n }\n else if (acc.lastMapped) {\n acc.map.set(acc.position, acc.lastMapped);\n }\n acc.position++;\n};\nconst shouldInsertBoundarySpace = (acc, nextCharacter) => {\n if (acc.inLeadingWhitespace ||\n acc.lastCharWasWhitespace ||\n acc.chars.length === 0) {\n return false;\n }\n const previous = acc.chars[acc.chars.length - 1];\n // Defer to the shared locale-aware decision (Intl.Segmenter, falling back to\n // alnum) so adjacent text nodes split into words consistently with the main\n // visible-text collector, instead of an ASCII-only heuristic.\n return shouldInsertWordBoundarySpace(previous, nextCharacter, acc.options);\n};\nconst appendTextNode = (acc, textNode) => {\n const raw = textNode.textContent || \"\";\n let appendedNonWhitespaceInNode = false;\n for (let i = 0; i < raw.length; i++) {\n const character = raw[i];\n const isWhitespace = /\\s/.test(character);\n if (acc.inLeadingWhitespace) {\n if (!isWhitespace) {\n acc.inLeadingWhitespace = false;\n appendCharacter(acc, character, { node: textNode, offset: i });\n appendedNonWhitespaceInNode = true;\n acc.lastCharWasWhitespace = false;\n }\n continue;\n }\n if (isWhitespace) {\n if (!acc.lastCharWasWhitespace) {\n appendCharacter(acc, \" \", { node: textNode, offset: i });\n }\n acc.lastCharWasWhitespace = true;\n continue;\n }\n if (!appendedNonWhitespaceInNode &&\n shouldInsertBoundarySpace(acc, character)) {\n appendCharacter(acc, \" \", { node: textNode, offset: i });\n }\n appendCharacter(acc, character, { node: textNode, offset: i });\n appendedNonWhitespaceInNode = true;\n acc.lastCharWasWhitespace = false;\n }\n};\nconst appendCollectedText = (acc, collected) => {\n for (let i = 0; i < collected.text.length; i++) {\n const character = collected.text[i];\n const isWhitespace = /\\s/.test(character);\n const mapping = collected.map.get(i) || null;\n const syntheticNode = mapping?.node || acc.lastMapped?.node || null;\n const syntheticOffset = mapping?.offset ?? acc.lastMapped?.offset ?? 0;\n const normalizedMapping = mapping\n ? { node: mapping.node, offset: mapping.offset }\n : syntheticNode\n ? { node: syntheticNode, offset: syntheticOffset }\n : null;\n if (acc.inLeadingWhitespace) {\n if (isWhitespace)\n continue;\n acc.inLeadingWhitespace = false;\n }\n if (isWhitespace) {\n if (!acc.lastCharWasWhitespace) {\n appendCharacter(acc, \" \", normalizedMapping);\n }\n acc.lastCharWasWhitespace = true;\n continue;\n }\n if (i === 0 && shouldInsertBoundarySpace(acc, character)) {\n appendCharacter(acc, \" \", normalizedMapping);\n }\n appendCharacter(acc, character, normalizedMapping);\n acc.lastCharWasWhitespace = false;\n if (mapping) {\n acc.map.set(acc.position - 1, {\n node: mapping.node,\n offset: mapping.offset,\n });\n acc.lastMapped = { node: mapping.node, offset: mapping.offset };\n }\n else if (syntheticNode) {\n acc.map.set(acc.position - 1, {\n node: syntheticNode,\n offset: syntheticOffset,\n });\n }\n }\n};\nconst textFallbackFromMathML = (mathml) => {\n if (typeof DOMParser === \"undefined\")\n return \"\";\n const parsed = new DOMParser().parseFromString(mathml, \"application/xml\");\n if (parsed.getElementsByTagName(\"parsererror\").length > 0)\n return \"\";\n const parts = [];\n const visit = (node) => {\n if (node.nodeType === 3) {\n const text = node.textContent || \"\";\n if (text.trim())\n parts.push(text);\n return;\n }\n if (node.nodeType !== 1)\n return;\n const element = node;\n if (isAnnotationElement(element))\n return;\n for (const child of Array.from(element.childNodes)) {\n visit(child);\n }\n };\n visit(parsed.documentElement);\n return normalizeTextForSpeech(parts.join(\" \"));\n};\nconst collectVisibleMathFallback = (element, canonicalMathML, options) => {\n const mathAcc = createAccumulator(options);\n const visit = (node) => {\n if (isNodeExcludedFromSpeech(node, element))\n return;\n if (node.nodeType === 3) {\n appendTextNode(mathAcc, node);\n return;\n }\n if (node.nodeType !== 1)\n return;\n const childElement = node;\n if (isAssistiveMathElement(childElement) ||\n isAnnotationElement(childElement)) {\n return;\n }\n for (const child of Array.from(childElement.childNodes)) {\n visit(child);\n }\n };\n visit(element);\n trimTrailingWhitespace(mathAcc);\n const text = normalizeTextForSpeech(mathAcc.chars.join(\"\"));\n if (text) {\n return { text, map: mathAcc.map };\n }\n const fallbackText = textFallbackFromMathML(canonicalMathML);\n if (!fallbackText) {\n return collectVisibleTextAndMap(element, options);\n }\n return {\n text: fallbackText,\n map: new Map(),\n };\n};\nconst trimTrailingWhitespace = (acc) => {\n while (acc.chars.length > 0 && /\\s/.test(acc.chars[acc.chars.length - 1])) {\n acc.chars.pop();\n acc.position--;\n acc.map.delete(acc.position);\n }\n};\nconst collectMathAware = (root, options) => {\n const acc = createAccumulator(options);\n const chunks = [];\n let textChunkStart = 0;\n let textChunkSourceElement;\n let containsMathMarkup = false;\n const flushTextChunk = () => {\n const text = normalizeTextForSpeech(acc.chars.slice(textChunkStart, acc.chars.length).join(\"\"));\n if (text) {\n chunks.push({\n type: \"text\",\n text,\n sourceElement: textChunkSourceElement,\n });\n }\n textChunkStart = acc.chars.length;\n textChunkSourceElement = undefined;\n };\n const processNode = (node) => {\n if (isNodeExcludedFromSpeech(node, root))\n return;\n if (node.nodeType === Node.TEXT_NODE) {\n const sourceElement = resolveTextChunkSourceElement(node, root);\n if (textChunkSourceElement && sourceElement !== textChunkSourceElement) {\n flushTextChunk();\n }\n textChunkSourceElement = sourceElement;\n appendTextNode(acc, node);\n return;\n }\n if (node.nodeType !== Node.ELEMENT_NODE)\n return;\n const element = node;\n if (isAssistiveMathElement(element))\n return;\n const canonicalMathML = findCanonicalMathML(element);\n if (canonicalMathML) {\n flushTextChunk();\n const collected = collectVisibleMathFallback(element, canonicalMathML, options);\n appendCollectedText(acc, collected);\n const fallbackText = normalizeTextForSpeech(collected.text);\n chunks.push({\n type: \"math\",\n mathml: canonicalMathML,\n fallbackText,\n sourceElement: element,\n });\n textChunkStart = acc.chars.length;\n containsMathMarkup = true;\n return;\n }\n for (const child of Array.from(element.childNodes)) {\n processNode(child);\n }\n };\n for (const child of Array.from(root.childNodes)) {\n processNode(child);\n }\n trimTrailingWhitespace(acc);\n flushTextChunk();\n const visibleText = acc.chars.join(\"\");\n while (acc.map.has(visibleText.length)) {\n acc.map.delete(visibleText.length);\n }\n return {\n visibleText,\n map: acc.map,\n chunks,\n containsMathMarkup,\n };\n};\nexport const collectMathAwareTextAndMap = (element, options) => {\n if (!hasMathCandidate(element)) {\n const { text, map } = collectVisibleTextAndMap(element, options);\n return {\n visibleText: text,\n map,\n chunks: text ? [{ type: \"text\", text }] : [],\n containsMathMarkup: false,\n };\n }\n return collectMathAware(element, options);\n};\n","import { normalizeTextForSpeech } from \"./text-processing.js\";\nlet sreLoadPromise = null;\nlet sreOperationQueue = Promise.resolve();\nconst normalizeLocale = (language) => (language || \"en\").split(\"-\")[0].toLowerCase() || \"en\";\nconst defaultLoadSre = async () => {\n if (!sreLoadPromise) {\n sreLoadPromise = import(\"speech-rule-engine\").then((module) => {\n const candidate = module.default ||\n module;\n if (!candidate || typeof candidate.toSpeech !== \"function\") {\n throw new Error(\"speech-rule-engine did not expose toSpeech\");\n }\n return candidate;\n });\n }\n return sreLoadPromise;\n};\n// SRE's ClearSpeak rule set is English-only; MathSpeak is localized to many more\n// locales. Use ClearSpeak for English (highest-quality math prose) and MathSpeak\n// elsewhere, so non-English content gets locale-appropriate voicing instead of\n// silently falling back to English ClearSpeak rules.\nconst domainForLocale = (locale) => locale === \"en\" ? \"clearspeak\" : \"mathspeak\";\nconst isPlainRecord = (value) => !!value && typeof value === \"object\" && !Array.isArray(value);\nconst trimOption = (value) => typeof value === \"string\" && value.trim() ? value.trim() : undefined;\nexport const normalizeSREMathSpeechOptions = (options) => {\n if (!isPlainRecord(options))\n return undefined;\n const domain = trimOption(options.domain);\n const style = trimOption(options.style);\n const engineOptions = isPlainRecord(options.engineOptions)\n ? options.engineOptions\n : undefined;\n if (!domain && !style && !engineOptions)\n return undefined;\n return {\n ...(domain ? { domain } : {}),\n ...(style ? { style } : {}),\n ...(engineOptions ? { engineOptions } : {}),\n };\n};\nconst setupSre = async (sre, language, markup, mathSpeech) => {\n const locale = normalizeLocale(language);\n const normalizedMathSpeech = normalizeSREMathSpeechOptions(mathSpeech);\n await sre.setupEngine?.({\n ...(normalizedMathSpeech?.engineOptions || {}),\n locale,\n domain: normalizedMathSpeech?.domain || domainForLocale(locale),\n ...(normalizedMathSpeech?.style\n ? { style: normalizedMathSpeech.style }\n : {}),\n modality: \"speech\",\n markup,\n });\n await sre.engineReady?.();\n};\nconst runSerializedSreOperation = async (operation) => {\n const result = sreOperationQueue.then(operation, operation);\n sreOperationQueue = result.then(() => undefined, () => undefined);\n return result;\n};\nconst toSpeechWithSreSettings = async (sre, mathml, language, markup, mathSpeech) => runSerializedSreOperation(async () => {\n await setupSre(sre, language, markup, mathSpeech);\n return sre.toSpeech(mathml);\n});\n// SRE's SSML rendering wraps the spoken words in highlight-safe structural tags\n// (`speak`, `prosody`, `say-as interpret-as=\"character\"`, `break`), all handled\n// by `extractSpokenText`, so word-boundary offsets into the raw SSML still map\n// back to spoken tokens. SRE also prepends an XML prolog (`<?xml …?>`); AWS\n// Polly and Google Cloud TTS reject SSML that does not begin with `<speak>`, so\n// we strip the prolog here. The stripped string is the single source of truth:\n// it is both what the provider receives and what the alignment tokenizes, so\n// offsets stay consistent. We only accept output that contains a `<speak>`\n// element, so a bad/empty render degrades to plain text.\nconst stripXmlProlog = (ssml) => ssml.replace(/^\\s*<\\?xml[^>]*\\?>\\s*/i, \"\");\nconst generateMathSsml = async (sre, mathml, language, mathSpeech) => {\n try {\n const ssml = stripXmlProlog(await toSpeechWithSreSettings(sre, mathml, language, \"ssml\", mathSpeech));\n return ssml.includes(\"<speak\") ? ssml : null;\n }\n catch (error) {\n console.debug(\"[TTSService] Math SSML generation failed; using plain\", {\n message: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n};\nexport const resolveMathSpeechFromChunks = async (chunks, options = {}) => {\n if (!chunks.some((chunk) => chunk.type === \"math\")) {\n return {\n speechText: normalizeTextForSpeech(chunks\n .map((chunk) => chunk.type === \"text\" ? chunk.text : chunk.fallbackText)\n .join(\" \")),\n usedMathSpeech: false,\n usedFallback: false,\n };\n }\n let sre = null;\n let usedMathSpeech = false;\n let usedFallback = false;\n const loadSre = options.loadSre || defaultLoadSre;\n const speechParts = [];\n for (const chunk of chunks) {\n if (chunk.type === \"text\") {\n speechParts.push(chunk.text);\n continue;\n }\n try {\n if (!sre) {\n sre = await loadSre();\n }\n const speech = normalizeTextForSpeech(await toSpeechWithSreSettings(sre, chunk.mathml, options.language, \"none\", options.mathSpeech));\n if (speech) {\n speechParts.push(speech);\n usedMathSpeech = true;\n continue;\n }\n usedFallback = true;\n speechParts.push(chunk.fallbackText);\n }\n catch (error) {\n usedFallback = true;\n console.debug(\"[TTSService] Math speech generation failed; using visible fallback\", {\n message: error instanceof Error ? error.message : String(error),\n });\n speechParts.push(chunk.fallbackText);\n }\n }\n // Generated-SSML path: only meaningful for a single math chunk (the runtime\n // composes one chunk per equation). Computed after the plain pass so the\n // markup: \"none\" `speechText` above is unchanged. The \"none\" → \"ssml\"\n // engine reconfiguration happens sequentially within this call.\n const speechText = normalizeTextForSpeech(speechParts.join(\" \"));\n let ssml;\n if (options.produceSsml &&\n sre &&\n usedMathSpeech &&\n chunks.length === 1 &&\n chunks[0].type === \"math\") {\n const generated = await generateMathSsml(sre, chunks[0].mathml, options.language, options.mathSpeech);\n ssml = generated ?? undefined;\n }\n return {\n speechText,\n usedMathSpeech,\n usedFallback,\n ssml,\n };\n};\n","import { resolveMathSpeechFromChunks, } from \"../math-speech.js\";\nimport { normalizeTextForSpeech } from \"../text-processing.js\";\nimport { segmentSentences as segmentTextToSentences } from \"../text-segmentation.js\";\nconst defaultMathSpeechResolver = (chunk, options) => resolveMathSpeechFromChunks([chunk], options);\nconst normalizeLocale = (language) => (language || \"en\").split(\"-\")[0].toLowerCase() || \"en\";\nconst PRESERVE_PROSE_CHUNK_TAGS = new Set([\n \"H1\",\n \"H2\",\n \"H3\",\n \"H4\",\n \"H5\",\n \"H6\",\n \"LI\",\n \"LABEL\",\n \"BUTTON\",\n]);\nconst PRESERVE_PROSE_CHUNK_ROLES = new Set([\n \"heading\",\n \"listitem\",\n \"option\",\n \"radio\",\n]);\nconst shouldPreserveProseChunk = (chunk) => {\n if (chunk.type !== \"text\" || !chunk.sourceElement)\n return false;\n const tagName = chunk.sourceElement.tagName.toUpperCase();\n const role = (chunk.sourceElement.getAttribute(\"role\") || \"\").toLowerCase();\n return (PRESERVE_PROSE_CHUNK_TAGS.has(tagName) ||\n PRESERVE_PROSE_CHUNK_ROLES.has(role));\n};\n/**\n * Assemble an anchor-free speech plan from already-collected math-aware chunks.\n *\n * PURE: no DOM walking, no app-service imports. Preserves the spoken-text and\n * visible-span bookkeeping from the inline generated path, so the runtime output\n * is stable once serialized to plain text.\n */\nexport const assembleGeneratedSpeech = async (args) => {\n const resolveMathSpeech = args.resolveMathSpeech ?? defaultMathSpeechResolver;\n const { visibleText } = args;\n const segments = [];\n // Cursor-based span tracking:\n // locate each chunk's normalized text within the aggregate visible text,\n // advancing a cursor so math fallbacks reserve their span even though only\n // prose spans are sliced for highlighting.\n let visibleCursor = 0;\n const nextVisibleSpan = (text) => {\n const normalized = normalizeTextForSpeech(text);\n const found = visibleText.indexOf(normalized, visibleCursor);\n const start = found >= 0 ? found : visibleCursor;\n const end = start + normalized.length;\n visibleCursor = end;\n return { start, end };\n };\n const speechParts = [];\n for (let index = 0; index < args.chunks.length; index++) {\n const chunk = args.chunks[index];\n if (chunk.type === \"text\") {\n const proseSegments = shouldPreserveProseChunk(chunk)\n ? [{ text: chunk.text, offset: 0 }]\n : segmentTextToSentences(chunk.text, {\n locale: args.language,\n });\n for (const prose of proseSegments) {\n const text = normalizeTextForSpeech(prose.text);\n if (!text)\n continue;\n const visibleSpan = nextVisibleSpan(text);\n segments.push({\n sourceChunkIndex: index,\n segment: {\n kind: \"prose\",\n spokenText: text,\n visibleText: text,\n visibleSpan,\n },\n });\n speechParts.push(text);\n }\n continue;\n }\n const visibleSpan = nextVisibleSpan(chunk.fallbackText);\n const generated = await resolveMathSpeech(chunk, {\n language: args.language,\n produceSsml: args.produceSsml,\n mathSpeech: args.mathSpeech,\n });\n const usedFallback = !generated.speechText;\n const spokenText = generated.speechText || chunk.fallbackText;\n segments.push({\n sourceChunkIndex: index,\n segment: {\n kind: \"math\",\n spokenText,\n mathml: chunk.mathml,\n fallbackText: chunk.fallbackText,\n visibleSpan,\n usedFallback,\n ssml: generated.ssml,\n },\n });\n speechParts.push(spokenText);\n }\n return {\n segments,\n locale: normalizeLocale(args.language),\n visibleText,\n plainSpeechText: normalizeTextForSpeech(speechParts.join(\" \")),\n };\n};\n","import { normalizeSREMathSpeechOptions, resolveMathSpeechFromChunks, } from \"../math-speech.js\";\nconst normalizeLocale = (language) => (language || \"en\").split(\"-\")[0].toLowerCase() || \"en\";\n// Bump when speech-rule-engine output semantics change in a way that must\n// invalidate cached spoken text (e.g. an SRE upgrade with different phrasing).\nconst SRE_CACHE_VERSION = \"sre-v1\";\nconst DEFAULT_MAX_ENTRIES = 256;\nconst stableStringify = (value) => {\n if (Array.isArray(value)) {\n return `array:[${value.map(stableStringify).join(\",\")}]`;\n }\n if (value && typeof value === \"object\") {\n return `object:{${Object.entries(value)\n .sort(([left], [right]) => left.localeCompare(right))\n .map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`)\n .join(\",\")}}`;\n }\n if (value === null)\n return \"null:null\";\n if (typeof value === \"undefined\")\n return \"undefined:\";\n if (typeof value === \"function\")\n return `function:${value.name || \"anonymous\"}`;\n if (typeof value === \"symbol\")\n return `symbol:${String(value)}`;\n if (typeof value === \"bigint\")\n return `bigint:${value.toString()}`;\n if (typeof value === \"number\") {\n return Number.isFinite(value)\n ? `number:${value}`\n : `number:${String(value)}`;\n }\n return `${typeof value}:${JSON.stringify(value)}`;\n};\nconst cacheKeyFor = (language, produceSsml, mathSpeech, mathml) => `${SRE_CACHE_VERSION}\\u0000${normalizeLocale(language)}\\u0000${produceSsml ? \"ssml\" : \"plain\"}\\u0000${stableStringify(mathSpeech ?? null)}\\u0000${mathml}`;\n/**\n * Build a memoized {@link MathSpeechResolver}.\n *\n * Caches only DOM-free spoken-text results keyed by\n * `(SRE version, locale, output mode, SRE mathSpeech options, MathML source)`.\n * Never caches DOM nodes or maps. Bounded by a simple LRU so long sessions do\n * not grow unbounded.\n */\nexport const createMemoizedMathSpeechResolver = (options = {}) => {\n const maxEntries = Math.max(1, options.maxEntries ?? DEFAULT_MAX_ENTRIES);\n const resolve = options.resolve ??\n ((chunk, opts) => resolveMathSpeechFromChunks([chunk], opts));\n const cache = new Map();\n const setCached = (key, value) => {\n cache.delete(key);\n cache.set(key, value);\n while (cache.size > maxEntries) {\n const oldest = cache.keys().next().value;\n if (oldest !== undefined)\n cache.delete(oldest);\n }\n };\n return async (chunk, opts) => {\n const mathSpeech = normalizeSREMathSpeechOptions(opts.mathSpeech);\n const produceSsml = opts.produceSsml === true;\n const key = cacheKeyFor(opts.language, produceSsml, mathSpeech, chunk.mathml);\n const cached = cache.get(key);\n if (cached) {\n // Refresh LRU recency.\n cache.delete(key);\n cache.set(key, cached);\n return cached;\n }\n const resolved = await resolve(chunk, { ...opts, mathSpeech });\n if (produceSsml && resolved.ssml && maxEntries > 1) {\n setCached(cacheKeyFor(opts.language, false, mathSpeech, chunk.mathml), {\n speechText: resolved.speechText,\n usedMathSpeech: resolved.usedMathSpeech,\n usedFallback: resolved.usedFallback,\n });\n }\n setCached(key, resolved);\n return resolved;\n };\n};\n","import { resolveSpokenBoundaryOffset } from \"../catalog-span-alignment.js\";\nimport { resolveBoundaryToSpeechToken, tokenizeSpeechSource, } from \"../math-alignment/speech-tokenizer.js\";\nconst normalizeBoundaryWord = (word) => {\n if (!word || /^<[^>]+>$/.test(word.trim()))\n return null;\n return (tokenizeSpeechSource({ speechText: word }).tokens[0]?.normalized || null);\n};\n// Resolve a provider boundary for a chunk that carries no catalog span\n// alignment — notably the generated-SSML math path, whose `speechText` is a\n// raw `<speak>` document. The provider's offset is an index into `speechText`\n// exactly as it was sent (which may include SSML tags), so we tokenize that\n// same string and let the shared speech tokenizer translate the offset into the\n// extracted spoken text. Returns the boundary in spoken-text space alongside\n// that spoken text, so the downstream word/offset checks share one coordinate\n// system. The previous \"direct\" path treated the raw-SSML offset as a\n// spoken-text offset and rejected every math boundary (PIE-623 regression).\nconst speechSourceBoundary = (chunk, event) => {\n const tokenization = tokenizeSpeechSource({ speechText: chunk.speechText });\n if (!Number.isFinite(event.position)) {\n return { boundary: null, spokenText: tokenization.spokenText };\n }\n const resolved = resolveBoundaryToSpeechToken({\n tokenization,\n position: event.position,\n length: event.length,\n boundaryWord: event.word,\n });\n return {\n boundary: resolved\n ? { start: resolved.start, length: resolved.length }\n : null,\n spokenText: tokenization.spokenText,\n };\n};\nconst tokenAtOffsetMatches = (speechText, start, normalizedWord) => {\n if (!normalizedWord)\n return true;\n const token = tokenizeSpeechSource({ speechText }).tokens.find((candidate) => candidate.start <= start && start < candidate.end);\n return token?.normalized === normalizedWord;\n};\nexport const normalizeBoundaryEvent = (chunk, event) => {\n const normalizedWord = normalizeBoundaryWord(event.word);\n if (chunk.id !== event.chunkId) {\n return {\n chunkId: event.chunkId,\n normalizedWord,\n chunkSpokenStart: null,\n chunkSpokenEnd: null,\n confidence: 0,\n reason: \"boundary chunk id did not match highlight chunk\",\n };\n }\n if (event.providerOffsetSpace === \"unknown\" ||\n chunk.offsetSpace === \"unsupported\") {\n return {\n chunkId: chunk.id,\n normalizedWord,\n chunkSpokenStart: null,\n chunkSpokenEnd: null,\n confidence: 0,\n reason: \"boundary offset space is unsupported\",\n };\n }\n let boundary;\n let spokenText;\n if (chunk.catalogAlignment) {\n boundary = resolveSpokenBoundaryOffset(chunk.catalogAlignment, event.position, event.length, event.word);\n spokenText = chunk.catalogAlignment.spokenText;\n }\n else {\n const resolved = speechSourceBoundary(chunk, event);\n boundary = resolved.boundary;\n spokenText = resolved.spokenText;\n }\n if (!boundary) {\n return {\n chunkId: chunk.id,\n normalizedWord,\n chunkSpokenStart: null,\n chunkSpokenEnd: null,\n confidence: 0,\n reason: \"could not resolve provider boundary to chunk speech\",\n };\n }\n if (!tokenAtOffsetMatches(spokenText, boundary.start, normalizedWord)) {\n return {\n chunkId: chunk.id,\n normalizedWord,\n chunkSpokenStart: null,\n chunkSpokenEnd: null,\n confidence: 0,\n reason: \"could not resolve provider boundary to matching word\",\n };\n }\n return {\n chunkId: chunk.id,\n normalizedWord,\n chunkSpokenStart: boundary.start,\n chunkSpokenEnd: boundary.start + boundary.length,\n confidence: normalizedWord ? 1 : 0.75,\n reason: chunk.catalogAlignment\n ? \"resolved through catalog alignment\"\n : \"resolved through speech tokenization\",\n };\n};\n","export const createHighlightDecision = (input) => {\n if (input.semanticTarget) {\n return {\n activeTarget: input.semanticTarget,\n regionTarget: input.regionTarget,\n quality: input.semanticTarget.quality === \"exact-word\"\n ? \"exact-word\"\n : input.semanticTarget.quality === \"expression\"\n ? \"expression\"\n : \"semantic-token\",\n confidence: input.confidence,\n reason: input.reason,\n };\n }\n if (input.expressionTarget) {\n return {\n activeTarget: input.expressionTarget,\n regionTarget: input.regionTarget,\n quality: \"expression\",\n confidence: input.confidence,\n reason: input.reason,\n };\n }\n return {\n activeTarget: null,\n regionTarget: input.regionTarget,\n quality: \"region\",\n confidence: input.confidence,\n reason: input.reason,\n };\n};\n","import { isNodeHiddenForTTS } from \"../text-processing.js\";\nconst MATHML_LEAF_TO_MATHJAX = new Map([\n [\"mi\", \"mjx-mi\"],\n [\"mn\", \"mjx-mn\"],\n [\"mo\", \"mjx-mo\"],\n [\"mtext\", \"mjx-mtext\"],\n]);\nconst MATHML_LEAF_SELECTOR = \"mi,mn,mo,mtext\";\nconst MATHJAX_LEAF_SELECTOR = \"mjx-mi,mjx-mn,mjx-mo,mjx-mtext\";\n// 2D layouts MathJax renders with extra, glyph-only nodes (radical surds,\n// fraction bars drawn as borders, table scaffolding) that have no source-MathML\n// leaf counterpart. They break the 1:1 token correspondence we rely on below,\n// so we refuse positional mapping inside them and fall back to the whole\n// expression instead of guessing.\nconst UNSUPPORTED_MATHJAX_LAYOUT_SELECTOR = [\n \"mjx-mfrac\",\n \"mjx-msqrt\",\n \"mjx-mroot\",\n \"mjx-mtable\",\n \"mjx-munder\",\n \"mjx-mover\",\n \"mjx-munderover\",\n].join(\",\");\nconst nearestElement = (target) => {\n if (target.type === \"text-range\")\n return target.node.parentElement;\n return target.element;\n};\nconst owningMathJaxContainer = (element) => {\n let current = element;\n while (current) {\n if (current.localName?.toLowerCase() === \"mjx-container\")\n return current;\n current = current.parentElement;\n }\n return null;\n};\nconst isVisibleNativeTarget = (element) => {\n if (!element)\n return false;\n if (owningMathJaxContainer(element))\n return false;\n return !isNodeHiddenForTTS(element);\n};\nconst hasVisibleGeometry = (element) => {\n const rect = element.getBoundingClientRect?.();\n return Boolean(rect && rect.width > 0 && rect.height > 0);\n};\nconst closestMathElement = (element) => {\n let current = element;\n while (current) {\n if (current.localName?.toLowerCase() === \"math\")\n return current;\n current = current.parentElement;\n }\n return null;\n};\n// MathJax CHTML renders each source-MathML token (mi/mn/mo/mtext) as exactly\n// one mjx-* token in the same document order — including invisible operators,\n// which it keeps as zero-size nodes. The original <math> survives, clipped, in\n// mjx-assistive-mml, so its glyph text nodes are not visible and the visible\n// CHTML tokens carry no readable textContent (glyphs come from web fonts).\n// We therefore map a source token to its rendered glyph by *structural\n// position* rather than text, but only after proving the two leaf lists are\n// isomorphic (equal length, matching token type at every index). When the\n// structure diverges we refuse to guess and let the caller fall back to the\n// whole expression. \"False positives are worse than coarse highlighting.\"\nconst tokensAreIsomorphic = (mathLeaves, chtmlLeaves) => {\n if (mathLeaves.length === 0)\n return false;\n if (mathLeaves.length !== chtmlLeaves.length)\n return false;\n for (let index = 0; index < mathLeaves.length; index += 1) {\n const expected = MATHML_LEAF_TO_MATHJAX.get(mathLeaves[index].localName.toLowerCase());\n if (!expected)\n return false;\n if (chtmlLeaves[index].localName.toLowerCase() !== expected)\n return false;\n }\n return true;\n};\nconst resolveMathJaxTokenByPosition = (semanticElement, container) => {\n if (!semanticElement)\n return null;\n if (!MATHML_LEAF_TO_MATHJAX.has(semanticElement.localName.toLowerCase()))\n return null;\n if (container.querySelector(UNSUPPORTED_MATHJAX_LAYOUT_SELECTOR))\n return null;\n const sourceMath = closestMathElement(semanticElement);\n const renderedMath = container.querySelector(\"mjx-math\");\n if (!sourceMath || !renderedMath)\n return null;\n const mathLeaves = Array.from(sourceMath.querySelectorAll(MATHML_LEAF_SELECTOR));\n const index = mathLeaves.indexOf(semanticElement);\n if (index < 0)\n return null;\n const chtmlLeaves = Array.from(renderedMath.querySelectorAll(MATHJAX_LEAF_SELECTOR));\n if (!tokensAreIsomorphic(mathLeaves, chtmlLeaves))\n return null;\n const token = chtmlLeaves[index];\n // The matched token must be a real, visible glyph. We deliberately do NOT\n // run isNodeHiddenForTTS here: MathJax marks its visual CHTML\n // (mjx-math) with aria-hidden=\"true\" because the accessible tree lives in\n // the clipped mjx-assistive-mml. aria-hidden is correct for screen readers\n // but irrelevant for a visual highlight — the glyph is painted on screen.\n // Visible geometry is the right test: it rejects display:none nodes and\n // zero-size invisible operators (e.g. U+2062 invisible-times, which is\n // never spoken anyway) without discarding the real, on-screen tokens.\n if (!token || !hasVisibleGeometry(token))\n return null;\n return token;\n};\nexport const classifyMathHighlightCapability = (mathElement) => {\n const container = owningMathJaxContainer(mathElement);\n if (container) {\n // 2D MathJax layouts add glyph-only nodes with no source-MathML\n // counterpart, so positional mapping is unsafe — commit to expression.\n if (container.querySelector(UNSUPPORTED_MATHJAX_LAYOUT_SELECTOR)) {\n return \"expression\";\n }\n const sourceMath = closestMathElement(mathElement) ?? mathElement;\n const renderedMath = container.querySelector(\"mjx-math\");\n if (!renderedMath)\n return \"expression\";\n const mathLeaves = Array.from(sourceMath.querySelectorAll(MATHML_LEAF_SELECTOR));\n const chtmlLeaves = Array.from(renderedMath.querySelectorAll(MATHJAX_LEAF_SELECTOR));\n if (!tokensAreIsomorphic(mathLeaves, chtmlLeaves))\n return \"expression\";\n // At least one rendered token must paint a real glyph; otherwise a\n // per-token highlight would have nothing visible to land on.\n return chtmlLeaves.some((leaf) => hasVisibleGeometry(leaf))\n ? \"token\"\n : \"expression\";\n }\n // Native MathML: every leaf is a real, browser-positioned element, so\n // per-token highlighting is reliable even inside 2D layouts (fractions,\n // radicals). It is token-capable as long as a visible leaf exists.\n const sourceMath = closestMathElement(mathElement) ?? mathElement;\n const leaves = Array.from(sourceMath.querySelectorAll(MATHML_LEAF_SELECTOR));\n return leaves.some((leaf) => !isNodeHiddenForTTS(leaf))\n ? \"token\"\n : \"expression\";\n};\nconst resolveRenderedMathTargetUncached = (target) => {\n const element = nearestElement(target);\n const mathJaxContainer = owningMathJaxContainer(element);\n if (mathJaxContainer) {\n const visibleToken = resolveMathJaxTokenByPosition(element, mathJaxContainer);\n if (visibleToken) {\n return {\n type: \"element\",\n quality: \"semantic-token\",\n element: visibleToken,\n };\n }\n return {\n type: \"element\",\n quality: \"expression\",\n element: mathJaxContainer,\n };\n }\n if (target.type === \"text-range\") {\n if (!isVisibleNativeTarget(target.node.parentElement))\n return null;\n return {\n type: \"text-range\",\n quality: \"semantic-token\",\n node: target.node,\n startOffset: target.startOffset,\n endOffset: target.endOffset,\n };\n }\n if (!isVisibleNativeTarget(target.element))\n return null;\n return {\n type: \"element\",\n quality: target.quality === \"region-fallback\" ? \"expression\" : \"semantic-token\",\n element: target.element,\n };\n};\nexport const resolveRenderedMathTarget = resolveRenderedMathTargetUncached;\nexport const createRenderedMathTargetResolver = () => {\n const mathJaxTargetCache = new WeakMap();\n return (target) => {\n const element = nearestElement(target);\n const mathJaxContainer = owningMathJaxContainer(element);\n if (!element || !mathJaxContainer) {\n return resolveRenderedMathTargetUncached(target);\n }\n if (mathJaxTargetCache.has(element)) {\n return mathJaxTargetCache.get(element) ?? null;\n }\n const rendered = resolveRenderedMathTargetUncached(target);\n mathJaxTargetCache.set(element, rendered);\n return rendered;\n };\n};\n","import { resolveMatchedHighlightTargetForSpokenBoundary, resolveUniqueMathTargetForBoundaryWord, } from \"../math-alignment/index.js\";\nimport { resolveRenderedMathTarget, } from \"./rendered-math-target-resolver.js\";\nexport const resolveMathBoundaryTarget = (chunk, boundary, event, candidates = chunk.mathAlignments, renderedResolver = resolveRenderedMathTarget) => {\n if (boundary.chunkSpokenStart === null || boundary.chunkSpokenEnd === null) {\n return null;\n }\n // Prefer a precise per-token target across all candidate equations before\n // settling for a coarse expression fallback: scan every candidate for a\n // semantic-token first, remembering the first expression-quality hit only as\n // a last resort.\n let expressionFallback = null;\n for (const mathAlignment of candidates) {\n const target = resolveMatchedHighlightTargetForSpokenBoundary(mathAlignment.alignment, {\n position: boundary.chunkSpokenStart,\n length: Math.max(1, boundary.chunkSpokenEnd - boundary.chunkSpokenStart),\n boundaryWord: event.word,\n }) ||\n resolveUniqueMathTargetForBoundaryWord(mathAlignment.alignment, {\n boundaryWord: event.word,\n });\n if (!target)\n continue;\n const rendered = renderedResolver(target);\n if (!rendered)\n continue;\n if (rendered.quality === \"semantic-token\")\n return rendered;\n expressionFallback ??= rendered;\n }\n return expressionFallback;\n};\n","export const createRangeFromVisibleMap = (visibleMap, start, end) => {\n if (!visibleMap || typeof document === \"undefined\")\n return null;\n if (end <= start)\n return null;\n const startMapping = visibleMap.get(start);\n let endMapping = visibleMap.get(Math.max(start, end - 1));\n if (!startMapping)\n return null;\n if (!endMapping)\n endMapping = startMapping;\n try {\n const range = document.createRange();\n range.setStart(startMapping.node, startMapping.offset);\n range.setEnd(endMapping.node, endMapping.offset + 1);\n return range;\n }\n catch {\n return null;\n }\n};\n","import { resolveVisibleSpanForBoundary } from \"../catalog-span-alignment.js\";\nimport { createRangeFromVisibleMap } from \"./visible-map-range.js\";\nexport const resolveProseBoundaryTarget = (chunk, boundary) => {\n if (!chunk.catalogAlignment || boundary.chunkSpokenStart === null)\n return null;\n const visibleSpan = resolveVisibleSpanForBoundary(chunk.catalogAlignment, boundary.chunkSpokenStart);\n if (!visibleSpan)\n return null;\n const range = createRangeFromVisibleMap(chunk.visibleMap, visibleSpan.start, visibleSpan.end);\n if (!range)\n return null;\n return {\n type: \"range\",\n quality: chunk.catalogAlignment.playbackMode === \"exact-word\"\n ? \"exact-word\"\n : \"semantic-token\",\n range,\n };\n};\n","import { normalizeBoundaryEvent } from \"./boundary-normalizer.js\";\nimport { createHighlightDecision } from \"./highlight-policy.js\";\nimport { resolveMathBoundaryTarget } from \"./math-semantic-resolver.js\";\nimport { resolveProseBoundaryTarget } from \"./prose-boundary-resolver.js\";\nimport { classifyMathHighlightCapability, createRenderedMathTargetResolver, } from \"./rendered-math-target-resolver.js\";\nconst regionTargetFor = (chunk) => chunk.regionRange\n ? {\n type: \"range\",\n quality: \"region\",\n range: chunk.regionRange,\n }\n : chunk.regionElement\n ? {\n type: \"element\",\n quality: \"region\",\n element: chunk.regionElement,\n }\n : null;\nconst expressionTargetFor = (planned, candidates = planned.chunk\n .mathAlignments) => {\n if (candidates.length !== 1)\n return null;\n const fallback = candidates[0]?.alignment.result.fallbackTarget;\n return fallback ? planned.renderedMathTargetResolver(fallback) : null;\n};\nconst mathCandidatesForTarget = (target, chunk) => {\n if (!target)\n return chunk.mathAlignments;\n return chunk.mathAlignments.filter(({ element }) => {\n try {\n if (target.type === \"range\")\n return target.range.intersectsNode(element);\n if (target.type === \"element\") {\n return target.element === element || target.element.contains(element);\n }\n return target.node.parentElement?.contains(element) || false;\n }\n catch {\n return false;\n }\n });\n};\nconst missingChunkDecision = () => ({\n activeTarget: null,\n regionTarget: null,\n quality: \"region\",\n confidence: 0,\n reason: \"boundary chunk id was not found\",\n});\nconst soleEquationElement = (candidates) => (candidates.length === 1 ? candidates[0].element : null);\nconst everyCandidateIsTokenMode = (planned, candidates) => candidates.length > 0 &&\n candidates.every(({ element }) => planned.mathCapabilityByElement.get(element) === \"token\");\nconst TEXT_NODE = 3;\n// Safety policy for token-mode equations. A prose \"range\" target comes from the\n// catalog span aligner, whose spoken→visible mapping inside an equation is\n// heuristic and not trustworthy at glyph granularity. A multi-node range fully\n// inside a token-mode equation is therefore rejected here in favor of holding\n// the last token — painting it would be a likely false positive, and \"false\n// positives are worse than coarse highlighting.\" A single-text-node prose range\n// is kept: it underlines one token cleanly and usefully fills in any token the\n// math resolver missed. (The highlight coordinator no longer escalates word\n// ranges to the whole <math> / <mjx-container>, so this is now a precision\n// policy rather than flash-suppression — see HighlightCoordinator\n// WORD_FALLBACK_SELECTOR.)\nconst wouldEscalateInsideTokenMath = (planned, target, candidates) => {\n if (!target || target.type !== \"range\")\n return false;\n const { startContainer, endContainer } = target.range;\n const singleTextNode = startContainer === endContainer && startContainer.nodeType === TEXT_NODE;\n if (singleTextNode)\n return false;\n return candidates.some(({ element }) => planned.mathCapabilityByElement.get(element) === \"token\" &&\n element.contains(startContainer) &&\n element.contains(endContainer));\n};\nconst createPlannedChunk = (chunk, mathTokenHighlighting) => ({\n chunk,\n regionTarget: regionTargetFor(chunk),\n renderedMathTargetResolver: createRenderedMathTargetResolver(),\n mathCapabilityByElement: new Map(chunk.mathAlignments.map(({ element }) => [\n element,\n // Forcing \"expression\" when per-token math highlighting is disabled\n // routes every equation through the sticky whole-block path, so the\n // formula is highlighted as one unit instead of glyph by glyph.\n mathTokenHighlighting\n ? classifyMathHighlightCapability(element)\n : \"expression\",\n ])),\n heldTokenByElement: new Map(),\n});\nexport const createTTSHighlightPlan = (args) => {\n const mathTokenHighlighting = args.mathTokenHighlighting !== false;\n const plannedChunksById = new Map(args.chunks.map((chunk) => [\n chunk.id,\n createPlannedChunk(chunk, mathTokenHighlighting),\n ]));\n return {\n chunks: args.chunks,\n resolveInitial(chunkId) {\n const planned = plannedChunksById.get(chunkId);\n if (!planned)\n return missingChunkDecision();\n const alignments = planned.chunk.mathAlignments;\n const soleElement = alignments.length === 1 ? alignments[0].element : null;\n const capability = soleElement\n ? planned.mathCapabilityByElement.get(soleElement)\n : null;\n // Sticky mode. Only an equation we already know cannot be tracked per\n // token gets the whole-expression paint up front. A token-mode equation\n // stays on the region layer until its first token resolves, so the full\n // equation never flashes before (or between) tokens.\n if (capability === \"expression\") {\n return createHighlightDecision({\n semanticTarget: null,\n expressionTarget: expressionTargetFor(planned),\n regionTarget: planned.regionTarget,\n confidence: 0.5,\n reason: \"initial expression (sticky expression mode)\",\n });\n }\n return createHighlightDecision({\n semanticTarget: null,\n expressionTarget: null,\n regionTarget: planned.regionTarget,\n confidence: 0,\n reason: capability === \"token\"\n ? \"initial region (sticky token mode, awaiting first token)\"\n : \"initial region fallback\",\n });\n },\n resolveBoundary(event) {\n const planned = plannedChunksById.get(event.chunkId);\n if (!planned)\n return missingChunkDecision();\n const { chunk } = planned;\n const normalized = normalizeBoundaryEvent(chunk, event);\n const proseTarget = resolveProseBoundaryTarget(chunk, normalized);\n const mathCandidates = mathCandidatesForTarget(proseTarget, chunk);\n const mathTarget = (!proseTarget || mathCandidates.length > 0\n ? resolveMathBoundaryTarget(chunk, normalized, event, mathCandidates, planned.renderedMathTargetResolver)\n : null) || null;\n const mathTokenTarget = mathTokenHighlighting &&\n mathTarget &&\n mathTarget.quality !== \"expression\"\n ? mathTarget\n : null;\n const mathExpressionFallback = mathTarget && mathTarget.quality === \"expression\" ? mathTarget : null;\n // (1) A precise token always wins, and becomes the held target for its\n // equation so a later gap can keep it lit instead of flashing the whole\n // expression.\n if (mathTokenTarget) {\n const equationElement = soleEquationElement(mathCandidates);\n if (equationElement) {\n planned.heldTokenByElement.set(equationElement, mathTokenTarget);\n }\n return createHighlightDecision({\n semanticTarget: mathTokenTarget,\n expressionTarget: null,\n regionTarget: planned.regionTarget,\n confidence: normalized.confidence,\n reason: normalized.reason,\n });\n }\n // (2) A spoken word that maps to visible prose. The prose anchor is\n // precise; a coarse math expression fallback must never override it.\n // Exception: a multi-node prose range inside a token-mode equation\n // would escalate to the whole expression, so it is rejected here and\n // falls through to the token hold below. When per-token math\n // highlighting is disabled, any prose range that lands inside a\n // formula is likewise rejected so the formula stays a single block.\n if (proseTarget &&\n (mathTokenHighlighting\n ? !wouldEscalateInsideTokenMath(planned, proseTarget, mathCandidates)\n : mathCandidates.length === 0)) {\n return createHighlightDecision({\n semanticTarget: proseTarget,\n expressionTarget: null,\n regionTarget: planned.regionTarget,\n confidence: normalized.confidence,\n reason: normalized.reason,\n });\n }\n // (3) A boundary inside a token-mode equation that did not map to a\n // token — an SSML break, a pause, or a gap between spoken tokens. Hold\n // the last token instead of flashing the whole expression; before the\n // first token there is nothing to hold, so fall to the region layer.\n // The whole expression is deliberately never painted in token mode.\n if (everyCandidateIsTokenMode(planned, mathCandidates)) {\n const equationElement = soleEquationElement(mathCandidates);\n const heldToken = equationElement\n ? (planned.heldTokenByElement.get(equationElement) ?? null)\n : null;\n return createHighlightDecision({\n semanticTarget: heldToken,\n expressionTarget: null,\n regionTarget: planned.regionTarget,\n confidence: normalized.confidence,\n reason: heldToken\n ? \"hold last token (sticky token mode)\"\n : \"region (sticky token mode, awaiting first token)\",\n });\n }\n // (4) An expression-mode (or mixed/ambiguous) math region: paint the\n // whole equation. Stable for the equation's full duration because\n // tokens never resolve here, so there is no flicker.\n return createHighlightDecision({\n semanticTarget: null,\n expressionTarget: mathExpressionFallback ??\n expressionTargetFor(planned, mathCandidates),\n regionTarget: planned.regionTarget,\n confidence: normalized.confidence,\n reason: normalized.reason,\n });\n },\n };\n};\n","const chunkOffsetSpaceFor = (chunk) => {\n if (chunk.alignment?.boundaryOffsetMode)\n return chunk.alignment.boundaryOffsetMode;\n const mathOffsetSpace = chunk.mathAlignment?.speech.boundaryOffsetSpace;\n if (mathOffsetSpace)\n return mathOffsetSpace;\n return \"plain-spoken-text\";\n};\nconst mathAlignmentsFor = (chunk) => {\n if (chunk.mathAlignments?.length)\n return chunk.mathAlignments;\n if (chunk.mathAlignment && chunk.sourceElement) {\n return [{ element: chunk.sourceElement, alignment: chunk.mathAlignment }];\n }\n return [];\n};\nexport const normalizeSpeechChunks = (args) => {\n const sourceChunks = args.chunks && args.chunks.length\n ? args.chunks\n : [\n {\n speechText: args.speechText || \"\",\n visibleText: args.visibleText || args.speechText || \"\",\n sourceElement: args.sourceElement || args.contentRoot,\n regionElement: args.regionElement || args.sourceElement || args.contentRoot,\n regionRange: args.regionRange,\n visibleMap: args.visibleMap,\n },\n ];\n return sourceChunks.map((chunk, index) => ({\n id: `tts-chunk-${index}`,\n speechText: chunk.speechText,\n visibleText: chunk.visibleText,\n sourceElement: chunk.sourceElement,\n contentRoot: args.contentRoot,\n regionElement: chunk.regionElement ?? chunk.sourceElement,\n regionRange: chunk.regionRange,\n visibleMap: chunk.visibleMap,\n catalogAlignment: chunk.alignment,\n mathAlignments: mathAlignmentsFor(chunk),\n offsetSpace: chunkOffsetSpaceFor(chunk),\n }));\n};\n","const READABLE_REGION_SELECTOR = [\n \"[data-pie-tts-region]\",\n \"[data-catalog-region]\",\n \"li\",\n \"p\",\n \"label\",\n \"section\",\n \"[role='group']\",\n \"[role='region']\",\n \"div\",\n].join(\",\");\nexport const resolveReadableRegion = (sourceElement, contentRoot) => {\n const region = sourceElement.closest(READABLE_REGION_SELECTOR);\n if (region && contentRoot.contains(region)) {\n return region;\n }\n return sourceElement;\n};\n","import { resolveReadableRegion } from \"../../highlight-pipeline/index.js\";\nimport { collectMathAwareTextAndMap } from \"../../math-aware-text-processing.js\";\nimport { assembleGeneratedSpeech, } from \"../assemble-plan.js\";\nconst sliceVisibleMap = (map, start, end) => {\n const sliced = new Map();\n for (let index = start; index < end; index++) {\n const mapping = map.get(index);\n if (mapping) {\n sliced.set(index - start, mapping);\n }\n }\n return sliced;\n};\n/**\n * DOM adapter: walk a live content root, assemble the (pure) speech plan, and\n * bind each segment to its live-DOM anchor. This is the only generated-speech\n * entry point that touches the DOM; assembly and serialization stay pure.\n */\nexport const buildGeneratedSpeechFromRoot = async (args) => {\n const extracted = collectMathAwareTextAndMap(args.contentRoot, args.textProcessingOptions);\n const assembled = await assembleGeneratedSpeech({\n chunks: extracted.chunks,\n visibleText: extracted.visibleText,\n language: args.language,\n mathSpeech: args.mathSpeech,\n produceSsml: args.produceSsml,\n resolveMathSpeech: args.resolveMathSpeech,\n });\n const items = assembled.segments.map(({ segment, sourceChunkIndex }) => {\n const sourceChunk = extracted.chunks[sourceChunkIndex];\n if (segment.kind === \"prose\") {\n const sourceElement = sourceChunk?.type === \"text\"\n ? (sourceChunk.sourceElement ?? args.contentRoot)\n : args.contentRoot;\n return {\n segment,\n anchor: {\n sourceElement,\n regionElement: resolveReadableRegion(sourceElement, args.contentRoot),\n visibleMap: sliceVisibleMap(extracted.map, segment.visibleSpan.start, segment.visibleSpan.end),\n },\n };\n }\n const mathElement = sourceChunk?.type === \"math\"\n ? (sourceChunk.sourceElement ?? null)\n : null;\n return {\n segment,\n anchor: {\n sourceElement: mathElement,\n regionElement: mathElement,\n },\n };\n });\n return {\n plan: {\n items,\n locale: assembled.locale,\n visibleText: assembled.visibleText,\n plainSpeechText: assembled.plainSpeechText,\n },\n containsMathMarkup: extracted.containsMathMarkup,\n visibleText: extracted.visibleText,\n };\n};\n","import { createCatalogSpanAlignment } from \"../../catalog-span-alignment.js\";\nimport { createRangeFromVisibleMap } from \"../../highlight-pipeline/visible-map-range.js\";\nimport { createMathAwareAlignment } from \"../../math-alignment/index.js\";\nconst buildProseChunk = (segment, anchor) => {\n const alignment = createCatalogSpanAlignment({\n speechText: segment.spokenText,\n visibleText: segment.spokenText,\n });\n return {\n speechText: segment.spokenText,\n visibleText: segment.visibleText,\n sourceElement: anchor.sourceElement,\n regionElement: anchor.regionElement,\n regionRange: createRangeFromVisibleMap(anchor.visibleMap, 0, segment.visibleText.length) ?? undefined,\n speechMatchesVisibleText: true,\n playbackMode: alignment.playbackMode,\n alignment,\n visibleMap: anchor.visibleMap,\n };\n};\nconst buildPlainMathChunk = (segment, anchor) => {\n const mathElement = anchor.sourceElement;\n return {\n speechText: segment.spokenText,\n visibleText: segment.fallbackText,\n sourceElement: mathElement,\n regionElement: anchor.regionElement,\n speechMatchesVisibleText: segment.spokenText === segment.fallbackText,\n mathAlignment: mathElement\n ? createMathAwareAlignment({\n mathElement,\n speechText: segment.spokenText,\n })\n : undefined,\n };\n};\nconst buildSsmlMathChunk = (segment, anchor, ssml) => {\n const mathElement = anchor.sourceElement;\n return {\n speechText: ssml,\n visibleText: segment.fallbackText,\n sourceElement: mathElement,\n regionElement: anchor.regionElement,\n // SSML never equals the visible fallback; the region-vs-token decision is\n // driven by alignment confidence, not by this flag.\n speechMatchesVisibleText: false,\n // SINGLE SOURCE OF TRUTH: the exact SSML string sent to the provider is\n // also the string alignment tokenizes, so provider word-boundary offsets\n // (into the raw SSML) map back to spoken tokens via `rawToSpokenOffsetMap`.\n mathAlignment: mathElement\n ? createMathAwareAlignment({ mathElement, speechText: ssml })\n : undefined,\n // Defensive net: if the provider rejects the SSML, retry with plain text.\n plainFallback: buildPlainMathChunk(segment, anchor),\n };\n};\n/**\n * Convert an anchored speech plan into playback chunks for\n * `TTSService.speakCatalogChunk`. The aggregate `contentToSpeak` stays plain\n * (see `plan.plainSpeechText`), so no SSML leaks into break-detection or seek\n * planning — SSML lives only in per-chunk `speechText`.\n */\nexport const planToCompositionChunkInputs = (plan, options = {}) => plan.items.map(({ segment, anchor }) => {\n if (segment.kind === \"prose\")\n return buildProseChunk(segment, anchor);\n if (options.format === \"ssml\" && segment.ssml) {\n return buildSsmlMathChunk(segment, anchor, segment.ssml);\n }\n return buildPlainMathChunk(segment, anchor);\n});\n","/**\n * Shared orchestration events for TTS tool UI controls.\n *\n * These events are intentionally UI-level coordination hints. They do not replace\n * playback controls such as stop/pause/resume.\n */\nexport const PIE_TTS_CONTROL_HANDOFF_EVENT = \"pie-tts-control-handoff\";\n","/**\n * TTSService\n *\n * Text-to-speech service with pluggable provider architecture.\n * Manages playback state, coordinates multiple TTS entry points,\n * and integrates with HighlightCoordinator for word highlighting.\n *\n * Features:\n * - Pluggable TTS providers (browser, AWS Polly, etc.)\n * - QTI 3.0 accessibility catalogs (pre-authored spoken content)\n * - Unified playback state management\n * - Prevents conflicts from simultaneous speech\n * - Word highlighting integration\n * - Playback controls: play, pause, resume, stop\n *\n * Part of PIE Assessment Toolkit.\n */\nimport { applyMediaFragment, enforceMediaFragment } from \"./catalog-media.js\";\nimport { HighlightColor, HighlightType } from \"./HighlightCoordinator.js\";\nimport { resolveSpokenAudioMedia, } from \"./spoken-audio-cards.js\";\nimport { BrowserTTSProvider } from \"./tts/browser-provider.js\";\nimport { collectRangeTextForSpeech, collectVisibleTextAndMap, isElementHiddenForTTS, isNodeExcludedFromSpeech, isNodeSuppressedForTTS, normalizeTextForSpeech, } from \"./tts/text-processing.js\";\nimport { createCatalogSpanAlignment, } from \"./tts/catalog-span-alignment.js\";\nimport { createMathAwareAlignment, } from \"./tts/math-alignment/index.js\";\nimport { collectMathAwareTextAndMap } from \"./tts/math-aware-text-processing.js\";\nimport { buildGeneratedSpeechFromRoot, createMemoizedMathSpeechResolver, planToCompositionChunkInputs, } from \"./tts/generated-speech/index.js\";\nimport { normalizeSREMathSpeechOptions, } from \"./tts/math-speech.js\";\nimport { segmentSentences as segmentTextToSentences, } from \"./tts/text-segmentation.js\";\nimport { createTTSHighlightPlan, normalizeSpeechChunks, resolveReadableRegion, } from \"./tts/highlight-pipeline/index.js\";\nimport { PIE_TTS_CONTROL_HANDOFF_EVENT, } from \"./tts-control-events.js\";\n/**\n * Playback state\n */\nexport var PlaybackState;\n(function (PlaybackState) {\n PlaybackState[\"IDLE\"] = \"idle\";\n PlaybackState[\"LOADING\"] = \"loading\";\n PlaybackState[\"PLAYING\"] = \"playing\";\n PlaybackState[\"PAUSED\"] = \"paused\";\n PlaybackState[\"ERROR\"] = \"error\";\n})(PlaybackState || (PlaybackState = {}));\nconst sameRange = (left, right) => left === right ||\n (left.startContainer === right.startContainer &&\n left.startOffset === right.startOffset &&\n left.endContainer === right.endContainer &&\n left.endOffset === right.endOffset);\nconst sameRenderableHighlightTarget = (left, right) => {\n if (left === right)\n return true;\n if (!left ||\n !right ||\n left.type !== right.type ||\n left.quality !== right.quality) {\n return false;\n }\n if (left.type === \"range\" && right.type === \"range\") {\n return sameRange(left.range, right.range);\n }\n if (left.type === \"element\" && right.type === \"element\") {\n return left.element === right.element;\n }\n if (left.type === \"text-range\" && right.type === \"text-range\") {\n return (left.node === right.node &&\n left.startOffset === right.startOffset &&\n left.endOffset === right.endOffset);\n }\n return false;\n};\n/**\n * TTSService\n *\n * Instantiable service for text-to-speech functionality.\n * Each instance manages its own playback state.\n */\nexport class TTSService {\n currentProvider = null;\n provider = null;\n highlightCoordinator = null;\n highlightTargetResolverProvider = null;\n catalogResolver = null;\n state = PlaybackState.IDLE;\n ttsConfig = {};\n currentText = null;\n currentContentElement = null;\n normalizedToDOM = new Map();\n listeners = new Map();\n lastError = null;\n speakRunId = 0;\n currentBoundaryOffset = 0;\n activeWordBoundaryOffset = 0;\n seekSegments = [];\n playbackChunks = [];\n // The recording currently playing, if any. `cancel` settles the pending play\n // promise as well as stopping the element, so stop/seek cannot wedge the\n // chunk loop on a run that has already been superseded.\n activeRecordedAudio = null;\n sentenceHighlightSegments = [];\n currentSeekSegmentIndex = 0;\n activeSentenceStartOffset = null;\n playbackStartDeferredRunId = null;\n pendingPlaybackStartHighlights = [];\n playbackStartBarrierCleanup = null;\n playbackRateWriteQueue = Promise.resolve();\n playbackRateRequestId = 0;\n pendingPlaybackRateRequest = null;\n activePlaybackRate = null;\n activeHighlightMode = \"word\";\n lastRenderedRegionTarget = null;\n telemetryReporter = null;\n // Memoized SRE resolver for the runtime generated-speech path (PIE-623).\n // Caches DOM-free spoken text keyed by SRE settings and MathML source across\n // utterances within this service instance.\n generatedMathSpeechResolver = createMemoizedMathSpeechResolver();\n // Verbose alignment/highlight tracing is opt-in: it is expensive (large\n // objects, a full text diff per utterance) and noisy in production. Enable\n // with `PIE_TTS_DEBUG=1` or `globalThis.__PIE_TTS_DEBUG__ = true`.\n static debugEnabled = (() => {\n try {\n if (typeof process !== \"undefined\" &&\n process.env?.PIE_TTS_DEBUG === \"1\") {\n return true;\n }\n }\n catch {\n // `process` is not defined in the browser; fall through to the global.\n }\n return (globalThis.__PIE_TTS_DEBUG__ === true);\n })();\n constructor() { }\n debugLog(message, detail) {\n if (!TTSService.debugEnabled)\n return;\n if (detail === undefined) {\n console.debug(message);\n }\n else {\n console.debug(message, detail);\n }\n }\n clearPlaybackStartBarrier(cleanup = this.playbackStartBarrierCleanup) {\n cleanup?.();\n if (this.playbackStartBarrierCleanup === cleanup) {\n this.playbackStartBarrierCleanup = null;\n }\n }\n notifyPlaybackStarted(runId) {\n if (this.playbackStartDeferredRunId !== runId ||\n runId !== this.speakRunId) {\n return;\n }\n this.setState(PlaybackState.PLAYING);\n const pendingHighlights = this.pendingPlaybackStartHighlights.splice(0);\n for (const applyHighlight of pendingHighlights) {\n applyHighlight();\n }\n }\n installPlaybackStartBarrier(runId, hasMediaStartSignal = false) {\n this.clearPlaybackStartBarrier();\n const provider = this.provider;\n const startAwareProvider = provider && \"onPlaybackStart\" in provider ? provider : null;\n if (!startAwareProvider && !hasMediaStartSignal)\n return null;\n const previousOnPlaybackStart = startAwareProvider?.onPlaybackStart;\n const onPlaybackStart = () => {\n try {\n this.notifyPlaybackStarted(runId);\n }\n finally {\n previousOnPlaybackStart?.();\n }\n };\n if (startAwareProvider) {\n startAwareProvider.onPlaybackStart = onPlaybackStart;\n }\n this.playbackStartDeferredRunId = runId;\n const cleanup = () => {\n if (startAwareProvider?.onPlaybackStart === onPlaybackStart) {\n startAwareProvider.onPlaybackStart = previousOnPlaybackStart;\n }\n if (this.playbackStartDeferredRunId === runId) {\n this.playbackStartDeferredRunId = null;\n this.pendingPlaybackStartHighlights = [];\n }\n };\n this.playbackStartBarrierCleanup = cleanup;\n return cleanup;\n }\n runWhenPlaybackStarts(runId, callback) {\n if (this.playbackStartDeferredRunId === runId) {\n this.pendingPlaybackStartHighlights.push(callback);\n return;\n }\n callback();\n }\n async emitTelemetry(eventName, payload) {\n try {\n await this.telemetryReporter?.(eventName, payload);\n }\n catch (error) {\n console.warn(\"[TTSService] telemetry callback failed:\", error);\n }\n }\n /**\n * Initialize TTS service with a provider\n *\n * @param provider TTS provider instance\n * @param config Provider configuration\n */\n async initialize(provider, config = {}) {\n this.currentProvider = provider;\n this.ttsConfig = { ...config };\n const providerOptions = config.providerOptions && typeof config.providerOptions === \"object\"\n ? config.providerOptions\n : {};\n this.telemetryReporter =\n typeof providerOptions.__pieTelemetry === \"function\"\n ? providerOptions.__pieTelemetry\n : null;\n // Initialize provider and get implementation. Browser fallback is only\n // allowed here, before the configured provider has successfully become\n // the active runtime. Per-call playback/synthesis errors must surface\n // instead of silently replacing a user-selected provider and voice.\n try {\n this.provider = await provider.initialize(config);\n }\n catch (error) {\n if (provider.providerId.toLowerCase() === \"browser\") {\n throw error;\n }\n if (!this.isBrowserSpeechFallbackAvailable()) {\n throw error;\n }\n const switched = await this.switchProviderToBrowser(error, {\n operation: \"tts-initialize\",\n });\n if (!switched) {\n throw error;\n }\n }\n }\n /**\n * Update TTS settings dynamically without full reinitialization\n *\n * This allows changing rate, pitch, and voice on the fly.\n * Note: Some providers may require reinitialization for voice changes.\n *\n * @param settings Partial settings to update (rate, pitch, voice)\n */\n async updateSettings(settings) {\n if (!this.provider) {\n throw new Error(\"TTSService not initialized. Call initialize() first.\");\n }\n // If the provider implementation has an updateSettings method, use it\n const provider = this.provider;\n if (typeof provider.updateSettings === \"function\") {\n const mergedSettings = {\n ...settings,\n ...(settings.providerOptions\n ? {\n providerOptions: {\n ...(this.ttsConfig.providerOptions || {}),\n ...settings.providerOptions,\n },\n }\n : {}),\n };\n await provider.updateSettings(mergedSettings);\n this.ttsConfig = { ...this.ttsConfig, ...mergedSettings };\n }\n else {\n // Fallback: Reinitialize with merged config\n // This requires storing the original config, which we don't have\n // So for now, just log a warning\n console.warn(\"[TTSService] Provider does not support dynamic settings updates. Some settings may require reinitialization.\");\n }\n }\n /**\n * Set highlight coordinator for word highlighting\n */\n setHighlightCoordinator(coordinator) {\n this.highlightCoordinator = coordinator;\n }\n /**\n * Set a late-bound provider for optional host TTS highlight target remapping.\n *\n * The returned disposer is the only thing that clears the registration: the\n * caller owns the lifetime, and a provider installed once keeps remapping\n * across stops, seek-restarts and later playbacks. Playback termination used to\n * clear it in `stop()` and on both exits of `restartFromSeekIndex`, which left a\n * host that installs before mount — the case a late-bound provider exists for —\n * remapping exactly one playback and then silently falling back to identity.\n *\n * Installing again replaces the previous provider, so a caller that reinstalls\n * per playback needs no disposal between them. A stale provider cannot paint\n * outside its scope in any case: targets are validated by containment in\n * `context.scopeElement` and a failing one falls back to its native range.\n */\n setHighlightTargetResolverProvider(provider) {\n this.highlightTargetResolverProvider = provider;\n return () => {\n if (this.highlightTargetResolverProvider === provider) {\n this.highlightTargetResolverProvider = null;\n }\n };\n }\n /**\n * Set accessibility catalog resolver for spoken content\n *\n * When set, the speak() method will check for pre-authored spoken\n * content in catalogs before falling back to generated TTS.\n *\n * @param resolver AccessibilityCatalogResolver instance\n */\n setCatalogResolver(resolver) {\n this.catalogResolver = resolver;\n }\n /**\n * Whether a catalog holds spoken content this service could actually speak.\n *\n * Exists because `data-catalog-idref` is one attribute with several readers:\n * a node can be docked to a catalog that carries only a signing card, and the\n * nearest docked ancestor of a selection is therefore not necessarily the one\n * holding its authored SSML. A caller resolving a selection climbs ancestors\n * and asks this before settling on an id — see the TTS tool's\n * `findSpokenCatalogId`. Without it, a signing card docked on an inner node\n * silently shadows authored speech on an outer one.\n */\n hasSpokenAlternate(catalogId, language = \"en-US\") {\n if (!catalogId || !this.catalogResolver)\n return false;\n const resolved = this.catalogResolver.getAlternative(catalogId, {\n type: \"spoken\",\n language,\n useFallback: true,\n // The string form specifically. A node may also carry a recording of the\n // same script; that one is not what this reports on, and card order must\n // not decide the answer.\n form: \"content\",\n });\n return resolved?.content !== undefined;\n }\n getHighlightResolverRuntime() {\n let provided = null;\n try {\n provided = this.highlightTargetResolverProvider?.() ?? null;\n }\n catch {\n provided = null;\n }\n const providedContext = provided?.context ?? {};\n const fallbackScope = typeof HTMLElement !== \"undefined\" &&\n this.currentContentElement instanceof HTMLElement\n ? this.currentContentElement\n : null;\n return {\n context: {\n ...providedContext,\n scopeElement: providedContext.scopeElement ?? fallbackScope,\n },\n resolver: provided?.resolver ?? null,\n };\n }\n getNodeElement(node) {\n if (!node)\n return null;\n return node.nodeType === Node.ELEMENT_NODE\n ? node\n : node.parentElement;\n }\n isElementWithinScope(element, scope) {\n if (!scope)\n return true;\n return element === scope || scope.contains(element);\n }\n isRangeWithinScope(range, scope) {\n const startElement = this.getNodeElement(range.startContainer);\n const endElement = this.getNodeElement(range.endContainer);\n if (!startElement || !endElement)\n return false;\n return (this.isElementWithinScope(startElement, scope) &&\n this.isElementWithinScope(endElement, scope));\n }\n resolveWordHighlightRange(nativeRange) {\n const { context, resolver } = this.getHighlightResolverRuntime();\n const scope = context.scopeElement ?? this.currentContentElement;\n try {\n const resolved = resolver?.resolveWordRange?.(nativeRange, context);\n if (resolved && this.isRangeWithinScope(resolved, scope)) {\n return { range: resolved, remapped: !sameRange(nativeRange, resolved) };\n }\n }\n catch {\n // Fail open: custom resolver failures must not interrupt TTS playback.\n }\n return { range: nativeRange, remapped: false };\n }\n resolveSentenceHighlightTargets(nativeRanges) {\n const { context, resolver } = this.getHighlightResolverRuntime();\n const scope = context.scopeElement ?? this.currentContentElement;\n try {\n const resolved = resolver?.resolveSentenceRanges?.(nativeRanges, context);\n if (!resolved)\n return { ranges: nativeRanges, elements: [] };\n const ranges = [];\n const elements = [];\n for (const target of resolved) {\n if (typeof Range !== \"undefined\" && target instanceof Range) {\n if (!this.isRangeWithinScope(target, scope)) {\n return { ranges: nativeRanges, elements: [] };\n }\n ranges.push(target);\n continue;\n }\n if (typeof Element !== \"undefined\" && target instanceof Element) {\n if (!this.isElementWithinScope(target, scope)) {\n return { ranges: nativeRanges, elements: [] };\n }\n elements.push(target);\n continue;\n }\n return { ranges: nativeRanges, elements: [] };\n }\n return { ranges, elements };\n }\n catch {\n // Fail open: custom resolver failures must not interrupt TTS playback.\n return { ranges: nativeRanges, elements: [] };\n }\n }\n createTextRange(node, startOffset, endOffset) {\n if (typeof document === \"undefined\")\n return null;\n if (typeof document.createRange !== \"function\")\n return null;\n try {\n const range = document.createRange();\n range.setStart(node, startOffset);\n range.setEnd(node, endOffset);\n if (range.startContainer !== node || range.endContainer !== node) {\n return null;\n }\n return range;\n }\n catch {\n return null;\n }\n }\n paintTTSWordRange(range) {\n if (!this.highlightCoordinator)\n return;\n try {\n if (range.startContainer === range.endContainer &&\n range.startContainer.nodeType === Node.TEXT_NODE) {\n this.highlightCoordinator.highlightTTSWord(range.startContainer, range.startOffset, range.endOffset);\n return;\n }\n }\n catch {\n // Fall through to generic range painting for lightweight test doubles.\n }\n this.highlightCoordinator.highlightRange(range, HighlightType.TTS_WORD, HighlightColor.YELLOW);\n }\n paintTTSSentenceRanges(nativeRanges) {\n if (!this.highlightCoordinator)\n return;\n const { ranges, elements } = this.resolveSentenceHighlightTargets(nativeRanges);\n if (elements.length > 0 &&\n ranges.length === 0 &&\n this.highlightCoordinator.highlightTTSSentenceElements) {\n this.highlightCoordinator.highlightTTSSentenceElements(elements);\n return;\n }\n const paintedRanges = [...ranges];\n for (const element of elements) {\n const elementRange = document.createRange();\n elementRange.selectNodeContents(element);\n paintedRanges.push(elementRange);\n }\n this.highlightCoordinator.highlightTTSSentence(paintedRanges);\n }\n /**\n * Get provider capabilities\n */\n getCapabilities() {\n return this.currentProvider?.getCapabilities() || null;\n }\n /**\n * Build a character-by-character map from normalized text positions to DOM positions\n * This handles the complexity of whitespace normalization\n */\n getTextProcessingOptions(language) {\n const providerOptions = (this.ttsConfig.providerOptions || {});\n const textNormalization = (providerOptions.textNormalization ||\n {});\n const mode = textNormalization.boundarySpacingMode;\n const boundarySpacingMode = mode === \"none\" || mode === \"alnum\" || mode === \"segmenterPreferred\"\n ? mode\n : undefined;\n const locale = language ||\n (typeof textNormalization.locale === \"string\"\n ? textNormalization.locale\n : undefined);\n return { locale, boundarySpacingMode };\n }\n getMathSpeechOptions() {\n const providerOptions = (this.ttsConfig.providerOptions || {});\n const mathSpeech = providerOptions.mathSpeech;\n return normalizeSREMathSpeechOptions(mathSpeech);\n }\n buildPositionMap(element, spokenText, language) {\n this.normalizedToDOM.clear();\n const { text: normalizedDomText, map } = collectVisibleTextAndMap(element, this.getTextProcessingOptions(language));\n this.normalizedToDOM = map;\n if (!TTSService.debugEnabled)\n return;\n this.debugLog(\"[TTSService] Text comparison:\", {\n spokenLength: spokenText.length,\n normalizedDomLength: normalizedDomText.length,\n match: spokenText === normalizedDomText,\n spokenPreview: spokenText.substring(0, 150),\n normalizedPreview: normalizedDomText.substring(0, 150),\n differAtIndex: spokenText === normalizedDomText\n ? null\n : (() => {\n for (let i = 0; i < Math.min(spokenText.length, normalizedDomText.length); i++) {\n if (spokenText[i] !== normalizedDomText[i]) {\n return {\n index: i,\n spokenChar: spokenText[i],\n normalizedChar: normalizedDomText[i],\n spokenContext: spokenText.substring(Math.max(0, i - 20), i + 20),\n normalizedContext: normalizedDomText.substring(Math.max(0, i - 20), i + 20),\n };\n }\n }\n return null;\n })(),\n });\n this.debugLog(\"[TTSService] Position map built:\", {\n entries: this.normalizedToDOM.size,\n spokenTextLength: spokenText.length,\n normalizedDomLength: normalizedDomText.length,\n mapLengthMatchesSpoken: this.normalizedToDOM.size === spokenText.length,\n firstFewMappings: Array.from(this.normalizedToDOM.entries())\n .slice(0, 10)\n .map(([pos, { node, offset }]) => ({\n pos,\n offset,\n char: node.textContent?.[offset],\n expected: spokenText[pos],\n })),\n });\n }\n getStructuralPauseProfile() {\n const providerOptions = (this.ttsConfig.providerOptions || {});\n const custom = (providerOptions.structuralPauses || {});\n const customUnits = (custom.units || {});\n const toNumber = (value, fallback) => {\n if (typeof value === \"number\" && Number.isFinite(value))\n return value;\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : fallback;\n }\n return fallback;\n };\n return {\n baseMs: toNumber(custom.baseMs, 280),\n units: {\n minor: toNumber(customUnits.minor, 0.65),\n section: toNumber(customUnits.section, 1.0),\n major: toNumber(customUnits.major, 1.35),\n },\n minMs: toNumber(custom.minMs, 120),\n maxMs: toNumber(custom.maxMs, 900),\n };\n }\n resolvePauseMsFromUnits(units) {\n const profile = this.getStructuralPauseProfile();\n const rate = Math.max(0.25, Math.min(4, Number(this.ttsConfig.rate || 1)));\n const raw = (profile.baseMs * Math.max(0, units)) / rate;\n return Math.max(profile.minMs, Math.min(profile.maxMs, Math.round(raw)));\n }\n resolveHighlightMode() {\n const providerOptions = (this.ttsConfig.providerOptions || {});\n const configuredMode = providerOptions.highlightMode;\n if (configuredMode === \"word\" || configuredMode === \"sentence\") {\n return configuredMode;\n }\n const providerId = (this.currentProvider?.providerId || \"\").toLowerCase();\n if (providerId === \"browser\") {\n return \"sentence\";\n }\n const supportsWordBoundary = this.currentProvider?.getCapabilities().supportsWordBoundary ?? false;\n return supportsWordBoundary ? \"word\" : \"sentence\";\n }\n hasExplicitBreakSemantics(text) {\n if (!text.includes(\"<\"))\n return false;\n return /<\\s*break\\b|<\\s*speak\\b|<\\s*prosody\\b|<\\s*p\\b|<\\s*s\\b/i.test(text);\n }\n isElementHidden(element) {\n return isElementHiddenForTTS(element);\n }\n getBoundaryStrength(element) {\n const explicitBreakMs = Number(element.getAttribute(\"data-tts-break-ms\"));\n if (Number.isFinite(explicitBreakMs) && explicitBreakMs > 0)\n return \"major\";\n const tagName = element.tagName.toUpperCase();\n if (tagName.match(/^H[1-6]$/))\n return \"major\";\n const role = (element.getAttribute(\"role\") || \"\").toLowerCase();\n if (role === \"heading\")\n return \"major\";\n if (role === \"listitem\" ||\n role === \"row\" ||\n role === \"option\" ||\n role === \"radio\" ||\n tagName === \"LI\") {\n return \"section\";\n }\n if (typeof window !== \"undefined\") {\n const display = window.getComputedStyle(element).display;\n if (display === \"block\" ||\n display === \"list-item\" ||\n display.startsWith(\"table\") ||\n display === \"flex\" ||\n display === \"grid\") {\n return \"minor\";\n }\n }\n return \"minor\";\n }\n getBoundaryAnchor(textNode, root) {\n let current = textNode.parentElement;\n let best = null;\n while (current && current !== root) {\n if (this.isElementHidden(current))\n return null;\n const explicitBreakMs = Number(current.getAttribute(\"data-tts-break-ms\"));\n if (Number.isFinite(explicitBreakMs) && explicitBreakMs > 0) {\n return {\n anchor: current,\n units: explicitBreakMs / this.getStructuralPauseProfile().baseMs,\n };\n }\n const role = (current.getAttribute(\"role\") || \"\").toLowerCase();\n const tagName = current.tagName.toUpperCase();\n if (tagName.match(/^H[1-6]$/) ||\n role === \"heading\" ||\n role === \"listitem\" ||\n tagName === \"LI\") {\n best = current;\n break;\n }\n if (!best) {\n if (typeof window !== \"undefined\") {\n const display = window.getComputedStyle(current).display;\n if (display === \"block\" ||\n display === \"list-item\" ||\n display.startsWith(\"table\") ||\n display === \"flex\" ||\n display === \"grid\") {\n best = current;\n }\n }\n }\n current = current.parentElement;\n }\n if (!best)\n return null;\n const strength = this.getBoundaryStrength(best);\n return {\n anchor: best,\n units: this.getStructuralPauseProfile().units[strength],\n };\n }\n createSpeechPlan(contentElement, normalizedText) {\n const boundaries = this.collectSpeechPlanBoundaries(contentElement, normalizedText);\n return this.createSpeechPlanSegments(normalizedText, boundaries);\n }\n collectSpeechPlanBoundaries(contentElement, normalizedText) {\n const boundaries = new Map();\n const { map } = collectVisibleTextAndMap(contentElement, this.getTextProcessingOptions());\n const nodeStartOffsets = this.createNodeStartOffsets(map);\n const walker = document.createTreeWalker(contentElement, NodeFilter.SHOW_TEXT);\n let currentNode = walker.nextNode();\n let previousBoundaryAnchor = null;\n while (currentNode) {\n const textNode = currentNode;\n const parent = textNode.parentElement;\n if (parent &&\n !this.isElementHidden(parent) &&\n !isNodeSuppressedForTTS(textNode)) {\n const boundary = this.getBoundaryAnchor(textNode, contentElement);\n const boundaryPoint = nodeStartOffsets.get(textNode);\n if (boundary &&\n boundaryPoint !== undefined &&\n boundary.anchor !== previousBoundaryAnchor &&\n boundaryPoint > 0) {\n boundaries.set(boundaryPoint, Math.max(boundaries.get(boundaryPoint) || 0, boundary.units));\n previousBoundaryAnchor = boundary.anchor;\n }\n }\n currentNode = walker.nextNode();\n }\n return boundaries;\n }\n createNodeStartOffsets(map) {\n const nodeStartOffsets = new Map();\n for (const [normalizedIndex, mapping] of map.entries()) {\n if (!nodeStartOffsets.has(mapping.node)) {\n nodeStartOffsets.set(mapping.node, normalizedIndex);\n }\n }\n return nodeStartOffsets;\n }\n createSpeechPlanSegments(normalizedText, boundaries) {\n const points = Array.from(boundaries.keys())\n .filter((point) => point > 0 && point < normalizedText.length)\n .sort((a, b) => a - b);\n const segments = [];\n let start = 0;\n for (const point of points) {\n const raw = normalizedText.substring(start, point);\n const leading = raw.match(/^\\s*/)?.[0].length || 0;\n const trailing = raw.match(/\\s*$/)?.[0].length || 0;\n const segmentStart = start + leading;\n const segmentEnd = point - trailing;\n if (segmentEnd > segmentStart) {\n const text = normalizedText.substring(segmentStart, segmentEnd);\n segments.push({\n text,\n startOffset: segmentStart,\n pauseMsAfter: this.resolvePauseMsFromUnits(boundaries.get(point) || 0),\n });\n }\n start = point;\n }\n const tail = normalizedText.substring(start);\n const tailLeading = tail.match(/^\\s*/)?.[0].length || 0;\n const tailStart = start + tailLeading;\n if (tailStart < normalizedText.length) {\n segments.push({\n text: normalizedText.substring(tailStart).trimEnd(),\n startOffset: tailStart,\n pauseMsAfter: 0,\n });\n }\n return segments.filter((segment) => segment.text.trim().length > 0);\n }\n segmentSentences(text) {\n const locale = this.ttsConfig.providerOptions\n ?.locale || undefined;\n return segmentTextToSentences(text, { locale });\n }\n createSeekSegmentsFromText(text) {\n return this.segmentSentences(text)\n .map((segment) => {\n const leadingWhitespace = segment.text.match(/^\\s*/)?.[0].length || 0;\n const trimmed = segment.text.trim();\n return {\n text: trimmed,\n startOffset: segment.offset + leadingWhitespace,\n pauseMsAfter: 0,\n };\n })\n .filter((segment) => segment.text.length > 0);\n }\n splitSegmentsAtBoundaries(segments, boundaryOffsets, sourceText) {\n if (segments.length === 0 || boundaryOffsets.length === 0)\n return segments;\n const normalizedBoundaries = Array.from(new Set(boundaryOffsets))\n .filter((offset) => Number.isFinite(offset) && offset > 0)\n .sort((left, right) => left - right);\n if (normalizedBoundaries.length === 0)\n return segments;\n const result = [];\n for (const segment of segments) {\n const segmentStart = segment.startOffset;\n const segmentEnd = segment.startOffset + segment.text.length;\n const splitPoints = normalizedBoundaries.filter((offset) => offset > segmentStart && offset < segmentEnd);\n if (splitPoints.length === 0) {\n result.push(segment);\n continue;\n }\n let cursor = segmentStart;\n for (const point of [...splitPoints, segmentEnd]) {\n const raw = sourceText.substring(cursor, point);\n const leadingWhitespace = raw.match(/^\\s*/)?.[0].length || 0;\n const trailingWhitespace = raw.match(/\\s*$/)?.[0].length || 0;\n const startOffset = cursor + leadingWhitespace;\n const endOffset = point - trailingWhitespace;\n if (endOffset > startOffset) {\n result.push({\n text: sourceText.substring(startOffset, endOffset),\n startOffset,\n pauseMsAfter: 0,\n });\n }\n cursor = point;\n }\n }\n return result;\n }\n createSentenceHighlightSegments(args) {\n const grammaticalSegments = this.createSeekSegmentsFromText(args.contentToSpeak);\n if (!args.shouldUsePlan || args.playbackSegments.length === 0) {\n return grammaticalSegments;\n }\n const structuralBoundaries = args.playbackSegments\n .map((segment) => segment.startOffset)\n .filter((offset) => offset > 0);\n return this.splitSegmentsAtBoundaries(grammaticalSegments, structuralBoundaries, args.contentToSpeak);\n }\n createSeekSegmentsFromSpeechChunks(chunks) {\n let offset = 0;\n return chunks.map((chunk) => {\n const speechText = chunk.plainFallback?.speechText ||\n (this.hasExplicitBreakSemantics(chunk.speechText)\n ? chunk.visibleText\n : chunk.speechText) ||\n chunk.visibleText;\n const text = normalizeTextForSpeech(speechText) || chunk.visibleText || \"\";\n const segment = {\n text,\n startOffset: offset,\n pauseMsAfter: 0,\n };\n offset += Math.max(1, text.length + 1);\n return segment;\n });\n }\n getCurrentSeekSegmentIndex() {\n if (this.seekSegments.length === 0)\n return 0;\n let index = 0;\n for (let i = 0; i < this.seekSegments.length; i++) {\n if (this.seekSegments[i].startOffset <= this.currentBoundaryOffset) {\n index = i;\n }\n else {\n break;\n }\n }\n return index;\n }\n async speakWithPlan(segments, runId, options) {\n if (!this.provider || segments.length === 0)\n return;\n const shouldTrackSentenceProgress = options?.highlightMode === \"sentence\";\n const providerWithPlan = this.provider;\n if (!shouldTrackSentenceProgress &&\n typeof providerWithPlan.speakSegments === \"function\") {\n this.currentBoundaryOffset = 0;\n const originalOnWordBoundary = this.provider.onWordBoundary;\n this.provider.onWordBoundary = (word, position, length) => {\n originalOnWordBoundary?.(word, position, length);\n if (Number.isFinite(position)) {\n this.currentBoundaryOffset = position;\n this.currentSeekSegmentIndex = this.getCurrentSeekSegmentIndex();\n }\n };\n try {\n await providerWithPlan.speakSegments(segments);\n }\n finally {\n if (runId === this.speakRunId && this.provider === providerWithPlan) {\n this.provider.onWordBoundary = originalOnWordBoundary;\n }\n }\n return;\n }\n this.configureWordBoundaryHighlighting({\n highlightMode: options?.highlightMode || \"word\",\n wordBoundaryOffset: this.activeWordBoundaryOffset,\n });\n for (const segment of segments) {\n if (runId !== this.speakRunId)\n return;\n const seekIndex = this.seekSegments.findIndex((candidate) => candidate.startOffset === segment.startOffset);\n if (seekIndex >= 0) {\n this.currentSeekSegmentIndex = seekIndex;\n }\n this.currentBoundaryOffset = segment.startOffset;\n if (shouldTrackSentenceProgress) {\n this.runWhenPlaybackStarts(runId, () => {\n this.highlightSentenceSegment(segment.startOffset, segment.text);\n });\n }\n await this.provider.speak(segment.text);\n const pauseMs = segment.pauseMsAfter ?? 0;\n if (pauseMs > 0) {\n await new Promise((resolve) => setTimeout(resolve, pauseMs));\n }\n }\n }\n highlightSentenceSegment(startOffset, text) {\n if (!this.highlightCoordinator || typeof document === \"undefined\")\n return;\n const length = text.trimEnd().length;\n if (length <= 0)\n return;\n const start = this.normalizedToDOM.get(startOffset);\n const end = this.normalizedToDOM.get(startOffset + length - 1);\n if (!start || !end)\n return;\n const range = document.createRange();\n range.setStart(start.node, start.offset);\n range.setEnd(end.node, end.offset + 1);\n this.paintTTSSentenceRanges([range]);\n this.activeSentenceStartOffset = startOffset;\n }\n getSegmentIndexForOffset(segments, offset) {\n if (segments.length === 0)\n return -1;\n let index = -1;\n for (let i = 0; i < segments.length; i++) {\n if (segments[i].startOffset <= offset) {\n index = i;\n }\n else {\n break;\n }\n }\n return index;\n }\n highlightSentenceForOffset(offset) {\n const segments = this.sentenceHighlightSegments;\n if (!this.highlightCoordinator || segments.length === 0)\n return;\n const segmentIndex = this.getSegmentIndexForOffset(segments, offset);\n if (segmentIndex < 0)\n return;\n const segment = segments[segmentIndex];\n if (!segment)\n return;\n if (this.activeSentenceStartOffset === segment.startOffset)\n return;\n this.highlightSentenceSegment(segment.startOffset, segment.text);\n }\n /**\n * Find text node and offsets for highlighting a word\n *\n * @param charIndex Character position in normalized/spoken text\n * @param length Length of the word\n * @returns Text node and local offsets, or null if not found\n */\n findHighlightRange(charIndex, length) {\n const startPos = this.normalizedToDOM.get(charIndex);\n if (!startPos) {\n console.warn(`[TTSService] No mapping found for start position ${charIndex}`, {\n totalMappings: this.normalizedToDOM.size,\n nearbyMappings: Array.from(this.normalizedToDOM.entries())\n .filter(([pos]) => Math.abs(pos - charIndex) < 5)\n .map(([pos, { offset, node }]) => ({\n pos,\n offset,\n char: node.textContent?.[offset],\n })),\n });\n return null;\n }\n // Find the end position (last character of the word)\n const endIndex = charIndex + length - 1;\n const endPos = this.normalizedToDOM.get(endIndex);\n if (!endPos) {\n console.warn(`[TTSService] No mapping found for end position ${endIndex}`, {\n startChar: charIndex,\n length,\n totalMappings: this.normalizedToDOM.size,\n });\n return null;\n }\n // For simplicity, if the word spans multiple nodes, just highlight in the first node\n // (This is a rare edge case and would require creating multiple ranges)\n if (startPos.node !== endPos.node) {\n console.warn(`[TTSService] Word spans multiple nodes, highlighting in first node only`);\n return {\n node: startPos.node,\n start: startPos.offset,\n end: (startPos.node.textContent || \"\").length,\n };\n }\n return {\n node: startPos.node,\n start: startPos.offset,\n end: endPos.offset + 1, // +1 because we want to include the character at endPos\n };\n }\n /**\n * Speak text with optional catalog support\n *\n * @param text Text to speak (will be normalized: trimmed and whitespace collapsed)\n * @param options Optional catalog ID, language, and content element for highlighting\n */\n async speak(text, options) {\n if (!this.provider) {\n throw new Error(\"TTS service not initialized\");\n }\n const runId = ++this.speakRunId;\n this.clearPlaybackStartBarrier();\n let playbackStartBarrier = null;\n try {\n await this.applyLanguageSettings(options);\n if (runId !== this.speakRunId)\n return;\n const resolvedContent = await this.resolveSpeechContent(text, options);\n if (runId !== this.speakRunId)\n return;\n const { contentToSpeak, speechText, highlightText, normalizedText, usedCatalogSpoken, speechSource, speechMatchesVisibleText, speechChunks, } = resolvedContent;\n this.logResolvedSpeechContent({\n contentToSpeak,\n speechSource,\n catalogId: options?.catalogId,\n });\n this.initializeSpeakTracking(highlightText, options);\n const highlightMode = options?.highlightModeOverride ||\n (speechMatchesVisibleText ? this.resolveHighlightMode() : \"sentence\");\n this.activeHighlightMode = highlightMode;\n this.activeWordBoundaryOffset = options?.wordBoundaryOffset || 0;\n const hasExplicitBreaks = this.hasExplicitBreakSemantics(contentToSpeak);\n const shouldUsePlan = !!this.currentContentElement &&\n !usedCatalogSpoken &&\n !hasExplicitBreaks &&\n speechMatchesVisibleText;\n this.playbackChunks = speechChunks?.length ? speechChunks : [];\n this.seekSegments = this.playbackChunks.length\n ? this.createSeekSegmentsFromSpeechChunks(this.playbackChunks)\n : hasExplicitBreaks || !speechMatchesVisibleText\n ? []\n : shouldUsePlan && this.currentContentElement\n ? this.createSpeechPlan(this.currentContentElement, normalizedText)\n : this.createSeekSegmentsFromText(highlightText);\n this.sentenceHighlightSegments = hasExplicitBreaks\n ? []\n : this.createSentenceHighlightSegments({\n contentToSpeak: highlightText,\n shouldUsePlan,\n playbackSegments: this.seekSegments,\n });\n this.setState(PlaybackState.LOADING);\n playbackStartBarrier = this.installPlaybackStartBarrier(runId, !!this.playbackChunks[0]?.audio);\n this.prepareHighlightsForSpeak({\n contentToSpeak: highlightText,\n options,\n highlightMode,\n shouldUsePlan,\n runId,\n });\n if (speechMatchesVisibleText) {\n this.configureWordBoundaryHighlighting({\n highlightMode,\n wordBoundaryOffset: options?.wordBoundaryOffset || 0,\n });\n }\n else {\n this.clearWordBoundaryHighlighting();\n }\n if (!playbackStartBarrier) {\n this.setState(PlaybackState.PLAYING);\n }\n this.activePlaybackRate = this.normalizePlaybackRate(Number(this.ttsConfig.rate ?? 1));\n await this.executeSpeakPlayback({\n shouldUsePlan,\n runId,\n highlightMode,\n contentToSpeak: speechText,\n speechChunks,\n });\n if (runId !== this.speakRunId)\n return;\n this.setState(PlaybackState.IDLE);\n this.clearHighlightsAndTracking();\n }\n catch (error) {\n let finalError = error;\n console.error(\"TTS error:\", finalError);\n this.lastError =\n finalError instanceof Error ? finalError.message : String(finalError);\n if (runId !== this.speakRunId)\n return;\n this.setState(PlaybackState.ERROR);\n this.clearHighlightsAndTracking();\n throw finalError;\n }\n finally {\n this.clearPlaybackStartBarrier(playbackStartBarrier);\n }\n }\n async switchProviderToBrowser(reason, context) {\n if (!this.currentProvider)\n return false;\n const fallbackProvider = new BrowserTTSProvider();\n const previousProviderId = this.currentProvider.providerId;\n // Voice identifiers and provider extensions belong to the provider that\n // rejected initialization. Carry only settings whose meaning is portable\n // when crossing the provider boundary; otherwise a Polly/Google/SC voice\n // such as \"Joanna\" can incorrectly become an explicit Browser voice.\n const browserConfig = {};\n if (this.ttsConfig.rate !== undefined) {\n browserConfig.rate = this.ttsConfig.rate;\n }\n if (this.ttsConfig.pitch !== undefined) {\n browserConfig.pitch = this.ttsConfig.pitch;\n }\n if (this.ttsConfig.mathTokenHighlighting !== undefined) {\n browserConfig.mathTokenHighlighting =\n this.ttsConfig.mathTokenHighlighting;\n }\n const operation = context?.operation || \"tts-initialize\";\n const offendingText = context?.contentToSpeak ?? \"\";\n const offendingPreview = offendingText\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 120);\n const offendingDiagnostic = offendingText.length > 0\n ? {\n textLength: offendingText.length,\n textPreview: offendingPreview.length < offendingText.length\n ? `${offendingPreview}…`\n : offendingPreview,\n }\n : {};\n try {\n this.provider?.stop();\n this.currentProvider.destroy();\n this.currentProvider = fallbackProvider;\n this.provider = await fallbackProvider.initialize(browserConfig);\n this.ttsConfig = browserConfig;\n await this.emitTelemetry(\"pie-tool-runtime-fallback\", {\n toolId: \"textToSpeech\",\n operation,\n fromProvider: previousProviderId,\n toProvider: fallbackProvider.providerId,\n reason: reason instanceof Error ? reason.message : String(reason),\n ...offendingDiagnostic,\n });\n console.warn(\"[TTSService] TTS provider initialization failed; switched to browser fallback\", {\n fromProvider: previousProviderId,\n reason,\n ...offendingDiagnostic,\n });\n return true;\n }\n catch (fallbackError) {\n await this.emitTelemetry(\"pie-tool-runtime-fallback-error\", {\n toolId: \"textToSpeech\",\n operation,\n fromProvider: previousProviderId,\n toProvider: \"browser\",\n errorType: \"TTSRuntimeFallbackError\",\n message: fallbackError instanceof Error\n ? fallbackError.message\n : String(fallbackError),\n });\n console.error(\"[TTSService] Failed to switch to browser fallback provider\", fallbackError);\n return false;\n }\n }\n isBrowserSpeechFallbackAvailable() {\n if (typeof window === \"undefined\")\n return false;\n if (!(\"speechSynthesis\" in window))\n return false;\n return (typeof globalThis\n .SpeechSynthesisUtterance === \"function\");\n }\n async applyLanguageSettings(options) {\n if (!options?.language || !this.provider)\n return;\n const providerOptions = (this.ttsConfig.providerOptions || {});\n const textNormalization = (providerOptions.textNormalization ||\n {});\n const segmenter = (providerOptions.segmenter || {});\n const mergedProviderOptions = {\n ...providerOptions,\n locale: options.language,\n textNormalization: {\n ...textNormalization,\n locale: options.language,\n },\n segmenter: {\n ...segmenter,\n locale: options.language,\n },\n };\n this.ttsConfig = {\n ...this.ttsConfig,\n providerOptions: mergedProviderOptions,\n };\n if (\"updateSettings\" in this.provider &&\n typeof this.provider.updateSettings ===\n \"function\") {\n await this.provider.updateSettings({ providerOptions: mergedProviderOptions });\n }\n }\n async resolveSpeechContent(text, options) {\n const normalizedInputText = normalizeTextForSpeech(text);\n if (options?.ignoreCatalogs) {\n return {\n contentToSpeak: normalizedInputText,\n speechText: normalizedInputText,\n visibleText: normalizedInputText,\n highlightText: normalizedInputText,\n usedCatalogSpoken: false,\n speechSource: \"dom-or-input\",\n normalizedText: normalizedInputText,\n containsMathMarkup: false,\n speechMatchesVisibleText: true,\n };\n }\n if (options?.catalogId && this.catalogResolver) {\n const catalogContent = this.catalogResolver.getAlternative(options.catalogId, {\n type: \"spoken\",\n language: options.language || \"en-US\",\n useFallback: true,\n context: options.catalogContext,\n form: \"content\",\n });\n // A card with no string form has nothing to speak — a signing card, for\n // instance. Fall through to generated TTS rather than speaking \"\".\n const spokenText = catalogContent?.content;\n if (catalogContent && spokenText !== undefined) {\n const visibleText = options?.contentElement\n ? collectMathAwareTextAndMap(options.contentElement, this.getTextProcessingOptions(options.language)).visibleText || normalizedInputText\n : normalizedInputText;\n const normalizedCatalogText = normalizeTextForSpeech(spokenText);\n this.debugLog(`[TTSService] Using catalog content for \"${options.catalogId}\" (${catalogContent.language})`);\n return {\n contentToSpeak: spokenText,\n speechText: spokenText,\n visibleText,\n highlightText: visibleText,\n usedCatalogSpoken: true,\n speechSource: \"catalog-spoken\",\n normalizedText: visibleText,\n containsMathMarkup: false,\n speechMatchesVisibleText: normalizedCatalogText === visibleText,\n };\n }\n this.debugLog(`[TTSService] No catalog found for \"${options.catalogId}\", falling back to generated TTS`);\n }\n const composed = options?.contentElement\n ? this.resolveCatalogComposedSpeechContent(options.contentElement, normalizedInputText, options)\n : null;\n if (composed)\n return composed;\n const generated = options?.contentElement\n ? await this.resolveGeneratedSpeechContent(options.contentElement, normalizedInputText, options.language)\n : {\n contentToSpeak: normalizedInputText,\n speechText: normalizedInputText,\n visibleText: normalizedInputText,\n highlightText: normalizedInputText,\n normalizedText: normalizedInputText,\n containsMathMarkup: false,\n speechMatchesVisibleText: true,\n };\n return {\n ...generated,\n usedCatalogSpoken: false,\n speechSource: \"dom-or-input\",\n };\n }\n resolveCatalogComposedSpeechContent(contentElement, normalizedInputText, options) {\n if (!this.catalogResolver)\n return null;\n const chunks = this.collectCatalogSpeechChunks(contentElement, options);\n if (!chunks.some((chunk) => chunk.sourceElement))\n return null;\n const speechText = normalizeTextForSpeech(chunks.map((chunk) => chunk.speechText).join(\" \"));\n const visibleText = collectMathAwareTextAndMap(contentElement, this.getTextProcessingOptions(options.language)).visibleText || normalizedInputText;\n return {\n contentToSpeak: speechText,\n speechText,\n visibleText,\n highlightText: visibleText,\n usedCatalogSpoken: true,\n speechSource: \"catalog-spoken\",\n normalizedText: visibleText,\n containsMathMarkup: false,\n speechMatchesVisibleText: chunks.every((chunk) => chunk.speechMatchesVisibleText),\n speechChunks: chunks,\n };\n }\n collectCatalogSpeechChunks(root, options) {\n const chunks = [];\n let textBuffer = \"\";\n const flushTextBuffer = () => {\n const visibleText = normalizeTextForSpeech(textBuffer);\n textBuffer = \"\";\n if (!visibleText)\n return;\n chunks.push({\n speechText: visibleText,\n visibleText,\n sourceElement: null,\n speechMatchesVisibleText: true,\n });\n };\n const resolveCatalog = (element) => {\n const catalogIdRef = element.getAttribute(\"data-catalog-idref\");\n if (!catalogIdRef)\n return null;\n const lookup = {\n type: \"spoken\",\n language: options.language || \"en-US\",\n useFallback: true,\n context: options.catalogContext,\n };\n // Two lookups rather than one, because `form` is a preference: asking for\n // the payload form happily returns a script card when no recording\n // exists, so the answer has to be checked rather than assumed.\n const audioCard = this.catalogResolver.getAlternative(catalogIdRef, {\n ...lookup,\n form: \"payload\",\n });\n const audio = audioCard?.payload\n ? (resolveSpokenAudioMedia({ payload: audioCard.payload }) ?? undefined)\n : undefined;\n const scriptCard = this.catalogResolver.getAlternative(catalogIdRef, {\n ...lookup,\n form: \"content\",\n });\n // Only a card with a string form can contribute synthesized speech. The\n // same docking node may also carry a signing card; that one is not ours.\n const script = scriptCard?.content;\n if (audio === undefined && script === undefined)\n return null;\n return { script, audio };\n };\n const getSingleMathElementForAlignment = (element, visibleText) => {\n const mathElements = getMathElementsForAlignment(element);\n if (mathElements.length !== 1)\n return null;\n const mathElement = mathElements[0];\n const mathVisibleText = collectMathAwareTextAndMap(mathElement, this.getTextProcessingOptions(options.language)).visibleText || normalizeTextForSpeech(mathElement.textContent || \"\");\n const compact = (value) => normalizeTextForSpeech(value).replace(/\\s+/g, \"\");\n return compact(mathVisibleText) === compact(visibleText)\n ? mathElement\n : null;\n };\n const getMathElementsForAlignment = (element) => {\n const mathElements = Array.from(element.querySelectorAll(\"math\"));\n if (element.localName?.toLowerCase() === \"math\") {\n return [element, ...mathElements];\n }\n return mathElements;\n };\n const visit = (node) => {\n // Before `resolveCatalog`, so suppression beats an authored `spoken`\n // card on the same node: the card says how to speak this content, the\n // suppression says it must not be spoken at all.\n if (isNodeExcludedFromSpeech(node, root))\n return;\n if (node.nodeType === Node.TEXT_NODE) {\n textBuffer += ` ${node.textContent || \"\"}`;\n return;\n }\n if (node.nodeType !== Node.ELEMENT_NODE)\n return;\n const element = node;\n const catalog = resolveCatalog(element);\n if (catalog) {\n flushTextBuffer();\n const collectedVisible = collectMathAwareTextAndMap(element, this.getTextProcessingOptions(options.language));\n const visibleText = collectedVisible.visibleText ||\n normalizeTextForSpeech(element.textContent || \"\");\n const regionElement = resolveReadableRegion(element, root);\n // The script chunk, when there is a script. Built exactly as before,\n // and it doubles as the recording's fallback: word-level alignment is\n // only meaningful for the synthesized path, which is the one that runs\n // if the audio cannot play.\n const scriptChunk = catalog.script !== undefined\n ? (() => {\n const script = catalog.script;\n const alignment = createCatalogSpanAlignment({\n speechText: script,\n visibleText,\n });\n const mathElement = getSingleMathElementForAlignment(element, visibleText);\n const mathAlignment = mathElement\n ? createMathAwareAlignment({\n mathElement,\n speechText: script,\n })\n : undefined;\n const mathAlignments = mathAlignment\n ? undefined\n : getMathElementsForAlignment(element).map((candidate) => ({\n element: candidate,\n alignment: createMathAwareAlignment({\n mathElement: candidate,\n speechText: script,\n }),\n }));\n return {\n speechText: script,\n visibleText,\n sourceElement: element,\n regionElement,\n speechMatchesVisibleText: normalizeTextForSpeech(script) === visibleText,\n playbackMode: alignment.playbackMode,\n alignment,\n mathAlignment,\n mathAlignments,\n visibleMap: collectedVisible.map,\n };\n })()\n : null;\n if (catalog.audio) {\n chunks.push(scriptChunk\n ? {\n ...scriptChunk,\n audio: catalog.audio,\n plainFallback: scriptChunk,\n }\n : {\n // No script to fall back to, and nothing synthesizes the\n // recording's words, so `speechText` exists only to keep seek\n // and offset bookkeeping consistent with the visible text.\n speechText: visibleText,\n visibleText,\n sourceElement: element,\n regionElement,\n speechMatchesVisibleText: false,\n visibleMap: collectedVisible.map,\n audio: catalog.audio,\n });\n return;\n }\n if (scriptChunk)\n chunks.push(scriptChunk);\n return;\n }\n for (const child of Array.from(element.childNodes)) {\n visit(child);\n }\n };\n visit(root);\n flushTextBuffer();\n return chunks;\n }\n /**\n * Decide the playback format for the generated (no authored catalog) math\n * path. SSML is only emitted to providers that report `supportsSSML`: the\n * browser Web Speech API speaks tags literally (capability `false`), and the\n * server bridge reports `true` only for SSML-reliable backends (Polly,\n * Google) — the `custom`/SchoolCity transport stays plain.\n *\n * A speak-time plain fallback (`SpeechCompositionChunk.plainFallback`) is the\n * defensive net if a capable provider still rejects a given SSML payload.\n */\n resolveGeneratedPlaybackFormat() {\n const provider = this.currentProvider;\n if (!provider)\n return \"plain\";\n // Belt-and-suspenders: the browser provider can never voice SSML.\n if (provider.providerId?.toLowerCase() === \"browser\")\n return \"plain\";\n return provider.getCapabilities?.().supportsSSML ? \"ssml\" : \"plain\";\n }\n async resolveGeneratedSpeechContent(contentElement, normalizedInputText, language) {\n // Delegate to the generated-speech module: a pure plan assembly + SRE\n // memoization core, plus a DOM adapter that binds live-DOM anchors and\n // emits playback chunks. The aggregate `contentToSpeak` stays plain text\n // (`plan.plainSpeechText`) so seek/structural-pause planning is unaffected.\n const playbackFormat = this.resolveGeneratedPlaybackFormat();\n const { plan, containsMathMarkup, visibleText: collectedVisibleText, } = await buildGeneratedSpeechFromRoot({\n contentRoot: contentElement,\n language,\n mathSpeech: this.getMathSpeechOptions(),\n textProcessingOptions: this.getTextProcessingOptions(language),\n produceSsml: playbackFormat === \"ssml\",\n resolveMathSpeech: this.generatedMathSpeechResolver,\n });\n const visibleText = collectedVisibleText || normalizedInputText;\n if (!containsMathMarkup) {\n return {\n contentToSpeak: visibleText,\n speechText: visibleText,\n visibleText,\n highlightText: visibleText,\n normalizedText: visibleText,\n containsMathMarkup: false,\n speechMatchesVisibleText: true,\n };\n }\n const speechChunks = planToCompositionChunkInputs(plan, {\n format: playbackFormat,\n });\n const speechText = plan.plainSpeechText;\n return {\n contentToSpeak: speechText,\n speechText,\n visibleText,\n highlightText: visibleText,\n normalizedText: visibleText,\n containsMathMarkup: true,\n speechMatchesVisibleText: speechText === visibleText,\n speechChunks,\n };\n }\n logResolvedSpeechContent(args) {\n const preview = args.contentToSpeak\n .replace(/\\s+/g, \" \")\n .trim()\n .slice(0, 200);\n this.debugLog(\"[TTSService] Speak resolved content\", {\n source: args.speechSource,\n catalogId: args.catalogId || null,\n length: args.contentToSpeak.length,\n preview,\n });\n }\n initializeSpeakTracking(contentToSpeak, options) {\n this.currentText = contentToSpeak;\n this.currentContentElement = options?.contentElement || null;\n this.lastError = null;\n this.currentBoundaryOffset = 0;\n this.playbackChunks = [];\n this.currentSeekSegmentIndex = 0;\n this.activeSentenceStartOffset = null;\n }\n prepareHighlightsForSpeak(args) {\n if (!this.currentContentElement || !this.highlightCoordinator)\n return;\n this.buildPositionMap(this.currentContentElement, args.contentToSpeak, args.options?.language);\n if (args.highlightMode === \"sentence\" && args.shouldUsePlan) {\n return;\n }\n const initialSegment = this.sentenceHighlightSegments[0] || this.seekSegments[0];\n this.runWhenPlaybackStarts(args.runId, () => {\n if (initialSegment) {\n this.highlightSentenceSegment(initialSegment.startOffset, initialSegment.text);\n this.debugLog(\"[TTSService] Applied initial sentence highlighting\");\n }\n else {\n try {\n const range = document.createRange();\n range.selectNodeContents(this.currentContentElement);\n this.paintTTSSentenceRanges([range]);\n }\n catch {\n // No-op fallback when DOM range creation fails.\n }\n }\n });\n }\n configureWordBoundaryHighlighting(args) {\n if (!this.provider ||\n args.highlightMode !== \"word\" ||\n !this.highlightCoordinator ||\n !this.currentContentElement) {\n return;\n }\n // Word index uses the same globalIndex as highlightTTSWord (browser boundaries\n // or ServerTTSProvider time-scaled onWordBoundary).\n this.provider.onWordBoundary = (word, charIndex, length) => {\n const wordLength = length || word.length;\n const globalIndex = charIndex + this.currentBoundaryOffset + args.wordBoundaryOffset;\n this.highlightSentenceForOffset(globalIndex);\n const highlightRange = this.findHighlightRange(globalIndex, wordLength);\n if (highlightRange && this.highlightCoordinator) {\n const highlightText = highlightRange.node.textContent?.substring(highlightRange.start, highlightRange.end) || \"\";\n this.debugLog(`[TTSService] Highlighting \"${highlightText}\" (word: \"${word}\") at position ${globalIndex}`);\n const nativeRange = this.createTextRange(highlightRange.node, highlightRange.start, highlightRange.end);\n if (nativeRange) {\n this.paintTTSWordRange(this.resolveWordHighlightRange(nativeRange).range);\n }\n else {\n this.highlightCoordinator.highlightTTSWord(highlightRange.node, highlightRange.start, highlightRange.end);\n }\n }\n else {\n console.warn(`[TTSService] Could not find highlight range for position ${globalIndex}, length ${wordLength}`);\n }\n };\n }\n clearWordBoundaryHighlighting() {\n if (this.provider) {\n this.provider.onWordBoundary = undefined;\n }\n }\n highlightCatalogRegion(chunk) {\n const element = chunk.regionElement || chunk.sourceElement;\n if ((!element && !chunk.regionRange) || !this.highlightCoordinator)\n return;\n try {\n this.lastRenderedRegionTarget = null;\n if (chunk.regionRange) {\n this.highlightCoordinator.clearHighlights?.(HighlightType.TTS_WORD);\n this.paintTTSSentenceRanges([chunk.regionRange]);\n return;\n }\n if (!element)\n return;\n const range = document.createRange();\n range.selectNodeContents(element);\n this.highlightCoordinator.clearHighlights?.(HighlightType.TTS_WORD);\n this.paintTTSSentenceRanges([range]);\n }\n catch {\n // Continue playback even when a detached node cannot be highlighted.\n }\n }\n highlightCatalogActiveRange(range) {\n if (!this.highlightCoordinator)\n return;\n this.paintTTSWordRange(this.resolveWordHighlightRange(range).range);\n }\n highlightRenderableRegionTarget(target) {\n if (!this.highlightCoordinator ||\n !target ||\n typeof document === \"undefined\") {\n return;\n }\n if (!this.highlightTargetResolverProvider &&\n sameRenderableHighlightTarget(this.lastRenderedRegionTarget, target)) {\n return;\n }\n try {\n const range = document.createRange();\n if (target.type === \"element\") {\n range.selectNodeContents(target.element);\n }\n else if (target.type === \"range\") {\n this.paintTTSSentenceRanges([target.range]);\n this.lastRenderedRegionTarget = target;\n return;\n }\n else {\n range.setStart(target.node, target.startOffset);\n range.setEnd(target.node, target.endOffset);\n }\n this.paintTTSSentenceRanges([range]);\n this.lastRenderedRegionTarget = target;\n }\n catch {\n // Continue playback even when a detached node cannot be highlighted.\n }\n }\n highlightRenderableActiveTarget(target) {\n if (!this.highlightCoordinator || typeof document === \"undefined\") {\n return;\n }\n if (!target) {\n // No active word for this boundary — an unresolved prose word, an SSML\n // break/pause, or a token-mode equation still awaiting its first token.\n // Clear the word layer so the previously spoken word does not stay\n // highlighted. (The \"hold last token\" behavior returns a non-null\n // target, so it does not reach here.)\n this.highlightCoordinator.clearHighlights(HighlightType.TTS_WORD);\n return;\n }\n if (target.type === \"text-range\") {\n const nativeRange = this.createTextRange(target.node, target.startOffset, target.endOffset);\n if (nativeRange) {\n this.paintTTSWordRange(this.resolveWordHighlightRange(nativeRange).range);\n }\n else {\n this.highlightCoordinator.highlightTTSWord(target.node, target.startOffset, target.endOffset);\n }\n return;\n }\n if (target.type === \"range\") {\n this.highlightCatalogActiveRange(target.range);\n return;\n }\n const elementNativeRange = document.createRange();\n elementNativeRange.selectNodeContents(target.element);\n const resolvedElementRange = this.resolveWordHighlightRange(elementNativeRange);\n if (resolvedElementRange.remapped) {\n this.paintTTSWordRange(resolvedElementRange.range);\n return;\n }\n // Element targets are atomic: a resolved math token, a whole-expression\n // fallback, or a replaced element (image/svg). Paint exactly the resolved\n // element. Native MathML / HTML tokens that expose a single text node keep\n // the CSS-range underline (it reads more precisely than an element box);\n // everything else — notably MathJax CHTML tokens (`<mjx-mi><mjx-c/>`),\n // which have no text node, and expression fallbacks — is marked on the\n // element itself. Crucially we no longer escalate to the enclosing\n // `<math>` / `<mjx-container>`: that escalation is why MathJax math only\n // ever highlighted as a full block while native MathML tracked per-token.\n const onlyChild = target.element.childNodes.length === 1 ? target.element.firstChild : null;\n if (target.quality === \"semantic-token\" &&\n onlyChild?.nodeType === Node.TEXT_NODE) {\n this.highlightCoordinator.highlightTTSWord(onlyChild, 0, onlyChild.textContent?.length || 0);\n return;\n }\n this.highlightCoordinator.highlightTTSWordElement?.(target.element);\n }\n renderHighlightDecision(decision) {\n this.highlightRenderableRegionTarget(decision.regionTarget);\n this.highlightRenderableActiveTarget(decision.activeTarget);\n }\n async speakCatalogChunk(chunk, runId) {\n try {\n await this.speakCatalogChunkOnce(chunk, runId);\n }\n catch (error) {\n // Speak-time fallback: if an SSML math chunk is rejected by the\n // provider, retry once with its precomputed plain-text variant (same\n // anchors, plain alignment). The fallback chunk carries no further\n // fallback, so this cannot recurse.\n if (chunk.plainFallback && runId === this.speakRunId) {\n this.debugLog(\"[TTSService] SSML chunk speak failed; retrying plain text\", { message: error instanceof Error ? error.message : String(error) });\n // A recorded-first run can own the start barrier even when its fallback\n // provider has no formal start signal. Drop the failed recording's queued\n // highlight and resume that non-start-aware provider's immediate-start lifecycle.\n if (this.playbackStartDeferredRunId === runId &&\n this.provider &&\n !(\"onPlaybackStart\" in this.provider)) {\n this.pendingPlaybackStartHighlights = [];\n this.clearPlaybackStartBarrier();\n this.setState(PlaybackState.PLAYING);\n }\n await this.speakCatalogChunkOnce(chunk.plainFallback, runId);\n return;\n }\n throw error;\n }\n }\n /**\n * Play a recorded spoken alternate, resolving when it finishes.\n *\n * Rejects if the clip cannot play, which is what routes playback to the\n * chunk's `plainFallback` — the reading script — in `speakCatalogChunk`.\n * Highlighting is the docked node as a block for the clip's duration: a\n * recording emits no word boundaries, and inventing them from its duration\n * would highlight the wrong words confidently rather than the right region\n * vaguely.\n */\n async playRecordedAudio(media, onPlaybackStart) {\n if (typeof document === \"undefined\") {\n throw new Error(\"[tts] no document available to play recorded audio\");\n }\n const source = media.sources[0];\n const element = document.createElement(\"audio\");\n element.preload = \"auto\";\n element.src = applyMediaFragment(source.src, media.fragment);\n element.playbackRate = this.normalizePlaybackRate(Number(this.ttsConfig.rate || 1));\n await new Promise((resolve, reject) => {\n let disposeFragment;\n let didStart = false;\n let settled = false;\n const markStarted = () => {\n if (settled || didStart)\n return;\n didStart = true;\n onPlaybackStart?.();\n };\n const cleanup = () => {\n element.removeEventListener(\"ended\", onEnded);\n element.removeEventListener(\"error\", onError);\n element.removeEventListener(\"playing\", markStarted);\n disposeFragment?.();\n if (this.activeRecordedAudio?.element === element) {\n this.activeRecordedAudio = null;\n }\n };\n const onEnded = () => {\n if (settled)\n return;\n settled = true;\n cleanup();\n resolve();\n };\n const onError = () => {\n if (settled)\n return;\n settled = true;\n cleanup();\n reject(new Error(`[tts] recorded audio failed to play: ${source.src}`));\n };\n // Cancellation has to settle this promise, not just stop the element:\n // `stop()` bumps the run id, and a pending play that never resolves would\n // wedge the chunk loop on a run nobody is listening to any more.\n this.activeRecordedAudio = {\n element,\n cancel: () => {\n if (settled)\n return;\n settled = true;\n cleanup();\n element.pause();\n resolve();\n },\n };\n element.addEventListener(\"ended\", onEnded);\n element.addEventListener(\"error\", onError);\n element.addEventListener(\"playing\", markStarted);\n // Reaching the slice's end is this clip finishing, so the chunk sequence\n // advances rather than the element merely pausing.\n disposeFragment = enforceMediaFragment(element, media.fragment, onEnded);\n Promise.resolve(element.play()).then(markStarted).catch(onError);\n }).finally(() => {\n if (this.activeRecordedAudio?.element === element) {\n this.activeRecordedAudio = null;\n }\n element.pause();\n element.removeAttribute(\"src\");\n });\n }\n cancelRecordedAudio() {\n const active = this.activeRecordedAudio;\n if (!active)\n return;\n this.activeRecordedAudio = null;\n active.cancel();\n }\n async speakCatalogChunkOnce(chunk, runId) {\n if (!this.provider)\n return;\n this.lastRenderedRegionTarget = null;\n if (chunk.audio) {\n this.runWhenPlaybackStarts(runId, () => {\n this.highlightCatalogRegion(chunk);\n });\n await this.playRecordedAudio(chunk.audio, () => {\n this.notifyPlaybackStarted(runId);\n });\n return;\n }\n const contentRoot = chunk.regionElement || chunk.sourceElement || this.currentContentElement;\n const pipelineChunk = contentRoot\n ? normalizeSpeechChunks({\n contentRoot,\n chunks: [chunk],\n })[0]\n : null;\n // Carried through the config channel (see buildRuntimeTTSConfig); defaults\n // to per-token math highlighting unless a host explicitly disables it.\n const mathTokenHighlighting = this.ttsConfig.mathTokenHighlighting !== false;\n const highlightPlan = pipelineChunk\n ? createTTSHighlightPlan({\n chunks: [pipelineChunk],\n mathTokenHighlighting,\n })\n : null;\n this.runWhenPlaybackStarts(runId, () => {\n if (highlightPlan && pipelineChunk && chunk.mathAlignment) {\n this.renderHighlightDecision(highlightPlan.resolveInitial(pipelineChunk.id));\n }\n else {\n this.highlightCatalogRegion(chunk);\n }\n });\n const canUseChunkBoundaries = chunk.sourceElement &&\n ((chunk.mathAlignment && chunk.mathAlignment.speech.tokens.length > 0) ||\n (chunk.mathAlignments && chunk.mathAlignments.length > 0) ||\n (chunk.alignment &&\n chunk.visibleMap &&\n (chunk.playbackMode === \"exact-word\" ||\n chunk.playbackMode === \"anchor-span\")));\n if (!canUseChunkBoundaries) {\n const provider = this.provider;\n const previousOnWordBoundary = provider.onWordBoundary;\n provider.onWordBoundary = undefined;\n try {\n await provider.speak(chunk.speechText);\n }\n finally {\n if (this.provider === provider &&\n runId === this.speakRunId &&\n provider.onWordBoundary === undefined) {\n provider.onWordBoundary = previousOnWordBoundary;\n }\n }\n return;\n }\n const provider = this.provider;\n const previousOnWordBoundary = provider.onWordBoundary;\n const installedHandler = (word, position, length) => {\n if (runId !== this.speakRunId)\n return;\n if (highlightPlan && pipelineChunk) {\n const providerOffsetSpace = pipelineChunk.offsetSpace === \"unsupported\"\n ? \"unknown\"\n : pipelineChunk.offsetSpace;\n this.renderHighlightDecision(highlightPlan.resolveBoundary({\n chunkId: pipelineChunk.id,\n word,\n position,\n length,\n providerOffsetSpace,\n }));\n return;\n }\n };\n provider.onWordBoundary = installedHandler;\n try {\n await provider.speak(chunk.speechText);\n }\n finally {\n if (this.provider === provider &&\n runId === this.speakRunId &&\n provider.onWordBoundary === installedHandler) {\n provider.onWordBoundary = previousOnWordBoundary;\n }\n }\n }\n async executeSpeakPlayback(args) {\n if (args.speechChunks?.length && this.provider) {\n for (let index = 0; index < args.speechChunks.length; index++) {\n if (args.runId !== this.speakRunId)\n return;\n this.currentSeekSegmentIndex = index;\n const segment = this.seekSegments[index];\n if (segment) {\n this.currentBoundaryOffset = segment.startOffset;\n }\n const chunk = args.speechChunks[index];\n await this.speakCatalogChunk(chunk, args.runId);\n }\n return;\n }\n if (args.shouldUsePlan && this.currentContentElement) {\n const segments = this.seekSegments;\n if (segments.length > 0) {\n await this.speakWithPlan(segments, args.runId, {\n highlightMode: args.highlightMode,\n });\n }\n else if (this.provider) {\n await this.provider.speak(args.contentToSpeak);\n }\n return;\n }\n if (this.provider) {\n await this.provider.speak(args.contentToSpeak);\n }\n }\n clearHighlightsAndTracking() {\n this.pendingPlaybackStartHighlights = [];\n this.activePlaybackRate = null;\n if (this.highlightCoordinator) {\n this.highlightCoordinator.clearTTS();\n }\n this.lastRenderedRegionTarget = null;\n this.currentContentElement = null;\n this.normalizedToDOM.clear();\n this.currentBoundaryOffset = 0;\n this.activeWordBoundaryOffset = 0;\n this.seekSegments = [];\n this.playbackChunks = [];\n this.sentenceHighlightSegments = [];\n this.currentSeekSegmentIndex = 0;\n this.activeSentenceStartOffset = null;\n }\n /**\n * Speak a text range with accurate word highlighting\n *\n * This calculates the offset of the range within its parent element\n * to ensure word highlighting aligns correctly with the selected text.\n *\n * @param range DOM Range to speak\n */\n async speakRange(range, options) {\n if (!this.provider) {\n throw new Error(\"TTS service not initialized\");\n }\n // Enforced from the live ancestors rather than from `root`, because the\n // element carrying the suppression may sit above whatever root the caller\n // passed or the range happens to resolve to.\n if (isNodeSuppressedForTTS(range.commonAncestorContainer)) {\n console.warn(\"[tts] selection lies inside content marked not-to-be-spoken; nothing was spoken. Selecting a node and pressing read-aloud must not become a way around suppression.\");\n return;\n }\n // Use explicit content root when provided; otherwise keep highlighting scoped\n // to the selected range's nearest element ancestor.\n const fromOptions = options?.contentRoot || null;\n let root = fromOptions;\n if (!root) {\n const ancestor = range.commonAncestorContainer;\n root =\n ancestor.nodeType === Node.ELEMENT_NODE\n ? ancestor\n : ancestor.parentElement;\n }\n if (!root)\n return;\n const selected = collectRangeTextForSpeech(range, root);\n const text = selected.text.trim();\n if (!text) {\n if (selected.filtered) {\n console.warn(\"[tts] every part of the selection is either hidden or marked not-to-be-spoken; nothing was spoken.\");\n }\n return;\n }\n // Calculate the offset of the range start within the root element. Filtered\n // the same way as the speech itself: the offset indexes into the highlight\n // text, which comes from the exclusion-aware collectors, so counting\n // characters here that never reach that text would shift every highlight\n // after the excluded node.\n const beforeRange = document.createRange();\n beforeRange.selectNodeContents(root);\n beforeRange.setEnd(range.startContainer, range.startOffset);\n const textBeforeRange = collectRangeTextForSpeech(beforeRange, root).text;\n const normalizedTextBeforeRange = normalizeTextForSpeech(textBeforeRange);\n const offset = normalizedTextBeforeRange.length +\n (/\\s$/.test(textBeforeRange) && normalizedTextBeforeRange ? 1 : 0);\n this.debugLog(\"[TTSService] speakRange offset calculation:\", {\n selectedText: text,\n textBeforeRange: textBeforeRange.substring(0, 100),\n offset,\n rootTag: root.tagName,\n });\n // Speak the text with the root element as context\n await this.speak(text, {\n contentElement: root,\n ignoreCatalogs: true,\n wordBoundaryOffset: offset,\n });\n }\n /**\n * Pause playback\n */\n pause() {\n if (!this.provider)\n return;\n if (this.state === PlaybackState.PLAYING) {\n this.activeRecordedAudio?.element.pause();\n this.provider.pause();\n this.setState(PlaybackState.PAUSED);\n }\n }\n /**\n * Resume playback\n */\n resume() {\n if (!this.provider)\n return;\n if (this.state === PlaybackState.PAUSED) {\n const recorded = this.activeRecordedAudio?.element;\n if (recorded)\n void Promise.resolve(recorded.play()).catch(() => { });\n this.provider.resume();\n this.setState(PlaybackState.PLAYING);\n }\n }\n normalizePlaybackRate(rate) {\n if (!Number.isFinite(rate))\n return 1;\n return Math.max(0.25, Math.min(4, rate));\n }\n async restartFromSeekIndex(targetIndex) {\n if (!this.provider || this.seekSegments.length === 0)\n return;\n const safeTargetIndex = Math.max(0, Math.min(this.seekSegments.length - 1, targetIndex));\n const restartChunks = this.playbackChunks.length\n ? this.playbackChunks.slice(safeTargetIndex)\n : null;\n this.speakRunId += 1;\n this.clearPlaybackStartBarrier();\n this.cancelRecordedAudio();\n this.provider.onWordBoundary = undefined;\n this.provider.stop();\n this.currentSeekSegmentIndex = safeTargetIndex;\n const runId = ++this.speakRunId;\n const restartSegments = this.seekSegments.slice(safeTargetIndex);\n this.highlightCoordinator?.clearTTS();\n this.activeSentenceStartOffset = null;\n this.setState(PlaybackState.LOADING);\n const playbackStartBarrier = this.installPlaybackStartBarrier(runId, !!restartChunks?.[0]?.audio);\n if (!playbackStartBarrier) {\n this.setState(PlaybackState.PLAYING);\n }\n this.activePlaybackRate = this.normalizePlaybackRate(Number(this.ttsConfig.rate ?? 1));\n try {\n this.configureWordBoundaryHighlighting({\n highlightMode: this.activeHighlightMode,\n wordBoundaryOffset: this.activeWordBoundaryOffset,\n });\n if (restartChunks) {\n for (let index = 0; index < restartChunks.length; index++) {\n if (runId !== this.speakRunId)\n return;\n const absoluteIndex = safeTargetIndex + index;\n this.currentSeekSegmentIndex = absoluteIndex;\n const segment = this.seekSegments[absoluteIndex];\n if (segment) {\n this.currentBoundaryOffset = segment.startOffset;\n }\n await this.speakCatalogChunk(restartChunks[index], runId);\n }\n }\n else {\n await this.speakWithPlan(restartSegments, runId, {\n highlightMode: this.activeHighlightMode,\n });\n }\n if (runId !== this.speakRunId)\n return;\n this.setState(PlaybackState.IDLE);\n this.clearHighlightsAndTracking();\n }\n catch (error) {\n if (runId !== this.speakRunId)\n return;\n this.lastError = error instanceof Error ? error.message : String(error);\n this.setState(PlaybackState.ERROR);\n this.clearHighlightsAndTracking();\n throw error;\n }\n finally {\n this.clearPlaybackStartBarrier(playbackStartBarrier);\n }\n }\n async setPlaybackRate(rate) {\n if (!this.provider) {\n throw new Error(\"TTSService not initialized. Call initialize() first.\");\n }\n const nextRate = this.normalizePlaybackRate(rate);\n const pendingRequest = this.pendingPlaybackRateRequest;\n if (pendingRequest?.rate === nextRate) {\n await pendingRequest.promise;\n return;\n }\n const requestId = ++this.playbackRateRequestId;\n const settingsWrite = this.playbackRateWriteQueue.then(async () => {\n const playbackRunId = this.speakRunId;\n // A newer distinct target supersedes queued work before it mutates either\n // provider settings or playback. An already-running write cannot be\n // cancelled, so its post-write generation check still suppresses restart.\n if (requestId !== this.playbackRateRequestId) {\n return { didUpdate: false, playbackRunId };\n }\n // An omitted rate is the provider-default 1× rate. Re-check inside the\n // serialized operation so overlapping callers observe the preceding write.\n const currentRate = this.normalizePlaybackRate(Number(this.ttsConfig.rate ?? 1));\n if (nextRate === currentRate) {\n return { didUpdate: false, playbackRunId };\n }\n await this.updateSettings({ rate: nextRate });\n return { didUpdate: true, playbackRunId };\n });\n this.playbackRateWriteQueue = settingsWrite.then(() => undefined, () => undefined);\n const operation = settingsWrite.then(async (result) => {\n if (requestId !== this.playbackRateRequestId ||\n result.playbackRunId !== this.speakRunId) {\n return;\n }\n const activePlaybackNeedsRate = this.activePlaybackRate !== null &&\n this.activePlaybackRate !== nextRate;\n if (!result.didUpdate && !activePlaybackNeedsRate)\n return;\n if ((this.state !== PlaybackState.PLAYING &&\n this.state !== PlaybackState.LOADING) ||\n !this.currentText ||\n this.seekSegments.length === 0 ||\n this.hasExplicitBreakSemantics(this.currentText)) {\n return;\n }\n await this.restartFromSeekIndex(this.getCurrentSeekSegmentIndex());\n });\n let trackedOperation;\n trackedOperation = operation.finally(() => {\n if (this.pendingPlaybackRateRequest?.promise === trackedOperation) {\n this.pendingPlaybackRateRequest = null;\n }\n });\n this.pendingPlaybackRateRequest = {\n rate: nextRate,\n promise: trackedOperation,\n };\n await trackedOperation;\n }\n async seekBy(units) {\n if (!this.provider || !this.currentText)\n return;\n if (this.state !== PlaybackState.PLAYING &&\n this.state !== PlaybackState.PAUSED) {\n return;\n }\n if (this.hasExplicitBreakSemantics(this.currentText))\n return;\n if (this.seekSegments.length === 0)\n return;\n const delta = Number.isFinite(units) ? Math.trunc(units) : 0;\n if (delta === 0)\n return;\n const currentIndex = this.getCurrentSeekSegmentIndex();\n const targetIndex = Math.max(0, Math.min(this.seekSegments.length - 1, currentIndex + delta));\n if (targetIndex === currentIndex)\n return;\n await this.restartFromSeekIndex(targetIndex);\n }\n async seekForward(units = 1) {\n const step = Number.isFinite(units) ? Math.max(1, Math.trunc(units)) : 1;\n await this.seekBy(step);\n }\n async seekBackward(units = 1) {\n const step = Number.isFinite(units) ? Math.max(1, Math.trunc(units)) : 1;\n await this.seekBy(-step);\n }\n /**\n * Stop playback\n */\n stop() {\n if (!this.provider)\n return;\n this.speakRunId += 1;\n this.clearPlaybackStartBarrier();\n this.cancelRecordedAudio();\n this.provider.onWordBoundary = undefined;\n this.provider.stop();\n this.setState(PlaybackState.IDLE);\n this.currentText = null;\n // Clear highlights\n if (this.highlightCoordinator) {\n this.highlightCoordinator.clearTTS();\n }\n // Clear tracking\n this.lastRenderedRegionTarget = null;\n this.currentContentElement = null;\n this.normalizedToDOM.clear();\n this.currentBoundaryOffset = 0;\n this.activeWordBoundaryOffset = 0;\n this.seekSegments = [];\n this.playbackChunks = [];\n this.sentenceHighlightSegments = [];\n this.currentSeekSegmentIndex = 0;\n this.activeSentenceStartOffset = null;\n this.activePlaybackRate = null;\n }\n /**\n * Request UI-level TTS controls to hand off/deactivate.\n *\n * This is intentionally separate from playback controls so hosts can orchestrate\n * control handoff explicitly (for example: stop playback, then dismiss controls).\n */\n requestControlHandoff() {\n if (typeof window === \"undefined\")\n return;\n const detail = { source: \"host\" };\n window.dispatchEvent(new CustomEvent(PIE_TTS_CONTROL_HANDOFF_EVENT, {\n detail,\n }));\n }\n /**\n * Check if currently playing\n */\n isPlaying() {\n return this.state === PlaybackState.PLAYING;\n }\n /**\n * Check if paused\n */\n isPaused() {\n return this.state === PlaybackState.PAUSED;\n }\n /**\n * Get current state\n */\n getState() {\n return this.state;\n }\n /**\n * Get current text being spoken\n */\n getCurrentText() {\n return this.currentText;\n }\n /**\n * Get the last error message\n * Returns null if no error has occurred\n */\n getLastError() {\n return this.lastError;\n }\n /**\n * Subscribe to state changes\n *\n * @param id Unique listener ID\n * @param callback Function to call on state change\n */\n onStateChange(id, callback) {\n if (!this.listeners.has(id)) {\n this.listeners.set(id, new Set());\n }\n this.listeners.get(id).add(callback);\n }\n /**\n * Unsubscribe from state changes\n */\n offStateChange(id, callback) {\n const callbacks = this.listeners.get(id);\n if (callbacks) {\n callbacks.delete(callback);\n if (callbacks.size === 0) {\n this.listeners.delete(id);\n }\n }\n }\n /**\n * Set state and notify listeners\n */\n setState(newState) {\n if (this.state === newState)\n return;\n const previousState = this.state;\n this.state = newState;\n // Notify all listeners\n for (const callbacks of this.listeners.values()) {\n for (const callback of callbacks) {\n callback(newState);\n }\n }\n void this.emitTelemetry(\"pie-tool-playback-state-changed\", {\n toolId: \"textToSpeech\",\n providerId: \"tts\",\n previousState,\n state: newState,\n });\n if (newState === PlaybackState.PLAYING) {\n const eventName = previousState === PlaybackState.PAUSED\n ? \"pie-tool-playback-resume\"\n : \"pie-tool-playback-start\";\n void this.emitTelemetry(eventName, {\n toolId: \"textToSpeech\",\n providerId: \"tts\",\n previousState,\n state: newState,\n });\n return;\n }\n if (newState === PlaybackState.PAUSED) {\n void this.emitTelemetry(\"pie-tool-playback-pause\", {\n toolId: \"textToSpeech\",\n providerId: \"tts\",\n previousState,\n state: newState,\n });\n return;\n }\n if (newState === PlaybackState.ERROR) {\n void this.emitTelemetry(\"pie-tool-playback-error\", {\n toolId: \"textToSpeech\",\n providerId: \"tts\",\n previousState,\n state: newState,\n message: this.lastError || undefined,\n });\n return;\n }\n if (newState === PlaybackState.IDLE &&\n (previousState === PlaybackState.PLAYING ||\n previousState === PlaybackState.PAUSED ||\n previousState === PlaybackState.LOADING)) {\n void this.emitTelemetry(\"pie-tool-playback-stop\", {\n toolId: \"textToSpeech\",\n providerId: \"tts\",\n previousState,\n state: newState,\n });\n }\n }\n}\n","import { normalizeSREMathSpeechOptions, } from \"./tts/math-speech.js\";\nconst VALID_TTS_LAYOUT_MODES = new Set([\n \"reserved-row\",\n \"expanding-row\",\n \"floating-overlay\",\n \"left-aligned\",\n]);\nconst toRecord = (value) => value && typeof value === \"object\" ? value : {};\nconst isServerBackend = (backend) => backend === \"polly\" || backend === \"google\" || backend === \"server\";\nconst withDefault = (value, fallback) => value === undefined ? fallback : value;\nexport const normalizeTTSLayoutMode = (value, fallback = \"left-aligned\") => typeof value === \"string\" &&\n VALID_TTS_LAYOUT_MODES.has(value)\n ? value\n : fallback;\n/** Legacy numeric helper defaults. Rendered controls add visible Normal separately. */\nexport const DEFAULT_TTS_SPEED_OPTIONS = Object.freeze([0.8, 1.25]);\nconst DEFAULT_TTS_SPEED_CONTROL_OPTIONS = Object.freeze([\n { rate: 0.8, label: \"Slow\", ariaLabel: \"Slow speed\" },\n { rate: 1, label: \"Normal\", ariaLabel: \"Normal speed\", default: true },\n { rate: 1.25, label: \"Fast\", ariaLabel: \"Fast speed\" },\n]);\nconst normalizeSpeedRate = (entry) => {\n if (typeof entry !== \"number\" || !Number.isFinite(entry) || entry <= 0) {\n return undefined;\n }\n const rounded = Math.round(entry * 100) / 100;\n return rounded === 1 ? undefined : rounded;\n};\nconst normalizeControlSpeedRate = (entry) => {\n if (typeof entry !== \"number\" || !Number.isFinite(entry) || entry <= 0) {\n return undefined;\n }\n return Math.round(entry * 100) / 100;\n};\nconst trimOptionalText = (value) => {\n if (typeof value !== \"string\")\n return undefined;\n const trimmed = value.trim();\n return trimmed.length ? trimmed : undefined;\n};\nconst formatSpeedLabel = (rate) => `${rate}x`;\nconst formatSpeedAriaLabel = (label, usedDefaultLabel) => label.toLowerCase() === \"normal\"\n ? \"Normal speed\"\n : usedDefaultLabel\n ? `Speed ${label}`\n : `${label} speed`;\nconst normalizeSpeedAriaLabel = (label, ariaLabel, usedDefaultLabel) => {\n if (!ariaLabel)\n return formatSpeedAriaLabel(label, usedDefaultLabel);\n if (ariaLabel.toLowerCase().includes(label.toLowerCase()))\n return ariaLabel;\n return `${label} ${ariaLabel}`;\n};\nconst normalizeTTSSpeedOptionConfig = (entry) => {\n if (typeof entry === \"number\")\n return normalizeSpeedRate(entry);\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry))\n return undefined;\n const record = entry;\n const rate = normalizeSpeedRate(record.rate);\n if (rate === undefined)\n return undefined;\n const label = trimOptionalText(record.label);\n const ariaLabel = trimOptionalText(record.ariaLabel);\n return {\n rate,\n ...(label ? { label } : {}),\n ...(ariaLabel ? { ariaLabel } : {}),\n };\n};\nexport const normalizeTTSSpeedOptionConfigs = (value) => {\n if (!Array.isArray(value))\n return [...DEFAULT_TTS_SPEED_OPTIONS];\n if (value.length === 0)\n return [];\n const dedupedRates = new Set();\n const normalized = [];\n for (const entry of value) {\n const option = normalizeTTSSpeedOptionConfig(entry);\n if (option === undefined)\n continue;\n const rate = typeof option === \"number\" ? option : option.rate;\n if (dedupedRates.has(rate))\n continue;\n dedupedRates.add(rate);\n normalized.push(option);\n }\n return normalized.length ? normalized : [...DEFAULT_TTS_SPEED_OPTIONS];\n};\n/**\n * Resolves inline toolbar speed options from host config.\n * - Omitted/non-array: default speed buttons.\n * - Empty array: hide speed buttons.\n * - Arrays that sanitize to no valid values: default speed buttons.\n * - 1.0× is never shown as a discrete speed button.\n */\nexport const normalizeTTSSpeedOptions = (value) => {\n if (!Array.isArray(value))\n return [...DEFAULT_TTS_SPEED_OPTIONS];\n if (value.length === 0)\n return [];\n return normalizeTTSSpeedOptionConfigs(value).map((option) => typeof option === \"number\" ? option : option.rate);\n};\nexport const normalizeTTSSpeedControlOptions = (value) => {\n const input = Array.isArray(value)\n ? value\n : [...DEFAULT_TTS_SPEED_CONTROL_OPTIONS];\n if (input.length === 0)\n return [];\n const dedupedRates = new Set();\n const normalized = [];\n for (const entry of input) {\n const record = toRecord(entry);\n const rate = typeof entry === \"number\"\n ? normalizeControlSpeedRate(entry)\n : normalizeControlSpeedRate(record.rate);\n if (rate === undefined || dedupedRates.has(rate))\n continue;\n dedupedRates.add(rate);\n const defaultLabel = rate === 1\n ? \"Normal\"\n : typeof entry === \"number\"\n ? formatSpeedLabel(rate)\n : formatSpeedLabel(rate);\n const label = typeof entry === \"number\"\n ? defaultLabel\n : trimOptionalText(record.label) || defaultLabel;\n const ariaLabel = typeof entry === \"number\"\n ? rate === 1\n ? \"Normal speed\"\n : formatSpeedAriaLabel(label, true)\n : normalizeSpeedAriaLabel(label, trimOptionalText(record.ariaLabel), label === defaultLabel);\n normalized.push({\n rate,\n label,\n ariaLabel,\n isDefault: false,\n requestedDefault: record.default === true ||\n record.isDefault === true,\n });\n }\n if (!normalized.length) {\n return normalizeTTSSpeedControlOptions(DEFAULT_TTS_SPEED_CONTROL_OPTIONS);\n }\n if (!dedupedRates.has(1)) {\n const normalOption = {\n rate: 1,\n label: \"Normal\",\n ariaLabel: \"Normal speed\",\n isDefault: false,\n requestedDefault: false,\n };\n const firstFasterIndex = normalized.findIndex((option) => option.rate > 1);\n if (firstFasterIndex >= 0) {\n normalized.splice(firstFasterIndex, 0, normalOption);\n }\n else {\n normalized.push(normalOption);\n }\n }\n const requestedDefaultIndex = normalized.findIndex((option) => option.requestedDefault);\n const defaultIndex = requestedDefaultIndex >= 0\n ? requestedDefaultIndex\n : normalized.findIndex((option) => option.rate === 1);\n return normalized.map(({ requestedDefault: _requestedDefault, ...option }, index) => ({\n ...option,\n isDefault: index === defaultIndex,\n }));\n};\nexport const formatTTSSpeedOptionsAsText = (values) => values.join(\", \");\nconst DEFAULT_TTS_SPEED_CONTROL_RATES = Object.freeze([0.8, 1, 1.25]);\n/**\n * Parse comma/semicolon-separated multipliers from settings UI text.\n * - Empty or whitespace-only string → hide speed buttons (`[]`).\n * - Non-empty text with no parseable finite numbers → same as invalid-only array config: defaults.\n */\nexport const parseTTSSpeedOptionsFromText = (text) => {\n const trimmed = text.trim();\n if (!trimmed)\n return [];\n const parts = trimmed\n .split(/[,;]+/)\n .map((p) => p.trim())\n .filter(Boolean);\n const candidates = parts\n .map((p) => Number.parseFloat(p))\n .filter((n) => Number.isFinite(n));\n if (!candidates.length)\n return [...DEFAULT_TTS_SPEED_CONTROL_RATES];\n const dedupedRates = new Set();\n const normalized = [];\n for (const candidate of candidates) {\n const rate = normalizeControlSpeedRate(candidate);\n if (rate === undefined || dedupedRates.has(rate))\n continue;\n dedupedRates.add(rate);\n normalized.push(rate);\n }\n return normalized.length ? normalized : [...DEFAULT_TTS_SPEED_CONTROL_RATES];\n};\nconst applyRuntimeDefaults = (config) => {\n const withLayoutDefaults = {\n ...config,\n layoutMode: normalizeTTSLayoutMode(config.layoutMode),\n };\n const backend = config.backend || \"browser\";\n if (!isServerBackend(backend))\n return withLayoutDefaults;\n const withServerDefaults = {\n ...withLayoutDefaults,\n apiEndpoint: withDefault(withLayoutDefaults.apiEndpoint, \"/api/tts\"),\n transportMode: withDefault(withLayoutDefaults.transportMode, \"pie\"),\n endpointValidationMode: withDefault(withLayoutDefaults.endpointValidationMode, \"voices\"),\n validateEndpoint: withDefault(withLayoutDefaults.validateEndpoint, true),\n includeAuthOnAssetFetch: withDefault(withLayoutDefaults.includeAuthOnAssetFetch, false),\n rate: withDefault(withLayoutDefaults.rate, 1.0),\n language: withDefault(withLayoutDefaults.language, \"en-US\"),\n };\n if (backend === \"polly\") {\n return {\n ...withServerDefaults,\n defaultVoice: withDefault(withServerDefaults.defaultVoice, \"Joanna\"),\n engine: withDefault(withServerDefaults.engine, \"neural\"),\n format: withDefault(withServerDefaults.format, \"mp3\"),\n speechMarksMode: withDefault(withServerDefaults.speechMarksMode, \"word+sentence\"),\n };\n }\n if (backend === \"google\") {\n return {\n ...withServerDefaults,\n defaultVoice: withDefault(withServerDefaults.defaultVoice, \"en-US-Wavenet-A\"),\n };\n }\n return withServerDefaults;\n};\nexport const resolveTTSRuntimeSettings = (config) => {\n const configRecord = toRecord(config);\n const settingsRecord = toRecord(configRecord.settings);\n return applyRuntimeDefaults({\n ...configRecord,\n ...settingsRecord,\n });\n};\nexport const resolveTTSBackend = (config) => config.backend || \"browser\";\nexport const resolveRuntimeProvider = (config, backend) => {\n if (backend === \"polly\" || backend === \"google\")\n return backend;\n if (backend === \"server\") {\n return config.serverProvider || config.provider;\n }\n return config.serverProvider || config.provider;\n};\nexport const resolveTransportMode = (config, runtimeProvider) => config.transportMode || (runtimeProvider === \"custom\" ? \"custom\" : \"pie\");\nexport const buildRuntimeTTSConfig = (config) => {\n const backend = resolveTTSBackend(config);\n const runtimeProvider = resolveRuntimeProvider(config, backend);\n const transportMode = resolveTransportMode(config, runtimeProvider);\n const mathSpeech = normalizeSREMathSpeechOptions(config.mathSpeech);\n return {\n voice: config.defaultVoice,\n rate: config.rate,\n pitch: config.pitch,\n providerOptions: {\n ...(config.language ? { locale: config.language } : {}),\n ...(backend === \"polly\" && config.engine\n ? { engine: config.engine }\n : {}),\n ...(backend === \"polly\" && typeof config.sampleRate === \"number\"\n ? { sampleRate: config.sampleRate }\n : {}),\n ...(backend === \"polly\" && config.format\n ? { format: config.format }\n : {}),\n ...(backend === \"polly\"\n ? {\n speechMarkTypes: config.speechMarksMode === \"word+sentence\"\n ? [\"word\", \"sentence\"]\n : [\"word\"],\n }\n : {}),\n ...(transportMode === \"custom\" && typeof config.cache === \"boolean\"\n ? { cache: config.cache }\n : {}),\n ...(transportMode === \"custom\" && config.speedRate\n ? { speedRate: config.speedRate }\n : {}),\n ...(transportMode === \"custom\" && config.lang_id\n ? { lang_id: config.lang_id }\n : {}),\n ...(mathSpeech ? { mathSpeech } : {}),\n },\n apiEndpoint: config.apiEndpoint,\n provider: runtimeProvider,\n language: config.language,\n transportMode,\n endpointMode: config.endpointMode,\n endpointValidationMode: config.endpointValidationMode,\n includeAuthOnAssetFetch: config.includeAuthOnAssetFetch,\n validateEndpoint: config.validateEndpoint,\n // Toolkit-level highlight setting carried through the config channel\n // (like apiEndpoint/transportMode); consumed by the highlight pipeline,\n // ignored by providers. Only forwarded when set so the pipeline default\n // (per-token enabled) applies otherwise.\n ...(typeof config.mathTokenHighlighting === \"boolean\"\n ? { mathTokenHighlighting: config.mathTokenHighlighting }\n : {}),\n };\n};\nexport const resolveTTSLayoutMode = (config) => normalizeTTSLayoutMode(config.layoutMode);\nexport const resolveTTSHostToolbarLayout = (config) => {\n const layoutMode = resolveTTSLayoutMode(config);\n switch (layoutMode) {\n case \"reserved-row\":\n return {\n mount: \"before-buttons\",\n controlsRow: {\n reserveSpace: true,\n expandWhenToolActive: false,\n },\n headerOverlay: {\n expandWhenToolActive: false,\n },\n };\n case \"expanding-row\":\n return {\n mount: \"before-buttons\",\n controlsRow: {\n reserveSpace: false,\n expandWhenToolActive: true,\n },\n headerOverlay: {\n expandWhenToolActive: false,\n },\n };\n case \"floating-overlay\":\n return {\n mount: \"before-buttons\",\n controlsRow: {\n reserveSpace: false,\n expandWhenToolActive: false,\n },\n headerOverlay: {\n expandWhenToolActive: false,\n },\n };\n case \"left-aligned\":\n default:\n return {\n mount: \"before-buttons\",\n controlsRow: {\n reserveSpace: false,\n expandWhenToolActive: false,\n },\n headerOverlay: {\n expandWhenToolActive: true,\n },\n };\n }\n};\n","/**\n * Tool Provider Registry\n *\n * Centralized registry for managing tool providers.\n * Handles initialization, authentication, and lazy loading.\n *\n * Part of PIE Assessment Toolkit.\n */\n/**\n * Tool Provider Registry\n *\n * Manages the lifecycle of tool providers:\n * - Registration\n * - Lazy initialization\n * - Auth credential fetching\n * - Provider lookup by ID or category\n *\n * @example\n * ```typescript\n * const registry = new ToolProviderRegistry();\n *\n * // Register a provider with auth fetcher\n * registry.register('desmos-calculator', {\n * provider: new DesmosToolProvider(),\n * config: {},\n * lazy: true,\n * authFetcher: async () => {\n * const response = await fetch('/api/desmos/token');\n * return response.json();\n * },\n * });\n *\n * // Get provider (auto-initializes if lazy)\n * const desmosProvider = await registry.getProvider('desmos-calculator');\n * ```\n */\nexport class ToolProviderRegistry {\n providers = new Map();\n configs = new Map();\n initialized = new Map();\n initializationPromises = new Map();\n async emitTelemetry(config, eventName, payload) {\n try {\n await config.onTelemetry?.(eventName, payload);\n }\n catch (error) {\n console.warn(\"[ToolProviderRegistry] Telemetry callback failed:\", error);\n }\n }\n /**\n * Register a tool provider\n *\n * Adds a provider to the registry. If lazy is false, initializes immediately.\n *\n * @param providerId Unique provider identifier\n * @param config Provider configuration\n * @throws Error if provider with same ID already registered\n */\n register(providerId, config) {\n if (this.providers.has(providerId)) {\n console.warn(`[ToolProviderRegistry] Provider \"${providerId}\" already registered, skipping`);\n return;\n }\n this.providers.set(providerId, config.provider);\n this.configs.set(providerId, config);\n this.initialized.set(providerId, false);\n console.log(`[ToolProviderRegistry] Registered provider \"${providerId}\" (${config.provider.providerName})`);\n // Initialize immediately if not lazy\n if (config.lazy === false) {\n this.initialize(providerId).catch((error) => {\n console.error(`[ToolProviderRegistry] Failed to initialize provider \"${providerId}\":`, error);\n });\n }\n }\n /**\n * Initialize a provider\n *\n * Fetches auth if needed and initializes the provider.\n * Safe to call multiple times - subsequent calls wait for first initialization.\n *\n * @param providerId Provider to initialize\n * @returns Promise that resolves when initialization complete\n * @throws Error if provider not registered or initialization fails\n */\n async initialize(providerId) {\n // Already initialized\n if (this.initialized.get(providerId)) {\n return;\n }\n // Initialization in progress - wait for it\n const existingPromise = this.initializationPromises.get(providerId);\n if (existingPromise) {\n return existingPromise;\n }\n // Start new initialization\n const initPromise = this._doInitialize(providerId);\n this.initializationPromises.set(providerId, initPromise);\n try {\n await initPromise;\n }\n finally {\n this.initializationPromises.delete(providerId);\n }\n }\n /**\n * Internal initialization logic\n */\n async _doInitialize(providerId) {\n const provider = this.providers.get(providerId);\n const config = this.configs.get(providerId);\n if (!provider || !config) {\n throw new Error(`[ToolProviderRegistry] Provider \"${providerId}\" not registered`);\n }\n // Start with base config\n let providerConfig = { ...config.config };\n const deriveBackend = (value) => {\n if (!value || typeof value !== \"object\")\n return \"unknown\";\n const typed = value;\n const direct = typeof typed.backend === \"string\"\n ? typed.backend\n : typeof typed.provider === \"string\"\n ? typed.provider\n : typeof typed.serverProvider === \"string\"\n ? typed.serverProvider\n : typeof typed.providerId === \"string\"\n ? typed.providerId\n : \"\";\n return direct || \"unknown\";\n };\n const providerInitStartedAt = Date.now();\n await this.emitTelemetry(config, \"pie-tool-init-start\", {\n toolId: providerId,\n providerId,\n backend: deriveBackend(providerConfig),\n operation: \"provider-initialize\",\n });\n // Fetch auth if needed\n if (provider.requiresAuth && config.authFetcher) {\n const authFetchStartedAt = Date.now();\n await this.emitTelemetry(config, \"pie-tool-backend-call-start\", {\n toolId: providerId,\n providerId,\n backend: deriveBackend(providerConfig),\n operation: \"auth-fetch\",\n });\n console.log(`[ToolProviderRegistry] Fetching auth for \"${providerId}\"...`);\n try {\n const authData = await config.authFetcher();\n providerConfig = { ...providerConfig, ...authData };\n await this.emitTelemetry(config, \"pie-tool-backend-call-success\", {\n toolId: providerId,\n providerId,\n backend: deriveBackend(providerConfig),\n operation: \"auth-fetch\",\n duration: Date.now() - authFetchStartedAt,\n });\n }\n catch (error) {\n await this.emitTelemetry(config, \"pie-tool-backend-call-error\", {\n toolId: providerId,\n providerId,\n backend: deriveBackend(providerConfig),\n operation: \"auth-fetch\",\n duration: Date.now() - authFetchStartedAt,\n errorType: \"ProviderAuthFetchError\",\n message: error instanceof Error ? error.message : String(error),\n });\n console.error(`[ToolProviderRegistry] Auth fetch failed for \"${providerId}\":`, error);\n throw new Error(`Failed to fetch auth credentials for provider \"${providerId}\"`);\n }\n }\n // Initialize provider\n try {\n await provider.initialize(providerConfig);\n this.initialized.set(providerId, true);\n await this.emitTelemetry(config, \"pie-tool-init-success\", {\n toolId: providerId,\n providerId,\n backend: deriveBackend(providerConfig),\n operation: \"provider-initialize\",\n duration: Date.now() - providerInitStartedAt,\n });\n console.log(`[ToolProviderRegistry] Provider \"${providerId}\" initialized`);\n }\n catch (error) {\n await this.emitTelemetry(config, \"pie-tool-init-error\", {\n toolId: providerId,\n providerId,\n backend: deriveBackend(providerConfig),\n operation: \"provider-initialize\",\n duration: Date.now() - providerInitStartedAt,\n errorType: \"ProviderInitializationError\",\n message: error instanceof Error ? error.message : String(error),\n });\n console.error(`[ToolProviderRegistry] Initialization failed for \"${providerId}\":`, error);\n throw error;\n }\n }\n /**\n * Get a provider instance\n *\n * Retrieves a registered provider. If autoInitialize is true and provider\n * is not initialized, initializes it first.\n *\n * @param providerId Provider identifier\n * @param autoInitialize Auto-initialize if not ready (default: true)\n * @returns Provider instance\n * @throws Error if provider not registered\n */\n async getProvider(providerId, autoInitialize = true) {\n console.log(\"[ToolProviderRegistry] getProvider called\", {\n providerId,\n autoInitialize,\n isRegistered: this.providers.has(providerId),\n isInitialized: this.initialized.get(providerId),\n allProviderIds: Array.from(this.providers.keys()),\n });\n const provider = this.providers.get(providerId);\n if (!provider) {\n console.error(\"[ToolProviderRegistry] Provider not found:\", {\n requestedId: providerId,\n availableProviders: Array.from(this.providers.keys()),\n });\n throw new Error(`[ToolProviderRegistry] Provider \"${providerId}\" not registered`);\n }\n // Auto-initialize if needed\n if (autoInitialize && !this.initialized.get(providerId)) {\n console.log(\"[ToolProviderRegistry] Auto-initializing provider:\", providerId);\n await this.initialize(providerId);\n }\n console.log(\"[ToolProviderRegistry] Returning provider:\", {\n providerId,\n providerName: provider.providerName,\n isReady: provider.isReady(),\n });\n return provider;\n }\n /**\n * Get all providers in a category\n *\n * @param category Tool category to filter by\n * @returns Array of provider IDs in the category\n */\n getProvidersByCategory(category) {\n return Array.from(this.providers.entries())\n .filter(([_, provider]) => provider.category === category)\n .map(([id]) => id);\n }\n /**\n * Get all registered provider IDs\n *\n * @returns Array of all provider IDs\n */\n getProviderIds() {\n return Array.from(this.providers.keys());\n }\n /**\n * Check if provider is registered\n *\n * @param providerId Provider identifier\n * @returns true if provider is registered\n */\n has(providerId) {\n return this.providers.has(providerId);\n }\n /**\n * Check if provider is initialized\n *\n * @param providerId Provider identifier\n * @returns true if provider is initialized\n */\n isInitialized(providerId) {\n return this.initialized.get(providerId) === true;\n }\n /**\n * Check if provider is currently initializing\n *\n * @param providerId Provider identifier\n * @returns true if initialization in progress\n */\n isInitializing(providerId) {\n return this.initializationPromises.has(providerId);\n }\n /**\n * Unregister and destroy a provider\n *\n * Removes the provider from the registry and calls its destroy method.\n *\n * @param providerId Provider to unregister\n */\n async unregister(providerId) {\n const provider = this.providers.get(providerId);\n if (provider) {\n // Wait for any pending initialization\n const initPromise = this.initializationPromises.get(providerId);\n if (initPromise) {\n try {\n await initPromise;\n }\n catch {\n // Ignore initialization errors during unregister\n }\n }\n // Destroy provider\n provider.destroy();\n // Remove from registry\n this.providers.delete(providerId);\n this.configs.delete(providerId);\n this.initialized.delete(providerId);\n this.initializationPromises.delete(providerId);\n console.log(`[ToolProviderRegistry] Unregistered provider \"${providerId}\"`);\n }\n }\n /**\n * Clean up all providers\n *\n * Unregisters and destroys all providers in the registry.\n */\n async destroy() {\n const providerIds = Array.from(this.providers.keys());\n await Promise.all(providerIds.map((id) => this.unregister(id)));\n console.log(\"[ToolProviderRegistry] Registry destroyed\");\n }\n}\n","/**\n * Feature policy decisions — eligibility for policy-addressable capabilities\n * that are not toolbar tools.\n *\n * \"Tool\" in this codebase means *policy-addressable capability*, not \"gadget on\n * a toolbar\" (see `docs/tools-and-accomodations/architecture.md`). Most such\n * capabilities render as toolbar surfaces, so the engine's main answer is a\n * placement-scoped `ToolPolicyDecision`. Some do not: a signed alternate renders\n * as its own region and is never placed on a toolbar, so asking\n * `decide({ level: \"item\", ... })` about it would answer the wrong question —\n * it would be absent because it is not in `tools.placement.item`, not because\n * policy said no.\n *\n * A feature decision answers only the eligibility half: *did policy grant this\n * feature id?* Whether the capability has anything to show is a separate,\n * independent check owned by its renderer — for signing, whether a matching\n * catalog card exists. Both are required; neither implies the other.\n *\n * A denial carries `assessmentBound`, because \"nobody asked for this\" and\n * \"nothing was bound to ask against\" are the same verdict for different\n * reasons, and only the second is a defect.\n */\n/**\n * Reason text for a denial that had no assessment to decide against.\n *\n * Replaces the `pnp-support` skip's \"not configured at any level\", which is\n * true but reads as a completed evaluation. `rule` and `precedence` stay as the\n * source reported them: nothing fired, so naming a seventh rule would describe\n * a precedence level that does not exist.\n */\nconst unboundAssessmentReason = (featureId) => `No assessment is bound, so no policy source could grant \"${featureId}\"`;\n/**\n * A host gate denied the feature outright, so no policy source was consulted.\n *\n * `precedence: 0` and the two `host-*` rules are the same values\n * `composeDecision(...)` records for the placement-scoped path, so a debugger\n * reads one vocabulary for both. `assessmentBound` is still reported: a host\n * blocklist is a verdict whether or not an assessment was bound, and the flag\n * only ever qualifies a *policy* denial.\n */\nexport function hostFeatureDenial(featureId, rule, hostValue, context) {\n return {\n featureId,\n granted: false,\n action: \"block\",\n rule,\n precedence: 0,\n sourceType: \"host\",\n reason: rule === \"host-blocked\"\n ? \"Listed in tools.policy.blocked\"\n : `Not listed in tools.policy.allowed (${hostValue.join(\", \")})`,\n required: false,\n assessmentBound: context.assessmentBound,\n };\n}\n/**\n * Whether a host gate produced the verdict, rather than a policy source.\n *\n * The distinction is load-bearing for a content-dependent capability that\n * declares `resolvesWithoutGrant`: an absent grant is a case it is allowed to\n * answer from the content alone, while a host denial is the host's off switch\n * and nothing may reopen it.\n */\nexport function isHostDeniedFeature(decision) {\n return (decision?.rule === \"host-blocked\" || decision?.rule === \"host-allowlist\");\n}\n/**\n * Interpret a single-feature `PnpPolicySource.resolveFeature(...)` result.\n *\n * `resolveFeature` evaluates exactly one support id, so the result carries\n * exactly one decision and at most one flags entry — no mapped-tool-id\n * bookkeeping is needed to read it back out.\n */\nexport function interpretFeatureResult(featureId, result, context) {\n const decision = result.decisions[0];\n const flags = Array.from(result.perToolFlags.values())[0];\n const granted = decision?.action === \"enable\";\n const reason = decision?.reason ?? `Feature \"${featureId}\" not configured`;\n return {\n featureId,\n granted,\n action: decision?.action ?? \"skip\",\n rule: decision?.rule ?? \"pnp-support\",\n precedence: decision?.precedence ?? 6,\n sourceType: decision?.sourceType ?? \"system\",\n // Only a denial is re-worded. An unbound host can still be granted the\n // feature — an item ref carrying `requiredTools` mandates it at precedence 4\n // with no assessment in sight — and there the source's reason is the true\n // one.\n reason: context.assessmentBound || granted\n ? reason\n : unboundAssessmentReason(featureId),\n required: Boolean(flags?.required),\n parameters: flags?.settings,\n assessmentBound: context.assessmentBound,\n };\n}\n","/**\n * Tool Policy Provenance.\n *\n * Precedence and the rule vocabulary are documented in\n * `docs/tools-and-accomodations/architecture.md`.\n *\n * Tracks decisions from every Pass-1 contributor: host placement, host policy,\n * provider veto, PNP/profile gates, and custom policy sources.\n */\n/**\n * Builder for `ToolPolicyProvenance`.\n */\nexport class ToolPolicyProvenanceBuilder {\n provenance;\n stepCounter = 0;\n constructor(contextId) {\n this.provenance = {\n contextId,\n resolvedAt: new Date(),\n sources: {},\n features: new Map(),\n decisionLog: [],\n summary: {\n totalFeatures: 0,\n enabled: 0,\n blocked: 0,\n notConfigured: 0,\n bySource: {},\n byRule: {},\n },\n };\n }\n addSource(type, data) {\n const base = { id: data.id, name: data.name ?? data.id };\n switch (type) {\n case \"organization\":\n this.provenance.sources.organization = {\n ...base,\n pnpDefaults: data.config,\n };\n break;\n case \"assessment\":\n this.provenance.sources.assessment = {\n ...base,\n settings: data.config,\n };\n break;\n case \"section\":\n this.provenance.sources.section = { ...base, settings: data.config };\n break;\n case \"item\":\n this.provenance.sources.item = { ...base, settings: data.config };\n break;\n case \"student\":\n this.provenance.sources.student = {\n id: data.id,\n pnpProfile: data.config,\n };\n break;\n case \"host\":\n this.provenance.sources.host = { id: data.id, config: data.config };\n break;\n }\n return this;\n }\n addDecision(params) {\n const decision = {\n step: ++this.stepCounter,\n precedence: params.precedence,\n rule: params.rule,\n featureId: params.featureId,\n action: params.action,\n source: {\n type: params.sourceType,\n id: params.sourceId,\n name: params.sourceName,\n },\n reason: params.reason,\n value: params.value,\n timestamp: new Date(),\n };\n this.provenance.decisionLog.push(decision);\n let trail = this.provenance.features.get(params.featureId);\n if (!trail) {\n trail = {\n featureId: params.featureId,\n finalState: \"not-configured\",\n allDecisions: [],\n explanation: \"\",\n };\n this.provenance.features.set(params.featureId, trail);\n }\n trail.allDecisions.push(decision);\n // \"advisory\" doesn't change finalState — it preserves the existing\n // blocked/enabled state and only flags a documented conflict.\n if (params.action === \"advisory\") {\n if (trail.finalState === \"not-configured\") {\n trail.finalState = \"advisory-only\";\n }\n }\n else if (params.action !== \"skip\") {\n const isWinning = !trail.winningDecision ||\n decision.precedence < trail.winningDecision.precedence;\n if (isWinning) {\n trail.winningDecision = decision;\n trail.finalState = decision.action === \"enable\" ? \"enabled\" : \"blocked\";\n }\n }\n this.provenance.summary.bySource[params.sourceType] =\n (this.provenance.summary.bySource[params.sourceType] || 0) + 1;\n this.provenance.summary.byRule[params.rule] =\n (this.provenance.summary.byRule[params.rule] || 0) + 1;\n return this;\n }\n /**\n * Reconcile every feature's `finalState` against the post-pipeline\n * candidate set.\n *\n * The eager `finalState` updates inside `addDecision` track the\n * highest-precedence non-skip decision per feature, but a tool's\n * *actual* visibility is only known after step 6 of the\n * composition pipeline — earlier decisions can be reversed by\n * later host gates, PNP/profile gates, or custom sources. This method\n * walks every feature trail and rewrites `finalState` from the\n * final candidate set so callers can rely on\n * `provenance.features.get(toolId)?.finalState` as the canonical\n * \"is this tool visible right now?\" answer (M8 design § 4 + § 12).\n *\n * Semantics applied per feature:\n * - In `survivingIds` → \"enabled\"\n * - Not in `survivingIds`, has any non-skip decision → \"blocked\"\n * - Not in `survivingIds`, only advisory decisions → \"advisory-only\"\n * - Otherwise → \"not-configured\"\n *\n * Surviving features without any logged decisions get a synthetic\n * \"enabled\" trail so the provenance is dense enough for hosts that\n * iterate `provenance.features` to find the visible set.\n */\n reconcileFinalStates(survivingIds) {\n for (const featureId of survivingIds) {\n let trail = this.provenance.features.get(featureId);\n if (!trail) {\n trail = {\n featureId,\n finalState: \"enabled\",\n allDecisions: [],\n explanation: \"\",\n };\n this.provenance.features.set(featureId, trail);\n continue;\n }\n trail.finalState = \"enabled\";\n }\n for (const trail of this.provenance.features.values()) {\n if (survivingIds.has(trail.featureId))\n continue;\n const hasNonSkip = trail.allDecisions.some((d) => d.action !== \"skip\" && d.action !== \"advisory\");\n const hasAdvisory = trail.allDecisions.some((d) => d.action === \"advisory\");\n if (hasNonSkip) {\n trail.finalState = \"blocked\";\n }\n else if (hasAdvisory) {\n trail.finalState = \"advisory-only\";\n }\n else {\n trail.finalState = \"not-configured\";\n }\n }\n return this;\n }\n build() {\n for (const trail of this.provenance.features.values()) {\n trail.explanation = generateExplanation(trail);\n }\n for (const trail of this.provenance.features.values()) {\n this.provenance.summary.totalFeatures++;\n if (trail.finalState === \"enabled\") {\n this.provenance.summary.enabled++;\n }\n else if (trail.finalState === \"blocked\") {\n this.provenance.summary.blocked++;\n }\n else {\n this.provenance.summary.notConfigured++;\n }\n }\n return this.provenance;\n }\n}\nfunction generateExplanation(trail) {\n if (!trail.winningDecision) {\n if (trail.finalState === \"advisory-only\") {\n const advisory = trail.allDecisions.find((d) => d.action === \"advisory\");\n return advisory\n ? `Feature \"${trail.featureId}\" was kept in its host-decided state; ${advisory.reason}`\n : `Feature \"${trail.featureId}\" carries an advisory note.`;\n }\n return `Feature \"${trail.featureId}\" was not configured at any level.`;\n }\n const decision = trail.winningDecision;\n const sourceName = decision.source.name || decision.source.type;\n let explanation = `Feature \"${trail.featureId}\" is ${trail.finalState}.\\n\\n`;\n explanation += `**Primary Reason** (${decision.rule}):\\n`;\n explanation += `${decision.reason}\\n`;\n explanation += `Source: ${sourceName} (${decision.source.type})\\n`;\n const overridden = trail.allDecisions.filter((d) => d.step !== decision.step &&\n d.action !== \"skip\" &&\n d.action !== \"advisory\" &&\n d.precedence > decision.precedence);\n if (overridden.length > 0) {\n explanation += `\\n**Overridden Rules**:\\n`;\n for (const d of overridden) {\n explanation += `- ${d.rule}: ${d.reason}\\n`;\n }\n }\n return explanation;\n}\n","/**\n * Compose-decision pipeline. See\n * `docs/tools-and-accomodations/architecture.md`.\n *\n * Pure function: given a decision request, the host's tools config,\n * an optional PNP policy source, and the registered custom sources, returns\n * a `ToolPolicyDecision`. The function performs no I/O, holds no\n * mutable state, and never reaches into Svelte / DOM — that is the\n * `ToolPolicyEngine` class's job.\n *\n * The tests in\n * `tests/policy/compose-decision.test.ts` lock the orchestration in.\n */\nimport { normalizeToolList, } from \"../../services/tools-config-normalizer.js\";\nimport { ToolPolicyProvenanceBuilder } from \"./provenance.js\";\nexport function composeDecision(inputs) {\n const { request, tools, pnpPolicy, customSources, contextId } = inputs;\n const builder = new ToolPolicyProvenanceBuilder(contextId);\n builder.addSource(\"host\", {\n id: request.scope.scopeId,\n name: `${request.level}:${request.scope.scopeId}`,\n config: {\n placement: tools.placement,\n policy: tools.policy,\n },\n });\n const placement = normalizeToolList(tools.placement[request.level]);\n const allowed = normalizeToolList(tools.policy.allowed);\n const blocked = new Set(normalizeToolList(tools.policy.blocked));\n // Step 1 — Membership filter.\n //\n // Logged with `action: \"skip\"` rather than `\"enable\"` because a\n // placement-membership entry is the pipeline's starting point, not\n // a winning decision. Subsequent steps may block the tool at the\n // same precedence (0); the builder's `decision.precedence <\n // winning.precedence` rule would otherwise let the placement entry\n // win equality and mask later blocks. Surviving tools are flipped\n // to `enabled` by `builder.reconcileFinalStates(...)` at the end of\n // the pipeline once the final candidate set is known.\n let candidates = [];\n for (const toolId of placement) {\n candidates.push(toolId);\n builder.addDecision({\n precedence: 0,\n rule: \"placement-membership\",\n featureId: toolId,\n action: \"skip\",\n sourceType: \"host\",\n reason: `Listed in tools.placement.${request.level}`,\n });\n }\n // Step 2 — Provider veto.\n candidates = candidates.filter((toolId) => {\n const providerEnabled = tools.providers?.[toolId]?.enabled;\n if (providerEnabled === false) {\n builder.addDecision({\n precedence: 0,\n rule: \"provider-disabled\",\n featureId: toolId,\n action: \"block\",\n sourceType: \"host\",\n reason: `tools.providers.${toolId}.enabled === false`,\n value: false,\n });\n return false;\n }\n return true;\n });\n // Step 3 — Host whitelist (only when non-empty).\n if (allowed.length > 0) {\n const allowedSet = new Set(allowed);\n candidates = candidates.filter((toolId) => {\n if (!allowedSet.has(toolId)) {\n builder.addDecision({\n precedence: 0,\n rule: \"host-allowlist\",\n featureId: toolId,\n action: \"block\",\n sourceType: \"host\",\n reason: \"Not present in tools.policy.allowed\",\n value: allowed,\n });\n return false;\n }\n return true;\n });\n }\n // Step 4 — Host blocklist (absolute).\n candidates = candidates.filter((toolId) => {\n if (blocked.has(toolId)) {\n builder.addDecision({\n precedence: 0,\n rule: \"host-blocked\",\n featureId: toolId,\n action: \"block\",\n sourceType: \"host\",\n reason: \"Listed in tools.policy.blocked\",\n value: tools.policy.blocked,\n });\n return false;\n }\n return true;\n });\n // Step 5 — PNP/profile policy gates.\n const diagnostics = [];\n const sourcesByTool = new Map();\n for (const toolId of candidates) {\n sourcesByTool.set(toolId, [\"placement\"]);\n }\n // Snapshot the post-host candidate set so step 5b can distinguish\n // \"host removed a required tool\" (requiredToolBlocked fires)\n // from \"profile policy's own precedence removed a required tool\" (fix\n // per M8 PR 1 R1 S1 — multi-rule conflict on the same tool must\n // not blame the host).\n const postHostCandidates = new Set(candidates);\n let pnpPolicyResult = null;\n if (pnpPolicy.enforcement === \"on\" &&\n pnpPolicy.source &&\n (pnpPolicy.assessment || pnpPolicy.currentItemRef)) {\n pnpPolicyResult = pnpPolicy.source.apply({\n assessment: pnpPolicy.assessment,\n currentItemRef: pnpPolicy.currentItemRef,\n });\n if (pnpPolicyResult.sources.assessment) {\n builder.addSource(\"assessment\", pnpPolicyResult.sources.assessment);\n }\n if (pnpPolicyResult.sources.student) {\n builder.addSource(\"student\", pnpPolicyResult.sources.student);\n }\n if (pnpPolicyResult.sources.item) {\n builder.addSource(\"item\", pnpPolicyResult.sources.item);\n }\n for (const decision of pnpPolicyResult.decisions) {\n builder.addDecision({\n precedence: decision.precedence,\n rule: decision.rule,\n featureId: decision.featureId,\n action: decision.action,\n sourceType: decision.sourceType,\n reason: decision.reason,\n value: decision.value,\n });\n }\n // 5a — remove PNP/profile-blocked tools from the candidate set.\n candidates = candidates.filter((toolId) => {\n return !pnpPolicyResult.blockedToolIds.has(toolId);\n });\n for (const toolId of Array.from(sourcesByTool.keys())) {\n if (pnpPolicyResult.blockedToolIds.has(toolId)) {\n sourcesByTool.delete(toolId);\n }\n }\n // 5b — surface requiredToolBlocked diagnostics ONLY for\n // PNP/profile-mandated tools that the host removed (i.e., the tool was\n // NOT in `postHostCandidates`). Mandated tools removed by\n // profile policy's own higher-precedence rule (e.g. `restrictedTools`\n // blocking a `requiredTools` mandate) are an internal policy\n // resolution and must not be reported as a host conflict — the\n // loser's `block` decision is already in the trail with full\n // provenance.\n //\n // `details` carries `{ rule, hostRule, hostValue }` so consumers\n // can render the conflict as a single sentence without\n // re-deriving the host gate from `provenance.features`. See\n // `RequiredToolBlockedDetails` for the typed shape.\n for (const mandatedToolId of pnpPolicyResult.mandatedToolIds) {\n const removedByHost = !postHostCandidates.has(mandatedToolId);\n if (!removedByHost)\n continue;\n const flag = pnpPolicyResult.perToolFlags.get(mandatedToolId);\n const ruleName = flag?.rule ?? \"required-tool\";\n const hostGate = detectHostRemovalGate(mandatedToolId, {\n placement,\n allowed,\n blocked,\n providers: tools.providers,\n });\n const details = {\n rule: ruleName,\n hostRule: hostGate.hostRule,\n hostValue: hostGate.hostValue,\n };\n diagnostics.push({\n code: \"tool-policy.requiredToolBlocked\",\n level: request.level,\n toolId: mandatedToolId,\n message: `Profile policy mandates \"${mandatedToolId}\" (${ruleName}) but host policy removed it from level \"${request.level}\" via ${hostGate.hostRule}.`,\n details,\n });\n builder.addDecision({\n precedence: 0,\n rule: \"required-tool-blocked\",\n featureId: mandatedToolId,\n action: \"advisory\",\n sourceType: \"host\",\n reason: `Host removed required tool \"${mandatedToolId}\" via ${hostGate.hostRule}`,\n value: details,\n });\n }\n // 5c — attach PNP policy source tags to surviving entries.\n for (const toolId of candidates) {\n const flag = pnpPolicyResult.perToolFlags.get(toolId);\n if (flag) {\n const tags = sourcesByTool.get(toolId) ?? [];\n tags.push(`pnp.${flag.rule}`);\n sourcesByTool.set(toolId, tags);\n }\n }\n }\n // Step 6 — Custom PolicySources.\n for (let i = 0; i < customSources.length; i++) {\n const source = customSources[i];\n const before = candidates.slice();\n const result = source.refine({\n request,\n candidates: before,\n });\n const refinedSet = new Set(result.refinedCandidates);\n // Reject any superset additions (custom sources can only narrow).\n for (const toolId of result.refinedCandidates) {\n if (!before.includes(toolId)) {\n diagnostics.push({\n code: \"tool-policy.placementMissing\",\n level: request.level,\n toolId,\n message: `Custom source \"${source.id}\" tried to add tool \"${toolId}\" that was not in candidates; ignored.`,\n source: `custom.${source.id}`,\n });\n refinedSet.delete(toolId);\n }\n }\n candidates = before.filter((id) => refinedSet.has(id));\n // Index the source's emitted block decisions by featureId so we\n // can detect \"silent removals\" — tools the source dropped from\n // the candidate set without logging an explicit block. Without\n // this auto-log, the provenance trail for a silently-removed\n // tool would show only the prior `enable` decisions and the\n // final-state reconciliation would have no evidence to mark it\n // `blocked` (M8 PR 1 R2 S1 / M1 case B).\n const explicitBlocks = new Set();\n if (result.decisions) {\n for (const event of result.decisions) {\n builder.addDecision({\n precedence: event.precedence ?? 100 + i,\n rule: event.rule,\n featureId: event.featureId,\n action: event.action,\n sourceType: event.sourceType,\n reason: event.reason,\n value: event.value,\n });\n if (event.action === \"block\") {\n explicitBlocks.add(event.featureId);\n }\n }\n }\n // Auto-log a `custom-source / block` decision for silent removals.\n for (const toolId of before) {\n if (refinedSet.has(toolId))\n continue;\n if (explicitBlocks.has(toolId))\n continue;\n builder.addDecision({\n precedence: 100 + i,\n rule: \"custom-source\",\n featureId: toolId,\n action: \"block\",\n sourceType: \"custom\",\n reason: `Custom policy source \"${source.id}\" removed tool \"${toolId}\" from candidates without emitting a decision; auto-logged for trail completeness.`,\n value: { customSourceId: source.id },\n });\n }\n // Annotate surviving entries with `custom.<id>` so hosts can see\n // which custom source kept them in.\n for (const toolId of candidates) {\n const tags = sourcesByTool.get(toolId) ?? [\"placement\"];\n tags.push(`custom.${source.id}`);\n sourcesByTool.set(toolId, tags);\n }\n // And drop attribution for IDs the source removed.\n for (const toolId of before) {\n if (!refinedSet.has(toolId)) {\n sourcesByTool.delete(toolId);\n }\n }\n }\n const survivingIds = new Set(candidates);\n const visibleTools = candidates.map((toolId) => {\n const flag = pnpPolicyResult?.perToolFlags.get(toolId);\n return {\n toolId,\n required: flag?.required ?? false,\n alwaysAvailable: flag?.alwaysAvailable ?? false,\n settings: flag?.settings,\n sources: sourcesByTool.get(toolId) ?? [\"placement\"],\n };\n });\n builder.reconcileFinalStates(survivingIds);\n return {\n visibleTools,\n diagnostics,\n provenance: builder.build(),\n };\n}\n/**\n * Identify which step-1-through-4 host gate removed a tool. Used by\n * step 5b to enrich `tool-policy.requiredToolBlocked` diagnostics. The\n * checks mirror the pipeline order — step 1 (placement) first, step 4\n * (blocklist) last — so the FIRST gate that would have matched wins,\n * which is the gate the pipeline actually invoked. Subsequent gates\n * never get to evaluate a tool that an earlier step already removed.\n */\nfunction detectHostRemovalGate(toolId, args) {\n if (!args.placement.includes(toolId)) {\n return { hostRule: \"placement-missing\", hostValue: args.placement };\n }\n if (args.providers?.[toolId]?.enabled === false) {\n return { hostRule: \"provider-disabled\", hostValue: false };\n }\n if (args.allowed.length > 0 && !args.allowed.includes(toolId)) {\n return { hostRule: \"host-allowlist\", hostValue: args.allowed };\n }\n if (args.blocked.has(toolId)) {\n return {\n hostRule: \"host-blocked\",\n hostValue: Array.from(args.blocked),\n };\n }\n // Defensive: `removedByHost` is true at the call site (the tool is\n // in `mandatedToolIds` but not in `postHostCandidates`), so one of\n // the four gates above MUST have fired. If none did, the host\n // pipeline has a bug; surface a best-effort rather than throwing.\n return { hostRule: \"placement-missing\", hostValue: args.placement };\n}\n","/**\n * PNP/profile policy input detection. See\n * `docs/tools-and-accomodations/architecture.md`.\n *\n * Pure helpers that decide whether the inputs the engine has been given\n * actually carry PNP/profile policy material. Used by:\n *\n * - {@link ToolPolicyEngine}'s constructor as the auto-default for\n * `pnpEnforcement` when the host did not pass an explicit `\"on\"` /\n * `\"off\"`.\n * - {@link ToolkitCoordinator.resolveEffectivePnpEnforcement} as the\n * auto-mode rule. PR 2 used a coarse \"any non-null assessment → on\"\n * placeholder; PR 4 narrows it to \"assessment OR currentItemRef\n * carries profile policy material.\"\n *\n * The rule is intentionally narrow. Hosts that bind a bare assessment\n * record (only `id` / `name`, no PNP and no settings) do not engage\n * PNP/profile gates. The flip happens the moment the assessment carries any of:\n *\n * - `personalNeedsProfile` (any `supports`, `prohibitedSupports`, or\n * `activateAtInit`),\n * - `settings.districtPolicy` (any `blockedTools`, `requiredTools`,\n * or `policies`),\n * - `settings.testAdministration` (any populated key — `mode`,\n * `toolOverrides`, etc.),\n * - or the bound `currentItemRef.settings` carries\n * `requiredTools` / `restrictedTools` / `toolParameters`.\n *\n * Hosts opt out of the auto-on behavior by passing\n * `pnpEnforcement: \"off\"` explicitly (engine input or\n * `ToolkitCoordinator.setPnpEnforcement(\"off\")`).\n */\n/**\n * Return `true` when the assessment carries any PNP/profile policy\n * material that the engine's `PnpPolicySource` would consume.\n *\n * The check is structural — the presence of a non-empty PNP, district\n * policy, or test administration block is enough; the content does not\n * have to validate against any specific rule.\n */\nexport function assessmentHasPnpPolicyInputs(assessment) {\n if (!assessment)\n return false;\n const pnp = assessment.personalNeedsProfile;\n if (pnp) {\n if (Array.isArray(pnp.supports) && pnp.supports.length > 0)\n return true;\n if (Array.isArray(pnp.prohibitedSupports) &&\n pnp.prohibitedSupports.length > 0) {\n return true;\n }\n if (Array.isArray(pnp.activateAtInit) && pnp.activateAtInit.length > 0) {\n return true;\n }\n }\n const settings = assessment.settings;\n if (settings) {\n const district = settings.districtPolicy;\n if (district) {\n if (Array.isArray(district.blockedTools) &&\n district.blockedTools.length > 0) {\n return true;\n }\n if (Array.isArray(district.requiredTools) &&\n district.requiredTools.length > 0) {\n return true;\n }\n if (district.policies &&\n typeof district.policies === \"object\" &&\n Object.keys(district.policies).length > 0) {\n return true;\n }\n }\n const admin = settings.testAdministration;\n if (admin && typeof admin === \"object\") {\n for (const key of Object.keys(admin)) {\n const value = admin[key];\n if (value === undefined || value === null)\n continue;\n if (Array.isArray(value) && value.length === 0)\n continue;\n if (typeof value === \"object\" &&\n !Array.isArray(value) &&\n Object.keys(value).length === 0) {\n continue;\n }\n return true;\n }\n }\n }\n return false;\n}\n/**\n * Return `true` when the bound item reference carries item-level profile policy\n * material (`requiredTools`, `restrictedTools`, or `toolParameters`).\n *\n * Used in addition to {@link assessmentHasPnpPolicyInputs} so a host that\n * navigates to an item with profile-relevant settings — without a parent\n * assessment carrying its own PNP/district/test-admin block — still\n * gets PNP/profile gates engaged for that item.\n */\nexport function itemRefHasPnpPolicyInputs(itemRef) {\n const settings = itemRef?.settings;\n if (!settings)\n return false;\n if (Array.isArray(settings.requiredTools) &&\n settings.requiredTools.length > 0) {\n return true;\n }\n if (Array.isArray(settings.restrictedTools) &&\n settings.restrictedTools.length > 0) {\n return true;\n }\n if (settings.toolParameters &&\n typeof settings.toolParameters === \"object\" &&\n Object.keys(settings.toolParameters).length > 0) {\n return true;\n }\n return false;\n}\n/**\n * Resolve the default `pnpEnforcement` mode given the bound inputs.\n *\n * Returns `\"on\"` when {@link assessmentHasPnpPolicyInputs} or\n * {@link itemRefHasPnpPolicyInputs} reports any profile policy material; otherwise\n * `\"off\"`. Hosts override the default by passing an explicit\n * `pnpEnforcement` value (engine input) or by calling\n * `ToolkitCoordinator.setPnpEnforcement(\"on\" | \"off\")`.\n */\nexport function resolveDefaultPnpEnforcement(args) {\n if (assessmentHasPnpPolicyInputs(args.assessment))\n return \"on\";\n if (itemRefHasPnpPolicyInputs(args.currentItemRef))\n return \"on\";\n return \"off\";\n}\n","/**\n * PNP Policy Source for the M8 engine\n * (see\n * `docs/tools-and-accomodations/architecture.md`).\n *\n * This source applies the PNP/profile precedence rules as a `(candidates, pnpPolicyInputs) →\n * (refinedCandidates, perToolFlags, mandates, decisions)` function the\n * engine can call once per `decide(...)` request, with all results\n * routed through the unified `ToolPolicyProvenanceBuilder`.\n */\nexport class PnpPolicySource {\n id = \"pnp\";\n toolRegistry;\n constructor(toolRegistry) {\n this.toolRegistry = toolRegistry;\n }\n apply(args) {\n const { ctx, result } = this.prepare(args);\n const { pnp, districtPolicy, itemSettings } = ctx;\n const allSupports = new Set();\n pnp?.supports?.forEach((s) => allSupports.add(s));\n pnp?.prohibitedSupports?.forEach((s) => allSupports.add(s));\n districtPolicy?.blockedTools?.forEach((s) => allSupports.add(s));\n districtPolicy?.requiredTools?.forEach((s) => allSupports.add(s));\n itemSettings?.requiredTools?.forEach((s) => allSupports.add(s));\n itemSettings?.restrictedTools?.forEach((s) => allSupports.add(s));\n for (const supportId of allSupports) {\n this.resolveSupport(supportId, ctx, result);\n }\n return result;\n }\n /**\n * Evaluate exactly one PNP support id through the same six-level\n * precedence `apply(...)` uses.\n *\n * This exists for **policy-addressable capabilities that are not toolbar\n * tools** — a signed alternate rendered as its own region, for example.\n * `apply(...)` only evaluates support ids that appear somewhere in the\n * bound policy inputs, and it keys its result maps by *mapped tool id*, so\n * a caller asking about one feature would have to re-derive that mapping\n * and could collide with another support id that maps to the same tool.\n * Evaluating one id in isolation avoids both problems: the returned result\n * carries exactly one decision, and `decisions[0].action` is the verdict.\n *\n * Reusing `resolveSupport(...)` rather than re-walking the precedence rules\n * is the point — a second copy of the six levels would drift.\n */\n resolveFeature(featureId, args) {\n const { ctx, result } = this.prepare(args);\n this.resolveSupport(featureId, ctx, result);\n return result;\n }\n /**\n * Build the rule-evaluation context and the empty result (with its\n * configuration-source attribution) from the bound policy inputs.\n */\n prepare(args) {\n const { assessment, currentItemRef } = args;\n const pnp = assessment?.personalNeedsProfile;\n const settings = assessment?.settings;\n const itemSettings = currentItemRef?.settings;\n const result = {\n blockedToolIds: new Set(),\n mandatedToolIds: new Set(),\n perToolFlags: new Map(),\n decisions: [],\n sources: {},\n };\n if (settings?.districtPolicy || settings?.testAdministration) {\n result.sources.assessment = {\n id: assessment?.id || \"unknown\",\n name: assessment?.name || assessment?.id || \"Assessment\",\n config: settings,\n };\n }\n if (pnp) {\n result.sources.student = {\n id: \"student\",\n name: \"Student PNP Profile\",\n config: pnp,\n };\n }\n if (currentItemRef && itemSettings) {\n result.sources.item = {\n id: currentItemRef.identifier,\n name: currentItemRef.identifier,\n config: itemSettings,\n };\n }\n const ctx = {\n pnp,\n districtPolicy: settings?.districtPolicy,\n testAdmin: settings?.testAdministration,\n itemSettings,\n toolConfigs: settings?.toolConfigs,\n };\n return { ctx, result };\n }\n resolveSupport(supportId, ctx, out) {\n // 1. District block (absolute veto)\n if (ctx.districtPolicy?.blockedTools?.includes(supportId)) {\n const toolId = this.mapSupportToToolId(supportId);\n out.blockedToolIds.add(toolId);\n out.decisions.push({\n precedence: 1,\n rule: \"district-block\",\n featureId: toolId,\n action: \"block\",\n sourceType: \"assessment\",\n reason: `District policy blocks \"${supportId}\" for all assessments`,\n value: ctx.districtPolicy.blockedTools,\n });\n return;\n }\n // 2. Test administration override\n if (ctx.testAdmin?.toolOverrides?.[supportId] === false) {\n const toolId = this.mapSupportToToolId(supportId);\n out.blockedToolIds.add(toolId);\n out.decisions.push({\n precedence: 2,\n rule: \"test-admin-override\",\n featureId: toolId,\n action: \"block\",\n sourceType: \"assessment\",\n reason: `Test administrator disabled \"${supportId}\" for this session`,\n value: ctx.testAdmin.toolOverrides,\n });\n return;\n }\n // 3. Item restriction (per-item block)\n if (ctx.itemSettings?.restrictedTools?.includes(supportId)) {\n const toolId = this.mapSupportToToolId(supportId);\n out.blockedToolIds.add(toolId);\n out.decisions.push({\n precedence: 3,\n rule: \"item-restriction\",\n featureId: toolId,\n action: \"block\",\n sourceType: \"item\",\n reason: `Item restricts \"${supportId}\" (e.g., mental math question blocks calculator)`,\n value: ctx.itemSettings.restrictedTools,\n });\n return;\n }\n // 4. Item requirement (forces enable)\n if (ctx.itemSettings?.requiredTools?.includes(supportId)) {\n const toolId = this.mapSupportToToolId(supportId);\n out.mandatedToolIds.add(toolId);\n out.perToolFlags.set(toolId, {\n required: true,\n alwaysAvailable: false,\n settings: this.resolveToolSettings(supportId, ctx),\n rule: \"item-requirement\",\n sourceType: \"item\",\n });\n out.decisions.push({\n precedence: 4,\n rule: \"item-requirement\",\n featureId: toolId,\n action: \"enable\",\n sourceType: \"item\",\n reason: `Item requires \"${supportId}\" for this question`,\n value: ctx.itemSettings.requiredTools,\n });\n return;\n }\n // 5. District requirement\n if (ctx.districtPolicy?.requiredTools?.includes(supportId)) {\n const toolId = this.mapSupportToToolId(supportId);\n out.mandatedToolIds.add(toolId);\n out.perToolFlags.set(toolId, {\n required: true,\n alwaysAvailable: false,\n settings: this.resolveToolSettings(supportId, ctx),\n rule: \"district-requirement\",\n sourceType: \"assessment\",\n });\n out.decisions.push({\n precedence: 5,\n rule: \"district-requirement\",\n featureId: toolId,\n action: \"enable\",\n sourceType: \"assessment\",\n reason: `District policy requires \"${supportId}\" for all assessments`,\n value: ctx.districtPolicy.requiredTools,\n });\n return;\n }\n // 6. PNP prohibitions and supports (student needs)\n if (ctx.pnp?.prohibitedSupports?.includes(supportId)) {\n const toolId = this.mapSupportToToolId(supportId);\n out.blockedToolIds.add(toolId);\n out.decisions.push({\n precedence: 6,\n rule: \"pnp-prohibited\",\n featureId: toolId,\n action: \"block\",\n sourceType: \"student\",\n reason: `Student PNP profile prohibits \"${supportId}\"`,\n value: ctx.pnp.prohibitedSupports,\n });\n return;\n }\n if (ctx.pnp?.supports?.includes(supportId)) {\n const toolId = this.mapSupportToToolId(supportId);\n out.perToolFlags.set(toolId, {\n required: false,\n alwaysAvailable: true,\n settings: this.resolveToolSettings(supportId, ctx),\n rule: \"pnp-support\",\n sourceType: \"student\",\n });\n out.decisions.push({\n precedence: 6,\n rule: \"pnp-support\",\n featureId: toolId,\n action: \"enable\",\n sourceType: \"student\",\n reason: `Student PNP profile requests \"${supportId}\"`,\n value: ctx.pnp.supports,\n });\n return;\n }\n // 6 (skip): support-id mentioned somewhere but no rule fired.\n // Use the mapped tool id as `featureId` so the trail is keyed\n // the same way as every other branch — PR 5's debugger surfaces\n // index provenance trails by tool id and would otherwise show\n // orphaned support-id entries here (M8 PR 1 R3 S1).\n const toolId = this.mapSupportToToolId(supportId);\n out.decisions.push({\n precedence: 6,\n rule: \"pnp-support\",\n featureId: toolId,\n action: \"skip\",\n sourceType: \"system\",\n reason: `Feature \"${supportId}\" not configured at any level`,\n value: { supportId },\n });\n }\n /**\n * Map a QTI / PNP support id (e.g. `\"calculator-basic\"`) to the\n * registered tool id that owns it.\n *\n * Resolution rules:\n *\n * 1. **Multiple tools register the same support id:** the\n * *first-registered* tool wins. `ToolRegistry.getToolsByPNPSupport`\n * returns a `Set<string>` whose iteration order matches the\n * `register(...)` insertion order, so the result is\n * deterministic across runs but order-sensitive at registration\n * time. This is an unusual configuration — the typical case is\n * one tool per support id — but it is reachable when an\n * integrator overrides a default tool with a replacement that\n * claims the same `pnpSupportIds`. In that case the integrator\n * should `unregister(...)` the default before registering the\n * replacement.\n *\n * 2. **No tool registers the support id:** the support id is\n * returned verbatim as the `featureId` for provenance trails\n * and `ToolPolicyEntry.toolId`. This lets hosts use raw QTI\n * strings for tools the registry does not (yet) carry without\n * losing them in policy evaluation.\n *\n * `tests/policy/PnpPolicySource.test.ts` locks this mapping behavior.\n */\n mapSupportToToolId(supportId) {\n const toolIds = this.toolRegistry.getToolsByPNPSupport(supportId);\n if (toolIds.size === 0)\n return supportId;\n return Array.from(toolIds)[0];\n }\n /**\n * Resolve tool-specific settings, item-level taking precedence over\n * assessment-level.\n *\n * Uses `??` (nullish-coalescing). Tool config values are typed `unknown` and may legitimately\n * be `false` / `0` / `\"\"` (e.g. a tool whose canonical \"off\" config\n * is the literal `false`). `||` would treat those as missing and\n * silently fall through to the assessment-level config, masking the\n * authored item-level intent. `??` only falls through on\n * `null`/`undefined`, which matches the semantic of \"value not\n * provided.\"\n */\n resolveToolSettings(supportId, ctx) {\n return (ctx.itemSettings?.toolParameters?.[supportId] ??\n ctx.toolConfigs?.[supportId]);\n }\n}\n","/**\n * Tool Policy Engine — facade class. See\n * `docs/tools-and-accomodations/architecture.md`.\n *\n * Wraps `composeDecision(...)` with engine-instance state:\n * - bound inputs (`tools`, `assessment`, `currentItemRef`, ...)\n * - registered custom `PolicySource`s\n * - `onPolicyChange` subscriber bus\n * - `dispose()` clean-up\n *\n * The class has no DOM dependency and no Svelte runes. It is safe to\n * instantiate inside a worker, in a Node test, or inside a CE\n * connectedCallback. The Svelte context glue (`TOOL_POLICY_ENGINE_KEY`)\n * lives in `engine-context.ts`.\n *\n * PR 1 ships the engine *without callers*. PR 2 wires it into\n * `ToolkitCoordinator`. PR 3 switches `<pie-item-toolbar>` over.\n */\nimport { normalizeToolList, normalizeToolsConfig, } from \"../../services/tools-config-normalizer.js\";\nimport { hostFeatureDenial, interpretFeatureResult, } from \"./feature-decision.js\";\nimport { composeDecision } from \"./compose-decision.js\";\nimport { resolveDefaultPnpEnforcement } from \"./pnp-policy-inputs.js\";\nimport { PnpPolicySource } from \"../sources/PnpPolicySource.js\";\nconst DEFAULT_TOOLS = normalizeToolsConfig({\n policy: { allowed: [], blocked: [] },\n placement: { section: [], item: [], passage: [] },\n providers: {},\n});\nexport class ToolPolicyEngine {\n toolRegistry;\n contextId;\n pnpPolicySource;\n customSources;\n listeners = new Set();\n tools;\n assessment;\n currentItemRef;\n pnpEnforcement;\n disposed = false;\n constructor(args) {\n this.toolRegistry = args.toolRegistry;\n this.contextId = args.contextId ?? \"tool-policy\";\n this.pnpPolicySource = new PnpPolicySource(this.toolRegistry);\n this.customSources = args.customSources ? [...args.customSources] : [];\n const inputs = args.inputs ?? {};\n this.tools = inputs.tools ?? DEFAULT_TOOLS;\n this.assessment = inputs.assessment ?? null;\n this.currentItemRef = inputs.currentItemRef ?? null;\n this.pnpEnforcement =\n inputs.pnpEnforcement ??\n resolveDefaultPnpEnforcement({\n assessment: this.assessment,\n currentItemRef: this.currentItemRef,\n });\n }\n /**\n * Resolve the visible tool set for a given placement level and\n * scope.\n *\n * `visibleTools` and `diagnostics` are deterministic with respect\n * to the engine's currently-bound inputs — calling `decide(...)`\n * twice with identical inputs returns structurally equal\n * `visibleTools` and `diagnostics`. The returned `provenance`\n * carries call-time `evaluatedAt` timestamps generated by\n * `ToolPolicyProvenanceBuilder` (one per `decide(...)`); two\n * back-to-back calls therefore produce different `evaluatedAt`\n * values even though the policy decision itself is identical.\n * Hosts that want timestamp-stable provenance should reuse a\n * cached `ToolPolicyDecision` rather than re-call `decide(...)`.\n */\n decide(request) {\n this.assertNotDisposed();\n const requestContextId = request.scope.scopeId\n ? `${this.contextId}:${request.level}:${request.scope.scopeId}`\n : `${this.contextId}:${request.level}`;\n return composeDecision({\n request,\n tools: this.tools,\n pnpPolicy: {\n source: this.pnpPolicySource,\n assessment: this.assessment ?? undefined,\n currentItemRef: this.currentItemRef ?? undefined,\n enforcement: this.pnpEnforcement,\n },\n customSources: this.customSources,\n contextId: requestContextId,\n });\n }\n /**\n * Resolve eligibility for one PNP/AfA feature id through the six-level\n * precedence, independent of toolbar placement.\n *\n * For capabilities that render as their own surface rather than a toolbar\n * button — a signed alternate's region, for example — `decide(...)` cannot\n * answer the question, because such a capability is deliberately absent from\n * `tools.placement` and would read as \"removed by policy\" when nothing of\n * the sort happened. See {@link FeaturePolicyDecision}.\n *\n * `pnpEnforcement` is deliberately **not** consulted here. That flag governs\n * whether PNP/profile policy *refines* an otherwise-visible tool set; a\n * feature with no placement has no unrefined baseline to fall back to, so\n * skipping the PNP read would make the capability permanently unavailable\n * rather than merely unrefined. Auto-mode already flips enforcement on\n * whenever profile material exists, so this only diverges for a host that\n * explicitly forces `\"off\"` while supplying a profile that grants the\n * feature — and there, honouring the profile is the safer failure.\n *\n * The decision reports whether an assessment was bound, which is the engine's\n * to answer rather than the policy source's — see\n * {@link FeaturePolicyDecision.assessmentBound}.\n */\n decideFeature(featureId) {\n this.assertNotDisposed();\n const hostDenial = this.hostFeatureGate(featureId);\n if (hostDenial)\n return hostDenial;\n return interpretFeatureResult(featureId, this.pnpPolicySource.resolveFeature(featureId, {\n assessment: this.assessment ?? undefined,\n currentItemRef: this.currentItemRef ?? undefined,\n }), \n // `resolveFeature` takes the assessment as `undefined` either way, so the\n // source cannot tell an unbound host from one whose profile is silent.\n // The engine can.\n { assessmentBound: this.assessment !== null });\n }\n /**\n * The host gates that hold for a feature id, or `null` when none fires.\n *\n * `policy.allowed` / `policy.blocked` name capabilities, not placements, so\n * they are the one part of the host pipeline that is meaningful without a\n * placement level — and the only lever a host has over a capability that\n * renders as its own surface, since a `region` capability is rejected from\n * `tools.placement` by configuration validation. `provider-disabled` and\n * `placement-membership` are deliberately not applied: both are statements\n * about a toolbar the feature was never on.\n */\n hostFeatureGate(featureId) {\n const context = { assessmentBound: this.assessment !== null };\n const blocked = normalizeToolList(this.tools.policy.blocked);\n if (blocked.includes(featureId)) {\n return hostFeatureDenial(featureId, \"host-blocked\", blocked, context);\n }\n const allowed = normalizeToolList(this.tools.policy.allowed);\n if (allowed.length > 0 && !allowed.includes(featureId)) {\n return hostFeatureDenial(featureId, \"host-allowlist\", allowed, context);\n }\n return null;\n }\n /**\n * Convenience wrapper for hosts that just want the visible tool\n * IDs. Equivalent to `decide(...).visibleTools.map(e => e.toolId)`.\n */\n getVisibleToolIds(level, scopeId) {\n return this.decide({\n level,\n scope: { level, scopeId },\n }).visibleTools.map((entry) => entry.toolId);\n }\n /**\n * Apply a partial input update.\n *\n * Each key is value-diffed via `Object.is` before storing, so callers\n * may safely re-push the same reference (e.g. on Svelte effect\n * re-runs caused by unrelated tracked reads): no-op patches do not\n * fire `onPolicyChange` listeners. This contract is relied on by\n * `PieAssessmentToolkit.svelte`'s prop-forwarding effect and by the\n * coordinator's `decideToolPolicy()` tests.\n *\n * `pnpEnforcement` is stored on its own field and always emits with\n * a distinct `\"pnp-enforcement\"` reason when no other key changed,\n * so PR 4's auto-on flip can target that reason without a separate\n * event channel.\n */\n updateInputs(patch) {\n this.assertNotDisposed();\n let changed = false;\n let pnpChanged = false;\n if (\"tools\" in patch) {\n const next = patch.tools ?? DEFAULT_TOOLS;\n if (!Object.is(this.tools, next)) {\n this.tools = next;\n changed = true;\n }\n }\n if (\"assessment\" in patch) {\n const next = patch.assessment ?? null;\n if (!Object.is(this.assessment, next)) {\n this.assessment = next;\n changed = true;\n }\n }\n if (\"currentItemRef\" in patch) {\n const next = patch.currentItemRef ?? null;\n if (!Object.is(this.currentItemRef, next)) {\n this.currentItemRef = next;\n changed = true;\n }\n }\n if (\"pnpEnforcement\" in patch && patch.pnpEnforcement) {\n if (this.pnpEnforcement !== patch.pnpEnforcement) {\n this.pnpEnforcement = patch.pnpEnforcement;\n pnpChanged = true;\n }\n }\n if (changed || pnpChanged) {\n this.emit({\n reason: pnpChanged && !changed ? \"pnp-enforcement\" : \"inputs\",\n inputs: this.snapshotInputs(),\n });\n }\n }\n registerPolicySource(source) {\n this.assertNotDisposed();\n this.customSources.push(source);\n this.emit({\n reason: \"policy-source-added\",\n inputs: this.snapshotInputs(),\n });\n return () => {\n const idx = this.customSources.indexOf(source);\n if (idx !== -1) {\n this.customSources.splice(idx, 1);\n if (!this.disposed) {\n this.emit({\n reason: \"policy-source-removed\",\n inputs: this.snapshotInputs(),\n });\n }\n }\n };\n }\n onPolicyChange(listener) {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n getInputs() {\n return this.snapshotInputs();\n }\n dispose() {\n if (this.disposed)\n return;\n this.disposed = true;\n this.emit({\n reason: \"disposed\",\n inputs: this.snapshotInputs(),\n });\n this.listeners.clear();\n this.customSources.length = 0;\n }\n snapshotInputs() {\n return Object.freeze({\n tools: this.tools,\n assessment: this.assessment,\n currentItemRef: this.currentItemRef,\n pnpEnforcement: this.pnpEnforcement,\n });\n }\n emit(event) {\n for (const listener of Array.from(this.listeners)) {\n try {\n listener(event);\n }\n catch {\n // Subscriber errors must not break the engine. Hosts that\n // want error telemetry should wrap their listener.\n }\n }\n }\n assertNotDisposed() {\n if (this.disposed) {\n throw new Error(\"ToolPolicyEngine has been disposed.\");\n }\n }\n}\n","/**\n * ToolkitCoordinator - Centralized Assessment Toolkit Service Management\n *\n * Orchestrates all toolkit services (TTS, tools, accessibility, state management) from a single entry point.\n * Provides centralized configuration for tool availability and settings.\n *\n * Key features:\n * - Owns all toolkit services (TTSService, ToolCoordinator, HighlightCoordinator, ElementToolStateStore, AccessibilityCatalogResolver)\n * - Single configuration point for tool availability and settings\n * - Sensible defaults for standalone usage\n * - Direct access for settings widgets (no player dependency)\n * - Clean separation: toolkit concerns only (NOT assessment state like navigation, timing, progress)\n *\n * Part of PIE Assessment Toolkit.\n */\nimport { normalizeToolsConfig, } from \"./tools-config-normalizer.js\";\nimport { normalizeAndValidateToolsConfig, normalizeToolConfigStrictness, } from \"./tool-config-validation.js\";\nimport { AccessibilityCatalogResolver } from \"./AccessibilityCatalogResolver.js\";\nimport { ElementToolStateStore } from \"./ElementToolStateStore.js\";\nimport { frameworkErrorFromCoordinatorContext, } from \"./framework-error.js\";\nimport { FrameworkErrorBus, } from \"./framework-error-bus.js\";\nimport { HighlightCoordinator } from \"./HighlightCoordinator.js\";\nimport { ToolCoordinator } from \"./ToolCoordinator.js\";\nimport { TTSService } from \"./TTSService.js\";\nimport { BrowserTTSProvider } from \"./tts/browser-provider.js\";\nimport { buildRuntimeTTSConfig, resolveTTSBackend, resolveTTSRuntimeSettings, } from \"./tts-runtime-config.js\";\nimport { ToolProviderRegistry } from \"./tool-providers/index.js\";\nimport { ToolRegistry } from \"./ToolRegistry.js\";\nimport { ToolRequestRegistry } from \"./tool-request.js\";\nimport { ToolPolicyEngine, } from \"../policy/engine.js\";\nimport { resolveDefaultPnpEnforcement } from \"../policy/internal.js\";\nconst isPlainRecord = (value) => !!value && typeof value === \"object\" && !Array.isArray(value);\nconst mergeToolConfigUpdate = (toolId, current, updates) => {\n const next = { ...current, ...updates };\n if (toolId === \"textToSpeech\" &&\n isPlainRecord(current.settings) &&\n isPlainRecord(updates.settings)) {\n next.settings = { ...current.settings, ...updates.settings };\n if (isPlainRecord(current.settings.mathSpeech) &&\n isPlainRecord(updates.settings.mathSpeech)) {\n next.settings.mathSpeech = {\n ...current.settings.mathSpeech,\n ...updates.settings.mathSpeech,\n };\n }\n }\n return next;\n};\nconst SECTION_ITEM_EVENT_TYPES = [\n \"item-selected\",\n \"item-session-data-changed\",\n \"item-session-meta-changed\",\n \"item-complete-changed\",\n \"content-loaded\",\n \"item-player-error\",\n];\nconst SECTION_SCOPED_EVENT_TYPES = [\n \"section-navigation-change\",\n \"section-session-applied\",\n \"section-loading-complete\",\n \"section-items-complete-changed\",\n \"section-error\",\n \"timed-media-cue-changed\",\n \"timed-media-policy-degraded\",\n \"timed-media-invalid\",\n];\n/**\n * ToolkitCoordinator - Orchestrates all assessment toolkit services\n *\n * @example\n * ```typescript\n * // Create coordinator with configuration\n * const coordinator = new ToolkitCoordinator({\n * assessmentId: 'demo-three-questions',\n * tools: {\n * providers: {\n * textToSpeech: { enabled: true, backend: 'browser' },\n * answerEliminator: { enabled: true, strategy: 'strikethrough' }\n * },\n * placement: {\n * item: ['textToSpeech', 'answerEliminator']\n * }\n * }\n * });\n *\n * // Pass to section player\n * player.toolkitCoordinator = coordinator;\n *\n * // Access services directly\n * const ttsService = coordinator.ttsService;\n * const toolState = coordinator.elementToolStateStore.getAllState();\n * ```\n */\nexport class ToolkitCoordinator {\n /** Assessment identifier (for scoping tool state) */\n assessmentId;\n /** Configuration */\n config;\n /** Managed services (public for direct access) */\n ttsService;\n toolCoordinator;\n highlightCoordinator;\n elementToolStateStore;\n catalogResolver;\n toolProviderRegistry;\n hooks;\n lazyInit;\n /** Track TTS initialization state */\n ttsInitialized = false;\n ttsInitPromise;\n ttsReconfigurePromise;\n stateLoaded = false;\n stateLoadPromise;\n coordinatorReadyPromise;\n coordinatorReadyNotified = false;\n providerInitPromises = new Map();\n toolRegistry;\n toolContextResolvers = new Map();\n toolContextResolverChangeListeners = new Set();\n toolRequests = new ToolRequestRegistry();\n sectionControllers = new Map();\n sectionControllerKeys = new Map();\n sectionControllerInitPromises = new Map();\n sectionPersistenceStrategies = new Map();\n sectionControllerLifecycleListeners = new Set();\n /**\n * Phase D: every active section-event subscription, indexed by\n * listener identity. The listener follows the toolkit's active\n * section cohort across transitions; this map is the registry the\n * coordinator iterates on every cohort change to detach the listener\n * from the outgoing controller, attach it to the new one, and replay\n * the snapshot (content-loaded × N then section-loading-complete) in\n * canonical order.\n *\n * Dedup is by listener identity: subscribing the same listener\n * function twice replaces the prior subscription's filter args.\n */\n activeSubscriptions = new Map();\n /**\n * Phase D: map key of the section controller currently treated as\n * the *active cohort*. Set by `getOrCreateSectionController` (both\n * the create-new and resolve-existing paths) and cleared when the\n * matching controller is disposed. `null` while no cohort exists,\n * which is the only state where `subscribeSectionEvents` throws.\n */\n activeCohortMapKey = null;\n /**\n * Latest requested active cohort. Async controller initialization can\n * resolve out of order; only the most recent request may migrate active\n * subscriptions. Older completions still populate the controller cache.\n */\n latestRequestedActiveCohortMapKey = null;\n telemetryListeners = new Set();\n frameworkErrorBus;\n ownsFrameworkErrorBus;\n /**\n * Unified Tool Policy Engine. Owned by the coordinator and lives\n * for the lifetime of the coordinator instance — there is no\n * explicit teardown path today; the engine and its listener set\n * are reclaimed by GC when the coordinator becomes unreachable.\n * Subscribers attached via {@link onPolicyChange} must therefore\n * detach via the unsubscribe function the engine returns; do not\n * rely on a `disposed` event being emitted on coordinator teardown.\n *\n * Hosts read decisions via {@link decideToolPolicy} or subscribe\n * to changes via {@link onPolicyChange}.\n */\n policyEngine;\n /**\n * Host-set override for PNP/profile enforcement. `null` (the default) means\n * \"auto\" — the coordinator infers the effective mode from the\n * PNP/profile policy inputs the bound `AssessmentEntity` and `AssessmentItemRef`\n * actually carry (see {@link resolveEffectivePnpEnforcement}).\n * `\"on\"` / `\"off\"` are explicit host opt-in / opt-out and stick\n * across subsequent assessment / item swaps until the host clears\n * the override by calling `setPnpEnforcement(null)`.\n */\n pnpEnforcementOverride = null;\n /**\n * Last assessment passed to {@link updateAssessment}. Read by\n * {@link resolveEffectivePnpEnforcement} to compute auto-mode.\n * The engine's own copy is the canonical record for decisions;\n * this mirror exists only so the auto-mode helper does not need\n * to round-trip through {@link policyEngine}'s frozen snapshot.\n */\n boundAssessment = null;\n /**\n * Last item reference passed to {@link updateCurrentItemRef}.\n * Mirrored alongside {@link boundAssessment} so\n * {@link resolveEffectivePnpEnforcement} can detect item-level\n * profile policy inputs (`requiredTools` / `restrictedTools` /\n * `toolParameters`) without round-tripping through the engine's\n * frozen snapshot.\n */\n boundCurrentItemRef = null;\n /**\n * Whether {@link decideFeaturePolicy} has already reported serving a decision\n * with no assessment bound.\n *\n * One report per coordinator, not per decision: a feature policy is consulted\n * once per capability per card, so a per-decision warning would bury itself.\n * Never reset — {@link updateAssessment} arriving later fixes the deployment,\n * and re-arming would report the same gap again on the next unbound coordinator\n * lifetime for no new information.\n */\n reportedUnboundFeaturePolicy = false;\n static resolveConfig(config) {\n const strictness = normalizeToolConfigStrictness(config.toolConfigStrictness);\n // An empty registry when the host supplies none. This package no longer\n // holds the packaged capability set, so there is nothing to fall back to —\n // a host that wants stock tools passes a registry from\n // `@pie-players/pie-default-tool-loaders`. Tool-id validation is skipped\n // against an empty registry (with a diagnostic saying so) rather than\n // rejecting every configured id.\n const toolRegistry = config.toolRegistry ?? new ToolRegistry();\n const normalized = config.deferToolConfigValidation === true\n ? normalizeToolsConfig(config.tools)\n : normalizeAndValidateToolsConfig(config.tools, {\n strictness,\n source: \"ToolkitCoordinator.init\",\n toolRegistry,\n }).config;\n const defaultProviders = {\n textToSpeech: {\n enabled: true,\n backend: \"browser\",\n },\n annotationToolbar: {\n enabled: true,\n },\n };\n return {\n ...config,\n toolConfigStrictness: strictness,\n toolRegistry,\n tools: {\n ...normalized,\n providers: {\n ...defaultProviders,\n ...normalized.providers,\n },\n },\n accessibility: {\n language: \"en-US\",\n ...(config.accessibility ?? {}),\n catalogs: config.accessibility?.catalogs ?? [],\n },\n };\n }\n constructor(config) {\n if (!config.assessmentId) {\n throw new Error(\"ToolkitCoordinator requires assessmentId in config\");\n }\n const resolvedConfig = ToolkitCoordinator.resolveConfig(config);\n this.assessmentId = resolvedConfig.assessmentId;\n this.config = resolvedConfig;\n this.toolRegistry = resolvedConfig.toolRegistry ?? new ToolRegistry();\n this.installToolContextResolvers(resolvedConfig.toolContextResolvers);\n this.hooks = resolvedConfig.hooks ?? {};\n this.lazyInit = config.lazyInit === true;\n this.pnpEnforcementOverride = this.resolveConfiguredPnpEnforcement();\n // Use the host-provided framework-error bus if one was passed\n // (typical when embedded inside <pie-assessment-toolkit>, so\n // pre-coordinator failures from the CE flow through the same\n // fan-out as coordinator failures). Otherwise own a private one.\n this.frameworkErrorBus =\n config.frameworkErrorBus ?? new FrameworkErrorBus();\n this.ownsFrameworkErrorBus = !config.frameworkErrorBus;\n this.subscribeFrameworkErrorHookAdapters();\n // Initialize all services\n this.toolCoordinator = new ToolCoordinator();\n this.highlightCoordinator = new HighlightCoordinator();\n this.elementToolStateStore = new ElementToolStateStore();\n this.catalogResolver = new AccessibilityCatalogResolver(resolvedConfig.accessibility?.catalogs || [], resolvedConfig.accessibility?.language || \"en-US\");\n // Initialize tool provider registry\n this.toolProviderRegistry = new ToolProviderRegistry();\n this._registerToolProviders();\n // Initialize TTS service based on config\n this.ttsService = new TTSService();\n this.setupStatePersistenceHooks();\n // M8 PR 2 — construct the unified ToolPolicyEngine seeded with\n // the validated tools config. PNP/profile inputs (`assessment`,\n // `currentItemRef`) start `null`; `pnpEnforcement` is resolved\n // through {@link resolveEffectivePnpEnforcement}, which flips\n // to `\"on\"` only once the bound assessment or item carries\n // actual profile material. Hosts that only consume the\n // engine for placement/policy gating get the pre-PR-2 behavior\n // bit-for-bit.\n this.policyEngine = new ToolPolicyEngine({\n toolRegistry: this.toolRegistry,\n contextId: `toolkit-coordinator:${this.assessmentId}`,\n inputs: {\n tools: this.config.tools,\n assessment: null,\n currentItemRef: null,\n pnpEnforcement: this.resolveEffectivePnpEnforcement(),\n },\n });\n if (!this.lazyInit) {\n void this.waitUntilReady().catch((err) => {\n console.error(\"[ToolkitCoordinator] Failed eager initialization:\", err);\n this.handleError(err, { phase: \"coordinator-ready\" });\n });\n }\n }\n /**\n * Subscribe the canonical `onFrameworkError` hook adapter to the\n * framework-error bus.\n *\n * Called once from the constructor. The adapter inspects the live\n * `this.hooks` reference, so a hook added later via {@link setHooks}\n * is picked up automatically without re-subscribing.\n */\n subscribeFrameworkErrorHookAdapters() {\n this.frameworkErrorBus.subscribeFrameworkErrors((model) => {\n const hook = this.hooks.onFrameworkError;\n if (!hook)\n return;\n try {\n hook(model);\n }\n catch (hookError) {\n console.warn(\"[ToolkitCoordinator] onFrameworkError hook failed:\", hookError);\n }\n });\n }\n /**\n * Emit a telemetry event to `onTelemetry` hook + all `subscribeTelemetry`\n * listeners.\n *\n * **Naming convention.** Event names MUST be prefixed at the call site,\n * not auto-decorated here. The convention is:\n *\n * - `pie-toolkit-*` for toolkit lifecycle (state load, providers,\n * coordinator readiness, section-controller register/dispose, TTS\n * bring-up, tool-config updates, etc.).\n * - `pie-tool-*` for individual tool events (provider init lifecycle,\n * provider backend calls, tool-specific telemetry forwarded from\n * `__pieTelemetry`).\n * - `pie-section-*` is reserved for section-player layout events\n * surfaced via `attachInstrumentationEventBridge` and is not emitted\n * from this method directly.\n *\n * Anything that does not fit a documented prefix is a deliberate decision\n * to be raised in code review, not a fallback. There is no \"auto prefix\"\n * here on purpose: it keeps every emit-site honest about which namespace\n * it owns, and lets `subscribeTelemetry` consumers compare against\n * documented strings without per-consumer normalization.\n */\n async emitTelemetry(eventName, payload) {\n try {\n await this.hooks.onTelemetry?.(eventName, payload);\n }\n catch (err) {\n console.warn(\"[ToolkitCoordinator] telemetry hook failed:\", err);\n }\n const nextPayload = payload ? { ...payload } : undefined;\n for (const listener of this.telemetryListeners) {\n try {\n listener({\n eventName,\n payload: nextPayload ? { ...nextPayload } : undefined,\n });\n }\n catch (err) {\n console.warn(\"[ToolkitCoordinator] telemetry listener failed:\", err);\n }\n }\n }\n emitSectionControllerLifecycle(event) {\n for (const listener of this.sectionControllerLifecycleListeners) {\n try {\n listener(event);\n }\n catch (error) {\n console.warn(\"[ToolkitCoordinator] section controller lifecycle listener failed:\", error);\n }\n }\n }\n handleError(error, context) {\n const model = frameworkErrorFromCoordinatorContext({\n error,\n context,\n });\n this.frameworkErrorBus.reportFrameworkError(model);\n }\n /**\n * Subscribe to framework-error events emitted by this coordinator.\n *\n * See `ToolkitCoordinatorApi.subscribeFrameworkErrors` for the\n * contract. The bus is shared with the canonical\n * `onFrameworkError` lifecycle hook, so a listener registered here\n * sees the same fan-out the hook sees.\n */\n subscribeFrameworkErrors(listener) {\n return this.frameworkErrorBus.subscribeFrameworkErrors(listener);\n }\n /**\n * Report a framework-error model directly into this coordinator's bus.\n *\n * Used by embedding hosts (e.g. `<pie-assessment-toolkit>`) that\n * pre-construct their own framework-error model in a path that does\n * not go through `handleError` — for example, `runtime-init` failures\n * raised before any coordinator phase, or `tool-config` failures\n * synthesized from validation diagnostics.\n *\n * Hosts that already share their bus via the constructor's\n * `frameworkErrorBus` config field do not need to call this; their\n * own `bus.reportFrameworkError(model)` is observed here.\n *\n * @internal\n */\n reportFrameworkError(model) {\n this.frameworkErrorBus.reportFrameworkError(model);\n }\n getSectionControllerMapKey(key) {\n return `${key.assessmentId}::${key.sectionId}::${key.attemptId || \"\"}`;\n }\n createDefaultSectionPersistence() {\n const storage = (() => {\n try {\n if (typeof window === \"undefined\")\n return null;\n return window.localStorage;\n }\n catch {\n return null;\n }\n })();\n const getStorageKey = (context) => {\n const { assessmentId, sectionId, attemptId } = context.key;\n return `pie:section-controller:v1:${assessmentId}:${sectionId}:${attemptId || \"default\"}`;\n };\n return {\n async loadSession(context) {\n if (!storage)\n return null;\n const value = storage.getItem(getStorageKey(context));\n if (!value)\n return null;\n try {\n return JSON.parse(value);\n }\n catch {\n return null;\n }\n },\n async saveSession(context, session) {\n if (!storage)\n return;\n storage.setItem(getStorageKey(context), JSON.stringify(session));\n },\n async clearSession(context) {\n if (!storage)\n return;\n storage.removeItem(getStorageKey(context));\n },\n };\n }\n async resolveSectionPersistence(context) {\n const cacheKey = this.getSectionControllerMapKey(context.key);\n const existing = this.sectionPersistenceStrategies.get(cacheKey);\n if (existing)\n return existing;\n const defaults = {\n createDefaultPersistence: () => this.createDefaultSectionPersistence(),\n };\n const strategy = (await this.hooks.createSectionSessionPersistence?.(context, defaults)) ??\n (await defaults.createDefaultPersistence());\n this.sectionPersistenceStrategies.set(cacheKey, strategy);\n return strategy;\n }\n setupStatePersistenceHooks() {\n this.elementToolStateStore.setOnStateChange((state) => {\n if (!this.hooks.saveToolState)\n return;\n void Promise.resolve(this.hooks.saveToolState(state)).catch((err) => {\n this.handleError(err, { phase: \"state-save\" });\n });\n });\n }\n async ensureStateLoaded() {\n if (this.stateLoaded)\n return;\n if (this.stateLoadPromise)\n return this.stateLoadPromise;\n this.stateLoadPromise = (async () => {\n const loader = this.hooks.loadToolState;\n if (!loader) {\n return;\n }\n try {\n const state = await loader();\n if (state && typeof state === \"object\") {\n this.elementToolStateStore.loadState(state);\n }\n this.stateLoaded = true;\n await this.emitTelemetry(\"pie-toolkit-tool-state-loaded\", {\n hasState: Boolean(state),\n });\n }\n catch (err) {\n this.handleError(err, { phase: \"state-load\" });\n }\n })().finally(() => {\n this.stateLoadPromise = undefined;\n });\n return this.stateLoadPromise;\n }\n /**\n * Register tool providers in the registry\n */\n _registerToolProviders() {\n const descriptorTools = this.getProviderDescriptorTools();\n for (const tool of descriptorTools) {\n void this.registerProviderFromTool(tool);\n }\n }\n getProviderDescriptorTools() {\n return this.toolRegistry.getAllTools().filter((tool) => !!tool.provider);\n }\n async registerProviderFromTool(tool) {\n const descriptor = tool.provider;\n if (!descriptor)\n return;\n const toolConfig = this.getToolConfig(tool.toolId) || undefined;\n if (toolConfig?.enabled === false)\n return;\n const providerId = descriptor.getProviderId?.(toolConfig) ??\n toolConfig?.provider?.id ??\n tool.toolId;\n if (this.toolProviderRegistry.has(providerId))\n return;\n const provider = descriptor.createProvider(toolConfig);\n const initConfig = descriptor.getInitConfig?.(toolConfig) ??\n toolConfig?.provider?.init ??\n {};\n const initConfigWithTelemetry = this.addToolTelemetryReporter({\n toolId: tool.toolId,\n providerId,\n initConfig,\n });\n const registryTelemetry = this.createToolTelemetryForwarder({\n toolId: tool.toolId,\n providerId,\n });\n const authFetcher = descriptor.getAuthFetcher?.(toolConfig) ??\n toolConfig?.provider?.runtime?.authFetcher;\n await this.registerProvider(providerId, {\n provider,\n config: initConfigWithTelemetry,\n lazy: descriptor.lazy ?? true,\n authFetcher,\n onTelemetry: registryTelemetry,\n });\n }\n createToolTelemetryForwarder(args) {\n return async (eventName, payload) => {\n await this.emitTelemetry(eventName, {\n ...(payload || {}),\n toolId: args.toolId,\n providerId: args.providerId,\n });\n };\n }\n addToolTelemetryReporter(args) {\n const configObject = args.initConfig && typeof args.initConfig === \"object\"\n ? { ...args.initConfig }\n : {};\n const existingReporter = typeof configObject.onTelemetry === \"function\"\n ? configObject.onTelemetry\n : null;\n const forwardTelemetry = this.createToolTelemetryForwarder({\n toolId: args.toolId,\n providerId: args.providerId,\n });\n configObject.onTelemetry = async (eventName, payload) => {\n if (existingReporter) {\n await existingReporter(eventName, payload);\n }\n await forwardTelemetry(eventName, payload);\n };\n return configObject;\n }\n async registerProvider(providerId, config) {\n try {\n this.toolProviderRegistry.register(providerId, config);\n const meta = {\n providerId,\n providerName: config.provider.providerName,\n };\n await this.hooks.onProviderRegistered?.(providerId, meta);\n await this.emitTelemetry(\"pie-toolkit-provider-registered\", {\n providerId,\n providerName: config.provider.providerName,\n });\n }\n catch (err) {\n console.warn(`[ToolkitCoordinator] Failed to register provider \"${providerId}\":`, err);\n this.handleError(err, { phase: \"provider-register\", providerId });\n }\n }\n async ensureProviderReady(providerId) {\n const existing = this.providerInitPromises.get(providerId);\n if (existing)\n return existing;\n const promise = (async () => {\n const provider = await this.toolProviderRegistry.getProvider(providerId, false);\n const meta = {\n providerId,\n providerName: provider.providerName,\n };\n try {\n await this.hooks.onProviderInitStart?.(providerId, meta);\n await this.toolProviderRegistry.initialize(providerId);\n await this.hooks.onProviderReady?.(providerId, meta);\n await this.emitTelemetry(\"pie-toolkit-provider-ready\", { providerId });\n return provider;\n }\n catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n this.handleError(error, { phase: \"provider-init\", providerId });\n throw error;\n }\n })().finally(() => {\n this.providerInitPromises.delete(providerId);\n });\n this.providerInitPromises.set(providerId, promise);\n return promise;\n }\n setHooks(hooks) {\n Object.assign(this.hooks, hooks);\n this.setupStatePersistenceHooks();\n if (hooks.onCoordinatorReady && this.isReady()) {\n void Promise.resolve(hooks.onCoordinatorReady(this)).catch((err) => {\n this.handleError(err, { phase: \"coordinator-ready\" });\n });\n }\n }\n subscribeTelemetry(listener) {\n this.telemetryListeners.add(listener);\n return () => {\n this.telemetryListeners.delete(listener);\n };\n }\n getSectionController(args) {\n const key = {\n assessmentId: this.assessmentId,\n sectionId: args.sectionId,\n attemptId: args.attemptId,\n };\n return this.sectionControllers.get(this.getSectionControllerMapKey(key));\n }\n subscribeSectionEvents(args) {\n // Phase D: subscriptions follow the toolkit's *active section\n // cohort* automatically. We bind the listener to whichever\n // controller is currently active and re-bind it on every\n // `getOrCreateSectionController` / `disposeSectionController`\n // transition, with snapshot replay on each migration.\n if (this.activeCohortMapKey === null) {\n throw new Error(\"[ToolkitCoordinator] subscribeSectionEvents requires an active section cohort; call getOrCreateSectionController first.\");\n }\n const previous = this.activeSubscriptions.get(args.listener);\n if (previous) {\n previous.unsubscribeCurrent?.();\n previous.unsubscribeCurrent = null;\n }\n const sub = {\n listener: args.listener,\n eventTypes: args.eventTypes,\n itemIds: args.itemIds,\n unsubscribeCurrent: null,\n };\n this.activeSubscriptions.set(args.listener, sub);\n const controller = this.sectionControllers.get(this.activeCohortMapKey);\n if (controller) {\n this.bindSubscriptionToController(sub, controller);\n }\n let detached = false;\n return () => {\n if (detached)\n return;\n detached = true;\n sub.unsubscribeCurrent?.();\n sub.unsubscribeCurrent = null;\n // Only delete if the registry still points at *this* sub. A\n // re-subscribe with the same listener replaces the entry; an\n // old disposer must not stomp the new one.\n if (this.activeSubscriptions.get(args.listener) === sub) {\n this.activeSubscriptions.delete(args.listener);\n }\n };\n }\n /**\n * Bind a Phase D subscription to a section controller. Detaches any\n * prior controller binding the subscription was holding, attaches a\n * fresh `controller.subscribe(...)` callback, and replays the\n * canonical late-subscribe sequence (content-loaded × N then\n * section-loading-complete) so the listener observes the same\n * ordering a fresh subscriber would have seen.\n *\n * Listener throws are caught and `console.warn`-logged; the throw\n * does not interrupt fan-out to the remaining listeners (matches\n * the {@link FrameworkErrorBus} isolation pattern).\n */\n bindSubscriptionToController(sub, controller) {\n sub.unsubscribeCurrent?.();\n sub.unsubscribeCurrent = null;\n const subscribe = controller.subscribe;\n if (typeof subscribe !== \"function\")\n return;\n const predicate = this.buildSectionEventPredicate(sub);\n sub.unsubscribeCurrent = subscribe.call(controller, (event) => {\n if (!predicate(event))\n return;\n this.deliverSectionEventSafely(sub.listener, event);\n });\n const contentLoadedReplays = this.buildContentLoadedReplayEvents(controller);\n for (const event of contentLoadedReplays) {\n if (predicate(event)) {\n this.deliverSectionEventSafely(sub.listener, event);\n }\n }\n const loadingComplete = this.buildLoadingCompleteReplayEvent(controller);\n if (loadingComplete && predicate(loadingComplete)) {\n this.deliverSectionEventSafely(sub.listener, loadingComplete);\n }\n }\n deliverSectionEventSafely(listener, event) {\n try {\n listener(event);\n }\n catch (error) {\n console.warn(\"[ToolkitCoordinator] section-event listener failed:\", error);\n }\n }\n /**\n * Mark the given map key as the active section cohort. Called from\n * `getOrCreateSectionController` (both create-new and resolve-existing\n * paths) so a cohort transition through either path migrates active\n * subscriptions.\n *\n * Same-cohort re-entry is a no-op so a same-cohort `updateInput`\n * (PnP toggle, prompt edit) doesn't double-replay snapshots to\n * already-bound listeners.\n */\n setActiveCohort(mapKey) {\n if (this.activeCohortMapKey === mapKey)\n return;\n this.activeCohortMapKey = mapKey;\n const controller = this.sectionControllers.get(mapKey);\n if (!controller)\n return;\n // Snapshot the subscription list before iterating: a listener may\n // synchronously call `subscribeSectionEvents(...)` from inside its\n // replay delivery, which inserts a new entry into\n // `activeSubscriptions`. Map iteration yields keys inserted\n // during the loop; without snapshotting, the inner subscribe path\n // would bind the new listener once (correctly, with replay) and\n // the outer loop would then visit it a second time, double-\n // replaying the snapshot. Snapshot keeps \"replay once per cohort\n // transition\" intact.\n for (const sub of Array.from(this.activeSubscriptions.values())) {\n this.bindSubscriptionToController(sub, controller);\n }\n }\n setActiveCohortIfLatestRequest(mapKey) {\n if (this.latestRequestedActiveCohortMapKey !== mapKey)\n return;\n this.setActiveCohort(mapKey);\n }\n suspendActiveCohortIfSuperseded(mapKey) {\n if (this.activeCohortMapKey === null)\n return;\n if (this.activeCohortMapKey === mapKey)\n return;\n this.activeCohortMapKey = null;\n for (const sub of Array.from(this.activeSubscriptions.values())) {\n sub.unsubscribeCurrent?.();\n sub.unsubscribeCurrent = null;\n }\n }\n /**\n * Clear the active cohort if `mapKey` matches it, detaching every\n * active subscription's current controller binding. Subscriptions\n * stay in the registry — a subsequent `setActiveCohort(...)` will\n * re-bind them to the new controller.\n */\n clearActiveCohortIfMatches(mapKey) {\n if (this.activeCohortMapKey !== mapKey)\n return;\n this.activeCohortMapKey = null;\n // Symmetric snapshot for safety: a disposer fired during detach\n // could mutate `activeSubscriptions`. Detach is silent (no listener\n // fan-out), so re-entrancy exposure is lower than `setActiveCohort`,\n // but the snapshot keeps both paths uniform.\n for (const sub of Array.from(this.activeSubscriptions.values())) {\n sub.unsubscribeCurrent?.();\n sub.unsubscribeCurrent = null;\n }\n }\n buildSectionEventPredicate(args) {\n const eventTypeFilter = args.eventTypes ? new Set(args.eventTypes) : null;\n const itemIdFilter = args.itemIds ? new Set(args.itemIds) : null;\n return (event) => {\n if (eventTypeFilter || itemIdFilter) {\n const eventType = event?.type || null;\n if (eventTypeFilter &&\n (!eventType || !eventTypeFilter.has(eventType))) {\n return false;\n }\n if (itemIdFilter) {\n const hasMatchingItem = Array.from(this.collectEventItemIds(event)).some((itemId) => itemIdFilter.has(itemId));\n if (!hasMatchingItem) {\n return false;\n }\n }\n }\n return true;\n };\n }\n collectEventItemIds(event) {\n const itemIds = new Set();\n if (\"itemId\" in event && typeof event.itemId === \"string\") {\n itemIds.add(event.itemId);\n }\n if (\"canonicalItemId\" in event &&\n typeof event.canonicalItemId === \"string\") {\n itemIds.add(event.canonicalItemId);\n }\n if (\"currentItemId\" in event && typeof event.currentItemId === \"string\") {\n itemIds.add(event.currentItemId);\n }\n if (\"previousItemId\" in event && typeof event.previousItemId === \"string\") {\n itemIds.add(event.previousItemId);\n }\n return itemIds;\n }\n /**\n * Build replay `content-loaded` events for renderables the controller has\n * already finished loading.\n *\n * Strict by design: only renderables explicitly reported in\n * `runtimeState.loadedRenderables` are replayed. Synthetic test harnesses\n * that omit the field (or controllers from older revisions that did not\n * populate it) get an empty replay set rather than a fabricated one — that\n * preserves the contract that replays mirror events that actually fired.\n *\n * Order follows registration order from\n * `SectionController.collectLoadedRenderableSnapshot`, which mirrors the\n * order live `content-loaded` events were emitted in.\n */\n buildContentLoadedReplayEvents(controller) {\n const runtimeState = controller.getRuntimeState?.();\n const loadedRenderables = runtimeState?.loadedRenderables;\n if (!Array.isArray(loadedRenderables) || loadedRenderables.length === 0) {\n return [];\n }\n const currentItemIndex = typeof runtimeState?.currentItemIndex === \"number\" &&\n Number.isFinite(runtimeState.currentItemIndex)\n ? runtimeState.currentItemIndex\n : 0;\n const timestamp = Date.now();\n const events = [];\n for (const renderable of loadedRenderables) {\n if (!renderable)\n continue;\n const itemId = renderable.itemId;\n const canonicalItemId = typeof renderable.canonicalItemId === \"string\" &&\n renderable.canonicalItemId\n ? renderable.canonicalItemId\n : itemId;\n if (typeof itemId !== \"string\" || !itemId)\n continue;\n events.push({\n type: \"content-loaded\",\n contentKind: renderable.contentKind ?? \"unknown\",\n itemId,\n canonicalItemId,\n currentItemIndex,\n timestamp,\n });\n }\n return events;\n }\n buildLoadingCompleteReplayEvent(controller) {\n const runtimeState = controller.getRuntimeState?.();\n if (runtimeState?.loadingComplete !== true)\n return null;\n const totalRegistered = typeof runtimeState.totalRegistered === \"number\" &&\n Number.isFinite(runtimeState.totalRegistered)\n ? Math.max(0, runtimeState.totalRegistered)\n : 0;\n const totalLoaded = typeof runtimeState.totalLoaded === \"number\" &&\n Number.isFinite(runtimeState.totalLoaded)\n ? Math.max(0, runtimeState.totalLoaded)\n : totalRegistered;\n return {\n type: \"section-loading-complete\",\n totalRegistered,\n totalLoaded,\n currentItemIndex: runtimeState.currentItemIndex,\n timestamp: Date.now(),\n };\n }\n /**\n * Subscribe to item-scoped controller events.\n *\n * Same active-cohort binding contract as\n * {@link subscribeSectionEvents}; defaults `eventTypes` to the\n * item-scoped subset.\n */\n subscribeItemEvents(args) {\n return this.subscribeSectionEvents({\n eventTypes: args.eventTypes || SECTION_ITEM_EVENT_TYPES,\n itemIds: args.itemIds,\n listener: args.listener,\n });\n }\n /**\n * Subscribe to section-scoped controller events.\n *\n * Same active-cohort binding contract as\n * {@link subscribeSectionEvents}; defaults `eventTypes` to the\n * section-scoped subset. Section-scoped events do not carry item\n * identifiers, so this helper intentionally does not expose\n * `itemIds` filtering.\n */\n subscribeSectionLifecycleEvents(args) {\n return this.subscribeSectionEvents({\n eventTypes: args.eventTypes || SECTION_SCOPED_EVENT_TYPES,\n listener: args.listener,\n });\n }\n onSectionControllerLifecycle(listener) {\n this.sectionControllerLifecycleListeners.add(listener);\n return () => {\n this.sectionControllerLifecycleListeners.delete(listener);\n };\n }\n async getOrCreateSectionController(args) {\n const key = {\n assessmentId: this.assessmentId,\n sectionId: args.sectionId,\n attemptId: args.attemptId,\n };\n const mapKey = this.getSectionControllerMapKey(key);\n this.latestRequestedActiveCohortMapKey = mapKey;\n this.suspendActiveCohortIfSuperseded(mapKey);\n const existingController = await this.resolveExistingSectionController({\n mapKey,\n key,\n input: args.input,\n updateExisting: args.updateExisting,\n });\n if (existingController)\n return existingController;\n const existingPromise = this.sectionControllerInitPromises.get(mapKey);\n if (existingPromise)\n return existingPromise;\n const initPromise = this.initializeNewSectionController({\n args,\n key,\n mapKey,\n })\n .catch((err) => {\n this.handleSectionControllerInitError(err, args);\n throw err;\n })\n .finally(() => {\n this.sectionControllerInitPromises.delete(mapKey);\n });\n this.sectionControllerInitPromises.set(mapKey, initPromise);\n return initPromise;\n }\n async resolveExistingSectionController(args) {\n const existingController = this.sectionControllers.get(args.mapKey);\n if (!existingController)\n return undefined;\n this.sectionControllerKeys.set(args.mapKey, args.key);\n if (args.updateExisting !== false) {\n // Existing controllers keep their in-memory session state across\n // input refresh; updateInput should rebuild composition/runtime view\n // without resetting responses.\n await existingController.updateInput?.(args.input);\n }\n // PIE-512 Phase D: a `getOrCreateSectionController` call that\n // resolves to a previously-created controller still represents a\n // cohort transition from the toolkit's perspective (same-cohort\n // re-entry is a no-op inside `setActiveCohort`). Active\n // subscriptions migrate here so a host that subscribed once on\n // `toolkit-ready` keeps receiving events after navigating back\n // to a section it visited earlier.\n this.setActiveCohortIfLatestRequest(args.mapKey);\n return existingController;\n }\n createSectionControllerContext(args) {\n return {\n key: args.key,\n coordinator: this,\n input: args.input,\n };\n }\n async initializeNewSectionController(args) {\n const context = this.createSectionControllerContext({\n key: args.key,\n input: args.args.input,\n });\n const persistence = await this.resolveSectionPersistence(context);\n const defaults = {\n createDefaultController: args.args.createDefaultController,\n };\n const controller = (await this.hooks.createSectionController?.(context, defaults)) ??\n (await defaults.createDefaultController());\n await controller.configureSessionPersistence?.({\n strategy: persistence,\n context,\n });\n await controller.initialize?.(args.args.input);\n await controller.hydrate?.();\n await this.finalizeSectionControllerReady({\n mapKey: args.mapKey,\n key: args.key,\n context,\n controller,\n });\n return controller;\n }\n async finalizeSectionControllerReady(args) {\n this.sectionControllers.set(args.mapKey, args.controller);\n this.sectionControllerKeys.set(args.mapKey, args.key);\n // PIE-512 Phase D: a freshly-resolved controller becomes the\n // active cohort. Active subscriptions migrate to it before the\n // `ready` lifecycle event and `onSectionControllerReady` hook\n // fire so any synchronous post-ready work observes a coherent\n // active-cohort view.\n this.setActiveCohortIfLatestRequest(args.mapKey);\n this.emitSectionControllerLifecycle({\n type: \"ready\",\n key: args.key,\n controller: args.controller,\n });\n await this.hooks.onSectionControllerReady?.(args.context, args.controller);\n await this.emitTelemetry(\"pie-toolkit-section-controller-ready\", {\n assessmentId: args.key.assessmentId,\n sectionId: args.key.sectionId,\n attemptId: args.key.attemptId,\n });\n }\n handleSectionControllerInitError(err, args) {\n this.handleError(err, {\n phase: \"section-controller-init\",\n details: {\n sectionId: args.sectionId,\n attemptId: args.attemptId,\n },\n });\n }\n async disposeSectionController(args) {\n const key = {\n assessmentId: this.assessmentId,\n sectionId: args.sectionId,\n attemptId: args.attemptId,\n };\n const mapKey = this.getSectionControllerMapKey(key);\n const controller = this.sectionControllers.get(mapKey);\n if (!controller)\n return;\n // PIE-512 Phase D: if the disposing cohort is the active one,\n // detach all listener-controller bindings before the controller\n // itself disposes. The subscription registry stays intact so a\n // later `getOrCreateSectionController(...)` re-binds the same\n // listeners to the new controller.\n this.clearActiveCohortIfMatches(mapKey);\n const context = this.createSectionControllerContext({\n key,\n input: undefined,\n });\n try {\n await this.runSectionControllerDisposePipeline({\n key,\n context,\n controller,\n persistBeforeDispose: args.persistBeforeDispose,\n });\n }\n catch (err) {\n this.handleError(err, {\n phase: \"section-controller-dispose\",\n details: {\n sectionId: args.sectionId,\n attemptId: args.attemptId,\n },\n });\n }\n finally {\n await this.finalizeSectionControllerDispose({\n mapKey,\n key,\n context,\n clearPersistence: args.clearPersistence,\n });\n }\n }\n async runSectionControllerDisposePipeline(args) {\n if (args.persistBeforeDispose !== false) {\n await args.controller.persist?.();\n }\n await args.controller.dispose?.();\n await this.hooks.onSectionControllerDispose?.(args.context, args.controller);\n await this.emitTelemetry(\"pie-toolkit-section-controller-disposed\", {\n assessmentId: args.key.assessmentId,\n sectionId: args.key.sectionId,\n attemptId: args.key.attemptId,\n });\n }\n async finalizeSectionControllerDispose(args) {\n this.sectionControllers.delete(args.mapKey);\n this.sectionControllerKeys.delete(args.mapKey);\n this.emitSectionControllerLifecycle({\n type: \"disposed\",\n key: args.key,\n });\n if (args.clearPersistence) {\n const strategy = this.sectionPersistenceStrategies.get(args.mapKey);\n await strategy?.clearSession?.(args.context);\n }\n this.sectionPersistenceStrategies.delete(args.mapKey);\n }\n /**\n * Initialize TTS service with provider\n */\n async ensureTTSReady(config) {\n await this.waitForPendingTTSReconfigure();\n if (this.ttsInitialized)\n return;\n if (this.ttsInitPromise)\n return this.ttsInitPromise;\n this.ttsInitPromise = this._initializeTTS(config).finally(() => {\n this.ttsInitPromise = undefined;\n });\n return this.ttsInitPromise;\n }\n async waitForPendingTTSReconfigure() {\n let pending = this.ttsReconfigurePromise;\n while (pending) {\n await pending;\n pending = this.ttsReconfigurePromise;\n }\n }\n async _initializeTTS(config) {\n if (this.ttsInitialized)\n return;\n const resolvedToolConfig = this.resolveTTSToolConfig(config);\n const runtimeSettings = resolveTTSRuntimeSettings(resolvedToolConfig);\n const resolvedBackend = resolveTTSBackend(runtimeSettings);\n const runtimeTTSConfig = buildRuntimeTTSConfig(runtimeSettings);\n await this.hooks.onBeforeTTSInit?.({\n phase: \"tts-init\",\n details: {\n backend: resolvedBackend,\n },\n });\n await this.emitTelemetry(\"pie-toolkit-tts-init-start\", {\n backend: resolvedBackend,\n });\n await this.emitTelemetry(\"pie-tool-init-start\", {\n toolId: \"textToSpeech\",\n operation: \"tts-init\",\n backend: resolvedBackend,\n });\n // Try to use TTS provider from registry if available\n if (this.toolProviderRegistry.has(\"tts\")) {\n try {\n const ttsProvider = await this.ensureProviderReady(\"tts\");\n const providerInstance = await ttsProvider.createInstance();\n await this.initializeTTSService(providerInstance, runtimeTTSConfig);\n await this.emitTelemetry(\"pie-toolkit-tts-init-success\", {\n provider: \"registry\",\n });\n await this.emitTelemetry(\"pie-tool-init-success\", {\n toolId: \"textToSpeech\",\n operation: \"tts-init\",\n backend: resolvedBackend,\n provider: \"registry\",\n });\n console.log(\"[ToolkitCoordinator] TTS initialized via ToolProviderRegistry\");\n return;\n }\n catch (error) {\n const normalized = error instanceof Error ? error : new Error(String(error));\n await this.emitTelemetry(\"pie-tool-init-error\", {\n toolId: \"textToSpeech\",\n providerId: \"tts\",\n operation: \"tts-init\",\n backend: resolvedBackend,\n errorType: \"TTSRegistryInitError\",\n message: normalized.message,\n recovered: true,\n });\n await this.emitTelemetry(\"pie-tool-init-fallback\", {\n toolId: \"textToSpeech\",\n providerId: \"tts\",\n operation: \"tts-init\",\n backend: resolvedBackend,\n fromProvider: \"registry\",\n toProvider: \"browser\",\n reason: normalized.message,\n });\n console.warn(\"[ToolkitCoordinator] Failed to initialize TTS via registry, falling back to browser provider:\", normalized);\n }\n }\n // Fallback to browser provider\n const provider = new BrowserTTSProvider();\n try {\n await this.initializeTTSService(provider, runtimeTTSConfig);\n await this.emitTelemetry(\"pie-toolkit-tts-init-success\", {\n provider: \"browser-fallback\",\n });\n await this.emitTelemetry(\"pie-tool-init-success\", {\n toolId: \"textToSpeech\",\n operation: \"tts-init\",\n backend: resolvedBackend,\n provider: \"browser-fallback\",\n });\n }\n catch (error) {\n const normalized = error instanceof Error ? error : new Error(String(error));\n this.handleError(normalized, { phase: \"tts-init\" });\n await this.emitTelemetry(\"pie-toolkit-tts-init-error\", {\n message: normalized.message,\n });\n await this.emitTelemetry(\"pie-tool-init-error\", {\n toolId: \"textToSpeech\",\n operation: \"tts-init\",\n backend: resolvedBackend,\n errorType: \"TTSInitError\",\n message: normalized.message,\n });\n throw normalized;\n }\n }\n resolveTTSToolConfig(config) {\n return config || this.getTTSConfigFromProviders() || {};\n }\n async initializeTTSService(provider, config) {\n const nextProviderOptions = {\n ...((config.providerOptions || {}) || {}),\n __pieTelemetry: async (eventName, payload) => {\n await this.emitTelemetry(eventName, {\n toolId: \"textToSpeech\",\n ...(payload || {}),\n });\n },\n };\n const nextConfig = {\n ...config,\n providerOptions: nextProviderOptions,\n };\n await this.ttsService.initialize(provider, nextConfig);\n await this.ensureBrowserVoicesReady(provider);\n this.ttsService.setCatalogResolver(this.catalogResolver);\n this.ttsInitialized = true;\n await this.hooks.onTTSReady?.();\n }\n async ensureBrowserVoicesReady(provider, timeoutMs = 1200) {\n if (provider.providerId !== \"browser\")\n return;\n if (typeof window === \"undefined\")\n return;\n if (!(\"speechSynthesis\" in window))\n return;\n const synth = window.speechSynthesis;\n const voices = synth.getVoices();\n if (voices.length > 0)\n return;\n await new Promise((resolve) => {\n let settled = false;\n const canUseEventTarget = typeof synth.addEventListener === \"function\" &&\n typeof synth.removeEventListener === \"function\";\n const canUseHandler = !canUseEventTarget && \"onvoiceschanged\" in synth;\n const previousHandler = canUseHandler ? synth.onvoiceschanged : null;\n let assignedHandler = false;\n const finish = () => {\n if (settled)\n return;\n settled = true;\n window.clearTimeout(timeoutId);\n if (canUseEventTarget) {\n synth.removeEventListener(\"voiceschanged\", onVoicesChanged);\n }\n else if (assignedHandler &&\n synth.onvoiceschanged === onVoicesChanged) {\n synth.onvoiceschanged = previousHandler;\n }\n resolve();\n };\n const onVoicesChanged = (event) => {\n if (!canUseEventTarget &&\n typeof previousHandler === \"function\" &&\n event) {\n previousHandler.call(synth, event);\n }\n finish();\n };\n const timeoutId = window.setTimeout(finish, timeoutMs);\n if (canUseEventTarget) {\n synth.addEventListener(\"voiceschanged\", onVoicesChanged, {\n once: true,\n });\n }\n else if (canUseHandler) {\n synth.onvoiceschanged = onVoicesChanged;\n assignedHandler = true;\n }\n });\n const voicesAfterWait = synth.getVoices();\n await this.emitTelemetry(\"pie-toolkit-tts-browser-voices-ready\", {\n voiceCount: voicesAfterWait.length,\n timedOut: voicesAfterWait.length === 0,\n });\n }\n /**\n * Get all services as a bundle for section player convenience.\n * Section player can extract and pass services to child components.\n */\n getServiceBundle() {\n return {\n ttsService: this.ttsService,\n toolCoordinator: this.toolCoordinator,\n highlightCoordinator: this.highlightCoordinator,\n elementToolStateStore: this.elementToolStateStore,\n catalogResolver: this.catalogResolver,\n toolProviderRegistry: this.toolProviderRegistry,\n };\n }\n /**\n * Get a tool provider from the registry\n *\n * @param providerId Provider identifier\n * @returns Tool provider instance\n */\n async getToolProvider(providerId) {\n return this.ensureProviderReady(providerId);\n }\n async waitUntilReady() {\n if (this.isReady())\n return;\n if (this.coordinatorReadyPromise)\n return this.coordinatorReadyPromise;\n this.coordinatorReadyPromise = (async () => {\n await this.ensureStateLoaded();\n const ttsConfig = this.getTTSConfigFromProviders();\n if (ttsConfig?.enabled !== false) {\n await this.ensureTTSReady(ttsConfig);\n }\n if (!this.coordinatorReadyNotified) {\n this.coordinatorReadyNotified = true;\n await this.hooks.onCoordinatorReady?.(this);\n await this.emitTelemetry(\"pie-toolkit-coordinator-ready\", {\n assessmentId: this.assessmentId,\n });\n }\n })().finally(() => {\n this.coordinatorReadyPromise = undefined;\n });\n return this.coordinatorReadyPromise;\n }\n isReady() {\n return this.getInitStatus().coordinator;\n }\n getInitStatus() {\n const providers = {};\n for (const providerId of this.toolProviderRegistry.getProviderIds()) {\n providers[providerId] =\n this.toolProviderRegistry.isInitialized(providerId);\n }\n const ttsConfig = this.getTTSConfigFromProviders();\n return {\n tts: this.ttsInitialized,\n stateLoaded: this.stateLoaded || !this.hooks.loadToolState,\n coordinator: (this.stateLoaded || !this.hooks.loadToolState) &&\n (this.ttsInitialized || ttsConfig?.enabled === false),\n providers,\n };\n }\n getTTSConfigFromProviders() {\n const providers = this.config.tools?.providers || {};\n return providers.textToSpeech;\n }\n assertCanonicalToolId(toolId) {\n if (typeof toolId !== \"string\" || toolId.trim().length === 0) {\n throw new Error(\"Tool id must be a non-empty string.\");\n }\n if (toolId === \"tts\") {\n throw new Error(`Tool id \"tts\" is no longer supported. Use \"textToSpeech\".`);\n }\n // An empty registry means the host supplied none, not that every id is\n // wrong. There is nothing to check an id against, and throwing turns a\n // host's every tool-config call into an exception — including the calls\n // this coordinator's own default-provider block provokes, which is how a\n // host that passes no registry ended up unable to read its own config.\n // `normalizeAndValidateToolsConfig` already reports the missing registry\n // once, as `tools.registryUnavailable`; a second report per call is noise.\n if (this.toolRegistry.getAllToolIds().length === 0)\n return;\n if (!this.toolRegistry.get(toolId)) {\n throw new Error(`Unknown tool id \"${toolId}\".`);\n }\n }\n installToolContextResolvers(resolvers) {\n if (!resolvers)\n return;\n for (const [toolId, resolver] of Object.entries(resolvers)) {\n if (resolver == null)\n continue;\n this.assertCanonicalToolId(toolId);\n if (typeof resolver !== \"function\") {\n throw new Error(`Invalid tool context resolver for \"${toolId}\": expected a function.`);\n }\n this.toolContextResolvers.set(toolId, resolver);\n }\n }\n setToolContextResolvers(resolvers) {\n this.toolContextResolvers.clear();\n this.installToolContextResolvers(resolvers ?? undefined);\n this.notifyToolContextResolverChange();\n }\n notifyToolContextResolverChange() {\n for (const listener of this.toolContextResolverChangeListeners) {\n try {\n listener();\n }\n catch (error) {\n console.warn(\"[ToolkitCoordinator] Tool context resolver listener threw:\", error);\n }\n }\n }\n /**\n * Check if a tool is enabled.\n * Tools are enabled by default unless explicitly disabled.\n *\n * @param toolId Tool identifier (e.g., 'textToSpeech', 'answerEliminator')\n * @returns True if tool is enabled\n */\n isToolEnabled(toolId) {\n this.assertCanonicalToolId(toolId);\n const toolConfig = this.config.tools?.providers?.[toolId];\n // Enabled by default unless explicitly set to false\n return toolConfig?.enabled !== false;\n }\n /**\n * Get tool configuration.\n *\n * @param toolId Tool identifier\n * @returns Tool configuration or null if not configured\n */\n getToolConfig(toolId) {\n this.assertCanonicalToolId(toolId);\n return (this.config.tools?.providers?.[toolId] || null);\n }\n updateToolConfig(toolId, updates) {\n // Update config\n this.assertCanonicalToolId(toolId);\n const current = this.getToolConfig(toolId) || {};\n if (!this.config.tools) {\n this.config.tools = normalizeAndValidateToolsConfig(undefined, {\n strictness: this.config.toolConfigStrictness ?? \"error\",\n source: \"ToolkitCoordinator.updateToolConfig\",\n toolRegistry: this.toolRegistry,\n }).config;\n }\n if (!this.config.tools.providers) {\n this.config.tools.providers = {};\n }\n const nextProviders = {\n ...(this.config.tools.providers || {}),\n [toolId]: mergeToolConfigUpdate(toolId, current, updates),\n };\n const validated = normalizeAndValidateToolsConfig({\n ...this.config.tools,\n providers: nextProviders,\n }, {\n strictness: this.config.toolConfigStrictness ?? \"error\",\n source: \"ToolkitCoordinator.updateToolConfig\",\n toolRegistry: this.toolRegistry,\n });\n this.config.tools = validated.config;\n // M8 PR 2 — keep the policy engine's tools input in lockstep\n // with the validated coordinator config. The engine emits an\n // `inputs` change event so subscribers (e.g. PR 3 toolbars) can\n // re-decide without us managing a parallel pub/sub.\n this.policyEngine.updateInputs({\n tools: this.config.tools,\n });\n void this.emitTelemetry(\"pie-toolkit-tool-config-updated\", { toolId });\n // Apply configuration changes to services\n this._applyToolConfigChange(toolId, updates);\n }\n /**\n * Update the enabled tool list for one placement level.\n *\n * This is the generic placement companion to {@link updateToolConfig}:\n * it validates the next canonical tools config, keeps the policy\n * engine in lockstep, and emits the same policy-change event used by\n * live toolbars/debug panels.\n */\n updateToolPlacement(level, toolIds) {\n this.updateToolsPlacement({ [level]: [...toolIds] });\n }\n /**\n * Patch one or more placement levels in the canonical tools config.\n */\n updateToolsPlacement(partial) {\n if (!this.config.tools) {\n this.config.tools = normalizeAndValidateToolsConfig(undefined, {\n strictness: this.config.toolConfigStrictness ?? \"error\",\n source: \"ToolkitCoordinator.updateToolsPlacement\",\n toolRegistry: this.toolRegistry,\n }).config;\n }\n const currentPlacement = this.config.tools?.placement ?? {\n section: [],\n item: [],\n passage: [],\n };\n const nextPlacement = {\n section: [...(partial.section ?? currentPlacement.section ?? [])],\n item: [...(partial.item ?? currentPlacement.item ?? [])],\n passage: [...(partial.passage ?? currentPlacement.passage ?? [])],\n };\n const validated = normalizeAndValidateToolsConfig({\n ...this.config.tools,\n placement: nextPlacement,\n }, {\n strictness: this.config.toolConfigStrictness ?? \"error\",\n source: \"ToolkitCoordinator.updateToolsPlacement\",\n toolRegistry: this.toolRegistry,\n });\n validated.config.placement = nextPlacement;\n this.config.tools = validated.config;\n this.policyEngine.updateInputs({\n tools: this.config.tools,\n });\n }\n /**\n * Resolve the visible tool set for a given placement level + scope.\n *\n * Thin shim over the owned tool-policy engine.\n */\n decideToolPolicy(request) {\n return this.policyEngine.decide(request);\n }\n /**\n * Resolve eligibility for one PNP/AfA feature id, independent of toolbar\n * placement.\n *\n * Thin shim over the owned tool-policy engine; see\n * {@link ToolPolicyEngine.decideFeature} for the contract, including why\n * `pnpEnforcement` is not consulted.\n *\n * Reports once per coordinator when it is asked about a feature with no\n * assessment bound. A host in that state gets a correct denial for every\n * capability it asks about, which is indistinguishable from a student who was\n * properly declined — so without this, forgetting {@link updateAssessment}\n * presents as an accommodation that silently never appears.\n */\n decideFeaturePolicy(featureId) {\n const decision = this.policyEngine.decideFeature(featureId);\n if (!decision.assessmentBound && !this.reportedUnboundFeaturePolicy) {\n this.reportedUnboundFeaturePolicy = true;\n console.warn(`[ToolkitCoordinator] Feature policy was asked about \"${featureId}\" with no assessment bound, so every capability will be declined for want of a profile to read. Call updateAssessment(...) with the assessment (its personalNeedsProfile, settings.districtPolicy and settings.testAdministration are what policy reads) before relying on any accommodation. Reported once per coordinator.`);\n }\n return decision;\n }\n /**\n * Subscribe to policy-engine change events. Fires whenever the\n * coordinator's bound inputs change (`updateToolConfig`,\n * `updateToolPlacement`, `updateAssessment`, `updateCurrentItemRef`,\n * `setPnpEnforcement`) or a custom `PolicySource` is registered /\n * removed via {@link registerPolicySource}.\n *\n * The listener receives a `ToolPolicyChangeEvent` with the event\n * `reason` and a frozen snapshot of the engine inputs. Listeners\n * that want the new visible tool set should call\n * {@link decideToolPolicy} with their level / scope.\n *\n * Note: the engine itself can also emit `reason: \"disposed\"`, but\n * the coordinator does not dispose its engine on teardown today,\n * so subscribers attached via this method will not observe that\n * reason. Detach via the returned unsubscribe function instead of\n * relying on a `disposed` event.\n */\n onPolicyChange(listener) {\n return this.policyEngine.onPolicyChange(listener);\n }\n /**\n * Subscribe to accessibility-catalog registrations and removals.\n *\n * Delegates to the owned resolver, the same way {@link onPolicyChange}\n * delegates to the owned policy engine, so a consumer holding only the\n * coordinator can react to both of the mutable inputs a catalog-backed\n * capability depends on without reaching for the services directly.\n *\n * @returns Unsubscribe function\n */\n onCatalogsChange(listener) {\n return this.catalogResolver.onCatalogsChange(listener);\n }\n /**\n * Bind (or clear) the active assessment for PNP/profile policy decisions.\n *\n * Under auto-mode (no host override via {@link setPnpEnforcement}),\n * the coordinator promotes the engine to `pnpEnforcement: \"on\"`\n * iff the assessment carries any profile precedence material\n * (`personalNeedsProfile`, `settings.districtPolicy`,\n * `settings.testAdministration`) or the currently-bound item ref\n * carries item-level profile policy inputs. A bare assessment record (just\n * `id` / `name`, no PNP, no settings) keeps `\"off\"`.\n *\n * The host override set via {@link setPnpEnforcement} is sticky\n * across assessment swaps; calling with `null` clears the binding\n * and re-runs the auto-mode helper.\n */\n updateAssessment(assessment) {\n this.boundAssessment = assessment;\n this.policyEngine.updateInputs({\n assessment,\n pnpEnforcement: this.resolveEffectivePnpEnforcement(),\n });\n }\n /**\n * Bind (or clear) the current item reference for policy decisions.\n *\n * Used by item-level profile gates (item `requiredTools` /\n * `restrictedTools` / `toolParameters`). Item-level profile material\n * also feeds {@link resolveEffectivePnpEnforcement} — navigating\n * to an item with profile settings can flip auto-mode to `\"on\"` even\n * when the parent assessment carries no profile block of its own.\n */\n updateCurrentItemRef(itemRef) {\n this.boundCurrentItemRef = itemRef;\n this.policyEngine.updateInputs({\n currentItemRef: itemRef,\n pnpEnforcement: this.resolveEffectivePnpEnforcement(),\n });\n }\n /**\n * Override the auto-mode PNP/profile enforcement decision.\n */\n setPnpEnforcement(mode) {\n this.pnpEnforcementOverride = mode;\n this.policyEngine.updateInputs({\n pnpEnforcement: this.resolveEffectivePnpEnforcement(),\n });\n }\n /**\n * Get the policy engine inputs currently driving decisions. Useful\n * for debugging / instrumentation; do not mutate.\n */\n getPolicyInputs() {\n return this.policyEngine.getInputs();\n }\n /**\n * Register a custom {@link PolicySource} with the owned policy\n * engine. The source participates in every subsequent\n * {@link decideToolPolicy} call until disposed (the returned\n * function detaches and emits a `policy-source-removed` event).\n *\n * Delegates verbatim to\n * {@link ToolPolicyEngine.registerPolicySource} — see that\n * method for the full contract (event ordering, idempotency of\n * the returned dispose function, and how registered sources\n * compose with the built-in PNP policy source).\n */\n registerPolicySource(source) {\n return this.policyEngine.registerPolicySource(source);\n }\n /**\n * Register a host-owned resolver for one tool's render context.\n *\n * Resolvers are evaluated only for tools that already survived the\n * framework policy pipeline. They can hide the tool for the current\n * scope or attach render params consumed by the packaged registration;\n * they cannot re-enable tools blocked by placement, provider config,\n * host policy, or PNP/profile rules.\n */\n registerToolContextResolver(toolId, resolver) {\n this.assertCanonicalToolId(toolId);\n if (typeof resolver !== \"function\") {\n throw new Error(`Invalid tool context resolver for \"${toolId}\": expected a function.`);\n }\n this.toolContextResolvers.set(toolId, resolver);\n this.notifyToolContextResolverChange();\n return () => {\n if (this.toolContextResolvers.get(toolId) !== resolver)\n return;\n this.toolContextResolvers.delete(toolId);\n this.notifyToolContextResolverChange();\n };\n }\n hasToolContextResolver(toolId) {\n this.assertCanonicalToolId(toolId);\n return this.toolContextResolvers.has(toolId);\n }\n resolveToolContext(context) {\n this.assertCanonicalToolId(context.toolId);\n const resolver = this.toolContextResolvers.get(context.toolId);\n if (!resolver)\n return null;\n let result;\n try {\n result = resolver(context);\n }\n catch (error) {\n console.error(`[ToolkitCoordinator] Tool context resolver for \"${context.toolId}\" threw:`, error);\n return {\n toolId: context.toolId,\n visible: false,\n params: {},\n reason: \"Tool context resolver threw.\",\n };\n }\n if (!result) {\n return {\n toolId: context.toolId,\n visible: true,\n params: {},\n };\n }\n const params = result.params &&\n typeof result.params === \"object\" &&\n !Array.isArray(result.params)\n ? result.params\n : {};\n return {\n toolId: context.toolId,\n visible: result.visible !== false,\n params,\n reason: typeof result.reason === \"string\" ? result.reason : undefined,\n };\n }\n onToolContextResolverChange(listener) {\n this.toolContextResolverChangeListeners.add(listener);\n return () => {\n this.toolContextResolverChangeListeners.delete(listener);\n };\n }\n /**\n * Claim requests for one placement level. Called by a toolbar on mount.\n */\n registerToolRequestTarget(target) {\n return this.toolRequests.registerTarget(target);\n }\n /**\n * Ask the toolbar hosting a tool to open it, handing it `params`.\n *\n * Returns whether a toolbar claimed the request. A surface offering this as an\n * affordance should gate on {@link canRequestTool} first rather than acting on\n * the return value, so the learner never sees a control that does nothing.\n */\n requestTool(request) {\n this.assertCanonicalToolId(request.toolId);\n return this.toolRequests.request(request);\n }\n /**\n * Answers `false` for a tool this deployment does not carry rather than\n * throwing as {@link requestTool} does. A composer asks this while rendering a\n * surface, and a host that swapped the registry for one without the tool would\n * otherwise lose the whole surface to an exception over an absent action.\n */\n canRequestTool(toolId, level) {\n try {\n this.assertCanonicalToolId(toolId);\n }\n catch {\n return false;\n }\n return this.toolRequests.canRequest(toolId, level);\n }\n onToolRequestTargetsChange(listener) {\n return this.toolRequests.onTargetsChange(listener);\n }\n /**\n * Compute the effective PNP/profile enforcement mode given the explicit\n * host override and the auto-mode helper.\n *\n * Auto-mode (no override) defers to\n * {@link resolveDefaultPnpEnforcement}, which returns `\"on\"`\n * exactly when the bound assessment or current item ref carries\n * profile precedence material (PNP, district policy, test\n * administration, item-level required/restricted/parameters), and\n * `\"off\"` otherwise. Profile gates engage the moment profile material\n * is present.\n */\n resolveEffectivePnpEnforcement() {\n if (this.pnpEnforcementOverride !== null) {\n return this.pnpEnforcementOverride;\n }\n return resolveDefaultPnpEnforcement({\n assessment: this.boundAssessment,\n currentItemRef: this.boundCurrentItemRef,\n });\n }\n resolveConfiguredPnpEnforcement() {\n const tools = this.config.tools;\n return tools?.pnpEnforcement ?? null;\n }\n /**\n * Apply tool configuration changes to underlying services.\n * Called after updateToolConfig().\n */\n _applyToolConfigChange(toolId, _updates) {\n // Apply configuration changes based on tool\n switch (toolId) {\n case \"textToSpeech\": {\n const reconfigurePromise = this._reconfigureTTSProvider();\n this.ttsReconfigurePromise = reconfigurePromise;\n void reconfigurePromise.finally(() => {\n if (this.ttsReconfigurePromise === reconfigurePromise) {\n this.ttsReconfigurePromise = undefined;\n }\n });\n void reconfigurePromise.then(async () => {\n const ttsConfig = this.getTTSConfigFromProviders();\n if (!this.lazyInit && ttsConfig?.enabled !== false) {\n await this.ensureTTSReady(ttsConfig);\n }\n });\n break;\n }\n case \"answerEliminator\":\n // Future: Could notify answer eliminator tools of strategy change\n break;\n // Add cases for other tools as needed\n }\n }\n async _reconfigureTTSProvider() {\n this.ttsInitialized = false;\n this.ttsInitPromise = undefined;\n try {\n this.ttsService.stop();\n }\n catch {\n // noop: stop best effort\n }\n if (this.toolProviderRegistry.has(\"tts\")) {\n await this.toolProviderRegistry.unregister(\"tts\");\n }\n const ttsRegistration = this.getProviderDescriptorTools().find((tool) => tool.toolId === \"textToSpeech\");\n if (!ttsRegistration)\n return;\n await this.registerProviderFromTool(ttsRegistration);\n }\n}\n","export const DEFAULT_TOOL_SCOPE_LEVELS = [\n \"assessment\",\n \"section\",\n \"item\",\n \"passage\",\n \"rubric\",\n];\nconst registeredToolScopeLevels = new Set(DEFAULT_TOOL_SCOPE_LEVELS);\nexport function getRegisteredToolScopeLevels() {\n return Array.from(registeredToolScopeLevels.values());\n}\nexport function registerToolScopeLevel(scopeLevel) {\n const normalized = scopeLevel.trim();\n if (!normalized) {\n throw new Error(\"Tool scope level must be a non-empty string\");\n }\n registeredToolScopeLevels.add(normalized);\n}\nexport function isRegisteredToolScopeLevel(scopeLevel) {\n return registeredToolScopeLevels.has(scopeLevel);\n}\nexport function createScopedToolId(baseToolId, scopeLevel, scopeId) {\n const normalizedBase = baseToolId.trim();\n const normalizedScopeId = scopeId.trim();\n if (!normalizedBase || !normalizedScopeId) {\n throw new Error(\"Tool instance ids require non-empty tool and scope ids\");\n }\n if (!isRegisteredToolScopeLevel(scopeLevel)) {\n throw new Error(`Unknown tool scope level '${scopeLevel}'. Register custom levels with registerToolScopeLevel().`);\n }\n return `${normalizedBase}:${scopeLevel}:${normalizedScopeId}`;\n}\nexport function parseScopedToolId(id) {\n const parts = id.split(\":\");\n if (parts.length !== 3)\n return null;\n const [baseToolId, scopeLevelRaw, scopeId] = parts;\n if (!baseToolId || !scopeId)\n return null;\n if (!isRegisteredToolScopeLevel(scopeLevelRaw)) {\n return null;\n }\n return {\n baseToolId,\n scopeLevel: scopeLevelRaw,\n scopeId,\n };\n}\nexport function toOverlayToolId(id) {\n const parsed = parseScopedToolId(id);\n if (!parsed)\n return id;\n return createScopedToolId(parsed.baseToolId, parsed.scopeLevel, parsed.scopeId);\n}\n"],"x_google_ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],"mappings":";;;AACA,IAAa,IAAkC,EAAc,OAAO,IAAI,sCAAsC,CAAC;AAC5D,EAAc,OAAO,IAAI,0CAA0C,CAAC;AACvH,IAAa,IAAgC,EAAc,OAAO,IAAI,oCAAoC,CAAC,GAC9F,IAAsC,EAAc,OAAO,IAAI,0CAA0C,CAAC;;;ACFvH,SAAS,EAAiC,GAAM,GAAS,GAAS;CAC9D,IAAI,IAAW,IACT,IAAW,IAAI,EAAgB,GAAM;EACvC;EACA,WAAW;EACX,UAAU,MAAU;GAEhB,AADA,IAAW,IACX,EAAQ,CAAK;EACjB;CACJ,CAAC;CACD,EAAS,QAAQ;CACjB,IAAM,KAAqB,MAAU;EAC7B,E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