@rimori/playwright-testing 0.2.2 → 0.2.3

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.
@@ -76,6 +76,7 @@ type MessageChannelSimulatorArgs = {
76
76
  rimoriInfo?: RimoriInfo;
77
77
  };
78
78
  type EventListener = (event: EventBusMessage) => void | Promise<void>;
79
+ type AutoResponder = (event: EventBusMessage) => unknown | Promise<unknown>;
79
80
  export declare class MessageChannelSimulator {
80
81
  private readonly page;
81
82
  private readonly pluginId;
@@ -111,6 +112,16 @@ export declare class MessageChannelSimulator {
111
112
  * Registers a handler for events emitted from the plugin.
112
113
  */
113
114
  on(topic: string, handler: EventListener): () => void;
115
+ /**
116
+ * Registers a one-time auto-responder for a request/response topic.
117
+ * When a request with an eventId comes in for this topic, the responder will
118
+ * be called once and then automatically removed.
119
+ *
120
+ * @param topic - The event topic to respond to
121
+ * @param responder - A function that returns the response data, or a value to return directly
122
+ * @returns A function to manually remove the responder before it's used
123
+ */
124
+ respondOnce(topic: string, responder: AutoResponder | unknown): () => void;
114
125
  /**
115
126
  * Overrides the default profile returned by the auto responders.
116
127
  */
@@ -142,6 +142,39 @@ class MessageChannelSimulator {
142
142
  }
143
143
  };
144
144
  }
145
+ /**
146
+ * Registers a one-time auto-responder for a request/response topic.
147
+ * When a request with an eventId comes in for this topic, the responder will
148
+ * be called once and then automatically removed.
149
+ *
150
+ * @param topic - The event topic to respond to
151
+ * @param responder - A function that returns the response data, or a value to return directly
152
+ * @returns A function to manually remove the responder before it's used
153
+ */
154
+ respondOnce(topic, responder) {
155
+ let used = false;
156
+ const wrappedResponder = (event) => {
157
+ if (used) {
158
+ return undefined;
159
+ }
160
+ used = true;
161
+ // Remove from autoResponders after first use
162
+ this.autoResponders.delete(topic);
163
+ // If responder is a function, call it with the event, otherwise return the value directly
164
+ if (typeof responder === 'function') {
165
+ return responder(event);
166
+ }
167
+ return responder;
168
+ };
169
+ this.autoResponders.set(topic, wrappedResponder);
170
+ // Return a function to manually remove the responder
171
+ return () => {
172
+ if (!used) {
173
+ this.autoResponders.delete(topic);
174
+ used = true;
175
+ }
176
+ };
177
+ }
145
178
  /**
146
179
  * Overrides the default profile returned by the auto responders.
147
180
  */
@@ -122,17 +122,63 @@ export declare class RimoriTestEnvironment {
122
122
  * @param options - Mock options including HTTP method (defaults to 'GET' if not specified)
123
123
  */
124
124
  mockFrom: (tableName: string, value: unknown, options?: MockOptions) => void;
125
- mockTable: () => void;
126
125
  };
