storybook-addon-sdc 0.9.7 → 0.11.1

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.
Files changed (3) hide show
  1. package/README.md +58 -24
  2. package/dist/preset.js +213 -93
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -13,6 +13,7 @@ This addon streamlines the integration of Drupal Single Directory Components (SD
13
13
  - [Configuration](#configuration)
14
14
  - [Creating Experimental Stories](#creating-experimental-stories)
15
15
  - [Support for Single Story Files (\*.story.yml)](#support-for-single-story-files-storyyml)
16
+ - [Namespaces](#namespaces)
16
17
  - [Regular Storybook](#regular-storybook)
17
18
  - [Configuration Options](#configuration-options)
18
19
  - [Setting Default Values](#setting-default-values)
@@ -44,6 +45,7 @@ The SDC Storybook Addon simplifies the integration of Drupal Single Directory Co
44
45
  - **Drupal Behavior Embedding**: Allows you to directly embed Drupal behaviors like `Drupal.attachBehaviors()` into Storybook previews, ensuring components behave similarly to their Drupal counterparts.
45
46
  - **Custom and External Schema Definitions**: Supports custom and external JSON schema definitions to validate components based on Drupal-specific configurations (e.g., UI Patterns, Experience Builder).
46
47
  - **Default and Custom Story Rendering**: Use `type: component` to nest components, `type: element` for HTML markup, and `type: image` for images within stories. Or create your own custom renderers.
48
+ - **Namespaces**: Supports multiple namespaces, allowing you to use components from different(parent/sibling) directories or packages.
47
49
 
48
50
  ## Quickstart Guide
49
51
 
@@ -92,7 +94,7 @@ The SDC Storybook Addon simplifies the integration of Drupal Single Directory Co
92
94
  ## Configuration
93
95
 
94
96
  To configure the addon, update `.storybook/main.js` as shown below:
95
- You can use this plugin either with [Twig.js](https://github.com/twigjs/twig.js) or [Twing.js](https://twing.nightlycommit.com/) by setting the `twigLib` option to `'twig'` or `'twing'` in your configuration. Only one of vitePluginTwigDrupalOptions or vitePluginTwingDrupalOptions should be active, depending on your twigLib setting.
97
+ You can use this plugin either with [Twig.js](https://github.com/twigjs/twig.js) or [Twing.js](https://twing.nightlycommit.com/) by setting the `twigLib` option to `'twig'` or `'twing'` in your configuration.
96
98
 
97
99
  ```js
98
100
  import { join } from 'node:path' // 1. Add dependencies.
@@ -106,24 +108,7 @@ const config = {
106
108
  options: {
107
109
  sdcStorybookOptions: {
108
110
  twigLib: 'twig', // 'twig' for Twig.js or 'twing' for Twing.
109
- namespace: 'umami', // Your namespace.
110
111
  },
111
-
112
- // vite-plugin-twig-drupal options. Comment if using Twing.
113
- vitePluginTwigDrupalOptions: {
114
- namespaces: {
115
- umami: join(cwd(), './components'), // Your namespace and path to components.
116
- },
117
- },
118
-
119
- // vite-plugin-twing-drupal options. Uncomment if using Twing.
120
- // vitePluginTwingDrupalOptions: {
121
- // namespaces: {
122
- // umami: [join(cwd(), './components')],
123
- // },
124
- // },
125
-
126
- jsonSchemaFakerOptions: {}, // json-schema-faker options.
127
112
  },
128
113
  },
129
114
  // Any other addons.
@@ -306,6 +291,61 @@ slots:
306
291
 
307
292
  The [community will have to decide](https://docs.google.com/document/d/1wCQLXrK1lrV2gYlqmqD2pybTql6_H1dByWIKB5xQFcQ/edit?tab=t.0#heading=h.3949vjfiqczr) what format the YAML stories should be.
308
293
 
294
+ ## Namespaces
295
+
296
+ Namespace logic mirrors the behavior of Drupal themes and modules. This means your namespaces can be used:
297
+
298
+ In Twig as `namespace:component`:
299
+
300
+ ```twig
301
+ {% include 'umami:title' %}
302
+ ```
303
+
304
+ And in story definitions within YAML files:
305
+
306
+ ```yaml
307
+ - type: component
308
+ component: 'umami:title'
309
+ ```
310
+
311
+ ### Namespace definitions:
312
+
313
+ - **Default Namespace**: The addon works out of the box without requiring namespace configuration and will use the current directory name as the default namespace, mirroring the behavior of a Drupal theme or module.
314
+ For example, if your `package.json` is in the `my-theme` directory, the default namespace will be `my-theme`, and this namespace will be linked to the `./components` directory.
315
+
316
+ - **Custom Namespace**: If you want to use a custom namespace or explicitly set the namespace, you can specify it in the plugin configuration:
317
+
318
+ ```js
319
+ sdcStorybookOptions: {
320
+ ...
321
+ namespace: 'umami',
322
+ },
323
+ ```
324
+
325
+ - **Multiple Namespaces**: The most powerful feature is the ability to use multiple namespaces.
326
+ This allows you to use components from other directories (parent or sibling).
327
+ These directories must also contain a `/components` directory with SDC components.
328
+
329
+ ```js
330
+ import { resolve } from 'node:path'
331
+ sdcStorybookOptions: {
332
+ namespaces: {
333
+ 'parent-namespace': resolve('../parent-namespace'),
334
+ 'grandparent-namespace': resolve('../../grandparent-namespace'),
335
+ },
336
+ },
337
+ ```
338
+
339
+ Due to the specifics of the indexer implementation, you also need to duplicate the component paths in the `stories` array:
340
+
341
+ ```js
342
+ stories: [
343
+ '../components/**/*.component.yml',
344
+ '../../parent-namespace/components/**/*.component.yml',
345
+ '../../../grandparent-namespace/components/**/*.component.yml',
346
+ ],
347
+ ```
348
+
309
349
  ## Regular storybook
310
350
 
311
351
  All Storybook functions work as usual, and you can import SDC YAML into `.stories.js` files.
@@ -350,9 +390,6 @@ It is possible to pass options to the underlying `vite-plugin-twig-drupal` plugi
350
390
 
351
391
  ```js
352
392
  vitePluginTwigDrupalOptions: {
353
- namespaces: {
354
- umami: join(cwd(), './components'), // Your namespace and path to components.
355
- },
356
393
  functions: {
357
394
  // You can add custom functions - each is a function that is passed the active Twig instance and should call
358
395
  // e.g. extendFunction to register a function
@@ -374,9 +411,6 @@ It is possible to pass options to the underlying `vite-plugin-twing-drupal` plug
374
411
 
375
412
  ```js
376
413
  vitePluginTwingDrupalOptions: {
377
- namespaces: {
378
- umami: [join(cwd(), './components')],
379
- },
380
414
  // (Optional) With twing hooks you can adjust twing environment.
381
415
  hooks: join(cwd(), '.storybook/twing-hooks.js'),
382
416
  },
package/dist/preset.js CHANGED
@@ -1,9 +1,20 @@
1
1
  // src/vite-plugin-storybook-yaml-stories.ts
2
2
  import { readdirSync as readdirSync2, readFileSync } from "fs";
3
3
  import { parse as parseYaml } from "yaml";
4
- import { join as join2, basename, dirname as dirname2, extname } from "path";
4
+ import { join as join2, basename as basename2, dirname as dirname2, extname } from "path";
5
5
  import { globSync } from "glob";
6
6
 
7
+ // src/logger.ts
8
+ import pino from "pino";
9
+ var logger = pino({
10
+ transport: {
11
+ target: "pino-pretty",
12
+ options: {
13
+ colorize: true
14
+ }
15
+ }
16
+ });
17
+
7
18
  // src/argsGenerator.ts
8
19
  import { JSONSchemaFaker } from "json-schema-faker";
9
20
  var generateArgs = (schema, defs) => {
@@ -25,10 +36,6 @@ var slotsToSchemaProperties = (slots) => {
25
36
  };
26
37
  function generateStorybookArgs(content, jsonSchemaFakerOptions) {
27
38
  JSONSchemaFaker.option({
28
- ignoreMissingRefs: true,
29
- failOnInvalidTypes: false,
30
- useExamplesValue: true,
31
- useDefaultValue: true,
32
39
  ...jsonSchemaFakerOptions
33
40
  });
34
41
  const { props, slots, $defs } = content;
@@ -56,19 +63,8 @@ var argTypesGenerator_default = (content) => {
56
63
  };
57
64
 
58
65
  // src/utils.ts
59
- import { readdirSync, existsSync } from "fs";
60
- import { join, resolve } from "path";
61
66
  var capitalize = (str) => str[0].toUpperCase() + str.slice(1);
62
67
  var convertToKebabCase = (str) => str.replace(/[-:]/g, "");
63
- var getSubdirectories = (baseDir) => readdirSync(baseDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join(baseDir, entry.name));
64
- var resolveComponentPath = (namespace, component) => {
65
- const baseDir = resolve("./components");
66
- const directories = [baseDir, ...getSubdirectories(baseDir)];
67
- const possiblePaths = directories.map(
68
- (dir) => join(dir, component, `${component}.component.yml`)
69
- );
70
- return possiblePaths.find(existsSync);
71
- };
72
68
  var toAttributes = (attrs) => {
73
69
  if (!attrs) return "";
74
70
  return " " + Object.entries(attrs).map(([key, value]) => {
@@ -105,7 +101,7 @@ var renderComponent = (item) => {
105
101
  const kebabCaseName = convertToKebabCase(item.component);
106
102
  const componentProps = `...{ ${generateArgs2(item.props ?? {}, false)}}, ...{${generateArgs2(item.slots ?? {}, true)}}`;
107
103
  const storyArgs = item.story ? `...${kebabCaseName}.${capitalize(item.story)}.args` : "...{}";
108
- return `${kebabCaseName}.default.component({...${kebabCaseName}.Basic.args, ${storyArgs}, ${componentProps}})`;
104
+ return `${kebabCaseName}.default.component({...${kebabCaseName}.Basic.baseArgs, ${storyArgs}, ${componentProps}})`;
109
105
  };
110
106
  var renderImage = (item) => {
111
107
  return JSON.stringify(
@@ -150,7 +146,7 @@ var storiesGenerator_default = (stories) => Object.entries(stories).map(
150
146
  ([storyKey, { props = {}, slots = {}, variants = {} }]) => `
151
147
  export const ${capitalize(storyKey)} = {
152
148
  args: {
153
- ...Basic.args,
149
+ ...Basic.baseArgs,
154
150
  ${generateArgs2(props, false)}
155
151
  ${generateArgs2(slots, true)}
156
152
  ${generateVariants(variants)}
@@ -169,9 +165,10 @@ var generateVariants = (variants) => {
169
165
 
170
166
  // src/componentMetadata.ts
171
167
  import { dirname, relative } from "path";
168
+ import { cwd } from "process";
172
169
  var componentMetadata_default = (id, content) => {
173
170
  return {
174
- path: relative(process.cwd(), dirname(id)),
171
+ path: relative(cwd(), dirname(id)),
175
172
  machineName: id,
176
173
  status: content.status || "stable",
177
174
  name: content.name,
@@ -182,19 +179,6 @@ var componentMetadata_default = (id, content) => {
182
179
  // src/validateJson.ts
183
180
  import { Validator } from "jsonschema";
184
181
  import fetch from "node-fetch";
185
-
186
- // src/logger.ts
187
- import pino from "pino";
188
- var logger = pino({
189
- transport: {
190
- target: "pino-pretty",
191
- options: {
192
- colorize: true
193
- }
194
- }
195
- });
196
-
197
- // src/validateJson.ts
198
182
  var validator = new Validator();
199
183
  var schemaCache = /* @__PURE__ */ new Map();
200
184
  var fetchSchema = async (url) => {
@@ -232,6 +216,130 @@ ${validationResult.errors.map((error) => error.stack).join("\n")}
232
216
  }
233
217
  };
234
218
 
219
+ // src/namespaces.ts
220
+ import { readdirSync, existsSync } from "fs";
221
+ import { basename, join, resolve, sep, relative as relative2 } from "path";
222
+ import { cwd as cwd2 } from "process";
223
+ import { normalizePath } from "vite";
224
+ var getSubdirectories = (baseDir) => readdirSync(baseDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join(baseDir, entry.name));
225
+ var getProjectName = (p) => {
226
+ const fullPath = resolve(p);
227
+ const parts = fullPath.split(sep);
228
+ const i = parts.lastIndexOf("components");
229
+ if (i < 1) {
230
+ throw new Error(`Could not find 'components' folder in path: ${fullPath}`);
231
+ }
232
+ return parts[i - 1];
233
+ };
234
+ var resolveComponentPath = (namespace, component, namespaces) => {
235
+ const baseDir = namespaces.findPath(namespace);
236
+ const directories = [baseDir, ...getSubdirectories(baseDir)];
237
+ const possiblePaths = directories.map(
238
+ (dir) => join(dir, component, `${component}.component.yml`)
239
+ );
240
+ return possiblePaths.find(existsSync);
241
+ };
242
+ var Namespaces = class {
243
+ namespaces;
244
+ stripTrailingSlash = (p) => p.replace(/\/+$/g, "");
245
+ constructor(namespaceDefinition) {
246
+ this.namespaces = namespaceDefinition.namespaces ?? {};
247
+ if (namespaceDefinition.namespace) {
248
+ this.namespaces[namespaceDefinition.namespace] = cwd2();
249
+ } else {
250
+ this.namespaces[basename(cwd2())] = cwd2();
251
+ }
252
+ logger.info(`REGISTER NAMESPACES: ${JSON.stringify(this.namespaces)}`);
253
+ }
254
+ toViteAlias() {
255
+ const aliases = [];
256
+ Object.entries(this.namespaces).forEach(([namespace, path]) => {
257
+ const hasComponents = existsSync(join(path, "components"));
258
+ aliases.push({
259
+ find: "@" + namespace,
260
+ replacement: normalizePath(
261
+ hasComponents ? join(path, "components") : path
262
+ )
263
+ });
264
+ });
265
+ logger.info(`REGISTER VITE ALIASES: ${JSON.stringify(aliases)}`);
266
+ return aliases;
267
+ }
268
+ toTwigJsNamespaces() {
269
+ let namespaces = {};
270
+ for (const [ns, path] of Object.entries(this.namespaces)) {
271
+ const componentsPath = join(path, "components");
272
+ if (existsSync(componentsPath)) {
273
+ namespaces[ns] = componentsPath;
274
+ } else {
275
+ namespaces[ns] = path;
276
+ }
277
+ }
278
+ return namespaces;
279
+ }
280
+ toTwingNamespaces() {
281
+ let namespaces = {};
282
+ for (const [ns, path] of Object.entries(this.namespaces)) {
283
+ const componentsPath = join(path, "components");
284
+ if (existsSync(componentsPath)) {
285
+ namespaces[ns] = [componentsPath];
286
+ } else {
287
+ namespaces[ns] = [path];
288
+ }
289
+ }
290
+ return namespaces;
291
+ }
292
+ findPath = (namespace) => {
293
+ return this.namespaces[namespace] || "";
294
+ };
295
+ find = (fsPath) => {
296
+ const fp = this.stripTrailingSlash(fsPath);
297
+ let bestPath;
298
+ let bestNs;
299
+ for (const [ns, path] of Object.entries(this.namespaces)) {
300
+ const base = this.stripTrailingSlash(path);
301
+ if (fp === base || fp.startsWith(base + "/")) {
302
+ if (!bestPath || base.length > bestPath.length) {
303
+ bestPath = base;
304
+ bestNs = ns;
305
+ }
306
+ }
307
+ }
308
+ return bestNs;
309
+ };
310
+ pathToNamespace(fsPath, makeComponentIdFormat = false) {
311
+ const ns = this.find(fsPath);
312
+ if (!ns) {
313
+ throw new Error(
314
+ `Could not find valid 'namespace' for folder: ${fsPath} in namespaces: ${JSON.stringify(this.namespaces)}`
315
+ );
316
+ }
317
+ const rootPath = resolve(this.namespaces[ns]);
318
+ const componentsDir = join(rootPath, "components");
319
+ if (existsSync(componentsDir)) {
320
+ const isExact = fsPath === componentsDir;
321
+ const isChild = fsPath.startsWith(componentsDir + sep);
322
+ if (!isExact && !isChild) {
323
+ throw new Error(
324
+ `Could not find 'components' folder in path: ${fsPath}, namespace: ${ns} (${Object.values(this.namespaces).join(", ")})`
325
+ );
326
+ }
327
+ let rel = relative2(componentsDir, fsPath);
328
+ if (sep !== "/") {
329
+ rel = rel.split(sep).join("/");
330
+ }
331
+ if (makeComponentIdFormat) {
332
+ return `${ns}:${rel}`;
333
+ }
334
+ return `@${ns}/${rel}`;
335
+ }
336
+ return `@${ns}`;
337
+ }
338
+ };
339
+ var toNamespaces = (namespaceDefinition) => {
340
+ return new Namespaces(namespaceDefinition ?? {});
341
+ };
342
+
235
343
  // src/vite-plugin-storybook-yaml-stories.ts
236
344
  var readSDC = (filePath, defs, validate) => {
237
345
  const sdcSchema = {
@@ -243,17 +351,23 @@ var readSDC = (filePath, defs, validate) => {
243
351
  }
244
352
  return sdcSchema;
245
353
  };
246
- var generateImports = (directory) => readdirSync2(directory).filter(
354
+ var generateImports = (directory, namespaces) => readdirSync2(directory).filter(
247
355
  (file) => [".css", ".js", ".mjs", ".twig", ".yml"].includes(extname(file))
248
356
  ).map((file) => {
249
357
  const filePath = `./${file}`;
250
- return extname(file) === ".twig" ? `import COMPONENT from '${filePath}';` : `import '${filePath}';`;
358
+ const namespace = namespaces.pathToNamespace(directory);
359
+ logger.info(`IMPORT ASSET ${directory}/${file}`);
360
+ return extname(file) === ".twig" ? `import COMPONENT from '${namespace}/${file}';` : `import '${filePath}';`;
251
361
  }).join("\n");
252
- var dynamicImports = (stories) => {
362
+ var dynamicImports = (stories, namespaces) => {
253
363
  const imports = /* @__PURE__ */ new Set();
254
364
  const importComponent = (item) => {
255
365
  const [namespace, componentName] = item.component.split(":");
256
- const resolvedPath = resolveComponentPath(namespace, componentName);
366
+ const resolvedPath = resolveComponentPath(
367
+ namespace,
368
+ componentName,
369
+ namespaces
370
+ );
257
371
  const kebabCaseName = convertToKebabCase(item.component);
258
372
  if (resolvedPath) {
259
373
  imports.add(`import * as ${kebabCaseName} from '${resolvedPath}';`);
@@ -305,7 +419,8 @@ var createStoryIndex = (fileName, baseTitle, stories) => {
305
419
  var vite_plugin_storybook_yaml_stories_default = ({
306
420
  jsonSchemaFakerOptions = {},
307
421
  sdcStorybookOptions = {},
308
- globalDefs = {}
422
+ globalDefs = {},
423
+ namespaces = {}
309
424
  }) => ({
310
425
  name: "vite-plugin-storybook-yaml-stories",
311
426
  async load(id) {
@@ -315,13 +430,13 @@ var vite_plugin_storybook_yaml_stories_default = ({
315
430
  if (!id.endsWith("component.yml")) return;
316
431
  try {
317
432
  const content = readSDC(id, globalDefs, sdcStorybookOptions.validate);
318
- const imports = generateImports(dirname2(id));
433
+ const imports = generateImports(dirname2(id), namespaces);
319
434
  const previewsStories = {
320
435
  ...content.thirdPartySettings?.sdcStorybook?.stories || {},
321
436
  ...loadStoryFilesSync(id)
322
437
  };
323
438
  storyNodeRenderer.register(sdcStorybookOptions.storyNodesRenderer ?? []);
324
- const storiesImports = dynamicImports(previewsStories);
439
+ const storiesImports = dynamicImports(previewsStories, namespaces);
325
440
  const metadata = componentMetadata_default(id, content);
326
441
  const argTypes = {
327
442
  componentMetadata: { table: { disable: true } },
@@ -338,16 +453,18 @@ var vite_plugin_storybook_yaml_stories_default = ({
338
453
  defaultAttributes: [
339
454
  [
340
455
  "data-component-id",
341
- `${sdcStorybookOptions?.namespace}:${basename(id, ".component.yml")}`
456
+ `${namespaces.pathToNamespace(dirname2(id), true)}`
342
457
  ]
343
458
  ],
344
459
  componentMetadata: metadata,
345
460
  ...content.variants && {
346
461
  variant: Object.keys(content.variants)[0]
347
- },
462
+ }
463
+ };
464
+ const basicArgs = {
465
+ ...args,
348
466
  ...generateStorybookArgs(content, jsonSchemaFakerOptions)
349
467
  };
350
- const basicArgs = { ...args };
351
468
  const stories = previewsStories ? storiesGenerator_default(previewsStories) : "";
352
469
  return `
353
470
  ${imports}
@@ -366,6 +483,7 @@ export default {
366
483
  };
367
484
 
368
485
  export const Basic = {
486
+ baseArgs: ${JSON.stringify(args, null, 2)},
369
487
  args: ${JSON.stringify(basicArgs, null, 2)},
370
488
  play: async ({ canvasElement }) => {
371
489
  Drupal.attachBehaviors(canvasElement, window.drupalSettings);
@@ -374,7 +492,7 @@ export const Basic = {
374
492
  ${stories}
375
493
  `;
376
494
  } catch (error) {
377
- console.error(`Error loading component YAML file: ${id}`, error);
495
+ logger.error(`Error loading component YAML file: ${id}, ${error}`);
378
496
  throw error;
379
497
  }
380
498
  }
@@ -384,13 +502,13 @@ var yamlStoriesIndexer = {
384
502
  createIndex: async (fileName, { makeTitle }) => {
385
503
  try {
386
504
  const content = readSDC(fileName);
387
- const baseTitle = makeTitle(`SDC/${content.name}`);
505
+ const baseTitle = makeTitle(`${getProjectName(fileName)}/${content.name}`);
388
506
  const stories = content.thirdPartySettings?.sdcStorybook?.stories;
389
507
  const storiesContent = loadStoryFilesSync(fileName);
390
508
  const mergedStories = { ...stories, ...storiesContent };
391
509
  return createStoryIndex(fileName, baseTitle, mergedStories);
392
510
  } catch (error) {
393
- console.error(`Error creating index for YAML file: ${fileName}`, error);
511
+ logger.error(`Error creating index for YAML file: ${fileName}, ${error}`);
394
512
  throw error;
395
513
  }
396
514
  }
@@ -401,7 +519,7 @@ var loadStoryFilesSync = (fileName) => {
401
519
  return storyFiles.reduce(
402
520
  (acc, file) => {
403
521
  const content = readFileSync(file, "utf8");
404
- const key = basename(file).split(".")[1];
522
+ const key = basename2(file).split(".")[1];
405
523
  return {
406
524
  ...acc,
407
525
  [key]: parseYaml(content)
@@ -413,10 +531,10 @@ var loadStoryFilesSync = (fileName) => {
413
531
 
414
532
  // src/preset.ts
415
533
  import { mergeConfig } from "vite";
416
- import { resolve as resolve2 } from "path";
417
- import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
534
+
535
+ // src/definitions.ts
418
536
  import { parse } from "yaml";
419
- import { sync } from "glob";
537
+ import { readFileSync as readFileSync2 } from "fs";
420
538
  import fetch2 from "node-fetch";
421
539
  async function loadExternalDef(defPath) {
422
540
  try {
@@ -436,28 +554,6 @@ async function loadExternalDef(defPath) {
436
554
  throw error;
437
555
  }
438
556
  }
439
- function getComponentDirectories() {
440
- return sync("./components/**/*.component.yml");
441
- }
442
- function resolveComponentPath2(namespace, component) {
443
- const componentDirectories = getComponentDirectories();
444
- const possiblePaths = componentDirectories.map(
445
- (dir) => resolve2(`${dir}/${component}/${component}.component.yml`)
446
- );
447
- const resolvedPath = possiblePaths.find((path) => existsSync2(path));
448
- if (!resolvedPath) {
449
- logger.error(
450
- `Component ${component} could not be resolved in namespace ${namespace}`
451
- );
452
- }
453
- return resolvedPath;
454
- }
455
- var defaultOptions = {
456
- validate: false,
457
- twigLib: "twig"
458
- // validate:
459
- // 'https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json',
460
- };
461
557
  async function loadAndMergeDefinitions(externalDefs, customDefs) {
462
558
  const globalDefs = {};
463
559
  if (externalDefs) {
@@ -477,24 +573,60 @@ async function loadAndMergeDefinitions(externalDefs, customDefs) {
477
573
  }
478
574
  if (Object.keys(globalDefs).length > 0) {
479
575
  logger.info(
480
- `Registering custom definitions: ${Object.keys(globalDefs).join(", ")}`
576
+ `REGISTER CUSTOM DEFINITIONS ${JSON.stringify(Object.keys(globalDefs))}`
481
577
  );
482
578
  }
483
579
  return globalDefs;
484
580
  }
581
+
582
+ // src/constants.ts
583
+ var DEFAULT_ADDON_OPTIONS = {
584
+ sdcStorybookOptions: {
585
+ twigLib: "twig",
586
+ validate: false
587
+ // validate:
588
+ // 'https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json',
589
+ },
590
+ vitePluginTwingDrupalOptions: {
591
+ include: /\.twig(\?.*)?$/
592
+ },
593
+ vitePluginTwigDrupalOptions: {},
594
+ jsonSchemaFakerOptions: {
595
+ ignoreMissingRefs: true,
596
+ failOnInvalidTypes: false,
597
+ useExamplesValue: true,
598
+ useDefaultValue: true
599
+ }
600
+ };
601
+
602
+ // src/preset.ts
485
603
  async function viteFinal(config, options) {
486
- options.sdcStorybookOptions = {
487
- ...defaultOptions,
488
- ...options.sdcStorybookOptions
604
+ options = {
605
+ ...DEFAULT_ADDON_OPTIONS,
606
+ ...options
489
607
  };
490
- const { namespace, customDefs, externalDefs } = options.sdcStorybookOptions;
491
- const globalDefs = await loadAndMergeDefinitions(externalDefs, customDefs);
608
+ const {
609
+ sdcStorybookOptions,
610
+ vitePluginTwigDrupalOptions,
611
+ vitePluginTwingDrupalOptions
612
+ } = options;
613
+ const { customDefs, externalDefs } = sdcStorybookOptions;
492
614
  const { nodePolyfills } = await import("vite-plugin-node-polyfills");
615
+ const globalDefs = await loadAndMergeDefinitions(externalDefs, customDefs);
616
+ const namespaces = toNamespaces(sdcStorybookOptions);
493
617
  let twigPlugin = null;
494
- if (options.sdcStorybookOptions.twigLib === "twing") {
618
+ if (sdcStorybookOptions.twigLib === "twing") {
619
+ options.vitePluginTwingDrupalOptions = {
620
+ ...vitePluginTwingDrupalOptions,
621
+ namespaces: { ...namespaces.toTwingNamespaces() }
622
+ };
495
623
  const { default: twing } = await import("vite-plugin-twing-drupal");
496
624
  twigPlugin = twing(options.vitePluginTwingDrupalOptions);
497
- } else if (options.sdcStorybookOptions.twigLib === "twig") {
625
+ } else if (sdcStorybookOptions.twigLib === "twig") {
626
+ options.vitePluginTwigDrupalOptions = {
627
+ ...vitePluginTwigDrupalOptions,
628
+ namespaces: { ...namespaces.toTwigJsNamespaces() }
629
+ };
498
630
  const { default: twig } = await import("vite-plugin-twig-drupal");
499
631
  twigPlugin = twig(options.vitePluginTwigDrupalOptions);
500
632
  }
@@ -504,22 +636,10 @@ async function viteFinal(config, options) {
504
636
  include: ["buffer", "stream", "path"]
505
637
  }),
506
638
  ...twigPlugin ? [twigPlugin] : [],
507
- vite_plugin_storybook_yaml_stories_default({ ...options, globalDefs })
639
+ vite_plugin_storybook_yaml_stories_default({ ...options, globalDefs, namespaces })
508
640
  ],
509
641
  resolve: {
510
- alias: [
511
- {
512
- find: new RegExp(`${namespace}:(.*)`),
513
- // Use namespace from options
514
- replacement: (match, component) => {
515
- const resolvedPath = resolveComponentPath2(namespace, component);
516
- if (!resolvedPath) {
517
- throw new Error(`Component ${component} could not be resolved.`);
518
- }
519
- return resolvedPath;
520
- }
521
- }
522
- ]
642
+ alias: [...namespaces.toViteAlias()]
523
643
  }
524
644
  });
525
645
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "storybook-addon-sdc",
3
- "version": "0.9.7",
3
+ "version": "0.11.1",
4
4
  "description": "Drupal Single Directory Components as stories",
5
5
  "keywords": [
6
6
  "SDC",