@pie-players/pie-tool-answer-eliminator 0.3.3 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,228 @@
1
+ var v = Object.defineProperty;
2
+ var y = (h, t, e) => t in h ? v(h, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : h[t] = e;
3
+ var o = (h, t, e) => y(h, typeof t != "symbol" ? t + "" : t, e);
4
+ class T {
5
+ constructor(t) {
6
+ o(this, "config");
7
+ o(this, "currentAudio", null);
8
+ o(this, "pausedState", !1);
9
+ o(this, "wordTimings", []);
10
+ o(this, "highlightInterval", null);
11
+ o(this, "intentionallyStopped", !1);
12
+ o(this, "onWordBoundary");
13
+ this.config = t;
14
+ }
15
+ async speak(t) {
16
+ this.stop(), this.intentionallyStopped = !1;
17
+ const { audioUrl: e, wordTimings: i } = await this.synthesizeSpeech(t), r = this.config.rate || 1;
18
+ return this.wordTimings = i.map((s) => ({
19
+ ...s,
20
+ time: s.time / r
21
+ })), new Promise((s, a) => {
22
+ const n = new Audio(e);
23
+ this.currentAudio = n, this.config.rate && (n.playbackRate = Math.max(0.25, Math.min(4, this.config.rate))), this.config.volume !== void 0 && (n.volume = Math.max(0, Math.min(1, this.config.volume))), n.onplay = () => {
24
+ this.pausedState = !1, this.onWordBoundary && this.wordTimings.length > 0 && this.startWordHighlighting();
25
+ }, n.onended = () => {
26
+ this.stopWordHighlighting(), URL.revokeObjectURL(e), this.currentAudio = null, this.wordTimings = [], s();
27
+ }, n.onerror = (l) => {
28
+ this.stopWordHighlighting(), URL.revokeObjectURL(e), this.currentAudio = null, this.wordTimings = [], this.intentionallyStopped ? s() : a(new Error("Failed to play audio from server"));
29
+ }, n.onpause = () => {
30
+ this.stopWordHighlighting(), this.pausedState = !0;
31
+ }, n.play().catch(a);
32
+ });
33
+ }
34
+ /**
35
+ * Call server API to synthesize speech
36
+ */
37
+ async synthesizeSpeech(t) {
38
+ const e = {
39
+ "Content-Type": "application/json",
40
+ ...this.config.headers
41
+ };
42
+ this.config.authToken && (e.Authorization = `Bearer ${this.config.authToken}`);
43
+ const i = this.config.providerOptions || {}, r = typeof this.config.engine == "string" ? this.config.engine : typeof i.engine == "string" ? i.engine : void 0, s = typeof i.sampleRate == "number" && Number.isFinite(i.sampleRate) ? i.sampleRate : void 0, a = i.format === "mp3" || i.format === "ogg" || i.format === "pcm" ? i.format : void 0, n = Array.isArray(i.speechMarkTypes) ? i.speechMarkTypes.filter((c) => c === "word" || c === "sentence" || c === "ssml") : void 0, l = {
44
+ text: t,
45
+ provider: this.config.provider || "polly",
46
+ voice: this.config.voice,
47
+ language: this.config.language,
48
+ rate: this.config.rate,
49
+ engine: r,
50
+ sampleRate: s,
51
+ format: a,
52
+ speechMarkTypes: n,
53
+ includeSpeechMarks: !0
54
+ }, u = await fetch(`${this.config.apiEndpoint}/synthesize`, {
55
+ method: "POST",
56
+ headers: e,
57
+ body: JSON.stringify(l)
58
+ });
59
+ if (!u.ok) {
60
+ const c = await u.json().catch(() => ({})), m = c.message || c.error?.message || `Server returned ${u.status}`;
61
+ throw new Error(m);
62
+ }
63
+ const d = await u.json(), g = this.base64ToBlob(d.audio, d.contentType), p = URL.createObjectURL(g), f = this.parseSpeechMarks(d.speechMarks);
64
+ return { audioUrl: p, wordTimings: f };
65
+ }
66
+ /**
67
+ * Convert base64 to Blob
68
+ */
69
+ base64ToBlob(t, e) {
70
+ const i = atob(t), r = new Array(i.length);
71
+ for (let a = 0; a < i.length; a++)
72
+ r[a] = i.charCodeAt(a);
73
+ const s = new Uint8Array(r);
74
+ return new Blob([s], { type: e });
75
+ }
76
+ /**
77
+ * Parse speech marks into word timings
78
+ */
79
+ parseSpeechMarks(t) {
80
+ return t.filter((e) => e.type === "word").map((e, i) => ({
81
+ time: e.time,
82
+ wordIndex: i,
83
+ charIndex: e.start,
84
+ length: e.end - e.start
85
+ }));
86
+ }
87
+ /**
88
+ * Start word highlighting synchronized with audio playback
89
+ */
90
+ startWordHighlighting() {
91
+ if (this.stopWordHighlighting(), !this.currentAudio || !this.onWordBoundary || this.wordTimings.length === 0) {
92
+ console.log("[ServerTTSProvider] Cannot start highlighting:", {
93
+ hasAudio: !!this.currentAudio,
94
+ hasCallback: !!this.onWordBoundary,
95
+ wordTimingsCount: this.wordTimings.length
96
+ });
97
+ return;
98
+ }
99
+ console.log("[ServerTTSProvider] Starting word highlighting with", this.wordTimings.length, "word timings"), console.log("[ServerTTSProvider] Playback rate:", this.currentAudio.playbackRate), console.log("[ServerTTSProvider] First 3 timings:", this.wordTimings.slice(0, 3));
100
+ let t = -1;
101
+ this.highlightInterval = window.setInterval(() => {
102
+ if (!this.currentAudio) {
103
+ this.stopWordHighlighting();
104
+ return;
105
+ }
106
+ const e = this.currentAudio.currentTime * 1e3;
107
+ for (let i = 0; i < this.wordTimings.length; i++) {
108
+ const r = this.wordTimings[i];
109
+ if (e >= r.time && i > t) {
110
+ this.onWordBoundary && (console.log("[ServerTTSProvider] Highlighting word at charIndex:", r.charIndex, "length:", r.length, "time:", r.time, "currentTime:", e), this.onWordBoundary("", r.charIndex, r.length)), t = i;
111
+ break;
112
+ }
113
+ }
114
+ }, 50);
115
+ }
116
+ /**
117
+ * Stop word highlighting
118
+ */
119
+ stopWordHighlighting() {
120
+ this.highlightInterval !== null && (clearInterval(this.highlightInterval), this.highlightInterval = null);
121
+ }
122
+ pause() {
123
+ this.currentAudio && !this.pausedState && (this.currentAudio.pause(), this.stopWordHighlighting(), this.pausedState = !0);
124
+ }
125
+ resume() {
126
+ this.currentAudio && this.pausedState && (this.currentAudio.play(), this.pausedState = !1, this.onWordBoundary && this.wordTimings.length > 0 && this.startWordHighlighting());
127
+ }
128
+ stop() {
129
+ this.stopWordHighlighting(), this.currentAudio && (this.intentionallyStopped = !0, this.currentAudio.pause(), this.currentAudio.src && URL.revokeObjectURL(this.currentAudio.src), this.currentAudio.src = "", this.currentAudio = null), this.pausedState = !1, this.wordTimings = [];
130
+ }
131
+ isPlaying() {
132
+ return this.currentAudio !== null && !this.pausedState;
133
+ }
134
+ isPaused() {
135
+ return this.pausedState;
136
+ }
137
+ /**
138
+ * Update settings dynamically (rate, pitch, voice)
139
+ * Note: Voice changes require resynthesis, so voice updates are stored but
140
+ * take effect on the next speak() call. Rate can be applied to current playback.
141
+ */
142
+ updateSettings(t) {
143
+ t.rate !== void 0 && (this.config.rate = t.rate, this.currentAudio && (this.currentAudio.playbackRate = Math.max(0.25, Math.min(4, t.rate)))), t.pitch !== void 0 && (this.config.pitch = t.pitch), t.voice !== void 0 && (this.config.voice = t.voice);
144
+ }
145
+ }
146
+ class S {
147
+ constructor() {
148
+ o(this, "providerId", "server-tts");
149
+ o(this, "providerName", "Server TTS");
150
+ o(this, "version", "1.0.0");
151
+ o(this, "config", null);
152
+ }
153
+ /**
154
+ * Initialize the server TTS provider.
155
+ *
156
+ * This is designed to be fast by default (no API calls).
157
+ * Set validateEndpoint: true in config to test API availability during initialization.
158
+ *
159
+ * @performance Default: <10ms, With validation: 100-500ms
160
+ */
161
+ async initialize(t) {
162
+ const e = t;
163
+ if (!e.apiEndpoint)
164
+ throw new Error("apiEndpoint is required for ServerTTSProvider");
165
+ if (this.config = e, e.validateEndpoint && !await this.testAPIAvailability())
166
+ throw new Error(`Server TTS API not available at ${e.apiEndpoint}`);
167
+ return new T(e);
168
+ }
169
+ /**
170
+ * Test if API endpoint is available (with timeout).
171
+ *
172
+ * @performance 100-500ms depending on network
173
+ */
174
+ async testAPIAvailability() {
175
+ if (!this.config)
176
+ return !1;
177
+ try {
178
+ const t = { ...this.config.headers };
179
+ this.config.authToken && (t.Authorization = `Bearer ${this.config.authToken}`);
180
+ const e = new AbortController(), i = setTimeout(() => e.abort(), 5e3);
181
+ try {
182
+ const r = await fetch(`${this.config.apiEndpoint}/voices`, {
183
+ headers: t,
184
+ signal: e.signal
185
+ });
186
+ return clearTimeout(i), r.ok;
187
+ } catch {
188
+ return clearTimeout(i), !1;
189
+ }
190
+ } catch {
191
+ return !1;
192
+ }
193
+ }
194
+ supportsFeature(t) {
195
+ switch (t) {
196
+ case "pause":
197
+ case "resume":
198
+ case "wordBoundary":
199
+ case "voiceSelection":
200
+ case "rateControl":
201
+ return !0;
202
+ case "pitchControl":
203
+ return !1;
204
+ default:
205
+ return !1;
206
+ }
207
+ }
208
+ getCapabilities() {
209
+ return {
210
+ supportsPause: !0,
211
+ supportsResume: !0,
212
+ supportsWordBoundary: !0,
213
+ // ✅ Via speech marks from server
214
+ supportsVoiceSelection: !0,
215
+ supportsRateControl: !0,
216
+ supportsPitchControl: !1,
217
+ // Depends on server provider
218
+ maxTextLength: 3e3
219
+ // Conservative estimate
220
+ };
221
+ }
222
+ destroy() {
223
+ this.config = null;
224
+ }
225
+ }
226
+ export {
227
+ S as ServerTTSProvider
228
+ };
@@ -0,0 +1,192 @@
1
+ var l = Object.defineProperty;
2
+ var n = (i, e, t) => e in i ? l(i, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : i[e] = t;
3
+ var o = (i, e, t) => n(i, typeof e != "symbol" ? e + "" : e, t);
4
+ class d {
5
+ constructor() {
6
+ o(this, "providerId", "desmos");
7
+ o(this, "providerName", "Desmos");
8
+ o(this, "supportedTypes", [
9
+ "basic",
10
+ "scientific",
11
+ "graphing"
12
+ ]);
13
+ o(this, "version", "1.10");
14
+ o(this, "initialized", !1);
15
+ o(this, "apiKey");
16
+ o(this, "proxyEndpoint");
17
+ o(this, "isDevelopment", !1);
18
+ }
19
+ /**
20
+ * Get the configured API key
21
+ * @internal Used internally by calculator instances
22
+ */
23
+ getApiKey() {
24
+ return this.apiKey;
25
+ }
26
+ /**
27
+ * Dynamically load the Desmos calculator library
28
+ * @private
29
+ */
30
+ async loadDesmosScript() {
31
+ return new Promise((e, t) => {
32
+ const s = document.createElement("script"), r = this.apiKey ? `https://www.desmos.com/api/v1.10/calculator.js?apiKey=${this.apiKey}` : "https://www.desmos.com/api/v1.10/calculator.js";
33
+ s.src = r, s.async = !0, s.onload = () => {
34
+ window.Desmos ? (console.log("[DesmosProvider] Desmos API loaded successfully"), e()) : t(new Error("Desmos API loaded but window.Desmos is undefined"));
35
+ }, s.onerror = () => {
36
+ t(new Error("Failed to load Desmos API from CDN"));
37
+ }, document.head.appendChild(s);
38
+ });
39
+ }
40
+ /**
41
+ * Initialize Desmos library
42
+ * @param config Configuration with API key (development) or proxy endpoint (production)
43
+ */
44
+ async initialize(e) {
45
+ if (!this.initialized) {
46
+ if (typeof window > "u")
47
+ throw new Error("Desmos calculators can only be initialized in the browser");
48
+ if (this.isDevelopment = process.env.NODE_ENV === "development" || typeof process > "u" || !process.env.NODE_ENV, e?.proxyEndpoint) {
49
+ this.proxyEndpoint = e.proxyEndpoint;
50
+ try {
51
+ const t = await fetch(e.proxyEndpoint);
52
+ if (!t.ok)
53
+ throw new Error(`Proxy endpoint returned ${t.status}`);
54
+ const s = await t.json();
55
+ this.apiKey = s.apiKey, console.log("[DesmosProvider] Initialized with server-side proxy (SECURE)");
56
+ } catch (t) {
57
+ throw new Error(`[DesmosProvider] Failed to fetch API key from proxy: ${t}`);
58
+ }
59
+ } 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!
60
+ This is insecure for production. Use proxyEndpoint instead.
61
+ See: https://pie-players.dev/docs/calculator-desmos#security`)) : console.warn(`[DesmosProvider] No API key or proxy endpoint provided.
62
+ Production usage requires authentication. Obtain API key from https://www.desmos.com/api
63
+ Recommended: Use proxyEndpoint for production, apiKey for development only.`);
64
+ window.Desmos || (console.log("[DesmosProvider] Loading Desmos API library..."), await this.loadDesmosScript()), this.initialized = !0;
65
+ }
66
+ }
67
+ /**
68
+ * Create a calculator instance
69
+ */
70
+ async createCalculator(e, t, s) {
71
+ if (this.initialized || await this.initialize(), !this.supportsType(e))
72
+ throw new Error(`Desmos does not support calculator type: ${e}`);
73
+ return new c(this, e, t, s, this.apiKey);
74
+ }
75
+ /**
76
+ * Check if type is supported
77
+ */
78
+ supportsType(e) {
79
+ return this.supportedTypes.includes(e);
80
+ }
81
+ /**
82
+ * Cleanup
83
+ */
84
+ destroy() {
85
+ this.initialized = !1;
86
+ }
87
+ /**
88
+ * Get provider capabilities
89
+ */
90
+ getCapabilities() {
91
+ return {
92
+ supportsHistory: !1,
93
+ // Desmos doesn't expose history API
94
+ supportsGraphing: !0,
95
+ supportsExpressions: !0,
96
+ canExport: !0,
97
+ maxPrecision: 15,
98
+ inputMethods: ["keyboard", "mouse", "touch"]
99
+ };
100
+ }
101
+ }
102
+ class c {
103
+ constructor(e, t, s, r, a) {
104
+ o(this, "provider");
105
+ o(this, "type");
106
+ o(this, "Desmos");
107
+ o(this, "calculator");
108
+ o(this, "container");
109
+ if (this.provider = e, this.type = t, this.container = s, this.Desmos = window.Desmos, !this.Desmos)
110
+ throw new Error("Desmos API not available");
111
+ this._initializeCalculator(r, a);
112
+ }
113
+ _initializeCalculator(e, t) {
114
+ const s = {
115
+ ...e?.desmos || {},
116
+ apiKey: t || e?.desmos?.apiKey
117
+ };
118
+ switch (e?.restrictedMode && Object.assign(s, {
119
+ expressionsTopbar: !1,
120
+ settingsMenu: !1,
121
+ zoomButtons: !1,
122
+ expressions: !1,
123
+ links: !1
124
+ }), this.type) {
125
+ case "graphing":
126
+ this.calculator = this.Desmos.GraphingCalculator(this.container, s);
127
+ break;
128
+ case "scientific":
129
+ this.calculator = this.Desmos.ScientificCalculator(this.container, s);
130
+ break;
131
+ case "basic":
132
+ this.calculator = this.Desmos.FourFunctionCalculator(this.container, s);
133
+ break;
134
+ default:
135
+ throw new Error(`Unsupported calculator type: ${this.type}`);
136
+ }
137
+ console.log(`[DesmosCalculator] Created ${this.type} calculator`);
138
+ }
139
+ getValue() {
140
+ if (this.type === "graphing" && this.calculator.getState) {
141
+ const e = this.calculator.getState();
142
+ return JSON.stringify(e);
143
+ }
144
+ return "";
145
+ }
146
+ setValue(e) {
147
+ if (this.type === "graphing" && this.calculator.setState)
148
+ try {
149
+ const t = JSON.parse(e);
150
+ this.calculator.setState(t);
151
+ } catch (t) {
152
+ console.error("[DesmosCalculator] Failed to set state:", t);
153
+ }
154
+ }
155
+ clear() {
156
+ this.calculator.setBlank && this.calculator.setBlank();
157
+ }
158
+ async evaluate(e) {
159
+ return this.type === "graphing" ? new Promise((t) => {
160
+ const s = `eval_${Date.now()}`;
161
+ this.calculator.setExpression({ id: s, latex: e }), setTimeout(() => {
162
+ const a = this.calculator.HelperExpression({
163
+ latex: e
164
+ }).numericValue || e;
165
+ this.calculator.removeExpression({ id: s }), t(String(a));
166
+ }, 100);
167
+ }) : e;
168
+ }
169
+ resize() {
170
+ this.calculator.resize && this.calculator.resize();
171
+ }
172
+ exportState() {
173
+ let e = {};
174
+ return this.type === "graphing" && this.calculator.getState && (e = this.calculator.getState()), {
175
+ type: this.type,
176
+ provider: "desmos",
177
+ value: this.getValue(),
178
+ providerState: e
179
+ };
180
+ }
181
+ importState(e) {
182
+ if (e.provider !== "desmos")
183
+ throw new Error(`Cannot import state from provider: ${e.provider}`);
184
+ e.providerState && this.calculator.setState ? this.calculator.setState(e.providerState) : e.value && this.setValue(e.value);
185
+ }
186
+ destroy() {
187
+ this.calculator && this.calculator.destroy && this.calculator.destroy(), this.container.replaceChildren(), console.log("[DesmosCalculator] destroyed");
188
+ }
189
+ }
190
+ export {
191
+ d as DesmosCalculatorProvider
192
+ };