127
126
  readonly event: {
128
- mockEmit: () => void;
129
- mockRequest: () => void;
130
- mockOn: () => void;
127
+ /**
128
+ * Emit an event into the plugin as if it came from Rimori main or another plugin.
129
+ *
130
+ * Note: This does NOT currently reach worker listeners such as those in
131
+ * `worker/listeners/decks.ts` or `worker/listeners/flascards.ts` – those run in a
132
+ * separate process. This helper is intended for UI‑side events only.
133
+ */
134
+ mockEmit: (topic: string, data: unknown, sender?: string) => Promise<void>;
135
+ /**
136
+ * Registers a one-time auto-responder for request/response style events.
137
+ *
138
+ * When the plugin calls `plugin.event.request(topic, data)`, this registered responder
139
+ * will automatically return the provided response value. The responder is automatically
140
+ * removed after the first request, ensuring it only responds once.
141
+ *
142
+ * Example:
143
+ * ```ts
144
+ * // Register a responder that will return deck summaries when requested
145
+ * env.event.mockRequest('deck.requestOpenToday', [
146
+ * { id: 'deck-1', name: 'My Deck', total_new: 5, total_learning: 2, total_review: 10 }
147
+ * ]);
148
+ *
149
+ * // Now when the plugin calls: plugin.event.request('deck.requestOpenToday', {})
150
+ * // It will receive the deck summaries array above
151
+ * ```
152
+ *
153
+ * @param topic - The event topic to respond to (e.g., 'deck.requestOpenToday')
154
+ * @param response - The response value to return, or a function that receives the event and returns the response
155
+ * @returns A function to manually remove the responder before it's used
156
+ */
157
+ mockRequest: (topic: string, response: unknown | ((event: unknown) => unknown)) => () => void;
158
+ /**
159
+ * Listen for events emitted by the plugin.
160
+ * @param topic - The event topic to listen for (e.g., 'global.accomplishment.triggerMicro')
161
+ * @param handler - The handler function that receives the event data
162
+ * @returns A function to unsubscribe from the event
163
+ */
164
+ on: (topic: string, handler: (data: unknown) => void) => (() => void);
131
165
  mockOnce: () => void;
132
166
  mockRespond: () => void;
133
167
  mockEmitAccomplishment: () => void;
134
168
  mockOnAccomplishment: () => void;
135
- mockEmitSidebarAction: () => void;
169
+ /**
170
+ * Emits a sidebar action event into the plugin as if Rimori main had triggered it.
171
+ * This is useful for testing sidebar-driven flows like flashcard creation from selected text.
172
+ *
173
+ * It sends a message on the 'global.sidebar.triggerAction' topic, which plugins can listen to via:
174
+ * plugin.event.on<{ action: string; text: string }>('global.sidebar.triggerAction', ...)
175
+ *
176
+ * @param payload - The payload forwarded to the plugin, typically including an `action` key and optional `text`.
177
+ */
178
+ triggerSidebarAction: (payload: {
179
+ action: string;
180
+ text?: string;
181
+ }) => Promise<void>;
136
182
  /**
137
183
  * Triggers a side panel action event as the parent application would.
138
184
  * This simulates how rimori-main's SidebarPluginHandler responds to plugin's 'action.requestSidebar' events.
@@ -166,6 +212,61 @@ export declare class RimoriTestEnvironment {
166
212
  mockGetTextFromVoice: (text: string, options?: MockOptions) => void;
167
213
  mockGetObject: (value: unknown, options?: MockOptions) => void;
168
214
  };
215
+ /**
216
+ * Helpers for tracking browser audio playback in tests.
217
+ *
218
+ * This is useful for components like the AudioPlayer in @rimori/react-client which:
219
+ * 1) Fetch audio data from the backend (mocked via `env.ai.mockGetVoice`)
220
+ * 2) Create `new Audio(url)` and call `.play()`
221
+ *
222
+ * With tracking enabled you can assert how many times audio playback was attempted:
223
+ *
224
+ * ```ts
225
+ * await env.audio.enableTracking();
226
+ * await env.ai.mockGetVoice(Buffer.from('dummy'), { method: 'POST' });
227
+ * await env.setup();
228
+ * // ...navigate and trigger audio...
229
+ * const counts = await env.audio.getPlayCounts();
230
+ * expect(counts.mediaPlayCalls).toBeGreaterThan(0);
231
+ * ```
232
+ *
233
+ * **Counter Types:**
234
+ * - `mediaPlayCalls`: Tracks calls to `.play()` on any `HTMLMediaElement` instance
235
+ * (including `<audio>`, `<video>` elements, or any element that inherits from `HTMLMediaElement`).
236
+ * This counter increments whenever `HTMLMediaElement.prototype.play()` is invoked.
237
+ * - `audioPlayCalls`: Tracks calls to `.play()` specifically on instances created via the `Audio` constructor
238
+ * (e.g., `new Audio(url).play()`). This is a subset of `mediaPlayCalls` but provides more specific
239
+ * tracking for programmatically created audio elements.
240
+ *
241
+ * **Note**: Since `Audio` instances are also `HTMLMediaElement` instances, calling `.play()` on an
242
+ * `Audio` object will increment **both** counters. For most use cases, checking `mediaPlayCalls`
243
+ * is sufficient as it captures all audio playback attempts.
244
+ */
245
+ readonly audio: {
246
+ /**
247
+ * Injects tracking hooks for HTMLMediaElement.play and the Audio constructor.
248
+ * Must be called before the plugin code runs (ideally before env.setup()).
249
+ */
250
+ enableTracking: () => Promise<void>;
251
+ /**
252
+ * Returns current audio play counters from the browser context.
253
+ *
254
+ * @returns An object with two counters:
255
+ * - `mediaPlayCalls`: Total number of `.play()` calls on any `HTMLMediaElement` (includes all audio/video elements)
256
+ * - `audioPlayCalls`: Number of `.play()` calls on instances created via `new Audio()` (subset of `mediaPlayCalls`)
257
+ *
258
+ * **Note**: Since `Audio` extends `HTMLMediaElement`, calling `.play()` on an `Audio` instance increments both counters.
259
+ * For general audio playback tracking, use `mediaPlayCalls` as it captures all playback attempts.
260
+ */
261
+ getPlayCounts: () => Promise<{
262
+ mediaPlayCalls: number;
263
+ audioPlayCalls: number;
264
+ }>;
265
+ /**
266
+ * Resets the audio play counters to zero.
267
+ */
268
+ resetPlayCounts: () => Promise<void>;
269
+ };
169
270
  readonly runtime: {
170
271
  mockFetchBackend: () => void;
171
272
  };
@@ -85,17 +85,83 @@ class RimoriTestEnvironment {
85
85
  const fullTableName = `${this.pluginId}_${tableName}`;
86
86
  this.addSupabaseRoute(fullTableName, value, options);
87
87
  },
88
- mockTable: () => { },
89
88
  };
