@storybook/addon-vitest 11.0.0-alpha.7 → 11.0.0-alpha.9

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,38 +1,37 @@
1
- import CJS_COMPAT_NODE_URL_mcj5sbv12wm from 'node:url';
2
- import CJS_COMPAT_NODE_PATH_mcj5sbv12wm from 'node:path';
3
- import CJS_COMPAT_NODE_MODULE_mcj5sbv12wm from "node:module";
1
+ import CJS_COMPAT_NODE_URL_924otrl8p9j from 'node:url';
2
+ import CJS_COMPAT_NODE_PATH_924otrl8p9j from 'node:path';
3
+ import CJS_COMPAT_NODE_MODULE_924otrl8p9j from "node:module";
4
4
 
5
- var __filename = CJS_COMPAT_NODE_URL_mcj5sbv12wm.fileURLToPath(import.meta.url);
6
- var __dirname = CJS_COMPAT_NODE_PATH_mcj5sbv12wm.dirname(__filename);
7
- var require = CJS_COMPAT_NODE_MODULE_mcj5sbv12wm.createRequire(import.meta.url);
5
+ var __filename = CJS_COMPAT_NODE_URL_924otrl8p9j.fileURLToPath(import.meta.url);
6
+ var __dirname = CJS_COMPAT_NODE_PATH_924otrl8p9j.dirname(__filename);
7
+ var require = CJS_COMPAT_NODE_MODULE_924otrl8p9j.createRequire(import.meta.url);
8
8
 
9
9
  // ------------------------------------------------------------
10
10
  // end of CJS compatibility banner, injected by Storybook's esbuild configuration
11
11
  // ------------------------------------------------------------
12
12
  import {
13
13
  any
14
- } from "./_node-chunks/chunk-ZBTRLSUY.js";
14
+ } from "./_node-chunks/chunk-UHQDBOIF.js";
15
15
  import {
16
16
  require_dist
17
- } from "./_node-chunks/chunk-P3WCWO47.js";
17
+ } from "./_node-chunks/chunk-ADERN52X.js";
18
18
  import {
19
19
  dirname,
20
20
  normalize,
21
21
  relative,
22
22
  resolve
23
- } from "./_node-chunks/chunk-R32VM5JX.js";
23
+ } from "./_node-chunks/chunk-S7MCOM2G.js";
24
24
  import {
25
25
  DOCUMENTATION_LINK
26
- } from "./_node-chunks/chunk-ZGV2ODKH.js";
26
+ } from "./_node-chunks/chunk-TS3UCOL3.js";
27
27
  import {
28
28
  __toESM
29
- } from "./_node-chunks/chunk-I4KLCFNQ.js";
29
+ } from "./_node-chunks/chunk-RI2UTKDA.js";
30
30
 
31
31
  // src/postinstall.ts
32
32
  import * as fs from "node:fs/promises";
33
33
  import { writeFile } from "node:fs/promises";
34
34
  import os from "node:os";
35
- import { babelParse as babelParse2, generate as generate2, traverse as traverse2 } from "storybook/internal/babel";
36
35
  import { AddonVitestService } from "storybook/internal/cli";
