@objectstack/plugin-msw 1.0.0 → 1.0.2

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.
@@ -1,6 +1,6 @@
1
1
  import { http, HttpResponse } from 'msw';
2
2
  import { setupWorker } from 'msw/browser';
3
- // import { IDataEngine } from '@objectstack/core';
3
+ import { HttpDispatcher } from '@objectstack/runtime';
4
4
  // Helper for parsing query parameters
5
5
  function parseQueryParams(url) {
6
6
  const params = {};
@@ -43,219 +43,9 @@ function parseQueryParams(url) {
43
43
  }
44
44
  return params;
45
45
  }
46
- // Helper to normalize flat parameters into 'where' clause
47
- function normalizeQuery(params) {
48
- // If 'where' is already present, trust it
49
- if (params.where)
50
- return params;
51
- const reserved = ['select', 'order', 'orderBy', 'sort', 'limit', 'skip', 'offset', 'top', 'page', 'pageSize', 'count'];
52
- const where = {};
53
- let hasWhere = false;
54
- for (const key in params) {
55
- if (!reserved.includes(key)) {
56
- where[key] = params[key];
57
- hasWhere = true;
58
- }
59
- }
60
- if (hasWhere) {
61
- // Keep original params but add where.
62
- // This allows protocols that look at root properties to still work,
63
- // while providing 'where' for strict drivers.
64
- return { ...params, where };
65
- }
66
- return params;
67
- }
68
- /**
69
- * ObjectStack Server Mock - Provides mock database functionality
70
- */
71
- export class ObjectStackServer {
72
- static init(protocol, logger) {
73
- this.protocol = protocol;
74
- this.logger = logger || {
75
- info: console.log,
76
- debug: console.debug,
77
- warn: console.warn,
78
- error: console.error
79
- };
80
- }
81
- static async findData(object, params) {
82
- if (!this.protocol) {
83
- throw new Error('ObjectStackServer not initialized. Call ObjectStackServer.init() first.');
84
- }
85
- this.logger?.debug?.('MSW: Finding records', { object, params });
86
- const result = await this.protocol.findData({ object, query: params || {} });
87
- this.logger?.debug?.('MSW: Find completed', { object, count: result?.records?.length ?? 0 });
88
- return {
89
- status: 200,
90
- data: result
91
- };
92
- }
93
- static async getData(object, id) {
94
- if (!this.protocol) {
95
- throw new Error('ObjectStackServer not initialized. Call ObjectStackServer.init() first.');
96
- }
97
- this.logger?.debug?.('MSW: Getting record', { object, id });
98
- try {
99
- const result = await this.protocol.getData({ object, id });
100
- this.logger?.debug?.('MSW: Get completed', { object, id });
101
- return {
102
- status: 200,
103
- data: result
104
- };
105
- }
106
- catch (error) {
107
- this.logger?.warn?.('MSW: Get failed - not found', { object, id });
108
- const message = error instanceof Error ? error.message : 'Unknown error';
109
- return {
110
- status: 404,
111
- data: { error: message }
112
- };
113
- }
114
- }
115
- static async createData(object, data) {
116
- if (!this.protocol) {
117
- throw new Error('ObjectStackServer not initialized. Call ObjectStackServer.init() first.');
118
- }
119
- this.logger?.debug?.('MSW: Creating record', { object });
120
- try {
121
- const result = await this.protocol.createData({ object, data });
122
- this.logger?.info?.('MSW: Record created', { object, id: result?.id });
123
- return {
124
- status: 201,
125
- data: result
126
- };
127
- }
128
- catch (error) {
129
- this.logger?.error?.('MSW: Create failed', error, { object });
130
- const message = error instanceof Error ? error.message : 'Unknown error';
131
- return {
132
- status: 400,
133
- data: { error: message }
134
- };
135
- }
136
- }
137
- static async updateData(object, id, data) {
138
- if (!this.protocol) {
139
- throw new Error('ObjectStackServer not initialized. Call ObjectStackServer.init() first.');
140
- }
141
- this.logger?.debug?.('MSW: Updating record', { object, id });
142
- try {
143
- const result = await this.protocol.updateData({ object, id, data });
144
- this.logger?.info?.('MSW: Record updated', { object, id });
145
- return {
146
- status: 200,
147
- data: result
148
- };
149
- }
150
- catch (error) {
151
- this.logger?.error?.('MSW: Update failed', error, { object, id });
152
- const message = error instanceof Error ? error.message : 'Unknown error';
153
- return {
154
- status: 400,
155
- data: { error: message }
156
- };
157
- }
158
- }
159
- static async deleteData(object, id) {
160
- if (!this.protocol) {
161
- throw new Error('ObjectStackServer not initialized. Call ObjectStackServer.init() first.');
162
- }
163
- this.logger?.debug?.('MSW: Deleting record', { object, id });
164
- try {
165
- const result = await this.protocol.deleteData({ object, id });
166
- this.logger?.info?.('MSW: Record deleted', { object, id, success: result?.success });
167
- return {
168
- status: 200,
169
- data: result
170
- };
171
- }
172
- catch (error) {
173
- this.logger?.error?.('MSW: Delete failed', error, { object, id });
174
- const message = error instanceof Error ? error.message : 'Unknown error';
175
- return {
176
- status: 400,
177
- data: { error: message }
178
- };
179
- }
180
- }
181
- static async analyticsQuery(request) {
182
- if (!this.protocol) {
183
- throw new Error('ObjectStackServer not initialized. Call ObjectStackServer.init() first.');
184
- }
185
- this.logger?.debug?.('MSW: Executing analytics query', { request });
186
- try {
187
- const result = await this.protocol.analyticsQuery(request);
188
- this.logger?.debug?.('MSW: Analytics query completed', { result });
189
- return {
190
- status: 200,
191
- data: result
192
- };
193
- }
194
- catch (error) {
195
- this.logger?.error?.('MSW: Analytics query failed', error);
196
- const message = error instanceof Error ? error.message : 'Unknown error';
197
- return {
198
- status: 400,
199
- data: { error: message }
200
- };
201
- }
202
- }
203
- static async getAnalyticsMeta(request) {
204
- if (!this.protocol) {
205
- throw new Error('ObjectStackServer not initialized. Call ObjectStackServer.init() first.');
206
- }
207
- this.logger?.debug?.('MSW: Getting analytics metadata', { request });
208
- try {
209
- const result = await this.protocol.getAnalyticsMeta(request);
210
- this.logger?.debug?.('MSW: Analytics metadata retrieved', { result });
211
- return {
212
- status: 200,
213
- data: result
214
- };
215
- }
216
- catch (error) {
217
- this.logger?.error?.('MSW: Analytics metadata failed', error);
218
- const message = error instanceof Error ? error.message : 'Unknown error';
219
- return {
220
- status: 400,
221
- data: { error: message }
222
- };
223
- }
224
- }
225
- static async triggerAutomation(request) {
226
- if (!this.protocol) {
227
- throw new Error('ObjectStackServer not initialized. Call ObjectStackServer.init() first.');
228
- }
229
- this.logger?.debug?.('MSW: Triggering automation', { request });
230
- try {
231
- const result = await this.protocol.triggerAutomation(request);
232
- this.logger?.info?.('MSW: Automation triggered', { result });
233
- return {
234
- status: 200,
235
- data: result
236
- };
237
- }
238
- catch (error) {
239
- this.logger?.error?.('MSW: Automation trigger failed', error);
240
- const message = error instanceof Error ? error.message : 'Unknown error';
241
- return {
242
- status: 400,
243
- data: { error: message }
244
- };
245
- }
246
- }
247
- // Legacy method names for compatibility
248
- static async getUser(id) {
249
- return this.getData('user', id);
250
- }
251
- static async createUser(data) {
252
- return this.createData('user', data);
253
- }
254
- }
255
- ObjectStackServer.protocol = null;
256
- ObjectStackServer.logger = null;
257
46
  /**
258
47
  * MSW Plugin for ObjectStack
48
+
259
49
  *
260
50
  * This plugin enables Mock Service Worker integration for testing and development.
261
51
  * It automatically mocks API endpoints using the ObjectStack runtime protocol.
@@ -350,260 +140,76 @@ export class MSWPlugin {
350
140
  * Setup MSW handlers
351
141
  */