90
89
  this.event = {
91
- mockEmit: () => { },
92
- mockRequest: () => { },
93
- mockOn: () => { },
90
+ /**
91
+ * Emit an event into the plugin as if it came from Rimori main or another plugin.
92
+ *
93
+ * Note: This does NOT currently reach worker listeners such as those in
94
+ * `worker/listeners/decks.ts` or `worker/listeners/flascards.ts` – those run in a
95
+ * separate process. This helper is intended for UI‑side events only.
96
+ */
97
+ mockEmit: async (topic, data, sender = 'test') => {
98
+ if (!this.messageChannelSimulator) {
99
+ throw new Error('MessageChannelSimulator not initialized. Call setup() first.');
100
+ }
101
+ await this.messageChannelSimulator.emit(topic, data, sender);
102
+ },
103
+ /**
104
+ * Registers a one-time auto-responder for request/response style events.
105
+ *
106
+ * When the plugin calls `plugin.event.request(topic, data)`, this registered responder
107
+ * will automatically return the provided response value. The responder is automatically
108
+ * removed after the first request, ensuring it only responds once.
109
+ *
110
+ * Example:
111
+ * ```ts
112
+ * // Register a responder that will return deck summaries when requested
113
+ * env.event.mockRequest('deck.requestOpenToday', [
114
+ * { id: 'deck-1', name: 'My Deck', total_new: 5, total_learning: 2, total_review: 10 }
115
+ * ]);
116
+ *
117
+ * // Now when the plugin calls: plugin.event.request('deck.requestOpenToday', {})
118
+ * // It will receive the deck summaries array above
119
+ * ```
120
+ *
121
+ * @param topic - The event topic to respond to (e.g., 'deck.requestOpenToday')
122
+ * @param response - The response value to return, or a function that receives the event and returns the response
123
+ * @returns A function to manually remove the responder before it's used
124
+ */
125
+ mockRequest: (topic, response) => {
126
+ if (!this.messageChannelSimulator) {
127
+ throw new Error('MessageChannelSimulator not initialized. Call setup() first.');
128
+ }
129
+ return this.messageChannelSimulator.respondOnce(topic, response);
130
+ },
131
+ /**
132
+ * Listen for events emitted by the plugin.
133
+ * @param topic - The event topic to listen for (e.g., 'global.accomplishment.triggerMicro')
134
+ * @param handler - The handler function that receives the event data
135
+ * @returns A function to unsubscribe from the event
136
+ */
137
+ on: (topic, handler) => {
138
+ if (!this.messageChannelSimulator) {
139
+ throw new Error('MessageChannelSimulator not initialized. Call setup() first.');
140
+ }
141
+ return this.messageChannelSimulator.on(topic, (event) => {
142
+ handler(event.data);
143
+ });
144
+ },
94
145
  mockOnce: () => { },
95
146
  mockRespond: () => { },
96
147
  mockEmitAccomplishment: () => { },
97
148
  mockOnAccomplishment: () => { },
98
- mockEmitSidebarAction: () => { },
149
+ /**
150
+ * Emits a sidebar action event into the plugin as if Rimori main had triggered it.
151
+ * This is useful for testing sidebar-driven flows like flashcard creation from selected text.
152
+ *
153
+ * It sends a message on the 'global.sidebar.triggerAction' topic, which plugins can listen to via:
154
+ * plugin.event.on<{ action: string; text: string }>('global.sidebar.triggerAction', ...)
155
+ *
156
+ * @param payload - The payload forwarded to the plugin, typically including an `action` key and optional `text`.
157
+ */
158
+ triggerSidebarAction: async (payload) => {
159
+ if (!this.messageChannelSimulator) {
160
+ throw new Error('MessageChannelSimulator not initialized. Call setup() first.');
161
+ }
162
+ // Simulate Rimori main emitting the sidebar trigger event towards the plugin
163
+ await this.messageChannelSimulator.emit('global.sidebar.triggerAction', payload, 'sidebar');
164
+ },
99
165
  /**
100
166
  * Triggers a side panel action event as the parent application would.
101
167
  * This simulates how rimori-main's SidebarPluginHandler responds to plugin's 'action.requestSidebar' events.
@@ -174,6 +240,125 @@ class RimoriTestEnvironment {
174
240
  this.addBackendRoute('/ai/llm-object', value, { ...options, method: 'POST' });
175
241
  },
176
242
  };
243
+ /**
244
+ * Helpers for tracking browser audio playback in tests.
245
+ *
246
+ * This is useful for components like the AudioPlayer in @rimori/react-client which:
247
+ * 1) Fetch audio data from the backend (mocked via `env.ai.mockGetVoice`)
248
+ * 2) Create `new Audio(url)` and call `.play()`
249
+ *
250
+ * With tracking enabled you can assert how many times audio playback was attempted:
251
+ *
252
+ * ```ts
253
+ * await env.audio.enableTracking();
254
+ * await env.ai.mockGetVoice(Buffer.from('dummy'), { method: 'POST' });
255
+ * await env.setup();
256
+ * // ...navigate and trigger audio...
257
+ * const counts = await env.audio.getPlayCounts();
258
+ * expect(counts.mediaPlayCalls).toBeGreaterThan(0);
259
+ * ```
260
+ *
261
+ * **Counter Types:**
262
+ * - `mediaPlayCalls`: Tracks calls to `.play()` on any `HTMLMediaElement` instance
263
+ * (including `<audio>`, `<video>` elements, or any element that inherits from `HTMLMediaElement`).
264
+ * This counter increments whenever `HTMLMediaElement.prototype.play()` is invoked.
265
+ * - `audioPlayCalls`: Tracks calls to `.play()` specifically on instances created via the `Audio` constructor
266
+ * (e.g., `new Audio(url).play()`). This is a subset of `mediaPlayCalls` but provides more specific
267
+ * tracking for programmatically created audio elements.
268
+ *
269
+ * **Note**: Since `Audio` instances are also `HTMLMediaElement` instances, calling `.play()` on an
270
+ * `Audio` object will increment **both** counters. For most use cases, checking `mediaPlayCalls`
271
+ * is sufficient as it captures all audio playback attempts.
272
+ */
273
+ this.audio = {
274
+ /**
275
+ * Injects tracking hooks for HTMLMediaElement.play and the Audio constructor.
276
+ * Must be called before the plugin code runs (ideally before env.setup()).
277
+ */
278
+ enableTracking: async () => {
279
+ await this.page.addInitScript(() => {
280
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
281
+ const w = window;
282
+ if (!w.__rimoriAudio) {
283
+ w.__rimoriAudio = {
284
+ mediaPlayCalls: 0,
285
+ audioPlayCalls: 0,
286
+ };
287
+ }
288
+ const proto = (w.HTMLMediaElement && w.HTMLMediaElement.prototype) || undefined;
289
+ if (proto && !proto.__rimoriPatched) {
290
+ const originalPlay = proto.play;
291
+ proto.play = function (...args) {
292
+ w.__rimoriAudio.mediaPlayCalls += 1;
293
+ return originalPlay.apply(this, args);
294
+ };
295
+ Object.defineProperty(proto, '__rimoriPatched', {
296
+ value: true,
297
+ configurable: false,
298
+ enumerable: false,
299
+ writable: false,
300
+ });
301
+ }
302
+ const OriginalAudio = w.Audio;
303
+ if (OriginalAudio && !OriginalAudio.__rimoriPatched) {
304
+ const PatchedAudio = function (...args) {
305
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
306
+ const audio = new OriginalAudio(...args);
307
+ const originalPlay = audio.play.bind(audio);
308
+ audio.play = () => {
309
+ w.__rimoriAudio.audioPlayCalls += 1;
310
+ return originalPlay();
311
+ };
312
+ return audio;
313
+ };
314
+ PatchedAudio.prototype = OriginalAudio.prototype;
315
+ Object.defineProperty(PatchedAudio, '__rimoriPatched', {
316
+ value: true,
317
+ configurable: false,
318
+ enumerable: false,
319
+ writable: false,
320
+ });
321
+ w.Audio = PatchedAudio;
322
+ }
323
+ });
324
+ },
325
+ /**
326
+ * Returns current audio play counters from the browser context.
327
+ *
328
+ * @returns An object with two counters:
329
+ * - `mediaPlayCalls`: Total number of `.play()` calls on any `HTMLMediaElement` (includes all audio/video elements)
330
+ * - `audioPlayCalls`: Number of `.play()` calls on instances created via `new Audio()` (subset of `mediaPlayCalls`)
331
+ *
332
+ * **Note**: Since `Audio` extends `HTMLMediaElement`, calling `.play()` on an `Audio` instance increments both counters.
333
+ * For general audio playback tracking, use `mediaPlayCalls` as it captures all playback attempts.
334
+ */
335
+ getPlayCounts: async () => {
336
+ return this.page.evaluate(() => {
337
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
338
+ const w = window;
339
+ if (!w.__rimoriAudio) {
340
+ return { mediaPlayCalls: 0, audioPlayCalls: 0 };
341
+ }
342
+ return {
343
+ mediaPlayCalls: Number(w.__rimoriAudio.mediaPlayCalls || 0),
344
+ audioPlayCalls: Number(w.__rimoriAudio.audioPlayCalls || 0),
345
+ };
346
+ });
347
+ },
348
+ /**
349
+ * Resets the audio play counters to zero.
350
+ */
351
+ resetPlayCounts: async () => {
352
+ await this.page.evaluate(() => {
353
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
354
+ const w = window;
355
+ if (w.__rimoriAudio) {
356
+ w.__rimoriAudio.mediaPlayCalls = 0;
357
+ w.__rimoriAudio.audioPlayCalls = 0;
358
+ }
359
+ });
360
+ },
361
+ };
177
362
  this.runtime = {
178
363
  mockFetchBackend: () => { },
179
364
  };
@@ -359,7 +544,6 @@ class RimoriTestEnvironment {
359
544
  }
360
545
  }
361
546
  async handleRoute(route, routes) {
362
- console.warn('handleRoute is not tested');
363
547
  const request = route.request();
364
548
  const requestUrl = request.url();
365
549
  const method = request.method().toUpperCase();
@@ -431,7 +615,6 @@ class RimoriTestEnvironment {
431
615
  * @param options - The options for the route. Method defaults to 'GET' if not specified.
432
616
  */
433
617
  addSupabaseRoute(path, values, options) {
434
- console.warn('addSupabaseRoute is not tested');
435
618
  const method = options?.method ?? 'GET';
436
619
  const fullPath = `${this.rimoriInfo.url}/rest/v1/${path}`;
437
620
  const routeKey = this.createRouteKey(method, fullPath);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rimori/playwright-testing",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Playwright testing utilities for Rimori plugins and workers",
5
5
  "license": "Apache-2.0",
6
6
  "main": "dist/index.js",