37
36
  import {
38
37
  JsPackageManagerFactory,
@@ -40,6 +39,12 @@ import {
40
39
  getProjectRoot,
41
40
  getStorybookInfo
42
41
  } from "storybook/internal/common";
42
+ import {
43
+ SourceEditor as SourceEditor3,
44
+ parseModule,
45
+ restoreLineEndings,
46
+ walk as walk2
47
+ } from "storybook/internal/csf-tools";
43
48
  import { CLI_COLORS } from "storybook/internal/node-logger";
44
49
  import {
45
50
  AddonVitestPostinstallConfigUpdateError,
@@ -51,302 +56,280 @@ var import_ts_dedent = __toESM(require_dist(), 1);
51
56
 
52
57
  // src/angular-vitest-postinstall.ts
53
58
  import {
54
- babelParse,
55
- generate,
56
- traverse,
57
- types as t
58
- } from "storybook/internal/babel";
59
+ SourceEditor,
60
+ arrayList,
61
+ insertAfterImports,
62
+ prependToList,
63
+ printString,
64
+ walk
65
+ } from "storybook/internal/csf-tools";
59
66
  var ANGULAR_VITEST_IMPORT_SOURCE = "@storybook/angular-vite/vitest", ANGULAR_VITEST_PLUGIN_CALL = "storybookAngularVitest", STORYBOOK_TEST_PLUGIN_SOURCE = "@storybook/addon-vitest/vitest-plugin", STORYBOOK_TEST_PLUGIN_CALL = "storybookTest";
60
67
  function isAngularVitestAlreadyWired(content) {
61
68
  return content.includes(ANGULAR_VITEST_IMPORT_SOURCE) || content.includes(`${ANGULAR_VITEST_PLUGIN_CALL}(`);
62
69
  }
63
- function collectStorybookTestLocalNames(ast) {
70
+ function collectStorybookTestLocalNames(program) {
64
71
  let names = /* @__PURE__ */ new Set([STORYBOOK_TEST_PLUGIN_CALL]);
65
- return traverse(ast, {
66
- ImportDeclaration(path) {
67
- path.node.source.value === STORYBOOK_TEST_PLUGIN_SOURCE && path.node.specifiers.forEach((specifier) => {
68
- "local" in specifier && specifier.local?.name && names.add(specifier.local.name);
69
- });
70
- }
71
- }), names;
72
- }
73
- function ensureImport(ast) {
74
- let hasImport = !1;
75
- if (traverse(ast, {
76
- ImportDeclaration(path) {
77
- if (path.node.source.value !== ANGULAR_VITEST_IMPORT_SOURCE)
78
- return;
79
- path.node.specifiers.some(
80
- (specifier) => specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === ANGULAR_VITEST_PLUGIN_CALL
81
- ) && (hasImport = !0, path.stop());
82
- }
83
- }), hasImport)
84
- return;
85
- let importDecl = t.importDeclaration(
86
- [
87
- t.importSpecifier(
88
- t.identifier(ANGULAR_VITEST_PLUGIN_CALL),
89
- t.identifier(ANGULAR_VITEST_PLUGIN_CALL)
90
- )
91
- ],
92
- t.stringLiteral(ANGULAR_VITEST_IMPORT_SOURCE)
93
- ), lastImportIndex = ast.program.body.findLastIndex((n) => n.type === "ImportDeclaration");
94
- ast.program.body.splice(lastImportIndex + 1, 0, importDecl);
95
- }
96
- function buildAngularVitestCall() {
97
- let call = t.callExpression(t.identifier(ANGULAR_VITEST_PLUGIN_CALL), [t.objectExpression([])]);
98
- return t.addComment(
99
- call,
100
- "leading",
101
- " Forwards Angular build options (styles, assets, zoneless, \u2026) into standalone vitest runs",
102
- !0
103
- ), call;
72
+ for (let node of program.body)
73
+ node.type === "ImportDeclaration" && node.source.value === STORYBOOK_TEST_PLUGIN_SOURCE && node.specifiers.forEach((specifier) => names.add(specifier.local.name));
74
+ return names;
104
75
  }
105
- function arrayHasAngularVitest(array) {
106
- return array.elements.some(
107
- (el) => el?.type === "CallExpression" && el.callee.type === "Identifier" && el.callee.name === ANGULAR_VITEST_PLUGIN_CALL
108
- );
109
- }
110
- function injectAngularVitestIntoAst(ast) {
111
- let localNames = collectStorybookTestLocalNames(ast), pluginsArray = null;
112
- if (traverse(ast, {
113
- CallExpression(path) {
114
- if (pluginsArray) {
115
- path.stop();
116
- return;
117
- }
118
- let { callee } = path.node;
119
- callee.type === "Identifier" && localNames.has(callee.name) && path.parentPath.isArrayExpression() && (pluginsArray = path.parentPath.node, path.stop());
120
- }
76
+ var hasAngularVitestImport = (program) => program.body.some(
77
+ (node) => node.type === "ImportDeclaration" && node.source.value === ANGULAR_VITEST_IMPORT_SOURCE && node.specifiers.some(
78
+ (specifier) => specifier.type === "ImportSpecifier" && specifier.imported.type === "Identifier" && specifier.imported.name === ANGULAR_VITEST_PLUGIN_CALL
79
+ )
80
+ ), isCallTo = (node, names) => node?.type === "CallExpression" && node.callee.type === "Identifier" && names.has(node.callee.name);
81
+ function injectAngularVitestIntoEditor(editor) {
82
+ let { program } = editor, localNames = collectStorybookTestLocalNames(program), pluginsArray;
83
+ if (walk(program, (node, parent) => {
84
+ if (pluginsArray)
85
+ return !1;
86
+ parent?.type === "ArrayExpression" && isCallTo(node, localNames) && (pluginsArray = parent);
121
87
  }), !pluginsArray)
122
88
  return !1;
123
- let array = pluginsArray;
124
- return arrayHasAngularVitest(array) || array.elements.unshift(buildAngularVitestCall()), ensureImport(ast), !0;
89
+ let bridge = /* @__PURE__ */ new Set([ANGULAR_VITEST_PLUGIN_CALL]);
90
+ if (pluginsArray.elements.some((element) => isCallTo(element, bridge)) || prependToList(editor, arrayList(editor, pluginsArray), [
91
+ `// Forwards Angular build options (styles, assets, zoneless, \u2026) into standalone vitest runs
92
+ ${ANGULAR_VITEST_PLUGIN_CALL}({})`
93
+ ]), !hasAngularVitestImport(program)) {
94
+ let statement = `import { ${ANGULAR_VITEST_PLUGIN_CALL} } from ${printString(ANGULAR_VITEST_IMPORT_SOURCE, editor.quote)};`;
95
+ insertAfterImports(editor, statement);
96
+ }
97
+ return !0;
125
98
  }
126
- function injectAngularVitestIntoConfig(content) {
127
- let ast;
99
+ function injectAngularVitestIntoConfig(content, fileName) {
100
+ let editor;
128
101
  try {
129
- ast = babelParse(content);
102
+ editor = new SourceEditor(content, fileName);
130
103
  } catch {
131
104
  return null;
132
105
  }
133
- return injectAngularVitestIntoAst(ast) ? generate(ast).code : null;
106
+ return injectAngularVitestIntoEditor(editor) ? editor.toString() : null;
134
107
  }
135
108
 
136
109
  // src/updateVitestFile.ts
110
+ import { isBuiltin } from "node:module";
137
111
  import {
112
+ findExportDefault,
138
113
  getConfigObjectFromMergeArg,
139
114
  getEffectiveMergeConfigCall,
140
115
  getTargetConfigObject,
141
- isDefineConfigLike,
142
116
  resolveExpression
143
- } from "storybook/internal/babel";
117
+ } from "storybook/internal/cli";
118
+ import {
119
+ SourceEditor as SourceEditor2,
120
+ appendToList,
121
+ arrayList as arrayList2,
122
+ insertAfterImports as insertAfterImports2,
123
+ itemText,
124
+ lineIndent,
125
+ reindent,
126
+ objectList,
127
+ prependToList as prependToList2,
128
+ printMembers,
129
+ statementSpan,
130
+ staticKey
131
+ } from "storybook/internal/csf-tools";
144
132
  async function getTemplatePath() {
145
- return import("./_node-chunks/vitest.config.4.template-MHVHJLPK.js");
133
+ return import("./_node-chunks/vitest.config.4.template-E6OQDFNU.js");
146
134
  }
147
135
  var loadTemplate = async (name, replacements) => {
148
136
  let template = (await getTemplatePath()).default;
149
137
  return Object.entries(replacements).forEach(
150
138
  ([key, value]) => template = template.replace(key, normalize(value))
151
139
  ), template;
152
- }, mergeProperties = (source, target) => {
153
- for (let sourceProp of source)
154
- if (sourceProp.type === "ObjectProperty") {
155
- let targetProp = target.find(
156
- (p) => sourceProp.key.type === "Identifier" && p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === sourceProp.key.name
157
- );
158
- targetProp && targetProp.type === "ObjectProperty" ? sourceProp.value.type === "ObjectExpression" && targetProp.value.type === "ObjectExpression" ? mergeProperties(sourceProp.value.properties, targetProp.value.properties) : sourceProp.value.type === "ArrayExpression" && targetProp.value.type === "ArrayExpression" ? targetProp.value.elements.push(...sourceProp.value.elements) : targetProp.value = sourceProp.value : target.push(sourceProp);
140
+ }, findNamedProp = (members, name) => members.find(
141
+ (member) => member.type === "Property" && !member.method && member.kind === "init" && staticKey(member) === name
142
+ ), isProjectsArrayProp = (member) => staticKey(member) === "projects" && member.value.type === "ArrayExpression", memberTexts = (editor, object, members) => members.map((member) => itemText(editor, objectList(editor, object), member)), elementTexts = (editor, array) => arrayList2(editor, array).items.map(
143
+ (element) => itemText(editor, arrayList2(editor, array), element)
144
+ ), mergeProperties = ({ source, target }, from, into, fromMembers = from.properties) => {
145
+ let appended = [];
146
+ for (let sourceProp of fromMembers) {
147
+ let name = staticKey(sourceProp);
148
+ if (!name)
149
+ continue;
150
+ let targetProp = findNamedProp(into.properties, name);
151
+ if (!targetProp) {
152
+ appended.push(...memberTexts(source, from, [sourceProp]));
153
+ continue;
159
154
  }
160
- }, resolveTestPropValue = (testProp, ast) => {
161
- if (testProp.value.type === "ObjectExpression")
162
- return testProp.value;
163
- let resolved = resolveExpression(testProp.value, ast);
164
- return resolved?.type === "ObjectExpression" ? resolved : null;
165
- }, findNamedProp = (properties, name) => properties.find(
166
- (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === name
167
- ), isProjectsArrayProp = (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "projects" && p.value.type === "ArrayExpression", appendToExistingProjectRefs = (existingProjectRefsProp, resolvedTestValue, templateTestProp, properties, targetConfigObject) => {
168
- if (templateTestProp && templateTestProp.value.type === "ObjectExpression") {
169
- let templateProjectRefsProp = templateTestProp.value.properties.find(
170
- (p) => isProjectsArrayProp(p)
171
- );
172
- templateProjectRefsProp && templateProjectRefsProp.value.type === "ArrayExpression" && existingProjectRefsProp.value.elements.push(
173
- ...templateProjectRefsProp.value.elements
155
+ let { value: sourceValue } = sourceProp, { value: targetValue } = targetProp;
156
+ sourceValue.type === "ObjectExpression" && targetValue.type === "ObjectExpression" ? mergeProperties({ source, target }, sourceValue, targetValue) : sourceValue.type === "ArrayExpression" && targetValue.type === "ArrayExpression" ? appendToList(target, arrayList2(target, targetValue), elementTexts(source, sourceValue)) : targetProp.shorthand ? target.edits.overwrite(
157
+ targetProp.start,
158
+ targetProp.end,
159
+ `${name}: ${source.source(sourceValue)}`
160
+ ) : target.edits.overwrite(targetValue.start, targetValue.end, source.source(sourceValue));
161
+ }
162
+ appended.length > 0 && appendToList(target, objectList(target, into), appended);
163
+ }, appendToExistingProjects = (merge, existingProjects, testObject, templateConfig, targetConfig) => {
164
+ let templateTest = findNamedProp(templateConfig.properties, "test");
165
+ if (templateTest?.value.type === "ObjectExpression") {
166
+ let templateTestObject = templateTest.value, templateProjects = templateTestObject.properties.find(isProjectsArrayProp);
167
+ templateProjects && appendToList(
168
+ merge.target,
169
+ arrayList2(merge.target, existingProjects),
170
+ elementTexts(merge.source, templateProjects.value)
174
171
  );
175
- let existingTestPropNames = new Set(
176
- resolvedTestValue.properties.filter(
177
- (p) => p.type === "ObjectProperty" && p.key.type === "Identifier"
178
- ).map((p) => p.key.name)
172
+ let existingNames = new Set(testObject.properties.map(staticKey)), added = templateTestObject.properties.filter((member) => {
173
+ let name = staticKey(member);
174
+ return name !== void 0 && name !== "projects" && !existingNames.has(name);
175
+ });
176
+ added.length > 0 && appendToList(
177
+ merge.target,
178
+ objectList(merge.target, testObject),
179
+ memberTexts(merge.source, templateTestObject, added)
179
180
  );
180
- for (let templateProp of templateTestProp.value.properties)
181
- templateProp.type === "ObjectProperty" && templateProp.key.type === "Identifier" && templateProp.key.name !== "projects" && !existingTestPropNames.has(templateProp.key.name) && resolvedTestValue.properties.push(templateProp);
182
181
  }
183
- let otherTemplateProps = properties.filter(
184
- (p) => !(p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "test")
182
+ mergeProperties(
183
+ merge,
184
+ templateConfig,
185
+ targetConfig,
186
+ templateConfig.properties.filter((member) => staticKey(member) !== "test")
185
187
  );
186
- otherTemplateProps.length > 0 && mergeProperties(otherTemplateProps, targetConfigObject.properties);
187
- }, wrapTestConfigAsProject = (resolvedTestValue, existingTestProp, templateTestProp, properties, targetConfigObject) => {
188
- let projectsProp = templateTestProp.value.type === "ObjectExpression" ? templateTestProp.value.properties.find((p) => isProjectsArrayProp(p)) : void 0;
189
- if (!projectsProp || projectsProp.value.type !== "ArrayExpression") {
190
- mergeProperties(properties, targetConfigObject.properties);
188
+ }, TOP_LEVEL_TEST_PROPERTIES = [
189
+ "shard",
190
+ "watch",
191
+ "run",
192
+ "cache",
193
+ "update",
194
+ "reporters",
195
+ "outputFile",
196
+ "teardownTimeout",
197
+ "silent",
198
+ "forceRerunTriggers",
199
+ "testNamePattern",
200
+ "ui",
201
+ "open",
202
+ "uiBase",
203
+ "snapshotFormat",
204
+ "resolveSnapshotPath",
205
+ "passWithNoTests",
206
+ "onConsoleLog",
207
+ "onStackTrace",
208
+ "dangerouslyIgnoreUnhandledErrors",
209
+ "slowTestThreshold",
210
+ "inspect",
211
+ "inspectBrk",
212
+ "coverage",
213
+ "watchTriggerPatterns"
214
+ ], wrapTestConfigAsProject = (merge, existingTest, testObject, templateConfig, targetConfig) => {
215
+ let { source, target } = merge, templateTestObject = findNamedProp(templateConfig().properties, "test").value, templateProjects = templateTestObject.properties.find(isProjectsArrayProp);
216
+ if (!templateProjects) {
217
+ mergeProperties(merge, templateConfig(), targetConfig);
191
218
  return;
192
219
  }
193
- let topLevelProps = [
194
- "shard",
195
- "watch",
196
- "run",
197
- "cache",
198
- "update",
199
- "reporters",
200
- "outputFile",
201
- "teardownTimeout",
202
- "silent",
203
- "forceRerunTriggers",
204
- "testNamePattern",
205
- "ui",
206
- "open",
207
- "uiBase",
208
- "snapshotFormat",
209
- "resolveSnapshotPath",
210
- "passWithNoTests",
211
- "onConsoleLog",
212
- "onStackTrace",
213
- "dangerouslyIgnoreUnhandledErrors",
214
- "slowTestThreshold",
215
- "inspect",
216
- "inspectBrk",
217
- "coverage",
218
- "watchTriggerPatterns"
219
- ].map(
220
- (name) => findNamedProp(resolvedTestValue.properties, name)
221
- ).filter(Boolean), topLevelPropSet = new Set(topLevelProps), projectTestProps = resolvedTestValue.properties.filter(
222
- (p) => !topLevelPropSet.has(p)
223
- ), existingTestProject = {
224
- type: "ObjectExpression",
225
- properties: [
226
- {
227
- type: "ObjectProperty",
228
- key: { type: "Identifier", name: "extends" },
229
- value: { type: "BooleanLiteral", value: !0 },
230
- computed: !1,
231
- shorthand: !1
232
- },
233
- {
234
- type: "ObjectProperty",
235
- key: { type: "Identifier", name: "test" },
236
- value: {
237
- type: "ObjectExpression",
238
- properties: projectTestProps
239
- },
240
- computed: !1,
241
- shorthand: !1
242
- }
243
- ]
244
- };
245
- projectsProp.value.elements.unshift(existingTestProject), targetConfigObject.properties = targetConfigObject.properties.filter(
246
- (p) => p !== existingTestProp
247
- ), topLevelProps.length > 0 && templateTestProp.value.type === "ObjectExpression" && templateTestProp.value.properties.unshift(...topLevelProps), mergeProperties(properties, targetConfigObject.properties);
248
- }, mergeTemplateIntoConfigObject = (targetConfigObject, properties, target) => {
249
- let existingTestProp = findNamedProp(targetConfigObject.properties, "test"), resolvedTestValue = existingTestProp ? resolveTestPropValue(existingTestProp, target) : null, templateTestProp = findNamedProp(properties, "test");
250
- if (existingTestProp && resolvedTestValue !== null) {
251
- let existingProjectRefsProp = resolvedTestValue.properties.find(isProjectsArrayProp);
252
- if (existingProjectRefsProp) {
253
- appendToExistingProjectRefs(
254
- existingProjectRefsProp,
255
- resolvedTestValue,
256
- templateTestProp,
257
- properties,
258
- targetConfigObject
220
+ let hoisted = TOP_LEVEL_TEST_PROPERTIES.map(
221
+ (name) => findNamedProp(testObject.properties, name)
222
+ ).filter((member) => member !== void 0), projectMembers = testObject.properties.filter(
223
+ (member) => !hoisted.includes(member)
224
+ ), layout = { indent: source.indent, trailingComma: !0 }, projectTest = printMembers(memberTexts(target, testObject, projectMembers), layout), project = printMembers(["extends: true", `test: ${projectTest}`], layout);
225
+ prependToList2(source, arrayList2(source, templateProjects.value), [project]), hoisted.length > 0 && prependToList2(
226
+ source,
227
+ objectList(source, templateTestObject),
228
+ memberTexts(target, testObject, hoisted)
229
+ ), source.commit();
230
+ let config = templateConfig(), templateTest = findNamedProp(config.properties, "test");
231
+ target.edits.overwrite(
232
+ existingTest.start,
233
+ existingTest.end,
234
+ reindent(
235
+ itemText(source, objectList(source, config), templateTest),
236
+ "",
237
+ lineIndent(target.code, existingTest.start)
238
+ )
239
+ ), mergeProperties(
240
+ merge,
241
+ config,
242
+ targetConfig,
243
+ config.properties.filter((member) => member !== templateTest)
244
+ );
245
+ }, findWritableConfigObject = (program, exportDefault) => {
246
+ let configObject = getTargetConfigObject(program, exportDefault);
247
+ if (configObject)
248
+ return configObject;
249
+ let mergeConfigCall = getEffectiveMergeConfigCall(exportDefault.declaration, program);
250
+ if (!mergeConfigCall || mergeConfigCall.arguments.length < 2)
251
+ return null;
252
+ let candidates = mergeConfigCall.arguments.map((arg) => getConfigObjectFromMergeArg(arg, program)).filter((object) => object !== null);
253
+ return candidates.find((object) => findNamedProp(object.properties, "test")) ?? candidates[0] ?? null;
254
+ }, normalizeProjectsValue = (merge, projectsProp) => {
255
+ let { target } = merge, value = projectsProp.value, valueText = target.source(value), replacement = value.type === "Literal" || value.type === "TemplateLiteral" ? `[${valueText}]` : resolveExpression(value, target.program)?.type === "ArrayExpression" ? `[...${valueText}]` : `[...((${valueText}) ?? [{ extends: true }])]`;
256
+ target.edits.overwrite(
257
+ value.start,
258
+ value.end,
259
+ projectsProp.shorthand ? `projects: ${replacement}` : replacement
260
+ ), target.commit();
261
+ let exportDefault = findExportDefault(target.program), freshConfig = exportDefault ? findWritableConfigObject(target.program, exportDefault) : null, freshTest = freshConfig && findNamedProp(freshConfig.properties, "test"), freshTestObject = freshTest ? resolveExpression(freshTest.value, target.program) : null, freshProjects = freshTestObject?.type === "ObjectExpression" ? findNamedProp(freshTestObject.properties, "projects") : void 0;
262
+ if (!freshConfig || !freshTest || freshTestObject?.type !== "ObjectExpression" || !freshProjects || !isProjectsArrayProp(freshProjects))
263
+ throw new Error(
264
+ "Could not re-resolve the config object after normalizing a non-array projects value"
265
+ );
266
+ return { targetConfig: freshConfig, testObject: freshTestObject, projects: freshProjects.value };
267
+ }, mergeTemplateIntoConfigObject = (merge, targetConfig, templateConfig) => {
268
+ let existingTest = findNamedProp(targetConfig.properties, "test"), testObject = existingTest ? resolveExpression(existingTest.value, merge.target.program) : null;
269
+ if (existingTest && testObject?.type === "ObjectExpression") {
270
+ let existingProjects = findNamedProp(testObject.properties, "projects");
271
+ if (existingProjects && isProjectsArrayProp(existingProjects)) {
272
+ appendToExistingProjects(
273
+ merge,
274
+ existingProjects.value,
275
+ testObject,
276
+ templateConfig(),
277
+ targetConfig
259
278
  );
260
279
  return;
261
280
  }
262
- if (templateTestProp && templateTestProp.value.type === "ObjectExpression") {
263
- wrapTestConfigAsProject(
264
- resolvedTestValue,
265
- existingTestProp,
266
- templateTestProp,
267
- properties,
268
- targetConfigObject
281
+ if (existingProjects) {
282
+ let normalized = normalizeProjectsValue(merge, existingProjects);
283
+ appendToExistingProjects(
284
+ merge,
285
+ normalized.projects,
286
+ normalized.testObject,
287
+ templateConfig(),
288
+ normalized.targetConfig
269
289
  );
270
290
  return;
271
291
  }
292
+ if (findNamedProp(templateConfig().properties, "test")?.value.type === "ObjectExpression") {
293
+ wrapTestConfigAsProject(merge, existingTest, testObject, templateConfig, targetConfig);
294
+ return;
295
+ }
272
296
  }
273
- mergeProperties(properties, targetConfigObject.properties);
274
- }, getWritableTargetConfigObject = (target, exportDefault) => {
275
- let directConfigObject = getTargetConfigObject(target, exportDefault);
276
- if (directConfigObject)
277
- return directConfigObject;
278
- let resolvedDecl = resolveExpression(exportDefault.declaration, target);
279
- if (resolvedDecl?.type !== "CallExpression" || !isDefineConfigLike(resolvedDecl, target))
280
- return null;
281
- let callbackArg = resolvedDecl.arguments[0];
282
- if (!callbackArg || callbackArg.type !== "ArrowFunctionExpression" && callbackArg.type !== "FunctionExpression")
283
- return null;
284
- if (callbackArg.body.type === "ObjectExpression")
285
- return callbackArg.body;
286
- if (callbackArg.body.type === "BlockStatement" && callbackArg.body.body.length === 1 && callbackArg.body.body[0]?.type === "ReturnStatement") {
287
- let returnedExpr = resolveExpression(callbackArg.body.body[0].argument, target);
288
- if (returnedExpr?.type === "ObjectExpression")
289
- return returnedExpr;
290
- }
291
- return null;
292
- }, updateConfigFile = (source, target) => {
293
- let updated = !1, sourceExportDefault = source.program.body.find(
294
- (n) => n.type === "ExportDefaultDeclaration"
295
- );
296
- if (!sourceExportDefault || sourceExportDefault.declaration.type !== "CallExpression")
297
- return !1;
298
- let targetExportDefault = target.program.body.find(
299
- (n) => n.type === "ExportDefaultDeclaration"
300
- );
301
- if (!targetExportDefault)
302
- return !1;
303
- let canHandleConfig = !1;
304
- if ((getWritableTargetConfigObject(target, targetExportDefault) !== null || getEffectiveMergeConfigCall(targetExportDefault.declaration, target) !== null) && (canHandleConfig = !0), !canHandleConfig)
305
- return !1;
306
- for (let sourceNode of source.program.body)
307
- if (sourceNode.type === "ImportDeclaration") {
308
- if (!target.program.body.some(
309
- (targetNode) => targetNode.type === sourceNode.type && targetNode.specifiers.some((s) => s.local.name === sourceNode.specifiers[0].local.name)
310
- )) {
311
- let lastImport = target.program.body.findLastIndex((n) => n.type === "ImportDeclaration");
312
- target.program.body.splice(lastImport + 1, 0, sourceNode);
313
- }
314
- } else if (sourceNode.type === "VariableDeclaration") {
315
- if (!target.program.body.some(
316
- (targetNode) => targetNode.type === sourceNode.type && targetNode.declarations.some(
317
- (d) => "name" in d.id && "name" in sourceNode.declarations[0].id && d.id.name === sourceNode.declarations[0].id.name
318
- )
319
- )) {
320
- let lastImport = target.program.body.findLastIndex((n) => n.type === "ImportDeclaration");
321
- target.program.body.splice(lastImport + 1, 0, sourceNode);
322
- }
323
- } else if (sourceNode.type === "ExportDefaultDeclaration") {
324
- let exportDefault = target.program.body.find((n) => n.type === "ExportDefaultDeclaration");
325
- if (exportDefault && sourceNode.declaration.type === "CallExpression" && sourceNode.declaration.arguments.length > 0 && sourceNode.declaration.arguments[0].type === "ObjectExpression") {
326
- let { properties } = sourceNode.declaration.arguments[0], targetConfigObject = getWritableTargetConfigObject(target, exportDefault);
327
- if (targetConfigObject !== null)
328
- mergeTemplateIntoConfigObject(targetConfigObject, properties, target), updated = !0;
329
- else {
330
- let mergeConfigCall = getEffectiveMergeConfigCall(exportDefault.declaration, target);
331
- if (mergeConfigCall && mergeConfigCall.arguments.length >= 2) {
332
- let configObjectNodes = [];
333
- for (let arg of mergeConfigCall.arguments) {
334
- let configObject = getConfigObjectFromMergeArg(arg, target);
335
- configObject && configObjectNodes.push(configObject);
336
- }
337
- let targetConfigObject2 = configObjectNodes.find(
338
- (obj) => obj.properties.some(
339
- (p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "test"
340
- )
341
- ) || configObjectNodes[0];
342
- if (!targetConfigObject2)
343
- return !1;
344
- mergeTemplateIntoConfigObject(targetConfigObject2, properties, target), updated = !0;
345
- }
346
- }
347
- }
297
+ mergeProperties(merge, templateConfig(), targetConfig);
298
+ }, importedExport = (binding) => {
299
+ if (binding.kind !== "import" || binding.declaration?.type !== "ImportDeclaration")
300
+ return;
301
+ let specifier = binding.node, source = binding.declaration.source.value.replace(/^node:/, ""), name = specifier.type === "ImportNamespaceSpecifier" ? "*" : specifier.type === "ImportDefaultSpecifier" ? "default" : specifier.imported.type === "Literal" ? specifier.imported.value : specifier.imported.name;
302
+ return `${name === "default" && isBuiltin(source) ? "*" : name} from ${source}`;
303
+ }, hasConflictingBinding = (source, target, at) => {
304
+ let scope = target.scopes.scopeOf(at), call = findExportDefault(source.program)?.declaration;
305
+ return [...source.scopes.program.bindings.values()].some((binding) => {
306
+ let existing = scope.lookup(binding.name), merged = binding.references.some((reference) => reference !== call.callee), imported = importedExport(binding);
307
+ return merged && existing && (!imported || importedExport(existing) !== imported);
308
+ });
309
+ }, missingStatements = (source, target) => {
310
+ let declared = (name) => target.scopes.program.bindings.has(name);
311
+ return source.program.body.flatMap((node) => {
312
+ let text = source.source(statementSpan(source, node));
313
+ if (node.type === "ImportDeclaration") {
314
+ let name = node.specifiers[0]?.local.name;
315
+ return name && !declared(name) ? [text] : [];
316
+ }
317
+ if (node.type === "VariableDeclaration") {
318
+ let id = node.declarations[0]?.id;
319
+ return id?.type === "Identifier" && !declared(id.name) ? [text] : [];
348
320
  }
349
- return updated;
321
+ return [];
322
+ });
323
+ }, updateConfigFile = (sourceCode, target) => {
324
+ let source = new SourceEditor2(sourceCode), templateConfig = () => {
325
+ let declaration = findExportDefault(source.program)?.declaration;
326
+ return declaration?.type === "CallExpression" && declaration.arguments[0]?.type === "ObjectExpression" ? declaration.arguments[0] : null;
327
+ }, exportDefault = findExportDefault(target.program), targetConfig = exportDefault && findWritableConfigObject(target.program, exportDefault);
328
+ if (!templateConfig() || !targetConfig || hasConflictingBinding(source, target, targetConfig))
329
+ return !1;
330
+ let statements = missingStatements(source, target);
331
+ return statements.length > 0 && insertAfterImports2(target, statements.join(`
332
+ `)), mergeTemplateIntoConfigObject({ source, target }, targetConfig, () => templateConfig()), target.commit(), !0;
350
333
  };
351
334
 
352
335
  // src/postinstall.ts
@@ -417,7 +400,7 @@ async function postInstall(options) {
417
400
  let isAngularVite = info.framework === SupportedFramework.ANGULAR_VITE, maybeWireAngular = async (filePath, content) => {
418
401
  if (!isAngularVite || isAngularVitestAlreadyWired(content))
419
402
  return;
420
- let injected = injectAngularVitestIntoConfig(content);
403
+ let injected = injectAngularVitestIntoConfig(content, filePath);
421
404
  if (injected === null) {
422
405
  logger.error(import_ts_dedent.dedent`
423
406
  We configured @storybook/addon-vitest, but could not automatically add the
@@ -440,15 +423,15 @@ async function postInstall(options) {
440
423
  if (!alreadyConfigured) {
441
424
  let configTemplate = await loadTemplate("vitest.config.4.template", {
442
425
  CONFIG_DIR: getTemplateConfigDir(rootConfig, options.configDir)
443
- }), source = babelParse2(configTemplate);
444
- target = babelParse2(configFile), updated = updateConfigFile(source, target);
426
+ });
427
+ target = new SourceEditor3(configFile, rootConfig), updated = updateConfigFile(configTemplate, target);
445
428
  }
446
429
  if (alreadyConfigured)
447
430
  await maybeWireAngular(rootConfig, configFile), logger.step(
448
431
  CLI_COLORS.success("Vitest for Storybook is already properly configured. Skipping setup.")
449
432
  );
450
433
  else if (target && updated) {
451
- logger.step(`Updating your ${vitestConfigFile ? "Vitest" : "Vite"} config file:`), logger.log(` ${rootConfig}`), isAngularVite && !isAngularVitestAlreadyWired(configFile) && (injectAngularVitestIntoAst(target) ? logger.step("Added the @storybook/angular-vite standalone-vitest bridge.") : (logger.error(import_ts_dedent.dedent`
434
+ logger.step(`Updating your ${vitestConfigFile ? "Vitest" : "Vite"} config file:`), logger.log(` ${rootConfig}`), isAngularVite && !isAngularVitestAlreadyWired(configFile) && (injectAngularVitestIntoEditor(target) ? logger.step("Added the @storybook/angular-vite standalone-vitest bridge.") : (logger.error(import_ts_dedent.dedent`
452
435
  We configured @storybook/addon-vitest, but could not automatically add the
453
436
  @storybook/angular-vite standalone-vitest bridge to:
454
437
  ${rootConfig}
@@ -457,11 +440,14 @@ async function postInstall(options) {
457
440
  and import it from "@storybook/angular-vite/vitest". See:
458
441
  https://storybook.js.org/docs/next/${DOCUMENTATION_LINK}#manual-setup-advanced
459
442
  `), errors.push(new AddonVitestPostinstallConfigUpdateError({ filePath: rootConfig }))));
460
- let formattedContent = await formatFileContent(rootConfig, generate2(target).code);
443
+ let formattedContent = await formatFileContent(rootConfig, target.toString());
461
444
  await writeFile(
462
445
  rootConfig,
463
- !configFileHasTypeReference && !vitestConfigFile ? `/// <reference types="vitest/config" />
464
- ` + formattedContent : formattedContent
446
+ !configFileHasTypeReference && !vitestConfigFile ? restoreLineEndings(
447
+ `/// <reference types="vitest/config" />
448
+ ` + formattedContent,
449
+ formattedContent
450
+ ) : formattedContent
465
451
  );
466
452
  } else
467
453
  logger.error(import_ts_dedent.dedent`
@@ -477,7 +463,7 @@ async function postInstall(options) {
477
463
  logger.step("Creating a Vitest config file:"), logger.log(`${newConfigFile}`);
478
464
  let configContent = configTemplate;
479
465
  if (isAngularVite) {
480
- let injected = injectAngularVitestIntoConfig(configTemplate);
466
+ let injected = injectAngularVitestIntoConfig(configTemplate, newConfigFile);
481
467
  injected !== null && (configContent = injected, logger.step("Added the @storybook/angular-vite standalone-vitest bridge."));
482
468
  }
483
469
  let formattedContent = await formatFileContent(newConfigFile, configContent);
@@ -507,32 +493,21 @@ async function postInstall(options) {
507
493
  function isStorybookTestPluginSource(value) {
508
494
  return value === STORYBOOK_TEST_PLUGIN_SOURCE2;
509
495
  }
510
- function isConfigAlreadySetup(_configPath, configContent) {
511
- let ast;
496
+ function isConfigAlreadySetup(configPath, configContent) {
497
+ let program;
512
498
  try {
513
- ast = babelParse2(configContent);
499
+ ({ program } = parseModule(configContent, configPath));
514
500
  } catch {
515
501
  return !1;
516
502
  }
517
- let pluginIdentifiers = /* @__PURE__ */ new Set();
518
- traverse2(ast, {
519
- ImportDeclaration(path) {
520
- let source = path.node.source.value;
521
- typeof source == "string" && isStorybookTestPluginSource(source) && path.node.specifiers.forEach((specifier) => {
522
- "local" in specifier && specifier.local?.name && pluginIdentifiers.add(specifier.local.name);
523
- });
524
- }
525
- });
503
+ let pluginIdentifiers = /* @__PURE__ */ new Set(["storybookTest"]);
504
+ for (let node of program.body)
505
+ node.type === "ImportDeclaration" && isStorybookTestPluginSource(node.source.value) && node.specifiers.forEach((specifier) => pluginIdentifiers.add(specifier.local.name));
526
506
  let pluginReferenced = !1;
527
- return traverse2(ast, {
528
- CallExpression(path) {
529
- if (pluginReferenced) {
530
- path.stop();
531
- return;
532
- }
533
- let callee = path.node.callee;
534
- callee.type === "Identifier" && (pluginIdentifiers.has(callee.name) || callee.name === "storybookTest") && (pluginReferenced = !0, path.stop());
535
- }
507
+ return walk2(program, (node) => {
508
+ if (pluginReferenced)
509
+ return !1;
510
+ node.type === "CallExpression" && node.callee.type === "Identifier" && pluginIdentifiers.has(node.callee.name) && (pluginReferenced = !0);
536
511
  }), pluginReferenced;
537
512
  }
538
513
  export {