@pie-qti/player-elements 0.1.24 → 0.1.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ItemToolBar-d36g3aw4-B6TGPyKt.js +3079 -0
- package/dist/ItemToolBar-d36g3aw4-B6TGPyKt.js.map +1 -0
- package/dist/{define-D7_K0JFy.js → define-D80uAEx4.js} +1902 -4395
- package/dist/define-D80uAEx4.js.map +1 -0
- package/dist/dist-BSG0NOza.js +229 -0
- package/dist/dist-BSG0NOza.js.map +1 -0
- package/dist/{dist-ffJZTPTU.js → dist-C8BDh5vZ.js} +987 -707
- package/dist/dist-C8BDh5vZ.js.map +1 -0
- package/dist/dist-CQel8-vi.js +2507 -0
- package/dist/dist-CQel8-vi.js.map +1 -0
- package/dist/{dist-BaQdJU08.js → dist-L-bDDBry.js} +116 -103
- package/dist/dist-L-bDDBry.js.map +1 -0
- package/dist/{element-DSCNeDLu.js → element-C5rTAwch.js} +2 -2
- package/dist/{element-DSCNeDLu.js.map → element-C5rTAwch.js.map} +1 -1
- package/dist/{element-class-DQy2cIPM-CldZrSRR.js → element-class-B_qAd8ET-DGj15cBY.js} +5124 -4448
- package/dist/element-class-B_qAd8ET-DGj15cBY.js.map +1 -0
- package/dist/elements.js +3 -3
- package/dist/index.js +2 -2
- package/dist/item-toolbar-element-BgqPFwsS.js +1990 -0
- package/dist/item-toolbar-element-BgqPFwsS.js.map +1 -0
- package/dist/{language-tags-DVlRltrl.js → language-tags-BwFWXo71.js} +3 -3
- package/dist/{language-tags-DVlRltrl.js.map → language-tags-BwFWXo71.js.map} +1 -1
- package/dist/{nl-NL-BeQBX6yq.js → nl-NL-BRA_1Wcl.js} +5 -3
- package/dist/nl-NL-BRA_1Wcl.js.map +1 -0
- package/dist/pie-DwmznDHb.js +363 -0
- package/dist/pie-DwmznDHb.js.map +1 -0
- package/dist/pie-assessment-toolkit-Cruxm385.js +5 -0
- package/dist/pie-assessment-toolkit-Cruxm385.js.map +1 -0
- package/dist/pie-assessment-toolkit-DJfg6laX.js +5 -0
- package/dist/pie-assessment-toolkit-DJfg6laX.js.map +1 -0
- package/dist/{pie-assessment-toolkit-element-CpiB3twr.js → pie-assessment-toolkit-element-CT5UuvVY.js} +1364 -1203
- package/dist/pie-assessment-toolkit-element-CT5UuvVY.js.map +1 -0
- package/dist/pie-tool-calculator-Crfk-IZe.js +378 -0
- package/dist/pie-tool-calculator-Crfk-IZe.js.map +1 -0
- package/dist/{provider-Y5PhmTAu.js → provider-gBXlGb0d.js} +3 -3
- package/dist/{provider-Y5PhmTAu.js.map → provider-gBXlGb0d.js.map} +1 -1
- package/dist/register-players.js +1 -1
- package/dist/register.js +10246 -9664
- package/dist/register.js.map +1 -1
- package/dist/{resolveItems-D8DJkv-4.js → resolveItems-CNMvD8LP.js} +2 -2
- package/dist/{resolveItems-D8DJkv-4.js.map → resolveItems-CNMvD8LP.js.map} +1 -1
- package/dist/{root-DSkIM1v3.js → root-dCY6j_Hh.js} +3 -3
- package/dist/{root-DSkIM1v3.js.map → root-dCY6j_Hh.js.map} +1 -1
- package/dist/tag-names-DZGvnAgd.js +2495 -0
- package/dist/tag-names-DZGvnAgd.js.map +1 -0
- package/dist/{tool-tts-inline-B71NTBbb.js → tool-tts-inline-k3hLJUfp.js} +1315 -1303
- package/dist/tool-tts-inline-k3hLJUfp.js.map +1 -0
- package/package.json +8 -8
- package/dist/define-D7_K0JFy.js.map +0 -1
- package/dist/dist-BRTWr852.js +0 -5809
- package/dist/dist-BRTWr852.js.map +0 -1
- package/dist/dist-BaQdJU08.js.map +0 -1
- package/dist/dist-DwvskOs6.js +0 -220
- package/dist/dist-DwvskOs6.js.map +0 -1
- package/dist/dist-ffJZTPTU.js.map +0 -1
- package/dist/element-class-DQy2cIPM-CldZrSRR.js.map +0 -1
- package/dist/item-toolbar-element-BW9Y_n5x.js +0 -1990
- package/dist/item-toolbar-element-BW9Y_n5x.js.map +0 -1
- package/dist/nl-NL-BeQBX6yq.js.map +0 -1
- package/dist/pie-assessment-toolkit-element-CpiB3twr.js.map +0 -1
- package/dist/pie-tool-calculator-BiWMTJe7.js +0 -2992
- package/dist/pie-tool-calculator-BiWMTJe7.js.map +0 -1
- package/dist/tool-tts-inline-B71NTBbb.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dist-BaQdJU08.js","names":[],"sources":["../../../node_modules/.bun/@pie-players+tts-server-core@0.3.68/node_modules/@pie-players/tts-server-core/dist/speech-marks.js","../../../node_modules/.bun/@pie-players+tts-server-core@0.3.68/node_modules/@pie-players/tts-server-core/dist/speed-rate.js","../../../node_modules/.bun/@pie-players+tts-client-server@0.3.68/node_modules/@pie-players/tts-client-server/dist/ServerTTSProvider.js"],"sourcesContent":["/**\n * Speech marks utilities\n * @module @pie-players/tts-server-core\n */\nconst asFiniteNumber = (value) => {\n const next = Number(value);\n return Number.isFinite(next) ? next : null;\n};\nconst sortWordMarks = (marks) => [...marks].sort((left, right) => {\n if (left.time !== right.time)\n return left.time - right.time;\n if (left.start !== right.start)\n return left.start - right.start;\n return left.end - right.end;\n});\n/**\n * Parse a provider's JSONL word-mark wire format: one `{time, type, start,\n * end, value}` object per line. Rows missing a numeric `time` are dropped —\n * that anchor is load-bearing for the timing correction below — but rows\n * missing `start`/`end` still surface (estimated from the previous mark's\n * end) rather than being lost outright.\n */\nconst parseWordMarksJsonl = (raw) => {\n const marks = [];\n let fallbackIndex = 0;\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed)\n continue;\n try {\n const parsed = JSON.parse(trimmed);\n if (parsed.type && parsed.type !== \"word\")\n continue;\n const time = asFiniteNumber(parsed.time);\n if (time === null)\n continue;\n const value = typeof parsed.value === \"string\" ? parsed.value : \"\";\n const start = asFiniteNumber(parsed.start) ?? fallbackIndex;\n const end = asFiniteNumber(parsed.end) ?? start + Math.max(1, value.length);\n fallbackIndex = Math.max(end + 1, fallbackIndex);\n marks.push({ time, type: \"word\", start, end, value });\n }\n catch {\n // Ignore malformed JSONL rows while preserving valid marks.\n }\n }\n return sortWordMarks(marks);\n};\nconst normalizeMarkTimeUnits = (marks) => {\n if (marks.length < 2)\n return marks;\n const times = marks.map((mark) => mark.time).filter((time) => time >= 0);\n const maxTime = times.length ? Math.max(...times) : 0;\n const deltas = [];\n for (let index = 1; index < times.length; index += 1) {\n const delta = times[index] - times[index - 1];\n if (delta > 0 && Number.isFinite(delta))\n deltas.push(delta);\n }\n const medianDelta = deltas.length > 0\n ? [...deltas].sort((a, b) => a - b)[Math.floor(deltas.length / 2)]\n : 0;\n const shapeSuggestsSeconds = (maxTime > 0 && maxTime < 100 && marks.length > 3) ||\n (medianDelta > 0 && medianDelta < 10);\n if (!shapeSuggestsSeconds)\n return marks;\n return marks.map((mark) => ({ ...mark, time: mark.time * 1000 }));\n};\nconst estimateOffsetShift = (marks, requestText) => {\n if (!marks.length || !requestText.length)\n return 0;\n const textLower = requestText.toLowerCase();\n const candidates = [];\n let cursor = 0;\n for (const mark of marks) {\n const token = mark.value.trim().toLowerCase();\n if (!token)\n continue;\n const found = textLower.indexOf(token, cursor);\n if (found < 0)\n continue;\n const delta = mark.start - found;\n if (delta >= 0)\n candidates.push(delta);\n cursor = found + token.length;\n if (candidates.length >= 8)\n break;\n }\n if (candidates.length > 0) {\n const ordered = [...candidates].sort((a, b) => a - b);\n return ordered[Math.floor(ordered.length / 2)];\n }\n return Math.max(0, Math.floor(marks[0].start));\n};\nconst rebaseOffsetsToRequestText = (marks, requestText) => {\n if (!marks.length || !requestText.length)\n return marks;\n const textLength = requestText.length;\n const maxEnd = Math.max(...marks.map((mark) => mark.end));\n if (maxEnd <= textLength + 2)\n return marks;\n const shift = estimateOffsetShift(marks, requestText);\n if (shift <= 0)\n return marks;\n return marks.map((mark) => ({\n ...mark,\n start: mark.start - shift,\n end: mark.end - shift,\n }));\n};\nconst clampMarkRanges = (marks, requestText) => {\n if (!requestText.length)\n return marks;\n const textLength = requestText.length;\n return sortWordMarks(marks.map((mark) => {\n const start = Math.max(0, Math.min(textLength, Math.floor(mark.start)));\n const end = Math.max(start + 1, Math.min(textLength, Math.floor(mark.end)));\n return { ...mark, start, end };\n }));\n};\n/**\n * Parse and correct a provider's JSONL word-mark response against the text\n * that was actually requested: normalizes second-vs-millisecond time units,\n * rebases offsets that drifted from the request text (a provider quirk seen\n * in production), and clamps ranges to the request text's bounds.\n *\n * Shared by every provider/transport that speaks this wire shape so the\n * correction is applied once rather than reimplemented per caller.\n */\nexport function normalizeSpeechMarks(raw, requestText) {\n const parsed = parseWordMarksJsonl(raw);\n const withTimes = normalizeMarkTimeUnits(parsed);\n const rebased = rebaseOffsetsToRequestText(withTimes, requestText);\n return clampMarkRanges(rebased, requestText);\n}\n/**\n * Estimate speech marks for text when provider doesn't support them\n *\n * Uses average speaking rate to estimate word timing.\n * Not as accurate as provider-generated marks, but better than nothing.\n *\n * @param text - Text to generate marks for\n * @param avgWordsPerMinute - Average speaking rate (default 150)\n * @returns Estimated speech marks\n */\nexport function estimateSpeechMarks(text, avgWordsPerMinute = 150) {\n const words = text.split(/\\s+/).filter((w) => w.length > 0);\n const msPerWord = (60 * 1000) / avgWordsPerMinute;\n const marks = [];\n let charIndex = 0;\n for (let i = 0; i < words.length; i++) {\n const word = words[i];\n // Find word position in original text (preserves spacing)\n const wordStart = text.indexOf(word, charIndex);\n if (wordStart === -1) {\n // Word not found (shouldn't happen), skip\n charIndex += word.length + 1;\n continue;\n }\n marks.push({\n time: Math.round(i * msPerWord),\n type: \"word\",\n start: wordStart,\n end: wordStart + word.length,\n value: word,\n });\n charIndex = wordStart + word.length;\n }\n return marks;\n}\n/**\n * Adjust speech marks timing for different speaking rates\n *\n * @param marks - Original speech marks\n * @param rate - Speech rate multiplier (0.25 to 4.0)\n * @returns Adjusted speech marks\n */\nexport function adjustSpeechMarksForRate(marks, rate) {\n if (rate === 1.0) {\n return marks; // No adjustment needed\n }\n return marks.map((mark) => ({\n ...mark,\n time: Math.round(mark.time / rate),\n }));\n}\n/**\n * Validate speech marks\n * Ensures marks are properly ordered and have valid data\n *\n * @param marks - Speech marks to validate\n * @returns Validation errors (empty array if valid)\n */\nexport function validateSpeechMarks(marks) {\n const errors = [];\n if (!marks || marks.length === 0) {\n return errors; // Empty is valid\n }\n for (let i = 0; i < marks.length; i++) {\n const mark = marks[i];\n // Check required fields\n if (typeof mark.time !== \"number\" || mark.time < 0) {\n errors.push(`Mark ${i}: invalid time (${mark.time})`);\n }\n if (typeof mark.start !== \"number\" || mark.start < 0) {\n errors.push(`Mark ${i}: invalid start (${mark.start})`);\n }\n if (typeof mark.end !== \"number\" || mark.end <= mark.start) {\n errors.push(`Mark ${i}: invalid end (${mark.end}, start: ${mark.start})`);\n }\n if (!mark.value || typeof mark.value !== \"string\") {\n errors.push(`Mark ${i}: invalid value`);\n }\n // Check ordering (time should be monotonically increasing)\n if (i > 0 && mark.time < marks[i - 1].time) {\n errors.push(`Mark ${i}: time (${mark.time}) is less than previous mark (${marks[i - 1].time})`);\n }\n }\n return errors;\n}\n/**\n * Merge overlapping or adjacent speech marks\n * Useful when combining marks from multiple sources\n *\n * @param marks - Speech marks to merge\n * @returns Merged speech marks\n */\nexport function mergeSpeechMarks(marks) {\n if (marks.length <= 1) {\n return marks;\n }\n // Sort by start position\n const sorted = [...marks].sort((a, b) => a.start - b.start);\n const merged = [sorted[0]];\n for (let i = 1; i < sorted.length; i++) {\n const current = sorted[i];\n const previous = merged[merged.length - 1];\n // Check if marks overlap or are adjacent\n if (current.start <= previous.end) {\n // Merge with previous mark\n previous.end = Math.max(previous.end, current.end);\n previous.value = previous.value + \" \" + current.value;\n previous.time = Math.min(previous.time, current.time); // Use earlier time\n }\n else {\n // No overlap, add as new mark\n merged.push(current);\n }\n }\n return merged;\n}\n/**\n * Filter speech marks by type\n *\n * @param marks - Speech marks to filter\n * @param type - Type to filter by\n * @returns Filtered speech marks\n */\nexport function filterSpeechMarksByType(marks, type) {\n return marks.filter((mark) => mark.type === type);\n}\n/**\n * Get speech mark at specific time\n *\n * @param marks - Speech marks\n * @param time - Time in milliseconds\n * @returns Speech mark at time, or null if none found\n */\nexport function getSpeechMarkAtTime(marks, time) {\n // Binary search for efficiency\n let left = 0;\n let right = marks.length - 1;\n let closest = null;\n while (left <= right) {\n const mid = Math.floor((left + right) / 2);\n const mark = marks[mid];\n if (mark.time === time) {\n return mark;\n }\n // Track closest mark\n if (!closest ||\n Math.abs(mark.time - time) < Math.abs(closest.time - time)) {\n closest = mark;\n }\n if (mark.time < time) {\n left = mid + 1;\n }\n else {\n right = mid - 1;\n }\n }\n // Return closest mark if within reasonable threshold (500ms)\n if (closest && Math.abs(closest.time - time) <= 500) {\n return closest;\n }\n return null;\n}\n/**\n * Calculate statistics for speech marks\n *\n * @param marks - Speech marks\n * @returns Statistics about the marks\n */\nexport function getSpeechMarksStats(marks) {\n if (marks.length === 0) {\n return {\n count: 0,\n totalDuration: 0,\n avgWordDuration: 0,\n wordsPerMinute: 0,\n };\n }\n const wordMarks = filterSpeechMarksByType(marks, \"word\");\n const totalDuration = marks[marks.length - 1].time;\n const avgWordDuration = totalDuration / wordMarks.length;\n const wordsPerMinute = (wordMarks.length / totalDuration) * 60 * 1000;\n return {\n count: marks.length,\n wordCount: wordMarks.length,\n totalDuration,\n avgWordDuration,\n wordsPerMinute,\n };\n}\n","/**\n * Speed-rate bucketing utility\n * @module @pie-players/tts-server-core\n */\n/**\n * Bucket a numeric rate multiplier into the three-value vocabulary some\n * providers (SchoolCity, and backends modeled on it) accept instead of a\n * continuous rate. `0.95` / `1.5` is a deliberate tolerance band around the\n * `1.0` default rather than a strict `<1` / `>1` split, so small rate\n * perturbations near normal speed still read as `fallback` instead of\n * immediately flipping to `slow`/`fast`.\n */\nexport function resolveSpeedRateBucket(rate, fallback = \"medium\") {\n const value = Number(rate ?? 1);\n if (!Number.isFinite(value))\n return fallback;\n if (value <= 0.95)\n return \"slow\";\n if (value >= 1.5)\n return \"fast\";\n return fallback;\n}\n","/**\n * ServerTTSProvider - Client-side TTS provider that calls server API\n *\n * Provides high-quality TTS by calling a server-side API that uses\n * providers like AWS Polly, Google Cloud TTS, etc.\n * Returns audio with precise word-level timing (speech marks).\n */\nimport { normalizeSpeechMarks, resolveSpeedRateBucket, } from \"@pie-players/tts-server-core\";\n/**\n * Parse a TTS asset URL (speech marks or audio). Rejects anything that is\n * not an absolute http(s) URL; relative URLs are resolved against\n * `apiEndpoint` when it is itself absolute.\n */\nfunction parseAssetUrl(rawUrl, config) {\n if (typeof rawUrl !== \"string\" || rawUrl.length === 0) {\n return null;\n }\n try {\n const base = typeof config.apiEndpoint === \"string\" &&\n /^https?:\\/\\//i.test(config.apiEndpoint)\n ? config.apiEndpoint\n : undefined;\n const parsed = base ? new URL(rawUrl, base) : new URL(rawUrl);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\") {\n return null;\n }\n return parsed;\n }\n catch {\n return null;\n }\n}\n/**\n * Decide whether a parsed asset URL is allowed to receive the provider's\n * `Authorization` header. Defaults to the origin of `apiEndpoint` when\n * `assetOrigins` is not configured.\n */\nfunction isOriginTrustedForAuth(url, config) {\n const configured = Array.isArray(config.assetOrigins)\n ? config.assetOrigins\n .filter((value) => typeof value === \"string\" && value.length > 0)\n .map((value) => {\n try {\n return new URL(value).origin;\n }\n catch {\n return value;\n }\n })\n : [];\n if (configured.length === 0) {\n if (typeof config.apiEndpoint === \"string\" &&\n /^https?:\\/\\//i.test(config.apiEndpoint)) {\n try {\n return new URL(config.apiEndpoint).origin === url.origin;\n }\n catch {\n return false;\n }\n }\n // Relative apiEndpoint (e.g. \"/api/tts\") implies same-origin usage;\n // only same-origin assets should carry auth.\n return (typeof window !== \"undefined\" &&\n typeof window.location?.origin === \"string\" &&\n window.location.origin === url.origin);\n }\n return configured.includes(url.origin);\n}\n/**\n * Strip auth-carrying headers when the target origin is not trusted.\n */\nfunction scrubAuthHeaders(headers) {\n const cleaned = {};\n for (const [key, value] of Object.entries(headers)) {\n const lower = key.toLowerCase();\n if (lower === \"authorization\" ||\n lower === \"proxy-authorization\" ||\n lower === \"cookie\" ||\n lower.startsWith(\"x-auth-\")) {\n continue;\n }\n cleaned[key] = value;\n }\n return cleaned;\n}\nconst getTelemetryReporter = (config) => {\n const providerOptions = config.providerOptions && typeof config.providerOptions === \"object\"\n ? config.providerOptions\n : {};\n const reporter = providerOptions.__pieTelemetry;\n return typeof reporter === \"function\"\n ? reporter\n : undefined;\n};\nconst MAX_TEXT_LENGTH_BY_MODE = {\n pie: 3000,\n custom: 3000,\n};\n/**\n * Server providers whose SSML support is reliable enough to receive generated\n * SSML (AWS Polly, Google Cloud TTS). This is an allow-list rather than a\n * deny-list: the `custom` transport (and unknown providers) report\n * `supportsSSML: false` so the toolkit falls back to plain text. Some custom\n * backends advertise SSML support server-side but mis-voice or ignore parts of\n * it, so we stay conservative at the client boundary.\n */\nconst SSML_CAPABLE_PIE_PROVIDERS = new Set([\"polly\", \"google\"]);\nconst resolveSupportsSSML = (config) => {\n if (!config)\n return false;\n if (resolveTransportMode(config) !== \"pie\")\n return false;\n // The pie transport defaults to Polly when no provider is named.\n const provider = (config.provider || \"polly\").toLowerCase();\n return SSML_CAPABLE_PIE_PROVIDERS.has(provider);\n};\nconst trimTrailingSlash = (value) => value.replace(/\\/+$/, \"\");\nconst resolveVoicesValidationUrl = (config) => {\n const base = trimTrailingSlash(config.apiEndpoint);\n const provider = (config.provider || \"\").toLowerCase();\n if (provider === \"polly\" || provider === \"google\") {\n return `${base}/${provider}/voices`;\n }\n return `${base}/voices`;\n};\nconst resolveTransportMode = (config) => {\n if (config.transportMode === \"custom\")\n return \"custom\";\n if (config.transportMode === \"pie\")\n return \"pie\";\n return config.provider === \"custom\" ? \"custom\" : \"pie\";\n};\nconst resolveEndpointMode = (config, mode) => {\n if (config.endpointMode)\n return config.endpointMode;\n return mode === \"custom\" ? \"rootPost\" : \"synthesizePath\";\n};\nconst resolveValidationMode = (config, mode) => {\n if (config.endpointValidationMode)\n return config.endpointValidationMode;\n return mode === \"custom\" ? \"none\" : \"voices\";\n};\nconst resolveSpeedRate = (config) => {\n const providerOptions = (config.providerOptions || {});\n if (typeof providerOptions.speedRate === \"string\") {\n return providerOptions.speedRate;\n }\n return resolveSpeedRateBucket(config.rate);\n};\nconst parseInlineSpeechMarks = (input) => {\n if (!Array.isArray(input))\n return [];\n const marks = [];\n let fallbackIndex = 0;\n for (const entry of input) {\n if (!entry || typeof entry !== \"object\")\n continue;\n const type = typeof entry.type === \"string\" ? entry.type : \"word\";\n const time = typeof entry.time === \"number\" && Number.isFinite(entry.time)\n ? entry.time\n : 0;\n const value = typeof entry.value === \"string\" ? entry.value : \"\";\n const explicitStart = typeof entry.start === \"number\" && Number.isFinite(entry.start)\n ? entry.start\n : null;\n const explicitEnd = typeof entry.end === \"number\" && Number.isFinite(entry.end)\n ? entry.end\n : null;\n const start = explicitStart ?? fallbackIndex;\n const end = explicitEnd ?? start + Math.max(1, value.length || 1);\n fallbackIndex = Math.max(fallbackIndex, end + 1);\n marks.push({ time, type, start, end, value });\n }\n return marks.sort((left, right) => {\n if (left.time !== right.time)\n return left.time - right.time;\n if (left.start !== right.start)\n return left.start - right.start;\n return left.end - right.end;\n });\n};\nconst pieAdapter = {\n id: \"pie\",\n resolveSynthesisUrl: (config) => {\n const endpointMode = resolveEndpointMode(config, \"pie\");\n const base = trimTrailingSlash(config.apiEndpoint);\n return endpointMode === \"rootPost\" ? base : `${base}/synthesize`;\n },\n buildRequestBody: (text, config) => {\n const providerOptions = (config.providerOptions || {});\n const engine = typeof config.engine === \"string\"\n ? config.engine\n : typeof providerOptions.engine === \"string\"\n ? providerOptions.engine\n : undefined;\n const sampleRate = typeof providerOptions.sampleRate === \"number\" &&\n Number.isFinite(providerOptions.sampleRate)\n ? providerOptions.sampleRate\n : undefined;\n const format = providerOptions.format === \"mp3\" ||\n providerOptions.format === \"ogg\" ||\n providerOptions.format === \"pcm\"\n ? providerOptions.format\n : undefined;\n const speechMarkTypes = Array.isArray(providerOptions.speechMarkTypes)\n ? providerOptions.speechMarkTypes.filter((entry) => entry === \"word\" || entry === \"sentence\" || entry === \"ssml\")\n : undefined;\n return {\n text,\n provider: config.provider || \"polly\",\n voice: config.voice,\n language: config.language,\n rate: config.rate,\n engine,\n sampleRate,\n format,\n speechMarkTypes,\n includeSpeechMarks: true,\n };\n },\n parseResponse: async (response, _config, _headers, _signal, _text) => {\n const data = await response.json();\n return {\n audio: {\n kind: \"base64\",\n data: data.audio,\n contentType: data.contentType,\n },\n speechMarks: Array.isArray(data.speechMarks) ? data.speechMarks : [],\n };\n },\n};\nconst customAdapter = {\n id: \"custom\",\n resolveSynthesisUrl: (config) => {\n const endpointMode = resolveEndpointMode(config, \"custom\");\n const base = trimTrailingSlash(config.apiEndpoint);\n return endpointMode === \"synthesizePath\" ? `${base}/synthesize` : base;\n },\n buildRequestBody: (text, config) => {\n const providerOptions = (config.providerOptions || {});\n const langId = typeof providerOptions.lang_id === \"string\"\n ? providerOptions.lang_id\n : config.language || \"en-US\";\n const cache = typeof providerOptions.cache === \"boolean\" ? providerOptions.cache : true;\n return {\n text,\n speedRate: resolveSpeedRate(config),\n lang_id: langId,\n cache,\n };\n },\n parseResponse: async (response, config, headers, signal, text) => {\n const data = await response.json();\n const marksHeaders = {};\n if (config.includeAuthOnAssetFetch) {\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === \"authorization\") {\n marksHeaders[key] = value;\n }\n }\n }\n let speechMarks = [];\n const inlineSpeechMarks = parseInlineSpeechMarks(data.speechMarks);\n if (inlineSpeechMarks.length > 0) {\n speechMarks = inlineSpeechMarks;\n }\n else if (typeof data.word === \"string\" && data.word.length > 0) {\n const marksUrl = parseAssetUrl(data.word, config);\n if (marksUrl !== null) {\n const effectiveMarksHeaders = isOriginTrustedForAuth(marksUrl, config)\n ? marksHeaders\n : scrubAuthHeaders(marksHeaders);\n const marksResponse = await fetch(marksUrl.toString(), {\n headers: effectiveMarksHeaders,\n signal,\n // Fail loud on redirects; the origin allow-list decision\n // is made pre-redirect and a silent hop could leak auth\n // to an unlisted origin.\n redirect: \"error\",\n });\n if (marksResponse.ok) {\n const marksRaw = await marksResponse.text();\n speechMarks = normalizeSpeechMarks(marksRaw, text);\n }\n }\n }\n const parsedAudioUrl = parseAssetUrl(data.audioContent, config);\n if (parsedAudioUrl === null) {\n throw new Error(\"TTS server returned an invalid audio URL\");\n }\n return {\n audio: {\n kind: \"url\",\n url: parsedAudioUrl.toString(),\n },\n speechMarks,\n };\n },\n};\nconst ADAPTERS = {\n pie: pieAdapter,\n custom: customAdapter,\n};\n/**\n * Provider implementation that handles audio playback\n */\nclass ServerTTSProviderImpl {\n config;\n adapter;\n currentAudio = null;\n pausedState = false;\n wordTimings = [];\n highlightInterval = null;\n intentionallyStopped = false;\n activeSynthesisController = null;\n synthesisRunId = 0;\n telemetryReporter;\n onPlaybackStart;\n onWordBoundary;\n constructor(config, adapter) {\n this.config = config;\n this.adapter = adapter;\n this.telemetryReporter = getTelemetryReporter(config);\n }\n async emitTelemetry(eventName, payload) {\n try {\n await this.telemetryReporter?.(eventName, payload);\n }\n catch (error) {\n console.warn(\"[ServerTTSProvider] telemetry callback failed:\", error);\n }\n }\n async speak(text) {\n // Stop any current playback\n this.stop();\n // Reset intentionally stopped flag for new playback\n this.intentionallyStopped = false;\n const runId = ++this.synthesisRunId;\n const synthesisController = new AbortController();\n this.activeSynthesisController = synthesisController;\n // Call server API to synthesize speech\n const { audioUrl, wordTimings } = await this.synthesizeSpeech(text, synthesisController.signal, runId);\n if (runId !== this.synthesisRunId) {\n URL.revokeObjectURL(audioUrl);\n return;\n }\n this.wordTimings = wordTimings;\n return new Promise((resolve, reject) => {\n // Create audio element\n const audio = new Audio(audioUrl);\n this.currentAudio = audio;\n // Apply volume from config\n if (this.config.volume !== undefined) {\n audio.volume = Math.max(0, Math.min(1, this.config.volume));\n }\n // Setup event handlers\n audio.onplay = () => {\n if (runId !== this.synthesisRunId || this.currentAudio !== audio) {\n return;\n }\n this.pausedState = false;\n try {\n this.onPlaybackStart?.();\n }\n catch (error) {\n console.warn(\"[ServerTTSProvider] playback-start callback failed:\", error);\n }\n // Start word highlighting\n if (this.onWordBoundary && this.wordTimings.length > 0) {\n this.startWordHighlighting();\n }\n };\n audio.onended = () => {\n this.stopWordHighlighting();\n URL.revokeObjectURL(audioUrl);\n this.currentAudio = null;\n this.wordTimings = [];\n resolve();\n };\n audio.onerror = (event) => {\n this.stopWordHighlighting();\n URL.revokeObjectURL(audioUrl);\n this.currentAudio = null;\n this.wordTimings = [];\n void event;\n // Only reject if this wasn't an intentional stop\n if (!this.intentionallyStopped) {\n reject(new Error(\"Failed to play audio from server\"));\n }\n else {\n // Intentional stop, resolve normally\n resolve();\n }\n };\n audio.onpause = () => {\n this.stopWordHighlighting();\n this.pausedState = true;\n };\n // Start playback\n audio.play().catch(reject);\n });\n }\n /**\n * Call server API to synthesize speech\n */\n async synthesizeSpeech(text, signal, runId) {\n const synthStartedAt = Date.now();\n await this.emitTelemetry(\"pie-tool-backend-call-start\", {\n toolId: \"tts\",\n backend: this.config.provider || \"server\",\n operation: \"synthesize-speech\",\n });\n const headers = {\n \"Content-Type\": \"application/json\",\n ...this.config.headers,\n };\n // Add authentication if provided\n if (this.config.authToken) {\n headers[\"Authorization\"] = `Bearer ${this.config.authToken}`;\n }\n const synthUrl = this.adapter.resolveSynthesisUrl(this.config);\n const requestBody = this.adapter.buildRequestBody(text, this.config);\n const response = await (async () => {\n try {\n return await fetch(synthUrl, {\n method: \"POST\",\n headers,\n body: JSON.stringify(requestBody),\n signal,\n });\n }\n catch (error) {\n await this.emitTelemetry(\"pie-tool-backend-call-error\", {\n toolId: \"tts\",\n backend: this.config.provider || \"server\",\n operation: \"synthesize-speech\",\n duration: Date.now() - synthStartedAt,\n errorType: \"TTSBackendNetworkError\",\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n })();\n if (!response.ok) {\n const rawBody = await response.text().catch(() => \"\");\n let errorData = {};\n if (rawBody) {\n try {\n errorData = JSON.parse(rawBody);\n }\n catch (parseError) {\n console.warn(\"[ServerTTSProvider] non-OK response body was not JSON\", {\n status: response.status,\n url: synthUrl,\n rawBodyPreview: rawBody.slice(0, 500),\n parseError: parseError instanceof Error\n ? parseError.message\n : String(parseError),\n });\n }\n }\n const errorMessage = (typeof errorData.message === \"string\" && errorData.message) ||\n (typeof errorData.error?.message === \"string\"\n ? errorData.error.message\n : undefined) ||\n `Server returned ${response.status}`;\n await this.emitTelemetry(\"pie-tool-backend-call-error\", {\n toolId: \"tts\",\n backend: this.config.provider || \"server\",\n operation: \"synthesize-speech\",\n duration: Date.now() - synthStartedAt,\n statusCode: response.status,\n errorType: \"TTSBackendRequestError\",\n message: errorMessage,\n });\n const textPreview = text.replace(/\\s+/g, \" \").trim().slice(0, 120);\n console.error(\"[ServerTTSProvider] synthesize request failed\", {\n status: response.status,\n url: synthUrl,\n backend: this.config.provider || \"server\",\n message: errorMessage,\n responseBody: errorData,\n textLength: text.length,\n textPreview: textPreview.length < text.length ? `${textPreview}…` : textPreview,\n });\n throw new Error(errorMessage);\n }\n const normalized = await this.adapter.parseResponse(response, this.config, headers, signal, text);\n if (runId !== this.synthesisRunId || signal.aborted) {\n throw new Error(\"Synthesis superseded by a newer request\");\n }\n let audioBlob;\n if (normalized.audio.kind === \"base64\") {\n audioBlob = this.base64ToBlob(normalized.audio.data, normalized.audio.contentType);\n }\n else {\n const audioAssetUrl = normalized.audio.url;\n const assetFetchStartedAt = Date.now();\n await this.emitTelemetry(\"pie-tool-backend-call-start\", {\n toolId: \"tts\",\n backend: this.config.provider || \"server\",\n operation: \"fetch-synthesized-audio-asset\",\n });\n const assetHeaders = {};\n if (this.config.includeAuthOnAssetFetch) {\n if (this.config.authToken) {\n assetHeaders[\"Authorization\"] = `Bearer ${this.config.authToken}`;\n }\n }\n const parsedAssetUrl = parseAssetUrl(audioAssetUrl, this.config);\n if (parsedAssetUrl === null) {\n await this.emitTelemetry(\"pie-tool-backend-call-error\", {\n toolId: \"tts\",\n backend: this.config.provider || \"server\",\n operation: \"fetch-synthesized-audio-asset\",\n duration: Date.now() - assetFetchStartedAt,\n errorType: \"TTSAssetInvalidUrl\",\n message: \"TTS asset URL rejected (non-http(s) or malformed)\",\n });\n throw new Error(\"TTS asset URL rejected (non-http(s) or malformed)\");\n }\n const effectiveAssetHeaders = isOriginTrustedForAuth(parsedAssetUrl, this.config)\n ? assetHeaders\n : scrubAuthHeaders(assetHeaders);\n const audioResponse = await (async () => {\n try {\n return await fetch(parsedAssetUrl.toString(), {\n headers: effectiveAssetHeaders,\n signal,\n redirect: \"error\",\n });\n }\n catch (error) {\n await this.emitTelemetry(\"pie-tool-backend-call-error\", {\n toolId: \"tts\",\n backend: this.config.provider || \"server\",\n operation: \"fetch-synthesized-audio-asset\",\n duration: Date.now() - assetFetchStartedAt,\n errorType: \"TTSAssetNetworkError\",\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n })();\n if (!audioResponse.ok) {\n await this.emitTelemetry(\"pie-tool-backend-call-error\", {\n toolId: \"tts\",\n backend: this.config.provider || \"server\",\n operation: \"fetch-synthesized-audio-asset\",\n duration: Date.now() - assetFetchStartedAt,\n statusCode: audioResponse.status,\n errorType: \"TTSAssetFetchError\",\n message: `Failed to download synthesized audio (${audioResponse.status})`,\n });\n throw new Error(`Failed to download synthesized audio (${audioResponse.status})`);\n }\n audioBlob = await audioResponse.blob();\n await this.emitTelemetry(\"pie-tool-backend-call-success\", {\n toolId: \"tts\",\n backend: this.config.provider || \"server\",\n operation: \"fetch-synthesized-audio-asset\",\n duration: Date.now() - assetFetchStartedAt,\n });\n }\n const audioUrl = URL.createObjectURL(audioBlob);\n // Convert speech marks to word timings\n const wordTimings = this.parseSpeechMarks(normalized.speechMarks);\n await this.emitTelemetry(\"pie-tool-backend-call-success\", {\n toolId: \"tts\",\n backend: this.config.provider || \"server\",\n operation: \"synthesize-speech\",\n duration: Date.now() - synthStartedAt,\n });\n return { audioUrl, wordTimings };\n }\n /**\n * Convert base64 to Blob\n */\n base64ToBlob(base64, contentType) {\n const byteCharacters = atob(base64);\n const byteNumbers = new Array(byteCharacters.length);\n for (let i = 0; i < byteCharacters.length; i++) {\n byteNumbers[i] = byteCharacters.charCodeAt(i);\n }\n const byteArray = new Uint8Array(byteNumbers);\n return new Blob([byteArray], { type: contentType });\n }\n /**\n * Parse speech marks into word timings\n */\n parseSpeechMarks(marks) {\n return marks\n .filter((mark) => mark.type === \"word\")\n .map((mark, index) => ({\n time: mark.time,\n wordIndex: index,\n charIndex: mark.start,\n length: mark.end - mark.start,\n word: mark.value,\n }));\n }\n /**\n * Start word highlighting synchronized with audio playback\n */\n startWordHighlighting() {\n this.stopWordHighlighting();\n if (!this.currentAudio ||\n !this.onWordBoundary ||\n this.wordTimings.length === 0) {\n console.log(\"[ServerTTSProvider] Cannot start highlighting:\", {\n hasAudio: !!this.currentAudio,\n hasCallback: !!this.onWordBoundary,\n wordTimingsCount: this.wordTimings.length,\n });\n return;\n }\n console.log(\"[ServerTTSProvider] Starting word highlighting with\", this.wordTimings.length, \"word timings\");\n console.log(\"[ServerTTSProvider] Playback rate:\", this.currentAudio.playbackRate);\n console.log(\"[ServerTTSProvider] First 3 timings:\", this.wordTimings.slice(0, 3));\n let lastWordIndex = -1;\n // Poll every 50ms to check current playback time\n this.highlightInterval = window.setInterval(() => {\n if (!this.currentAudio) {\n this.stopWordHighlighting();\n return;\n }\n // Get current playback time in milliseconds\n const currentTime = this.currentAudio.currentTime * 1000;\n // Find words that should be highlighted at current time\n for (let i = 0; i < this.wordTimings.length; i++) {\n const timing = this.wordTimings[i];\n if (currentTime >= timing.time && i > lastWordIndex) {\n // Fire word boundary callback\n if (this.onWordBoundary) {\n console.log(\"[ServerTTSProvider] Highlighting word at charIndex:\", timing.charIndex, \"length:\", timing.length, \"time:\", timing.time, \"currentTime:\", currentTime);\n this.onWordBoundary(timing.word, timing.charIndex, timing.length);\n }\n lastWordIndex = i;\n break;\n }\n }\n }, 50); // 50ms polling = 20 times per second\n }\n /**\n * Stop word highlighting\n */\n stopWordHighlighting() {\n if (this.highlightInterval !== null) {\n clearInterval(this.highlightInterval);\n this.highlightInterval = null;\n }\n }\n pause() {\n if (this.currentAudio && !this.pausedState) {\n this.currentAudio.pause();\n this.stopWordHighlighting();\n this.pausedState = true;\n }\n }\n resume() {\n if (this.currentAudio && this.pausedState) {\n this.currentAudio.play();\n this.pausedState = false;\n // Resume word highlighting\n if (this.onWordBoundary && this.wordTimings.length > 0) {\n this.startWordHighlighting();\n }\n }\n }\n stop() {\n this.synthesisRunId += 1;\n if (this.activeSynthesisController) {\n this.activeSynthesisController.abort();\n this.activeSynthesisController = null;\n }\n this.stopWordHighlighting();\n if (this.currentAudio) {\n // Mark as intentionally stopped to prevent error handler from rejecting\n this.intentionallyStopped = true;\n this.currentAudio.pause();\n if (this.currentAudio.src) {\n URL.revokeObjectURL(this.currentAudio.src);\n }\n this.currentAudio.src = \"\";\n this.currentAudio = null;\n }\n this.pausedState = false;\n this.wordTimings = [];\n }\n isPlaying() {\n return this.currentAudio !== null && !this.pausedState;\n }\n isPaused() {\n return this.pausedState;\n }\n /**\n * Update settings dynamically (rate, pitch, voice)\n * Note: Server-side synthesis bakes rate, pitch, and voice into the audio and\n * speech marks. Settings updates are stored for the next synthesis; active\n * speed changes are handled by TTSService replaying from the current segment.\n */\n updateSettings(settings) {\n // Update config\n if (settings.rate !== undefined) {\n this.config.rate = settings.rate;\n this.config.providerOptions = {\n ...(this.config.providerOptions || {}),\n speedRate: resolveSpeedRateBucket(settings.rate),\n };\n }\n if (settings.pitch !== undefined) {\n // Server-side pitch is baked into audio, so this only affects next speak()\n this.config.pitch = settings.pitch;\n }\n if (settings.voice !== undefined) {\n // Voice change requires resynthesis, affects next speak()\n this.config.voice = settings.voice;\n }\n }\n}\n/**\n * Server TTS Provider\n *\n * Client-side provider that calls a server API for TTS synthesis.\n * The server handles provider selection (Polly, Google, etc.) and credential management.\n */\nexport class ServerTTSProvider {\n providerId = \"server-tts\";\n providerName = \"Server TTS\";\n version = \"1.0.0\";\n config = null;\n adapter = null;\n telemetryReporter;\n async emitTelemetry(eventName, payload) {\n try {\n await this.telemetryReporter?.(eventName, payload);\n }\n catch (error) {\n console.warn(\"[ServerTTSProvider] telemetry callback failed:\", error);\n }\n }\n /**\n * Initialize the server TTS provider.\n *\n * This is designed to be fast by default (no API calls).\n * Set validateEndpoint: true in config to test API availability during initialization.\n *\n * @performance Default: <10ms, With validation: 100-500ms\n */\n async initialize(config) {\n const serverConfig = config;\n if (!serverConfig.apiEndpoint) {\n throw new Error(\"apiEndpoint is required for ServerTTSProvider\");\n }\n this.config = serverConfig;\n this.telemetryReporter = getTelemetryReporter(serverConfig);\n const transportMode = resolveTransportMode(serverConfig);\n this.adapter = ADAPTERS[transportMode];\n // Only test API availability if explicitly requested (slower but safer)\n if (serverConfig.validateEndpoint) {\n const validationStartedAt = Date.now();\n await this.emitTelemetry(\"pie-tool-backend-call-start\", {\n toolId: \"tts\",\n backend: serverConfig.provider || \"server\",\n operation: \"validate-endpoint\",\n });\n const available = await this.testAPIAvailability();\n if (!available) {\n await this.emitTelemetry(\"pie-tool-backend-call-error\", {\n toolId: \"tts\",\n backend: serverConfig.provider || \"server\",\n operation: \"validate-endpoint\",\n duration: Date.now() - validationStartedAt,\n errorType: \"TTSEndpointValidationError\",\n message: `Server TTS API not available at ${serverConfig.apiEndpoint}`,\n });\n throw new Error(`Server TTS API not available at ${serverConfig.apiEndpoint}`);\n }\n await this.emitTelemetry(\"pie-tool-backend-call-success\", {\n toolId: \"tts\",\n backend: serverConfig.provider || \"server\",\n operation: \"validate-endpoint\",\n duration: Date.now() - validationStartedAt,\n });\n }\n return new ServerTTSProviderImpl(serverConfig, this.adapter);\n }\n /**\n * Test if API endpoint is available (with timeout).\n *\n * @performance 100-500ms depending on network\n */\n async testAPIAvailability() {\n if (!this.config || !this.adapter)\n return false;\n try {\n const headers = { ...this.config.headers };\n if (this.config.authToken) {\n headers[\"Authorization\"] = `Bearer ${this.config.authToken}`;\n }\n // Create abort controller for timeout\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), 5000); // 5 second timeout\n const mode = resolveValidationMode(this.config, this.adapter.id);\n if (mode === \"none\") {\n clearTimeout(timeoutId);\n return true;\n }\n const validationUrl = mode === \"voices\"\n ? resolveVoicesValidationUrl(this.config)\n : this.adapter.resolveSynthesisUrl(this.config);\n const method = mode === \"voices\" ? \"GET\" : \"OPTIONS\";\n try {\n const response = await fetch(validationUrl, {\n method,\n headers,\n signal: controller.signal,\n });\n clearTimeout(timeoutId);\n // Some endpoints may not accept OPTIONS; treat 405 as reachable.\n return response.ok || response.status === 405;\n }\n catch {\n clearTimeout(timeoutId);\n return false;\n }\n }\n catch {\n return false;\n }\n }\n supportsFeature(feature) {\n switch (feature) {\n case \"pause\":\n case \"resume\":\n case \"wordBoundary\":\n case \"voiceSelection\":\n case \"rateControl\":\n return true;\n case \"pitchControl\":\n // Depends on server provider, assume no for safety\n return false;\n default:\n return false;\n }\n }\n getCapabilities() {\n const mode = this.config ? resolveTransportMode(this.config) : \"pie\";\n return {\n supportsPause: true,\n supportsResume: true,\n supportsWordBoundary: true, // ✅ Via speech marks from server\n supportsVoiceSelection: true,\n supportsRateControl: true,\n supportsPitchControl: false, // Depends on server provider\n supportsSSML: resolveSupportsSSML(this.config),\n maxTextLength: MAX_TEXT_LENGTH_BY_MODE[mode],\n };\n }\n destroy() {\n this.config = null;\n this.adapter = null;\n this.telemetryReporter = undefined;\n }\n}\n"],"x_google_ignoreList":[0,1,2],"mappings":";AAIA,IAAM,KAAkB,MAAU;CAC9B,IAAM,IAAO,OAAO,CAAK;CACzB,OAAO,OAAO,SAAS,CAAI,IAAI,IAAO;AAC1C,GACM,KAAiB,MAAU,CAAC,GAAG,CAAK,CAAC,CAAC,MAAM,GAAM,MAChD,EAAK,SAAS,EAAM,OAEpB,EAAK,UAAU,EAAM,QAElB,EAAK,MAAM,EAAM,MADb,EAAK,QAAQ,EA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G,KAAK,OAAO,QAAQ;GACzC,AAAI,KAAK,OAAO,cACZ,EAAQ,gBAAmB,UAAU,KAAK,OAAO;GAGrD,IAAM,IAAa,IAAI,gBAAgB,GACjC,IAAY,iBAAiB,EAAW,MAAM,GAAG,GAAI,GACrD,IAAO,EAAsB,KAAK,QAAQ,KAAK,QAAQ,EAAE;GAC/D,IAAI,MAAS,QAET,OADA,aAAa,CAAS,GACf;GAEX,IAAM,IAAgB,MAAS,WACzB,EAA2B,KAAK,MAAM,IACtC,KAAK,QAAQ,oBAAoB,KAAK,MAAM,GAC5C,IAAS,MAAS,WAAW,QAAQ;GAC3C,IAAI;IACA,IAAM,IAAW,MAAM,MAAM,GAAe;KACxC;KACA;KACA,QAAQ,EAAW;IACvB,CAAC;IAGD,OAFA,aAAa,CAAS,GAEf,EAAS,MAAM,EAAS,WAAW;GAC9C,QACM;IAEF,OADA,aAAa,CAAS,GACf;GACX;EACJ,QACM;GACF,OAAO;EACX;CACJ;CACA,gBAAgB,GAAS;EACrB,QAAQ,GAAR;GACI,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK;GACL,KAAK,eACD,OAAO;GACX,KAAK,gBAED,OAAO;GACX,SACI,OAAO;EACf;CACJ;CACA,kBAAkB;EACd,IAAM,IAAO,KAAK,SAAS,EAAqB,KAAK,MAAM,IAAI;EAC/D,OAAO;GACH,eAAe;GACf,gBAAgB;GAChB,sBAAsB;GACtB,wBAAwB;GACxB,qBAAqB;GACrB,sBAAsB;GACtB,cAAc,EAAoB,KAAK,MAAM;GAC7C,eAAe,EAAwB;EAC3C;CACJ;CACA,UAAU;EAGN,AAFA,KAAK,SAAS,MACd,KAAK,UAAU,MACf,KAAK,oBAAoB,KAAA;CAC7B;AACJ"}
|
package/dist/dist-DwvskOs6.js
DELETED
|
@@ -1,220 +0,0 @@
|
|
|
1
|
-
//#region ../../node_modules/.bun/@pie-players+pie-calculator-desmos@0.3.68/node_modules/@pie-players/pie-calculator-desmos/dist/desmos-provider.js
|
|
2
|
-
var e = class {
|
|
3
|
-
providerId = "desmos";
|
|
4
|
-
providerName = "Desmos";
|
|
5
|
-
supportedTypes = [
|
|
6
|
-
"basic",
|
|
7
|
-
"scientific",
|
|
8
|
-
"graphing"
|
|
9
|
-
];
|
|
10
|
-
version = "1.12";
|
|
11
|
-
initialized = !1;
|
|
12
|
-
apiKey;
|
|
13
|
-
proxyEndpoint;
|
|
14
|
-
isDevelopment = !1;
|
|
15
|
-
onTelemetry;
|
|
16
|
-
async emitTelemetry(e, t) {
|
|
17
|
-
try {
|
|
18
|
-
await this.onTelemetry?.(e, t);
|
|
19
|
-
} catch (e) {
|
|
20
|
-
console.warn("[DesmosProvider] telemetry callback failed:", e);
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
getApiKey() {
|
|
24
|
-
return this.apiKey;
|
|
25
|
-
}
|
|
26
|
-
async loadDesmosScript() {
|
|
27
|
-
return new Promise((e, t) => {
|
|
28
|
-
let n = document.createElement("script");
|
|
29
|
-
n.src = this.apiKey ? `https://www.desmos.com/api/v1.12/calculator.js?apiKey=${this.apiKey}` : "https://www.desmos.com/api/v1.12/calculator.js", n.async = !0, n.onload = () => {
|
|
30
|
-
window.Desmos ? (console.log("[DesmosProvider] Desmos API loaded successfully"), e()) : t(/* @__PURE__ */ Error("Desmos API loaded but window.Desmos is undefined"));
|
|
31
|
-
}, n.onerror = () => {
|
|
32
|
-
t(/* @__PURE__ */ Error("Failed to load Desmos API from CDN"));
|
|
33
|
-
}, document.head.appendChild(n);
|
|
34
|
-
});
|
|
35
|
-
}
|
|
36
|
-
async initialize(e) {
|
|
37
|
-
if (!this.initialized) {
|
|
38
|
-
if (this.onTelemetry = e?.onTelemetry, typeof window > "u") throw Error("Desmos calculators can only be initialized in the browser");
|
|
39
|
-
if (this.isDevelopment = process.env.NODE_ENV === "development" || typeof process > "u" || !process.env.NODE_ENV, e?.proxyEndpoint) {
|
|
40
|
-
this.proxyEndpoint = e.proxyEndpoint;
|
|
41
|
-
let t = Date.now();
|
|
42
|
-
await this.emitTelemetry("pie-tool-backend-call-start", {
|
|
43
|
-
toolId: "calculator",
|
|
44
|
-
backend: "desmos",
|
|
45
|
-
operation: "proxy-auth-fetch"
|
|
46
|
-
});
|
|
47
|
-
try {
|
|
48
|
-
let n = await fetch(e.proxyEndpoint);
|
|
49
|
-
if (!n.ok) throw Error(`Proxy endpoint returned ${n.status}`);
|
|
50
|
-
let r = await n.json();
|
|
51
|
-
this.apiKey = r.apiKey, await this.emitTelemetry("pie-tool-backend-call-success", {
|
|
52
|
-
toolId: "calculator",
|
|
53
|
-
backend: "desmos",
|
|
54
|
-
operation: "proxy-auth-fetch",
|
|
55
|
-
duration: Date.now() - t
|
|
56
|
-
}), console.log("[DesmosProvider] Initialized with server-side proxy (SECURE)");
|
|
57
|
-
} catch (e) {
|
|
58
|
-
throw await this.emitTelemetry("pie-tool-backend-call-error", {
|
|
59
|
-
toolId: "calculator",
|
|
60
|
-
backend: "desmos",
|
|
61
|
-
operation: "proxy-auth-fetch",
|
|
62
|
-
duration: Date.now() - t,
|
|
63
|
-
errorType: "CalculatorProxyAuthError",
|
|
64
|
-
message: e instanceof Error ? e.message : String(e)
|
|
65
|
-
}), Error(`[DesmosProvider] Failed to fetch API key from proxy: ${e}`);
|
|
66
|
-
}
|
|
67
|
-
} else e?.apiKey ? (this.apiKey = e.apiKey, this.isDevelopment ? console.log("[DesmosProvider] Initialized with direct API key (DEVELOPMENT MODE)") : console.error("⚠️ [DesmosProvider] SECURITY WARNING: API key exposed in client-side code!\nThis is insecure for production. Use proxyEndpoint instead.\nSee: https://pie-players.dev/docs/calculator-desmos#security")) : console.warn("[DesmosProvider] No API key or proxy endpoint provided.\nProduction usage requires authentication. Obtain API key from https://www.desmos.com/api\nRecommended: Use proxyEndpoint for production, apiKey for development only.");
|
|
68
|
-
if (!window.Desmos) {
|
|
69
|
-
console.log("[DesmosProvider] Loading Desmos API library...");
|
|
70
|
-
let e = Date.now();
|
|
71
|
-
await this.emitTelemetry("pie-tool-library-load-start", {
|
|
72
|
-
toolId: "calculator",
|
|
73
|
-
backend: "desmos",
|
|
74
|
-
operation: "desmos-script-load"
|
|
75
|
-
});
|
|
76
|
-
try {
|
|
77
|
-
await this.loadDesmosScript(), await this.emitTelemetry("pie-tool-library-load-success", {
|
|
78
|
-
toolId: "calculator",
|
|
79
|
-
backend: "desmos",
|
|
80
|
-
operation: "desmos-script-load",
|
|
81
|
-
duration: Date.now() - e
|
|
82
|
-
});
|
|
83
|
-
} catch (t) {
|
|
84
|
-
throw await this.emitTelemetry("pie-tool-library-load-error", {
|
|
85
|
-
toolId: "calculator",
|
|
86
|
-
backend: "desmos",
|
|
87
|
-
operation: "desmos-script-load",
|
|
88
|
-
duration: Date.now() - e,
|
|
89
|
-
errorType: "ToolLibraryLoadError",
|
|
90
|
-
message: t instanceof Error ? t.message : String(t)
|
|
91
|
-
}), t;
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
this.initialized = !0;
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
async createCalculator(e, n, r) {
|
|
98
|
-
if (this.initialized || await this.initialize(), !this.supportsType(e)) throw Error(`Desmos does not support calculator type: ${e}`);
|
|
99
|
-
return new t(this, e, n, r, this.apiKey);
|
|
100
|
-
}
|
|
101
|
-
supportsType(e) {
|
|
102
|
-
return this.supportedTypes.includes(e);
|
|
103
|
-
}
|
|
104
|
-
destroy() {
|
|
105
|
-
this.initialized = !1, this.onTelemetry = void 0;
|
|
106
|
-
}
|
|
107
|
-
getCapabilities() {
|
|
108
|
-
return {
|
|
109
|
-
supportsHistory: !1,
|
|
110
|
-
supportsGraphing: !0,
|
|
111
|
-
supportsExpressions: !0,
|
|
112
|
-
canExport: !0,
|
|
113
|
-
maxPrecision: 15,
|
|
114
|
-
inputMethods: [
|
|
115
|
-
"keyboard",
|
|
116
|
-
"mouse",
|
|
117
|
-
"touch"
|
|
118
|
-
]
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
}, t = class {
|
|
122
|
-
provider;
|
|
123
|
-
type;
|
|
124
|
-
Desmos;
|
|
125
|
-
calculator;
|
|
126
|
-
container;
|
|
127
|
-
constructor(e, t, n, r, i) {
|
|
128
|
-
if (this.provider = e, this.type = t, this.container = n, this.Desmos = window.Desmos, !this.Desmos) throw Error("Desmos API not available");
|
|
129
|
-
this._initializeCalculator(r, i);
|
|
130
|
-
}
|
|
131
|
-
_initializeCalculator(e, t) {
|
|
132
|
-
let n = {
|
|
133
|
-
...e?.desmos || {},
|
|
134
|
-
apiKey: t || e?.desmos?.apiKey
|
|
135
|
-
};
|
|
136
|
-
switch (e?.restrictedMode && Object.assign(n, {
|
|
137
|
-
expressionsTopbar: !1,
|
|
138
|
-
settingsMenu: !1,
|
|
139
|
-
zoomButtons: !1,
|
|
140
|
-
expressions: !1,
|
|
141
|
-
links: !1
|
|
142
|
-
}), this.type) {
|
|
143
|
-
case "graphing":
|
|
144
|
-
this.calculator = this.Desmos.GraphingCalculator(this.container, n);
|
|
145
|
-
break;
|
|
146
|
-
case "scientific":
|
|
147
|
-
this.calculator = this.Desmos.ScientificCalculator(this.container, n);
|
|
148
|
-
break;
|
|
149
|
-
case "basic":
|
|
150
|
-
this.calculator = this.Desmos.FourFunctionCalculator(this.container, n);
|
|
151
|
-
break;
|
|
152
|
-
default: throw Error(`Unsupported calculator type: ${this.type}`);
|
|
153
|
-
}
|
|
154
|
-
console.log(`[DesmosCalculator] Created ${this.type} calculator`);
|
|
155
|
-
}
|
|
156
|
-
getValue() {
|
|
157
|
-
if (this.type === "graphing" && this.calculator.getState) {
|
|
158
|
-
let e = this.calculator.getState();
|
|
159
|
-
return JSON.stringify(e);
|
|
160
|
-
}
|
|
161
|
-
return "";
|
|
162
|
-
}
|
|
163
|
-
setValue(e) {
|
|
164
|
-
if (this.type === "graphing" && this.calculator.setState) try {
|
|
165
|
-
let t = JSON.parse(e);
|
|
166
|
-
this.calculator.setState(t);
|
|
167
|
-
} catch (e) {
|
|
168
|
-
console.error("[DesmosCalculator] Failed to set state:", e);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
clear() {
|
|
172
|
-
this.calculator.setBlank && this.calculator.setBlank();
|
|
173
|
-
}
|
|
174
|
-
async evaluate(e) {
|
|
175
|
-
return this.type === "graphing" ? new Promise((t) => {
|
|
176
|
-
let n = `eval_${Date.now()}`;
|
|
177
|
-
this.calculator.setExpression({
|
|
178
|
-
id: n,
|
|
179
|
-
latex: e
|
|
180
|
-
}), setTimeout(() => {
|
|
181
|
-
let r = this.calculator.HelperExpression({ latex: e }).numericValue || e;
|
|
182
|
-
this.calculator.removeExpression({ id: n }), t(String(r));
|
|
183
|
-
}, 100);
|
|
184
|
-
}) : e;
|
|
185
|
-
}
|
|
186
|
-
resize() {
|
|
187
|
-
this.calculator.resize && this.calculator.resize();
|
|
188
|
-
}
|
|
189
|
-
focus() {
|
|
190
|
-
try {
|
|
191
|
-
if (this.type === "graphing" && typeof this.calculator?.focusFirstExpression == "function") {
|
|
192
|
-
this.calculator.focusFirstExpression();
|
|
193
|
-
return;
|
|
194
|
-
}
|
|
195
|
-
this.container.querySelector(".dcg-mq-editable-field[tabindex=\"0\"], textarea, [contenteditable=\"true\"], [tabindex]:not([tabindex=\"-1\"])")?.focus();
|
|
196
|
-
} catch (e) {
|
|
197
|
-
console.warn("[DesmosCalculator] focus() failed:", e);
|
|
198
|
-
}
|
|
199
|
-
}
|
|
200
|
-
exportState() {
|
|
201
|
-
let e = {};
|
|
202
|
-
return this.type === "graphing" && this.calculator.getState && (e = this.calculator.getState()), {
|
|
203
|
-
type: this.type,
|
|
204
|
-
provider: "desmos",
|
|
205
|
-
value: this.getValue(),
|
|
206
|
-
providerState: e
|
|
207
|
-
};
|
|
208
|
-
}
|
|
209
|
-
importState(e) {
|
|
210
|
-
if (e.provider !== "desmos") throw Error(`Cannot import state from provider: ${e.provider}`);
|
|
211
|
-
e.providerState && this.calculator.setState ? this.calculator.setState(e.providerState) : e.value && this.setValue(e.value);
|
|
212
|
-
}
|
|
213
|
-
destroy() {
|
|
214
|
-
this.calculator && this.calculator.destroy && this.calculator.destroy(), this.container.replaceChildren(), console.log("[DesmosCalculator] destroyed");
|
|
215
|
-
}
|
|
216
|
-
};
|
|
217
|
-
//#endregion
|
|
218
|
-
export { e as DesmosCalculatorProvider };
|
|
219
|
-
|
|
220
|
-
//# sourceMappingURL=dist-DwvskOs6.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"dist-DwvskOs6.js","names":[],"sources":["../../../node_modules/.bun/@pie-players+pie-calculator-desmos@0.3.68/node_modules/@pie-players/pie-calculator-desmos/dist/desmos-provider.js"],"sourcesContent":["/**\n * Desmos Calculator Provider\n * Implementation of CalculatorProvider for Desmos calculators\n *\n * Supports: Basic, Scientific, and Graphing calculators\n * Based on Desmos API v1.12+\n * Requires: Desmos API key (obtain from https://www.desmos.com/api)\n *\n * SECURITY BEST PRACTICE:\n * - Development: Pass apiKey directly for local testing\n * - Production: Use proxyEndpoint to keep API key server-side\n *\n * Example server-side proxy (Express.js):\n * ```\n * app.get('/api/desmos/token', requireAuth, (req, res) => {\n * res.json({ apiKey: process.env.DESMOS_API_KEY });\n * });\n * ```\n */\n/**\n * Desmos Calculator Provider Implementation\n */\nexport class DesmosCalculatorProvider {\n providerId = \"desmos\";\n providerName = \"Desmos\";\n supportedTypes = [\n \"basic\",\n \"scientific\",\n \"graphing\",\n ];\n version = \"1.12\";\n initialized = false;\n apiKey;\n proxyEndpoint;\n isDevelopment = false;\n onTelemetry;\n async emitTelemetry(eventName, payload) {\n try {\n await this.onTelemetry?.(eventName, payload);\n }\n catch (error) {\n console.warn(\"[DesmosProvider] telemetry callback failed:\", error);\n }\n }\n /**\n * Get the configured API key\n * @internal Used internally by calculator instances\n */\n getApiKey() {\n return this.apiKey;\n }\n /**\n * Dynamically load the Desmos calculator library\n * @private\n */\n async loadDesmosScript() {\n return new Promise((resolve, reject) => {\n const script = document.createElement(\"script\");\n // Include API key in script URL if available\n const scriptUrl = this.apiKey\n ? `https://www.desmos.com/api/v1.12/calculator.js?apiKey=${this.apiKey}`\n : \"https://www.desmos.com/api/v1.12/calculator.js\";\n script.src = scriptUrl;\n script.async = true;\n script.onload = () => {\n if (window.Desmos) {\n console.log(\"[DesmosProvider] Desmos API loaded successfully\");\n resolve();\n }\n else {\n reject(new Error(\"Desmos API loaded but window.Desmos is undefined\"));\n }\n };\n script.onerror = () => {\n reject(new Error(\"Failed to load Desmos API from CDN\"));\n };\n document.head.appendChild(script);\n });\n }\n /**\n * Initialize Desmos library\n * @param config Configuration with API key (development) or proxy endpoint (production)\n */\n async initialize(config) {\n if (this.initialized)\n return;\n this.onTelemetry = config?.onTelemetry;\n // SSR guard\n if (typeof window === \"undefined\") {\n throw new Error(\"Desmos calculators can only be initialized in the browser\");\n }\n // Determine if we're in development mode\n this.isDevelopment =\n process.env.NODE_ENV === \"development\" ||\n typeof process === \"undefined\" ||\n !process.env.NODE_ENV;\n // Configure API access pattern\n if (config?.proxyEndpoint) {\n // Production pattern: server-side proxy\n this.proxyEndpoint = config.proxyEndpoint;\n const authStartedAt = Date.now();\n await this.emitTelemetry(\"pie-tool-backend-call-start\", {\n toolId: \"calculator\",\n backend: \"desmos\",\n operation: \"proxy-auth-fetch\",\n });\n try {\n const response = await fetch(config.proxyEndpoint);\n if (!response.ok) {\n throw new Error(`Proxy endpoint returned ${response.status}`);\n }\n const data = await response.json();\n this.apiKey = data.apiKey;\n await this.emitTelemetry(\"pie-tool-backend-call-success\", {\n toolId: \"calculator\",\n backend: \"desmos\",\n operation: \"proxy-auth-fetch\",\n duration: Date.now() - authStartedAt,\n });\n console.log(\"[DesmosProvider] Initialized with server-side proxy (SECURE)\");\n }\n catch (error) {\n await this.emitTelemetry(\"pie-tool-backend-call-error\", {\n toolId: \"calculator\",\n backend: \"desmos\",\n operation: \"proxy-auth-fetch\",\n duration: Date.now() - authStartedAt,\n errorType: \"CalculatorProxyAuthError\",\n message: error instanceof Error ? error.message : String(error),\n });\n throw new Error(`[DesmosProvider] Failed to fetch API key from proxy: ${error}`);\n }\n }\n else if (config?.apiKey) {\n // Development pattern: direct API key\n this.apiKey = config.apiKey;\n // Security warning in production\n if (!this.isDevelopment) {\n console.error(\"⚠️ [DesmosProvider] SECURITY WARNING: API key exposed in client-side code!\\n\" +\n \"This is insecure for production. Use proxyEndpoint instead.\\n\" +\n \"See: https://pie-players.dev/docs/calculator-desmos#security\");\n }\n else {\n console.log(\"[DesmosProvider] Initialized with direct API key (DEVELOPMENT MODE)\");\n }\n }\n else {\n // No API key provided\n console.warn(\"[DesmosProvider] No API key or proxy endpoint provided.\\n\" +\n \"Production usage requires authentication. Obtain API key from https://www.desmos.com/api\\n\" +\n \"Recommended: Use proxyEndpoint for production, apiKey for development only.\");\n }\n // Load Desmos API if not already loaded\n if (!window.Desmos) {\n console.log(\"[DesmosProvider] Loading Desmos API library...\");\n const libraryLoadStartedAt = Date.now();\n await this.emitTelemetry(\"pie-tool-library-load-start\", {\n toolId: \"calculator\",\n backend: \"desmos\",\n operation: \"desmos-script-load\",\n });\n try {\n await this.loadDesmosScript();\n await this.emitTelemetry(\"pie-tool-library-load-success\", {\n toolId: \"calculator\",\n backend: \"desmos\",\n operation: \"desmos-script-load\",\n duration: Date.now() - libraryLoadStartedAt,\n });\n }\n catch (error) {\n await this.emitTelemetry(\"pie-tool-library-load-error\", {\n toolId: \"calculator\",\n backend: \"desmos\",\n operation: \"desmos-script-load\",\n duration: Date.now() - libraryLoadStartedAt,\n errorType: \"ToolLibraryLoadError\",\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n this.initialized = true;\n }\n /**\n * Create a calculator instance\n */\n async createCalculator(type, container, config) {\n if (!this.initialized) {\n await this.initialize();\n }\n if (!this.supportsType(type)) {\n throw new Error(`Desmos does not support calculator type: ${type}`);\n }\n return new DesmosCalculator(this, type, container, config, this.apiKey);\n }\n /**\n * Check if type is supported\n */\n supportsType(type) {\n return this.supportedTypes.includes(type);\n }\n /**\n * Cleanup\n */\n destroy() {\n this.initialized = false;\n this.onTelemetry = undefined;\n }\n /**\n * Get provider capabilities\n */\n getCapabilities() {\n return {\n supportsHistory: false, // Desmos doesn't expose history API\n supportsGraphing: true,\n supportsExpressions: true,\n canExport: true,\n maxPrecision: 15,\n inputMethods: [\"keyboard\", \"mouse\", \"touch\"],\n };\n }\n}\n/**\n * Desmos Calculator Instance\n */\nclass DesmosCalculator {\n provider;\n type;\n Desmos;\n calculator;\n container;\n constructor(provider, type, container, config, apiKey) {\n this.provider = provider;\n this.type = type;\n this.container = container;\n this.Desmos = window.Desmos;\n if (!this.Desmos) {\n throw new Error(\"Desmos API not available\");\n }\n this._initializeCalculator(config, apiKey);\n }\n _initializeCalculator(config, apiKey) {\n // Merge Desmos-specific config with defaults\n const desmosConfig = {\n ...(config?.desmos || {}),\n apiKey: apiKey || config?.desmos?.apiKey,\n };\n // Apply restricted mode if specified\n if (config?.restrictedMode) {\n Object.assign(desmosConfig, {\n expressionsTopbar: false,\n settingsMenu: false,\n zoomButtons: false,\n expressions: false,\n links: false,\n });\n }\n // Create appropriate calculator type\n switch (this.type) {\n case \"graphing\":\n this.calculator = this.Desmos.GraphingCalculator(this.container, desmosConfig);\n break;\n case \"scientific\":\n this.calculator = this.Desmos.ScientificCalculator(this.container, desmosConfig);\n break;\n case \"basic\":\n this.calculator = this.Desmos.FourFunctionCalculator(this.container, desmosConfig);\n break;\n default:\n throw new Error(`Unsupported calculator type: ${this.type}`);\n }\n console.log(`[DesmosCalculator] Created ${this.type} calculator`);\n }\n getValue() {\n // For graphing calculator, get the state\n if (this.type === \"graphing\" && this.calculator.getState) {\n const state = this.calculator.getState();\n return JSON.stringify(state);\n }\n // For other calculators, return empty (Desmos doesn't expose value API)\n return \"\";\n }\n setValue(value) {\n // For graphing calculator, set the state\n if (this.type === \"graphing\" && this.calculator.setState) {\n try {\n const state = JSON.parse(value);\n this.calculator.setState(state);\n }\n catch (error) {\n console.error(\"[DesmosCalculator] Failed to set state:\", error);\n }\n }\n }\n clear() {\n if (this.calculator.setBlank) {\n this.calculator.setBlank();\n }\n }\n async evaluate(expression) {\n // Desmos doesn't provide a direct evaluate API\n // For graphing calculator, add expression and observe\n if (this.type === \"graphing\") {\n return new Promise((resolve) => {\n const id = `eval_${Date.now()}`;\n this.calculator.setExpression({ id, latex: expression });\n // Give Desmos time to process\n setTimeout(() => {\n const helperExpression = this.calculator.HelperExpression({\n latex: expression,\n });\n const result = helperExpression.numericValue || expression;\n this.calculator.removeExpression({ id });\n resolve(String(result));\n }, 100);\n });\n }\n return expression;\n }\n resize() {\n if (this.calculator.resize) {\n this.calculator.resize();\n }\n }\n focus() {\n try {\n if (this.type === \"graphing\" &&\n typeof this.calculator?.focusFirstExpression === \"function\") {\n this.calculator.focusFirstExpression();\n return;\n }\n const target = this.container.querySelector('.dcg-mq-editable-field[tabindex=\"0\"], textarea, [contenteditable=\"true\"], [tabindex]:not([tabindex=\"-1\"])');\n target?.focus();\n }\n catch (error) {\n console.warn(\"[DesmosCalculator] focus() failed:\", error);\n }\n }\n exportState() {\n let providerState = {};\n if (this.type === \"graphing\" && this.calculator.getState) {\n providerState = this.calculator.getState();\n }\n return {\n type: this.type,\n provider: \"desmos\",\n value: this.getValue(),\n providerState,\n };\n }\n importState(state) {\n if (state.provider !== \"desmos\") {\n throw new Error(`Cannot import state from provider: ${state.provider}`);\n }\n if (state.providerState && this.calculator.setState) {\n this.calculator.setState(state.providerState);\n }\n else if (state.value) {\n this.setValue(state.value);\n }\n }\n destroy() {\n if (this.calculator && this.calculator.destroy) {\n this.calculator.destroy();\n }\n this.container.replaceChildren();\n console.log(\"[DesmosCalculator] destroyed\");\n }\n}\n"],"x_google_ignoreList":[0],"mappings":";AAsBA,IAAa,IAAb,MAAsC;CAClC,aAAa;CACb,eAAe;CACf,iBAAiB;EACb;EACA;EACA;CACJ;CACA,UAAU;CACV,cAAc;CACd;CACA;CACA,gBAAgB;CAChB;CACA,MAAM,cAAc,GA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