352
142
  setupHandlers(ctx) {
353
- if (!this.protocol) {
354
- ctx.logger.warn('[MSWPlugin] Protocol not initialized. Skipping default API handlers.');
355
- this.handlers = [
356
- ...(this.options.customHandlers || [])
357
- ];
358
- return;
143
+ // Initialize HttpDispatcher
144
+ try {
145
+ this.dispatcher = new HttpDispatcher(ctx.getKernel());
146
+ }
147
+ catch (e) {
148
+ ctx.logger.warn('[MSWPlugin] Could not initialize HttpDispatcher via Kernel. Falling back to simple handlers.');
359
149
  }
360
- const protocol = this.protocol;
361
- // Initialize ObjectStackServer with structured logger
362
- ObjectStackServer.init(protocol, this.options.logRequests ? ctx.logger : undefined);
363
- ctx.logger.debug('Initialized ObjectStackServer', { logRequests: this.options.logRequests });
364
150
  const baseUrl = this.options.baseUrl || '/api/v1';
365
- // Define standard ObjectStack API handlers
151
+ // Custom handlers have priority
366
152
  this.handlers = [
367
- // Discovery endpoint
368
- http.get(`${baseUrl}`, async () => {
369
- const discovery = await protocol.getDiscovery({});
370
- return HttpResponse.json({
371
- ...discovery,
372
- routes: {
373
- data: `${baseUrl}/data`,
374
- metadata: `${baseUrl}/meta`,
375
- ui: `${baseUrl}/ui`,
376
- auth: `${baseUrl}/auth`
377
- }
378
- });
379
- }),
380
- // Meta endpoints
381
- http.get(`${baseUrl}/meta`, async ({ request }) => {
382
- const url = new URL(request.url);
383
- const query = parseQueryParams(url);
384
- return HttpResponse.json(await protocol.getMetaTypes({ query }));
385
- }),
386
- http.get(`${baseUrl}/meta/:type`, async ({ params, request }) => {
153
+ ...(this.options.customHandlers || [])
154
+ ];
155
+ if (this.dispatcher) {
156
+ const dispatcher = this.dispatcher;
157
+ // Catch-all handler for ObjectStack Runtime
158
+ // We use a wildcard to capture all methods and paths under baseUrl
159
+ const catchAll = async ({ request, params }) => {
387
160
  const url = new URL(request.url);
388
- const query = parseQueryParams(url);
389
- return HttpResponse.json(await protocol.getMetaItems({ type: params.type, query }));
390
- }),
391
- http.get(`${baseUrl}/meta/:type/:name`, async ({ params }) => {
392
- try {
393
- return HttpResponse.json(await protocol.getMetaItem({ type: params.type, name: params.name }));
394
- }
395
- catch (error) {
396
- const message = error instanceof Error ? error.message : 'Unknown error';
397
- return HttpResponse.json({ error: message }, { status: 404 });
398
- }
399
- }),
400
- // Data endpoints
401
- http.get(`${baseUrl}/data/:object`, async ({ params, request }) => {
402
- try {
403
- const url = new URL(request.url);
404
- // Use helper to parse properly (handle multiple values, JSON strings, numbers)
405
- const rawParams = parseQueryParams(url);
406
- // Normalize to standard query object (move flats to 'where')
407
- const queryParams = normalizeQuery(rawParams);
408
- const result = await ObjectStackServer.findData(params.object, queryParams);
409
- return HttpResponse.json(result.data, {
410
- status: result.status,
411
- headers: { 'Cache-Control': 'no-store' }
412
- });
413
- }
414
- catch (error) {
415
- const message = error instanceof Error ? error.message : 'Unknown error';
416
- return HttpResponse.json({ error: message }, { status: 404 });
417
- }
418
- }),
419
- http.get(`${baseUrl}/data/:object/:id`, async ({ params }) => {
420
- try {
421
- const result = await ObjectStackServer.getData(params.object, params.id);
422
- return HttpResponse.json(result.data, {
423
- status: result.status,
424
- headers: { 'Cache-Control': 'no-store' }
425
- });
426
- }
427
- catch (error) {
428
- const message = error instanceof Error ? error.message : 'Unknown error';
429
- return HttpResponse.json({ error: message }, { status: 404 });
430
- }
431
- }),
432
- http.post(`${baseUrl}/data/:object`, async ({ params, request }) => {
433
- try {
434
- const body = await request.json();
435
- const result = await ObjectStackServer.createData(params.object, body);
436
- return HttpResponse.json(result.data, { status: result.status });
437
- }
438
- catch (error) {
439
- const message = error instanceof Error ? error.message : 'Unknown error';
440
- return HttpResponse.json({ error: message }, { status: 400 });
441
- }
442
- }),
443
- http.patch(`${baseUrl}/data/:object/:id`, async ({ params, request }) => {
444
- try {
445
- const body = await request.json();
446
- const result = await ObjectStackServer.updateData(params.object, params.id, body);
447
- return HttpResponse.json(result.data, { status: result.status });
448
- }
449
- catch (error) {
450
- const message = error instanceof Error ? error.message : 'Unknown error';
451
- return HttpResponse.json({ error: message }, { status: 400 });
452
- }
453
- }),
454
- http.delete(`${baseUrl}/data/:object/:id`, async ({ params }) => {
455
- try {
456
- const result = await ObjectStackServer.deleteData(params.object, params.id);
457
- return HttpResponse.json(result.data, { status: result.status });
458
- }
459
- catch (error) {
460
- const message = error instanceof Error ? error.message : 'Unknown error';
461
- return HttpResponse.json({ error: message }, { status: 400 });
462
- }
463
- }),
464
- // Batch Operations
465
- http.post(`${baseUrl}/data/:object/batch`, async ({ params, request }) => {
466
- try {
467
- const body = await request.json();
468
- const result = await protocol.batchData({ object: params.object, request: body });
469
- return HttpResponse.json(result);
470
- }
471
- catch (error) {
472
- const message = error instanceof Error ? error.message : 'Unknown error';
473
- return HttpResponse.json({ error: message }, { status: 400 });
474
- }
475
- }),
476
- http.post(`${baseUrl}/data/:object/createMany`, async ({ params, request }) => {
477
- try {
478
- const body = await request.json();
479
- const records = Array.isArray(body) ? body : [];
480
- const result = await protocol.createManyData({ object: params.object, records });
481
- return HttpResponse.json(result, { status: 201 });
482
- }
483
- catch (error) {
484
- const message = error instanceof Error ? error.message : 'Unknown error';
485
- return HttpResponse.json({ error: message }, { status: 400 });
486
- }
487
- }),
488
- http.post(`${baseUrl}/data/:object/updateMany`, async ({ params, request }) => {
489
- try {
490
- const body = await request.json();
491
- const result = await protocol.updateManyData({
492
- object: params.object,
493
- records: body?.records || [],
494
- options: body?.options
495
- });
496
- return HttpResponse.json(result);
497
- }
498
- catch (error) {
499
- const message = error instanceof Error ? error.message : 'Unknown error';
500
- return HttpResponse.json({ error: message }, { status: 400 });
501
- }
502
- }),
503
- http.post(`${baseUrl}/data/:object/deleteMany`, async ({ params, request }) => {
504
- try {
505
- const body = await request.json();
506
- const result = await protocol.deleteManyData({
507
- object: params.object,
508
- ids: body?.ids || [],
509
- options: body?.options
510
- });
511
- return HttpResponse.json(result);
512
- }
513
- catch (error) {
514
- const message = error instanceof Error ? error.message : 'Unknown error';
515
- return HttpResponse.json({ error: message }, { status: 400 });
516
- }
517
- }),
518
- // Enhanced Metadata with Cache Support
519
- http.get(`${baseUrl}/meta/:type/:name`, async ({ params, request }) => {
520
- try {
521
- const cacheRequest = {
522
- ifNoneMatch: request.headers.get('if-none-match') || undefined,
523
- ifModifiedSince: request.headers.get('if-modified-since') || undefined,
524
- };
525
- const result = await protocol.getMetaItemCached({
526
- type: params.type,
527
- name: params.name,
528
- cacheRequest
529
- });
530
- if (result.notModified) {
531
- return new HttpResponse(null, { status: 304 });
161
+ // Calculate path relative to API prefix
162
+ // e.g. /api/v1/data/contacts -> /data/contacts
163
+ let path = url.pathname;
164
+ if (path.startsWith(baseUrl)) {
165
+ path = path.slice(baseUrl.length);
166
+ }
167
+ // Parse Body if present
168
+ let body = undefined;
169
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
170
+ try {
171
+ body = await request.clone().json();
532
172
  }
533
- // Build response headers
534
- const headers = {};
535
- if (result.etag) {
536
- const etagValue = result.etag.weak ? `W/"${result.etag.value}"` : `"${result.etag.value}"`;
537
- headers['ETag'] = etagValue;
173
+ catch (e) {
174
+ try {
175
+ // Try form data if json fails?
176
+ // Dispatcher expects objects usually.
177
+ // For file upload, body might be FormData logic needed?
178
+ // For now assume JSON or text
179
+ }
180
+ catch (e2) { }
538
181
  }
539
- if (result.lastModified) {
540
- headers['Last-Modified'] = new Date(result.lastModified).toUTCString();
182
+ }
183
+ // Parse Query
184
+ const query = parseQueryParams(url);
185
+ // Dispatch
186
+ const result = await dispatcher.dispatch(request.method, path, body, query, { request });
187
+ if (result.handled) {
188
+ if (result.response) {
189
+ return HttpResponse.json(result.response.body, {
190
+ status: result.response.status,
191
+ headers: result.response.headers
192
+ });
541
193
  }
542
- if (result.cacheControl) {
543
- const directives = result.cacheControl.directives.join(', ');
544
- const maxAge = result.cacheControl.maxAge ? `, max-age=${result.cacheControl.maxAge}` : '';
545
- headers['Cache-Control'] = directives + maxAge;
194
+ if (result.result) {
195
+ // Handle special results (streams/redirects - unlikely in MSW but possible)
196
+ if (result.result.type === 'redirect') {
197
+ return HttpResponse.redirect(result.result.url);
198
+ }
199
+ // Fallback for others
200
+ return HttpResponse.json(result.result);
546
201
  }
547
- return HttpResponse.json(result.data, { headers });
548
- }
549
- catch (error) {
550
- const message = error instanceof Error ? error.message : 'Unknown error';
551
- return HttpResponse.json({ error: message }, { status: 404 });
552
- }
553
- }),
554
- // UI Protocol endpoint
555
- http.get(`${baseUrl}/ui/view/:object`, async ({ params, request }) => {
556
- try {
557
- const url = new URL(request.url);
558
- const viewType = url.searchParams.get('type') || 'list';
559
- const view = await protocol.getUiView({ object: params.object, type: viewType });
560
- return HttpResponse.json(view);
561
- }
562
- catch (error) {
563
- const message = error instanceof Error ? error.message : 'Unknown error';
564
- return HttpResponse.json({ error: message }, { status: 404 });
565
- }
566
- }),
567
- // Analytics Operations
568
- http.post(`${baseUrl}/analytics/query`, async ({ request }) => {
569
- try {
570
- const body = await request.json();
571
- const result = await ObjectStackServer.analyticsQuery(body);
572
- return HttpResponse.json(result.data, { status: result.status });
573
202
  }
574
- catch (error) {
575
- const message = error instanceof Error ? error.message : 'Unknown error';
576
- return HttpResponse.json({ error: message }, { status: 400 });
577
- }
578
- }),
579
- http.get(`${baseUrl}/analytics/meta`, async ({ request }) => {
580
- try {
581
- const url = new URL(request.url);
582
- const query = parseQueryParams(url);
583
- const result = await ObjectStackServer.getAnalyticsMeta(query);
584
- return HttpResponse.json(result.data, { status: result.status });
585
- }
586
- catch (error) {
587
- const message = error instanceof Error ? error.message : 'Unknown error';
588
- return HttpResponse.json({ error: message }, { status: 400 });
589
- }
590
- }),
591
- // Automation Operations
592
- http.post(`${baseUrl}/automation/trigger`, async ({ request }) => {
593
- try {
594
- const body = await request.json();
595
- const result = await ObjectStackServer.triggerAutomation(body);
596
- return HttpResponse.json(result.data, { status: result.status });
597
- }
598
- catch (error) {
599
- const message = error instanceof Error ? error.message : 'Unknown error';
600
- return HttpResponse.json({ error: message }, { status: 400 });
601
- }
602
- }),
603
- // Add custom handlers
604
- ...(this.options.customHandlers || [])
605
- ];
606
- ctx.logger.info('MSW request handlers installed', { count: this.handlers.length, baseUrl });
203
+ // Not handled by dispatcher (404 for this route subset)
204
+ return undefined; // Let MSW pass through or handle next
205
+ };
206
+ this.handlers.push(http.all(`${baseUrl}/*`, catchAll), http.all(`${baseUrl}`, catchAll) // Handle root if needed
207
+ );
208
+ ctx.logger.info('MSW handlers set up using HttpDispatcher', { baseUrl });
209
+ }
210
+ else {
211
+ ctx.logger.warn('[MSWPlugin] No dispatcher available. No API routes registered.');
212
+ }
607
213
  }
608
214
  /**
609
215
  * Start the MSW worker
@@ -644,3 +250,37 @@ export class MSWPlugin {
644
250
  return this.handlers;
645
251
  }
646
252
  }
253
+ /**
254
+ * Static helper for interacting with ObjectStack protocol in MSW handlers
255
+ */
256
+ export class ObjectStackServer {
257
+ static init(protocol) {
258
+ this.protocol = protocol;
259
+ }
260
+ static getProtocol() {
261
+ if (!this.protocol) {
262
+ throw new Error('ObjectStackServer not initialized. Call ObjectStackServer.init(protocol) first.');
263
+ }
264
+ return this.protocol;
265
+ }
266
+ static async findData(objectName, query) {
267
+ const body = await this.getProtocol().findData({ object: objectName, query });
268
+ return { data: body, status: 200 };
269
+ }
270
+ static async getData(objectName, id) {
271
+ const body = await this.getProtocol().getData({ object: objectName, id });
272
+ return { data: body, status: 200 };
273
+ }
274
+ static async createData(objectName, data) {
275
+ const body = await this.getProtocol().createData({ object: objectName, data });
276
+ return { data: body, status: 201 };
277
+ }
278
+ static async updateData(objectName, id, data) {
279
+ const body = await this.getProtocol().updateData({ object: objectName, id, data });
280
+ return { data: body, status: 200 };
281
+ }
282
+ static async deleteData(objectName, id) {
283
+ const body = await this.getProtocol().deleteData({ object: objectName, id });
284
+ return { data: body, status: 200 };
285
+ }
286
+ }
package/package.json CHANGED
@@ -1,24 +1,25 @@
1
1
  {
2
2
  "name": "@objectstack/plugin-msw",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "description": "MSW (Mock Service Worker) Plugin for ObjectStack Runtime",
5
5
  "license": "Apache-2.0",
6
6
  "main": "dist/index.js",
7
7
  "types": "dist/index.d.ts",
8
8
  "peerDependencies": {
9
- "@objectstack/runtime": "^1.0.0"
9
+ "@objectstack/runtime": "^1.0.2"
10
10
  },
11
11
  "dependencies": {
12
12
  "msw": "^2.0.0",
13
- "@objectstack/spec": "1.0.0",
14
- "@objectstack/types": "1.0.0",
15
- "@objectstack/objectql": "1.0.0"
13
+ "@objectstack/core": "1.0.2",
14
+ "@objectstack/objectql": "1.0.2",
15
+ "@objectstack/spec": "1.0.2",
16
+ "@objectstack/types": "1.0.2"
16
17
  },
17
18
  "devDependencies": {
18
19
  "@types/node": "^25.1.0",
19
20
  "typescript": "^5.0.0",
20
21
  "vitest": "^4.0.18",
21
- "@objectstack/runtime": "1.0.0"
22
+ "@objectstack/runtime": "1.0.2"
22
23
  },
23
24
  "scripts": {
24
25
  "build": "tsc",