@canonical/storybook-addon-msw 0.10.0-experimental.4 → 0.11.0

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,9 +1,9 @@
1
- import React, { memo } from "react";
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { memo } from "react";
2
3
  import { AddonPanel, SyntaxHighlighter } from "storybook/internal/components";
3
- import { useParameter, useStorybookState, } from "storybook/internal/manager-api";
4
+ import { useParameter } from "storybook/manager-api";
4
5
  import { PARAM_KEY } from "../constants.js";
5
- export const Panel = memo(function MswPanel({ api, active }) {
6
- const state = useStorybookState();
6
+ export const Panel = memo(function MswPanel({ active }) {
7
7
  const parameter = useParameter(PARAM_KEY);
8
8
  if (!active || !parameter?.handlers) {
9
9
  return null;
@@ -24,14 +24,6 @@ export const Panel = memo(function MswPanel({ api, active }) {
24
24
  description: `Handler ${index + 1}`,
25
25
  };
26
26
  });
27
- return (React.createElement(AddonPanel, { active: active },
28
- React.createElement("div", { style: { padding: "1rem" } },
29
- React.createElement("h3", null, "Active MSW Handlers"),
30
- React.createElement("p", { style: { marginBottom: "1rem", opacity: 0.7 } },
31
- parameter.handlers.length,
32
- " handler",
33
- parameter.handlers.length !== 1 ? "s" : "",
34
- " registered"),
35
- React.createElement(SyntaxHighlighter, { language: "json" }, JSON.stringify(handlerInfo, null, 2)))));
27
+ return (_jsx(AddonPanel, { active: active, children: _jsxs("div", { style: { padding: "1rem" }, children: [_jsx("h3", { children: "Active MSW Handlers" }), _jsxs("p", { style: { marginBottom: "1rem", opacity: 0.7 }, children: [parameter.handlers.length, " handler", parameter.handlers.length !== 1 ? "s" : "", " registered"] }), _jsx(SyntaxHighlighter, { language: "json", children: JSON.stringify(handlerInfo, null, 2) })] }) }));
36
28
  });
37
29
  //# sourceMappingURL=Panel.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Panel.js","sourceRoot":"","sources":["../../../src/components/Panel.tsx"],"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WAAW,KAAK,GAAG,CAAC,EAAE;SACpC,CAAC;IACJ,CAAC,CACF,CAAC;IAEF,OAAO,CACL,KAAC,UAAU,IAAC,MAAM,EAAE,MAAM,YACxB,eAAK,KAAK,EAAE,EAAE,OAAO,EAAE,MAAM,EAAE,aAC7B,+CAA4B,EAC5B,aAAG,KAAK,EAAE,EAAE,YAAY,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,aAC7C,SAAS,CAAC,QAAQ,CAAC,MAAM,cACzB,SAAS,CAAC,QAAQ,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,mBACzC,EACJ,KAAC,iBAAiB,IAAC,QAAQ,EAAC,MAAM,YAC/B,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC,GACnB,IAChB,GACK,CACd,CAAC;AACJ,CAAC,CAAC,CAAC"}
@@ -1,9 +1,10 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
1
2
  import { LightningIcon } from "@storybook/icons";
2
- import React, { memo, useCallback } from "react";
3
+ import { memo, useCallback } from "react";
3
4
  import { IconButton } from "storybook/internal/components";
4
- import { useGlobals } from "storybook/internal/manager-api";
5
+ import { useGlobals } from "storybook/manager-api";
5
6
  import { KEY, TOOL_ID } from "../constants.js";
6
- export const Tool = memo(function MyAddonSelector({ api }) {
7
+ export const Tool = memo(function MyAddonSelector(_props) {
7
8
  const [globals, updateGlobals, storyGlobals] = useGlobals();
8
9
  const isLocked = KEY in storyGlobals;
9
10
  const isActive = !!globals[KEY];
@@ -22,7 +23,6 @@ export const Tool = memo(function MyAddonSelector({ api }) {
22
23
  // action: toggle,
23
24
  // });
24
25
  // }, [toggle, api]);
25
- return (React.createElement(IconButton, { key: TOOL_ID, active: isActive, disabled: isLocked, title: isActive ? "MSW Active" : "MSW Inactive", onClick: toggle },
26
- React.createElement(LightningIcon, null)));
26
+ return (_jsx(IconButton, { active: isActive, disabled: isLocked, title: isActive ? "MSW Active" : "MSW Inactive", onClick: toggle, children: _jsx(LightningIcon, {}) }, TOOL_ID));
27
27
  });
28
28
  //# sourceMappingURL=Tool.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Tool.js","sourceRoot":"","sources":["../../../src/components/Tool.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACjD,OAAO,KAAK,EAAE,EAAE,IAAI,EAAE,WAAW,EAAa,MAAM,OAAO,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAC3D,OAAO,EAAY,UAAU,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,CAAC,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,eAAe,CAAC,EAAE,GAAG,EAAgB;IACrE,MAAM,CAAC,OAAO,EAAE,aAAa,EAAE,YAAY,CAAC,GAAG,UAAU,EAAE,CAAC;IAE5D,MAAM,QAAQ,GAAG,GAAG,IAAI,YAAY,CAAC;IACrC,MAAM,QAAQ,GAAG,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IAEhC,MAAM,MAAM,GAAG,WAAW,CAAC,GAAG,EAAE;QAC9B,aAAa,CAAC;YACZ,CAAC,GAAG,CAAC,EAAE,CAAC,QAAQ;SACjB,CAAC,CAAC;IACL,CAAC,EAAE,CAAC,QAAQ,EAAE,aAAa,CAAC,CAAC,CAAC;IAE9B,6CAA6C;IAC7C,oBAAoB;IACpB,qCAAqC;IACrC,qCAAqC;IACrC,8BAA8B;IAC9B,8BAA8B;IAC9B,yBAAyB;IACzB,sBAAsB;IACtB,QAAQ;IACR,qBAAqB;IAErB,OAAO,CACL,oBAAC,UAAU,IACT,GAAG,EAAE,OAAO,EACZ,MAAM,EAAE,QAAQ,EAChB,QAAQ,EAAE,QAAQ,EAClB,KAAK,EAAE,QA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CAAC,CAAC,CAAC,cAAc,EAC/C,OAAO,EAAE,MAAM,YAEf,KAAC,aAAa,KAAG,IANZ,OAAO,CAOD,CACd,CAAC;AACJ,CAAC,CAAC,CAAC"}
@@ -1,5 +1,5 @@
1
- import React from "react";
2
- import { addons, types } from "storybook/internal/manager-api";
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { addons, types } from "storybook/manager-api";
3
3
  import { Panel } from "./components/Panel.js";
4
4
  import { Tool } from "./components/Tool.js";
5
5
  import { ADDON_ID, PANEL_ID, TOOL_ID } from "./constants.js";
@@ -9,15 +9,15 @@ addons.register(ADDON_ID, (api) => {
9
9
  addons.add(TOOL_ID, {
10
10
  type: types.TOOL,
11
11
  title: "Toggle MSW",
12
- match: ({ viewMode, tabId }) => !!viewMode?.match(/^(story|docs)$/),
13
- render: () => React.createElement(Tool, { api: api }),
12
+ match: ({ viewMode }) => !!viewMode?.match(/^(story|docs)$/),
13
+ render: () => _jsx(Tool, { api: api }),
14
14
  });
15
15
  // Register a panel to show active handlers
16
16
  addons.add(PANEL_ID, {
17
17
  type: types.PANEL,
18
18
  title: "MSW",
19
19
  match: ({ viewMode }) => viewMode === "story",
20
- render: ({ active }) => React.createElement(Panel, { api: api, active: active }),
20
+ render: ({ active }) => (_jsx(Panel, { api: api, active: active })),
21
21
  });
22
22
  });
23
23
  //# sourceMappingURL=manager.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"manager.js","sourceRoot":"","sources":["../../src/manager.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,gCAAgC,CAAC;AAC/D,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AAE7D,qBAAqB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;QAClB,IAAI,EAAE,KAAK,CAAC,IAAI;QAChB,KAAK,EAAE,YAAY;QACnB,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAyC,EAAE,EAAE,CAC7D,CAAC,CAAC,QAAQ,EAAE,KAAK,CAAC,gBAAgB,CAAC;QACrC,MAAM,EAAE,GAAG,EAAE,CAAC,KAAC,IAAI,IAAC,GAAG,EAAE,GAAG,GAAI;KACjC,CAAC,CAAC;IAEH,2CAA2C;IAC3C,MAAM,CAAC,GAAG,CAAC,QAAQ,EAAE;QACnB,IAAI,EAAE,KAAK,CAAC,KAAK;QACjB,KAAK,EAAE,KAAK;QACZ,KAAK,EAAE,CAAC,EAAE,QAAQ,EAAyB,EAAE,EAAE,CAAC,QAAQ,KAAK,OAAO;QACpE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAwB,EAAE,EAAE,CAAC,CAC5C,KAAC,KAAK,IAAC,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,GAAI,CACpC;KACF,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -1,16 +1,10 @@
1
1
  // This entry is a node-specific file, contrary to the other files in this folder which are made to be loaded in the browser.
2
- // You can use presets to augment the Storybook configuration
3
- // You rarely want to do this in addons,
4
- // so often you want to delete this file and remove the reference to it in package.json#exports and package.json#bunder.nodeEntries
5
- // Read more about presets at https://storybook.js.org/docs/addons/writing-presets
6
- // biome-ignore lint: untouched boilerplate
7
- export const viteFinal = async (config) => {
8
- console.log("This addon is augmenting the Vite config");
9
- return config;
10
- };
11
- // biome-ignore lint: untouched boilerplate
12
- export const webpack = async (config) => {
13
- console.log("This addon is augmenting the Webpack config");
14
- return config;
15
- };
2
+ // This preset automatically provides the mockServiceWorker.js to consuming packages.
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const __dirname = dirname(fileURLToPath(import.meta.url));
6
+ // Automatically serve mockServiceWorker.js for packages that include this addon.
7
+ // The public/ folder contains the MSW service worker generated via `npx msw init public/`.
8
+ // This eliminates the need for each consuming package to have its own copy.
9
+ export const staticDirs = [join(__dirname, "../../public")];
16
10
  //# sourceMappingURL=preset.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"preset.js","sourceRoot":"","sources":["../../src/preset.ts"],"names":[],"mappings":"AAAA,6HAA6H;AAE7H,6DAA6D;AAC7D,wCAAwC;AACxC,mIAAmI;AACnI,kFAAkF;AAElF,2CAA2C;AAC3C,MAAM,CAAC,MAAM,SAAS,GAAG,KAAK,EAAE,MAAW,EAAE,EAAE;IAC7C,OAAO,CAAC,GAAG,CAAC,0CAA0C,CAAC,CAAC;IACxD,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAEF,2CAA2C;AAC3C,MAAM,CAAC,MAAM,OAAO,GAAG,KAAK,EAAE,MAAW,EAAE,EAAE;IAC3C,OAAO,CAAC,GAAG,CAAC,6CAA6C,CAAC,CAAC;IAC3D,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC"}
1
+ {"version":3,"file":"preset.js","sourceRoot":"","sources":["../../src/preset.ts"],"names":[],"mappings":"AAAA,6HAA6H;AAC7H,qFAAqF;AAErF,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AAEzC,MAAM,SAAS,GAAG,OAAO,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;AAE1D,iFAAiF;AACjF,2FAA2F;AAC3F,4EAA4E;AAC5E,MAAM,CAAC,MAAM,UAAU,GAAG,CAAC,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,CAAC,CAAC"}
@@ -1,7 +1,6 @@
1
1
  import { setupWorker } from "msw/browser";
2
- // src/withMSW.ts
3
2
  import React from "react";
4
- import { useEffect, useGlobals, useParameter, useState, } from "storybook/internal/preview-api";
3
+ import { useEffect, useGlobals, useParameter, useRef, useState, } from "storybook/internal/preview-api";
5
4
  import { KEY, PARAM_KEY } from "./constants.js";
6
5
  // Singleton worker instance
7
6
  let worker = null;
@@ -13,7 +12,6 @@ const initializeWorker = async () => {
13
12
  serviceWorker: { url: "/mockServiceWorker.js" },
14
13
  onUnhandledRequest: "bypass",
15
14
  });
16
- console.log("Worker initialized and started");
17
15
  workerPromise = Promise.resolve(worker);
18
16
  }
19
17
  return workerPromise;
@@ -25,38 +23,40 @@ export const withMSW = (StoryFn) => {
25
23
  const mswParameter = useParameter(PARAM_KEY);
26
24
  const isEnabled = mswGlobals?.enabled ?? true;
27
25
  const isDisabled = mswParameter?.disable ?? false;
28
- const handlers = mswParameter?.handlers ?? [];
26
+ const handlers = mswParameter?.handlers;
27
+ // Store handlers in a ref to avoid re-running effect on every render
28
+ // The handlers array reference changes on each render even if contents are same
29
+ const handlersRef = useRef(handlers);
30
+ handlersRef.current = handlers;
29
31
  useEffect(() => {
30
- console.log("useEffect running", { isEnabled, isDisabled, handlers });
31
32
  if (!isEnabled || isDisabled) {
32
- setIsWorkerReady(true); // Skip MSW setup and render immediately
33
+ setIsWorkerReady(true);
33
34
  return;
34
35
  }
36
+ let cancelled = false;
35
37
  const setupHandlers = async () => {
36
- console.log("Setting up handlers");
37
38
  const activeWorker = await initializeWorker();
38
- if (activeWorker && handlers.length > 0) {
39
+ if (cancelled)
40
+ return;
41
+ const currentHandlers = handlersRef.current;
42
+ if (currentHandlers && currentHandlers.length > 0) {
39
43
  activeWorker.resetHandlers();
40
- activeWorker.use(...handlers);
41
- console.log("Handlers applied", handlers);
44
+ activeWorker.use(...currentHandlers);
42
45
  }
43
- else if (activeWorker) {
46
+ else {
44
47
  activeWorker.resetHandlers();
45
- console.log("Handlers reset");
46
48
  }
47
- setIsWorkerReady(true); // Signal that setup is complete
49
+ setIsWorkerReady(true);
48
50
  };
49
51
  setupHandlers();
50
52
  return () => {
53
+ cancelled = true;
51
54
  if (worker) {
52
55
  worker.resetHandlers();
53
- console.log("Cleanup: handlers reset");
54
56
  }
55
57
  };
56
- }, [isEnabled, isDisabled, handlers]);
57
- // Delay rendering until the worker is ready
58
+ }, [isEnabled, isDisabled]);
58
59
  if (!isWorkerReady) {
59
- console.log("Waiting for MSW worker...");
60
60
  return React.createElement("div", {}, "Loading MSW...");
61
61
  }
62
62
  return StoryFn();
@@ -1 +1 @@
1
- {"version":3,"file":"withMSW.js","sourceRoot":"","sources":["../../src/withMSW.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,WAAW,EAAE,MAAM,aAAa,CAAC;AAC5D,iBAAiB;AACjB,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EACL,SAAS,EACT,UAAU,EACV,YAAY,EACZ,QAAQ,GACT,MAAM,gCAAgC,CAAC;AAKxC,OAAO,EAAE,GAAG,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAC;AAGhD,4BAA4B;AAC5B,IAAI,MAAM,GAAuB,IAAI,CAAC;AACtC,IAAI,aAAa,GAAgC,IAAI,CAAC;AAEtD,MAAM,gBAAgB,GAAG,KAAK,IAA0B,EAAE;IACxD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,MAAM,GAAG,WAAW,EAAE,CAAC;QACvB,MAAM,MAAM,CAAC,KAAK,CAAC;YACjB,aAAa,EAAE,EAAE,GAAG,EAAE,uBAAuB,EAAE;YAC/C,kBAAkB,EAAE,QAAQ;SAC7B,CAAC,CAAC;QACH,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;QAC9C,aAAa,GAAG,OAAO,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC;IAC1C,CAAC;IACD,OAAO,aAAqC,CAAC;AAC/C,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,OAAgC,EAAE,EAAE;IAC1D,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC1D,MAAM,CAAC,OAAO,CAAC,GAAG,UAAU,EAAE,CAAC;IAC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,EAAE,CAAC;QAEhB,OAAO,GAAG,EAAE;YACV,SAAS,GAAG,IAAI,CAAC;YACjB,IAAI,MAAM,EAAE,CAAC;gBACX,MAAM,CAAC,aAAa,EAAE,CAAC;YACzB,CAAC;QACH,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC,CAAC;IAE5B,IAAI,CAAC,aAAa,EAAE,CAAC;QACnB,OAAO,KAAK,CAAC,aAAa,CAAC,KAAK,EAAE,EAAE,EAAE,gBAAgB,CAAC,CAAC;IAC1D,CAAC;IAED,OAAO,OAAO,EAAE,CAAC;AACnB,CAAC,CAAC"}
@@ -1,9 +1,8 @@
1
- import React from "react";
2
- import { type API } from "storybook/internal/manager-api";
1
+ import { type API } from "storybook/manager-api";
3
2
  interface PanelProps {
4
3
  api: API;
5
4
  active?: boolean;
6
5
  }
7
- export declare const Panel: React.NamedExoticComponent<PanelProps>;
6
+ export declare const Panel: import("react").NamedExoticComponent<PanelProps>;
8
7
  export {};
9
8
  //# sourceMappingURL=Panel.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Panel.d.ts","sourceRoot":"","sources":["../../../src/components/Panel.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAe,MAAM,OAAO,CAAC;AAEpC,OAAO,EACL,KAAK,GAAG,EAGT,MAAM,gCAAgC,CAAC;AAIxC,UAAU,UAAU;IAClB,GAAG,EAAE,GAAG,CAAC;IACT,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,eAAO,MAAM,KAAK,wCAwChB,CAAC"}
1
+ {"version":3,"file":"Panel.d.ts","sourceRoot":"","sources":["../../../src/components/Panel.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,GAAG,EAAgB,MAAM,uBAAuB,CAAC;AAI/D,UAAU,UAAU;IAClB,GAAG,EAAE,GAAG,CAAC;IACT,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB;AAED,eAAO,MAAM,KAAK,kDAyChB,CAAC"}
@@ -1,6 +1,5 @@
1
- import React from "react";
2
- import { type API } from "storybook/internal/manager-api";
3
- export declare const Tool: React.NamedExoticComponent<{
1
+ import { type API } from "storybook/manager-api";
2
+ export declare const Tool: import("react").NamedExoticComponent<{
4
3
  api: API;
5
4
  }>;
6
5
  //# sourceMappingURL=Tool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Tool.d.ts","sourceRoot":"","sources":["../../../src/components/Tool.tsx"],"names":[],"mappings":"AACA,OAAO,KAAuC,MAAM,OAAO,CAAC;AAE5D,OAAO,EAAE,KAAK,GAAG,EAAc,MAAM,gCAAgC,CAAC;AAGtE,eAAO,MAAM,IAAI;SAAiD,GAAG;EAkCnE,CAAC"}
1
+ {"version":3,"file":"Tool.d.ts","sourceRoot":"","sources":["../../../src/components/Tool.tsx"],"names":[],"mappings":"AAGA,OAAO,EAAE,KAAK,GAAG,EAAc,MAAM,uBAAuB,CAAC;AAG7D,eAAO,MAAM,IAAI;SAAgD,GAAG;EAkClE,CAAC"}
@@ -1,3 +1,2 @@
1
- export declare const viteFinal: (config: any) => Promise<any>;
2
- export declare const webpack: (config: any) => Promise<any>;
1
+ export declare const staticDirs: string[];
3
2
  //# sourceMappingURL=preset.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"preset.d.ts","sourceRoot":"","sources":["../../src/preset.ts"],"names":[],"mappings":"AAQA,eAAO,MAAM,SAAS,GAAU,QAAQ,GAAG,iBAG1C,CAAC;AAGF,eAAO,MAAM,OAAO,GAAU,QAAQ,GAAG,iBAGxC,CAAC"}
1
+ {"version":3,"file":"preset.d.ts","sourceRoot":"","sources":["../../src/preset.ts"],"names":[],"mappings":"AAWA,eAAO,MAAM,UAAU,UAAoC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"withMSW.d.ts","sourceRoot":"","sources":["../../src/withMSW.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EACV,QAAQ,EACR,cAAc,IAAI,aAAa,EAChC,MAAM,0BAA0B,CAAC;AAqBlC,eAAO,MAAM,OAAO,GAAI,SAAS,aAAa,CAAC,QAAQ,CAAC,QA+CvD,CAAC"}
1
+ {"version":3,"file":"withMSW.d.ts","sourceRoot":"","sources":["../../src/withMSW.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EACV,QAAQ,EACR,cAAc,IAAI,aAAa,EAChC,MAAM,0BAA0B,CAAC;AAoBlC,eAAO,MAAM,OAAO,GAAI,SAAS,aAAa,CAAC,QAAQ,CAAC,QAoDvD,CAAC"}
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@canonical/storybook-addon-msw",
3
- "version": "0.10.0-experimental.4",
3
+ "version": "0.11.0",
4
4
  "type": "module",
5
5
  "files": [
6
- "dist"
6
+ "dist",
7
+ "public"
7
8
  ],
8
9
  "types": "dist/types/index.d.ts",
9
10
  "author": {
@@ -43,26 +44,26 @@
43
44
  "check:ts": "tsc --noEmit"
44
45
  },
45
46
  "dependencies": {
46
- "@canonical/styles-debug": "^0.10.0-experimental.4",
47
- "@storybook/icons": "^1.2.10"
47
+ "@canonical/styles-debug": "^0.11.0",
48
+ "@storybook/icons": "^2.0.1"
48
49
  },
49
50
  "devDependencies": {
50
- "@biomejs/biome": "2.2.4",
51
- "@canonical/biome-config": "^0.10.0-experimental.4",
52
- "@canonical/typescript-config-react": "^0.10.0-experimental.4",
51
+ "@biomejs/biome": "2.3.11",
52
+ "@canonical/biome-config": "^0.11.0",
53
+ "@canonical/typescript-config-react": "^0.11.0",
53
54
  "@types/node": "^24.0.0",
54
- "@types/react": "^19.1.8",
55
- "@types/react-dom": "^19.1.6",
56
- "@vitejs/plugin-react": "^5.0.0",
57
- "msw": "^2.10.2",
58
- "react": "^19.1.0",
59
- "react-dom": "^19.1.0",
60
- "storybook": "^9.0.8",
61
- "typescript": "^5.8.3",
62
- "vite": "^7.0.0"
55
+ "@types/react": "^19.2.8",
56
+ "@types/react-dom": "^19.2.3",
57
+ "@vitejs/plugin-react": "^5.1.2",
58
+ "msw": "^2.12.7",
59
+ "react": "^19.2.3",
60
+ "react-dom": "^19.2.3",
61
+ "storybook": "^10.1.11",
62
+ "typescript": "^5.9.3",
63
+ "vite": "^7.3.1"
63
64
  },
64
65
  "peerDependencies": {
65
- "storybook": "^9.0.8"
66
+ "storybook": "^10.1.11"
66
67
  },
67
68
  "storybook": {
68
69
  "displayName": "DS Baseline Grid",
@@ -84,5 +85,5 @@
84
85
  "public"
85
86
  ]
86
87
  },
87
- "gitHead": "2c35cfbe5527808f3d612a1c683da1b113861e3d"
88
+ "gitHead": "29125736059d1880b3d0fc277b218a63a2574f28"
88
89
  }
@@ -0,0 +1,349 @@
1
+ /* eslint-disable */
2
+ /* tslint:disable */
3
+
4
+ /**
5
+ * Mock Service Worker.
6
+ * @see https://github.com/mswjs/msw
7
+ * - Please do NOT modify this file.
8
+ */
9
+
10
+ const PACKAGE_VERSION = '2.12.7'
11
+ const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
12
+ const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
13
+ const activeClientIds = new Set()
14
+
15
+ addEventListener('install', function () {
16
+ self.skipWaiting()
17
+ })
18
+
19
+ addEventListener('activate', function (event) {
20
+ event.waitUntil(self.clients.claim())
21
+ })
22
+
23
+ addEventListener('message', async function (event) {
24
+ const clientId = Reflect.get(event.source || {}, 'id')
25
+
26
+ if (!clientId || !self.clients) {
27
+ return
28
+ }
29
+
30
+ const client = await self.clients.get(clientId)
31
+
32
+ if (!client) {
33
+ return
34
+ }
35
+
36
+ const allClients = await self.clients.matchAll({
37
+ type: 'window',
38
+ })
39
+
40
+ switch (event.data) {
41
+ case 'KEEPALIVE_REQUEST': {
42
+ sendToClient(client, {
43
+ type: 'KEEPALIVE_RESPONSE',
44
+ })
45
+ break
46
+ }
47
+
48
+ case 'INTEGRITY_CHECK_REQUEST': {
49
+ sendToClient(client, {
50
+ type: 'INTEGRITY_CHECK_RESPONSE',
51
+ payload: {
52
+ packageVersion: PACKAGE_VERSION,
53
+ checksum: INTEGRITY_CHECKSUM,
54
+ },
55
+ })
56
+ break
57
+ }
58
+
59
+ case 'MOCK_ACTIVATE': {
60
+ activeClientIds.add(clientId)
61
+
62
+ sendToClient(client, {
63
+ type: 'MOCKING_ENABLED',
64
+ payload: {
65
+ client: {
66
+ id: client.id,
67
+ frameType: client.frameType,
68
+ },
69
+ },
70
+ })
71
+ break
72
+ }
73
+
74
+ case 'CLIENT_CLOSED': {
75
+ activeClientIds.delete(clientId)
76
+
77
+ const remainingClients = allClients.filter((client) => {
78
+ return client.id !== clientId
79
+ })
80
+
81
+ // Unregister itself when there are no more clients
82
+ if (remainingClients.length === 0) {
83
+ self.registration.unregister()
84
+ }
85
+
86
+ break
87
+ }
88
+ }
89
+ })
90
+
91
+ addEventListener('fetch', function (event) {
92
+ const requestInterceptedAt = Date.now()
93
+
94
+ // Bypass navigation requests.
95
+ if (event.request.mode === 'navigate') {
96
+ return
97
+ }
98
+
99
+ // Opening the DevTools triggers the "only-if-cached" request
100
+ // that cannot be handled by the worker. Bypass such requests.
101
+ if (
102
+ event.request.cache === 'only-if-cached' &&
103
+ event.request.mode !== 'same-origin'
104
+ ) {
105
+ return
106
+ }
107
+
108
+ // Bypass all requests when there are no active clients.
109
+ // Prevents the self-unregistered worked from handling requests
110
+ // after it's been terminated (still remains active until the next reload).
111
+ if (activeClientIds.size === 0) {
112
+ return
113
+ }
114
+
115
+ const requestId = crypto.randomUUID()
116
+ event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
117
+ })
118
+
119
+ /**
120
+ * @param {FetchEvent} event
121
+ * @param {string} requestId
122
+ * @param {number} requestInterceptedAt
123
+ */
124
+ async function handleRequest(event, requestId, requestInterceptedAt) {
125
+ const client = await resolveMainClient(event)
126
+ const requestCloneForEvents = event.request.clone()
127
+ const response = await getResponse(
128
+ event,
129
+ client,
130
+ requestId,
131
+ requestInterceptedAt,
132
+ )
133
+
134
+ // Send back the response clone for the "response:*" life-cycle events.
135
+ // Ensure MSW is active and ready to handle the message, otherwise
136
+ // this message will pend indefinitely.
137
+ if (client && activeClientIds.has(client.id)) {
138
+ const serializedRequest = await serializeRequest(requestCloneForEvents)
139
+
140
+ // Clone the response so both the client and the library could consume it.
141
+ const responseClone = response.clone()
142
+
143
+ sendToClient(
144
+ client,
145
+ {
146
+ type: 'RESPONSE',
147
+ payload: {
148
+ isMockedResponse: IS_MOCKED_RESPONSE in response,
149
+ request: {
150
+ id: requestId,
151
+ ...serializedRequest,
152
+ },
153
+ response: {
154
+ type: responseClone.type,
155
+ status: responseClone.status,
156
+ statusText: responseClone.statusText,
157
+ headers: Object.fromEntries(responseClone.headers.entries()),
158
+ body: responseClone.body,
159
+ },
160
+ },
161
+ },
162
+ responseClone.body ? [serializedRequest.body, responseClone.body] : [],
163
+ )
164
+ }
165
+
166
+ return response
167
+ }
168
+
169
+ /**
170
+ * Resolve the main client for the given event.
171
+ * Client that issues a request doesn't necessarily equal the client
172
+ * that registered the worker. It's with the latter the worker should
173
+ * communicate with during the response resolving phase.
174
+ * @param {FetchEvent} event
175
+ * @returns {Promise<Client | undefined>}
176
+ */
177
+ async function resolveMainClient(event) {
178
+ const client = await self.clients.get(event.clientId)
179
+
180
+ if (activeClientIds.has(event.clientId)) {
181
+ return client
182
+ }
183
+
184
+ if (client?.frameType === 'top-level') {
185
+ return client
186
+ }
187
+
188
+ const allClients = await self.clients.matchAll({
189
+ type: 'window',
190
+ })
191
+
192
+ return allClients
193
+ .filter((client) => {
194
+ // Get only those clients that are currently visible.
195
+ return client.visibilityState === 'visible'
196
+ })
197
+ .find((client) => {
198
+ // Find the client ID that's recorded in the
199
+ // set of clients that have registered the worker.
200
+ return activeClientIds.has(client.id)
201
+ })
202
+ }
203
+
204
+ /**
205
+ * @param {FetchEvent} event
206
+ * @param {Client | undefined} client
207
+ * @param {string} requestId
208
+ * @param {number} requestInterceptedAt
209
+ * @returns {Promise<Response>}
210
+ */
211
+ async function getResponse(event, client, requestId, requestInterceptedAt) {
212
+ // Clone the request because it might've been already used
213
+ // (i.e. its body has been read and sent to the client).
214
+ const requestClone = event.request.clone()
215
+
216
+ function passthrough() {
217
+ // Cast the request headers to a new Headers instance
218
+ // so the headers can be manipulated with.
219
+ const headers = new Headers(requestClone.headers)
220
+
221
+ // Remove the "accept" header value that marked this request as passthrough.
222
+ // This prevents request alteration and also keeps it compliant with the
223
+ // user-defined CORS policies.
224
+ const acceptHeader = headers.get('accept')
225
+ if (acceptHeader) {
226
+ const values = acceptHeader.split(',').map((value) => value.trim())
227
+ const filteredValues = values.filter(
228
+ (value) => value !== 'msw/passthrough',
229
+ )
230
+
231
+ if (filteredValues.length > 0) {
232
+ headers.set('accept', filteredValues.join(', '))
233
+ } else {
234
+ headers.delete('accept')
235
+ }
236
+ }
237
+
238
+ return fetch(requestClone, { headers })
239
+ }
240
+
241
+ // Bypass mocking when the client is not active.
242
+ if (!client) {
243
+ return passthrough()
244
+ }
245
+
246
+ // Bypass initial page load requests (i.e. static assets).
247
+ // The absence of the immediate/parent client in the map of the active clients
248
+ // means that MSW hasn't dispatched the "MOCK_ACTIVATE" event yet
249
+ // and is not ready to handle requests.
250
+ if (!activeClientIds.has(client.id)) {
251
+ return passthrough()
252
+ }
253
+
254
+ // Notify the client that a request has been intercepted.
255
+ const serializedRequest = await serializeRequest(event.request)
256
+ const clientMessage = await sendToClient(
257
+ client,
258
+ {
259
+ type: 'REQUEST',
260
+ payload: {
261
+ id: requestId,
262
+ interceptedAt: requestInterceptedAt,
263
+ ...serializedRequest,
264
+ },
265
+ },
266
+ [serializedRequest.body],
267
+ )
268
+
269
+ switch (clientMessage.type) {
270
+ case 'MOCK_RESPONSE': {
271
+ return respondWithMock(clientMessage.data)
272
+ }
273
+
274
+ case 'PASSTHROUGH': {
275
+ return passthrough()
276
+ }
277
+ }
278
+
279
+ return passthrough()
280
+ }
281
+
282
+ /**
283
+ * @param {Client} client
284
+ * @param {any} message
285
+ * @param {Array<Transferable>} transferrables
286
+ * @returns {Promise<any>}
287
+ */
288
+ function sendToClient(client, message, transferrables = []) {
289
+ return new Promise((resolve, reject) => {
290
+ const channel = new MessageChannel()
291
+
292
+ channel.port1.onmessage = (event) => {
293
+ if (event.data && event.data.error) {
294
+ return reject(event.data.error)
295
+ }
296
+
297
+ resolve(event.data)
298
+ }
299
+
300
+ client.postMessage(message, [
301
+ channel.port2,
302
+ ...transferrables.filter(Boolean),
303
+ ])
304
+ })
305
+ }
306
+
307
+ /**
308
+ * @param {Response} response
309
+ * @returns {Response}
310
+ */
311
+ function respondWithMock(response) {
312
+ // Setting response status code to 0 is a no-op.
313
+ // However, when responding with a "Response.error()", the produced Response
314
+ // instance will have status code set to 0. Since it's not possible to create
315
+ // a Response instance with status code 0, handle that use-case separately.
316
+ if (response.status === 0) {
317
+ return Response.error()
318
+ }
319
+
320
+ const mockedResponse = new Response(response.body, response)
321
+
322
+ Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
323
+ value: true,
324
+ enumerable: true,
325
+ })
326
+
327
+ return mockedResponse
328
+ }
329
+
330
+ /**
331
+ * @param {Request} request
332
+ */
333
+ async function serializeRequest(request) {
334
+ return {
335
+ url: request.url,
336
+ mode: request.mode,
337
+ method: request.method,
338
+ headers: Object.fromEntries(request.headers.entries()),
339
+ cache: request.cache,
340
+ credentials: request.credentials,
341
+ destination: request.destination,
342
+ integrity: request.integrity,
343
+ redirect: request.redirect,
344
+ referrer: request.referrer,
345
+ referrerPolicy: request.referrerPolicy,
346
+ body: await request.arrayBuffer(),
347
+ keepalive: request.keepalive,
348
+ }
349
+ }