-
-
Notifications
You must be signed in to change notification settings - Fork 9.3k
/
presets.ts
429 lines (369 loc) · 12.1 KB
/
presets.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
import { join, parse } from 'node:path';
import type {
BuilderOptions,
CLIOptions,
CoreCommon_ResolvedAddonPreset,
CoreCommon_ResolvedAddonVirtual,
LoadOptions,
LoadedPreset,
PresetConfig,
Presets,
StorybookConfigRaw,
} from '@storybook/core/types';
import { logger } from '@storybook/core/node-logger';
import { CriticalPresetLoadError } from '@storybook/core/server-errors';
import { dedent } from 'ts-dedent';
import { interopRequireDefault } from './utils/interpret-require';
import { loadCustomPresets } from './utils/load-custom-presets';
import { safeResolve, safeResolveFrom } from './utils/safeResolve';
import { stripAbsNodeModulesPath } from './utils/strip-abs-node-modules-path';
type InterPresetOptions = Omit<
CLIOptions &
LoadOptions &
BuilderOptions & { isCritical?: boolean; build?: StorybookConfigRaw['build'] },
'frameworkPresets'
>;
const isObject = (val: unknown): val is Record<string, any> =>
val != null && typeof val === 'object' && Array.isArray(val) === false;
const isFunction = (val: unknown): val is Function => typeof val === 'function';
export function filterPresetsConfig(presetsConfig: PresetConfig[]): PresetConfig[] {
return presetsConfig.filter((preset) => {
const presetName = typeof preset === 'string' ? preset : preset.name;
return !/@storybook[\\\\/]preset-typescript/.test(presetName);
});
}
function resolvePathToMjs(filePath: string): string {
const { dir, name } = parse(filePath);
const mjsPath = join(dir, `${name}.mjs`);
if (safeResolve(mjsPath)) {
return mjsPath;
}
return filePath;
}
function resolvePresetFunction<T = any>(
input: T[] | Function,
presetOptions: any,
storybookOptions: InterPresetOptions
): T[] {
if (isFunction(input)) {
return [...input({ ...storybookOptions, ...presetOptions })];
}
if (Array.isArray(input)) {
return [...input];
}
return [];
}
/**
* Parse an addon into either a managerEntries or a preset. Throw on invalid input.
*
* Valid inputs:
*
* - `'@storybook/addon-actions/manager' => { type: 'virtual', item }`
* - `'@storybook/addon-docs/preset' => { type: 'presets', item }`
* - `'@storybook/addon-docs' => { type: 'presets', item: '@storybook/addon-docs/preset' }`
* - `{ name: '@storybook/addon-docs(/preset)?', options: { } } => { type: 'presets', item: { name:
* '@storybook/addon-docs/preset', options } }`
*/
export const resolveAddonName = (
configDir: string,
name: string,
options: any
): CoreCommon_ResolvedAddonPreset | CoreCommon_ResolvedAddonVirtual | undefined => {
const resolve = name.startsWith('/') ? safeResolve : safeResolveFrom.bind(null, configDir);
const resolved = resolve(name);
if (resolved) {
const { dir: fdir, name: fname } = parse(resolved);
if (name.match(/\/(manager|register(-panel)?)(\.(js|mjs|ts|tsx|jsx))?$/)) {
return {
type: 'virtual',
name,
// we remove the extension
// this is a bit of a hack to try to find .mjs files
// node can only ever resolve .js files; it does not look at the exports field in package.json
managerEntries: [resolvePathToMjs(join(fdir, fname))],
};
}
if (name.match(/\/(preset)(\.(js|mjs|ts|tsx|jsx))?$/)) {
return {
type: 'presets',
name: resolved,
};
}
}
const checkExists = (exportName: string) => {
if (resolve(`${name}${exportName}`)) {
return `${name}${exportName}`;
}
return undefined;
};
/**
* This is used to maintain back-compat with community addons that do not re-export their
* sub-addons but reference the sub-addon name directly. We need to turn it into an absolute path
* so that webpack can serve it up correctly when yarn pnp or pnpm is being used. Vite will be
* broken in such cases, because it does not process absolute paths, and it will try to import
* from the bare import, breaking in pnp/pnpm.
*/
const absolutizeExport = (exportName: string, preferMJS: boolean) => {
const found = resolve(`${name}${exportName}`);
if (found) {
return preferMJS ? resolvePathToMjs(found) : found;
}
return undefined;
};
const managerFile = absolutizeExport(`/manager`, true);
const registerFile =
absolutizeExport(`/register`, true) || absolutizeExport(`/register-panel`, true);
const previewFile = checkExists(`/preview`);
const previewFileAbsolute = absolutizeExport('/preview', true);
const presetFile = absolutizeExport(`/preset`, false);
if (!(managerFile || previewFile) && presetFile) {
return {
type: 'presets',
name: presetFile,
};
}
if (managerFile || registerFile || previewFile || presetFile) {
const managerEntries = [];
if (managerFile) {
managerEntries.push(managerFile);
}
// register file is the old way of registering addons
if (!managerFile && registerFile && !presetFile) {
managerEntries.push(registerFile);
}
return {
type: 'virtual',
name,
...(managerEntries.length ? { managerEntries } : {}),
...(previewFile
? {
previewAnnotations: [
previewFileAbsolute
? {
// TODO: Evaluate if searching for node_modules in a yarn pnp environment is correct
bare: previewFile.includes('node_modules')
? stripAbsNodeModulesPath(previewFile)
: previewFile,
absolute: previewFileAbsolute,
}
: previewFile,
],
}
: {}),
...(presetFile ? { presets: [{ name: presetFile, options }] } : {}),
};
}
if (resolved) {
return {
type: 'presets',
name: resolved,
};
}
return undefined;
};
const map =
({ configDir }: InterPresetOptions) =>
(item: any) => {
const options = isObject(item) ? item['options'] || undefined : undefined;
const name = isObject(item) ? item['name'] : item;
let resolved;
try {
resolved = resolveAddonName(configDir, name, options);
} catch (err) {
logger.error(
`Addon value should end in /manager or /preview or /register OR it should be a valid preset https://storybook.js.org/docs/react/addons/writing-presets/\n${item}`
);
return undefined;
}
if (!resolved) {
logger.warn(`Could not resolve addon "${name}", skipping. Is it installed?`);
return undefined;
}
return {
...(options ? { options } : {}),
...resolved,
};
};
async function getContent(input: any) {
if (input.type === 'virtual') {
const { type, name, ...rest } = input;
return rest;
}
const name = input.name ? input.name : input;
return interopRequireDefault(name);
}
export async function loadPreset(
input: PresetConfig,
level: number,
storybookOptions: InterPresetOptions
): Promise<LoadedPreset[]> {
// @ts-expect-error (Converted from ts-ignore)
const presetName: string = input.name ? input.name : input;
try {
// @ts-expect-error (Converted from ts-ignore)
const presetOptions = input.options ? input.options : {};
let contents = await getContent(input);
if (typeof contents === 'function') {
// allow the export of a preset to be a function, that gets storybookOptions
contents = contents(storybookOptions, presetOptions);
}
if (Array.isArray(contents)) {
const subPresets = contents;
return await loadPresets(subPresets, level + 1, storybookOptions);
}
if (isObject(contents)) {
const { addons: addonsInput = [], presets: presetsInput = [], ...rest } = contents;
let filter = (i: PresetConfig) => {
return true;
};
if (
storybookOptions.isCritical !== true &&
(storybookOptions.build?.test?.disabledAddons?.length || 0) > 0
) {
filter = (i: PresetConfig) => {
// @ts-expect-error (Converted from ts-ignore)
const name = i.name ? i.name : i;
return !storybookOptions.build?.test?.disabledAddons?.find((n) => name.includes(n));
};
}
const subPresets = resolvePresetFunction(
presetsInput,
presetOptions,
storybookOptions
).filter(filter);
const subAddons = resolvePresetFunction(addonsInput, presetOptions, storybookOptions).filter(
filter
);
return [
...(await loadPresets([...subPresets], level + 1, storybookOptions)),
...(await loadPresets(
[...subAddons.map(map(storybookOptions))].filter(Boolean) as PresetConfig[],
level + 1,
storybookOptions
)),
{
name: presetName,
preset: rest,
options: presetOptions,
},
];
}
throw new Error(dedent`
${input} is not a valid preset
`);
} catch (error: any) {
if (storybookOptions?.isCritical) {
throw new CriticalPresetLoadError({
error,
presetName,
});
}
const warning =
level > 0
? ` Failed to load preset: ${JSON.stringify(input)} on level ${level}`
: ` Failed to load preset: ${JSON.stringify(input)}`;
logger.warn(warning);
logger.error(error);
return [];
}
}
async function loadPresets(
presets: PresetConfig[],
level: number,
storybookOptions: InterPresetOptions
): Promise<LoadedPreset[]> {
if (!presets || !Array.isArray(presets) || !presets.length) {
return [];
}
return (
await Promise.all(
presets.map(async (preset) => {
return loadPreset(preset, level, storybookOptions);
})
)
).reduce((acc, loaded) => {
return acc.concat(loaded);
}, []);
}
function applyPresets(
presets: LoadedPreset[],
extension: string,
config: any,
args: any,
storybookOptions: InterPresetOptions
): Promise<any> {
const presetResult = new Promise((res) => res(config));
if (!presets.length) {
return presetResult;
}
return presets.reduce((accumulationPromise: Promise<unknown>, { preset, options }) => {
const change = preset[extension];
if (!change) {
return accumulationPromise;
}
if (typeof change === 'function') {
const extensionFn = change;
const context = {
preset,
combinedOptions: {
...storybookOptions,
...args,
...options,
presetsList: presets,
presets: {
apply: async (ext: string, c: any, a = {}) =>
applyPresets(presets, ext, c, a, storybookOptions),
},
},
};
return accumulationPromise.then((newConfig) =>
extensionFn.call(context.preset, newConfig, context.combinedOptions)
);
}
return accumulationPromise.then((newConfig) => {
if (Array.isArray(newConfig) && Array.isArray(change)) {
return [...newConfig, ...change];
}
if (isObject(newConfig) && isObject(change)) {
return { ...newConfig, ...change };
}
return change;
});
}, presetResult);
}
export async function getPresets(
presets: PresetConfig[],
storybookOptions: InterPresetOptions
): Promise<Presets> {
const loadedPresets: LoadedPreset[] = await loadPresets(presets, 0, storybookOptions);
return {
apply: async (extension: string, config: any, args = {}) =>
applyPresets(loadedPresets, extension, config, args, storybookOptions),
};
}
export async function loadAllPresets(
options: CLIOptions &
LoadOptions &
BuilderOptions & {
corePresets: PresetConfig[];
overridePresets: PresetConfig[];
/** Whether preset failures should be critical or not */
isCritical?: boolean;
build?: StorybookConfigRaw['build'];
}
) {
const { corePresets = [], overridePresets = [], ...restOptions } = options;
const presetsConfig: PresetConfig[] = [
...corePresets,
...loadCustomPresets(options),
...overridePresets,
];
// Remove `@storybook/preset-typescript` and add a warning if in use.
const filteredPresetConfig = filterPresetsConfig(presetsConfig);
if (filteredPresetConfig.length < presetsConfig.length) {
logger.warn(
'Storybook now supports TypeScript natively. You can safely remove `@storybook/preset-typescript`.'
);
}
return getPresets(filteredPresetConfig, restOptions);
}