storybook-addon-sdc 0.25.1 → 0.26.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.
package/README.md CHANGED
@@ -706,7 +706,7 @@ $schema: https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schema
706
706
 
707
707
  - **Validation Warnings:** Validation errors or warnings are logged to the console, helping developers identify any issues with component configurations. **Note:** Validation will not break the rendering of the components. Even if a validation error occurs, the component will still appear in Storybook, and the warning will be logged for review.
708
708
 
709
- To enable validation, set `validate: URL of schema`:
709
+ To enable validation, set `validate: true` (Drupal core's schema) or pass the URL of your own default schema:
710
710
 
711
711
  ```js
712
712
  const config = {
@@ -716,8 +716,8 @@ const config = {
716
716
  name: 'storybook-addon-sdc',
717
717
  options: {
718
718
  sdcStorybookOptions: {
719
- validate:
720
- 'https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json',
719
+ // true = https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json
720
+ validate: true,
721
721
  },
722
722
  },
723
723
  },
@@ -725,6 +725,8 @@ const config = {
725
725
  }
726
726
  ```
727
727
 
728
+ A component's own `$schema` always takes precedence over the default. Validation only warns: a failing or unreachable schema never removes a component from Storybook.
729
+
728
730
  ### `useBasicArgsForStories`
729
731
 
730
732
  By default, when generating stories for your SDC components, the addon automatically spreads the `Basic.args` into each generated story. This behavior can be controlled using the `useBasicArgsForStories` option.
package/dist/preset.js CHANGED
@@ -7469,9 +7469,9 @@ var require_twig_path = __commonJS({
7469
7469
  } else if (template.path) {
7470
7470
  const path2 = __require("path");
7471
7471
  const sep3 = path2.sep || sepChr;
7472
- const relative5 = new RegExp("^\\.{1,2}" + sep3.replace("\\", "\\\\"));
7472
+ const relative6 = new RegExp("^\\.{1,2}" + sep3.replace("\\", "\\\\"));
7473
7473
  file = file.replace(/\//g, sep3);
7474
- if (template.base !== void 0 && file.match(relative5) === null) {
7474
+ if (template.base !== void 0 && file.match(relative6) === null) {
7475
7475
  file = file.replace(template.base, "");
7476
7476
  base = template.base + sep3;
7477
7477
  } else {
@@ -8039,32 +8039,26 @@ var require_state2 = __commonJS({
8039
8039
 
8040
8040
  // src/preset.ts
8041
8041
  init_esm_shims();
8042
- import { existsSync as existsSync6, statSync as statSync2 } from "fs";
8043
- import { join as join6, dirname as dirname5, relative as relative4 } from "path";
8042
+ import { existsSync as existsSync5, statSync as statSync2 } from "fs";
8043
+ import { dirname as dirname5, relative as relative5 } from "path";
8044
8044
 
8045
8045
  // src/vite/storybookYamlStories.ts
8046
8046
  init_esm_shims();
8047
- import { readdirSync as readdirSync5, readFileSync as readFileSync4, existsSync as existsSync5 } from "fs";
8047
+ import { readFileSync as readFileSync4, existsSync as existsSync4 } from "fs";
8048
8048
  import { parse as parseYaml3 } from "yaml";
8049
- import { join as join5, basename as basename3, dirname as dirname4 } from "path";
8049
+ import { join as join6, basename as basename4, dirname as dirname4 } from "path";
8050
8050
 
8051
8051
  // src/logger.ts
8052
8052
  init_esm_shims();
8053
- import pino from "pino";
8054
- var logger = pino({
8055
- transport: {
8056
- target: "pino-pretty",
8057
- options: {
8058
- colorize: true
8059
- }
8060
- }
8061
- });
8053
+ import { logger } from "storybook/internal/node-logger";
8062
8054
 
8063
8055
  // src/utils.ts
8064
8056
  init_esm_shims();
8065
- import { dirname, sep } from "path";
8057
+ import { readdirSync } from "fs";
8058
+ import { dirname, join, relative, sep } from "path";
8059
+ var isRemoteUrl = (s) => /^https?:\/\//.test(s);
8066
8060
  var capitalize = (str) => str[0].toUpperCase() + str.slice(1);
8067
- var convertToKebabCase = (str) => str.replace(/[-:]/g, "");
8061
+ var toIdentifier = (componentId) => componentId.replace(/[-:]/g, "");
8068
8062
  var deriveGroupFromPath = (fileName) => {
8069
8063
  const dir = dirname(fileName);
8070
8064
  const parts = dir.split(sep).filter(Boolean);
@@ -8086,6 +8080,36 @@ var jsLiteral = (value, indent) => {
8086
8080
  if (json === void 0) return "undefined";
8087
8081
  return json.replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
8088
8082
  };
8083
+ var isPlainObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v) && Object.getPrototypeOf(v) === Object.prototype;
8084
+ function mergeOptions(defaults, overrides) {
8085
+ const out = {
8086
+ ...defaults
8087
+ };
8088
+ for (const [key, value] of Object.entries(overrides ?? {})) {
8089
+ if (value === void 0) continue;
8090
+ const base = out[key];
8091
+ out[key] = isPlainObject(base) && isPlainObject(value) ? mergeOptions(base, value) : value;
8092
+ }
8093
+ return out;
8094
+ }
8095
+ var posixDirname = (rel) => rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : "";
8096
+ function listDir(root) {
8097
+ let entries2;
8098
+ try {
8099
+ entries2 = readdirSync(root, { recursive: true, withFileTypes: true });
8100
+ } catch {
8101
+ return [];
8102
+ }
8103
+ return entries2.filter((entry) => entry.isFile() || entry.isDirectory()).map((entry) => {
8104
+ const path2 = join(entry.parentPath, entry.name);
8105
+ return {
8106
+ path: path2,
8107
+ name: entry.name,
8108
+ relative: relative(root, path2).split(sep).join("/"),
8109
+ isDirectory: entry.isDirectory()
8110
+ };
8111
+ });
8112
+ }
8089
8113
 
8090
8114
  // src/generate/args.ts
8091
8115
  init_esm_shims();
@@ -8389,10 +8413,10 @@ var renderStoryNode = (item) => {
8389
8413
  }
8390
8414
  };
8391
8415
  var renderComponent = (item) => {
8392
- const kebabCaseName = convertToKebabCase(item.component);
8416
+ const identifier = toIdentifier(item.component);
8393
8417
  const componentProps = `...{ ${generateArgs2(item.props ?? {}, false)}}, ...{${generateArgs2(item.slots ?? {}, true)}}`;
8394
- const storyArgs = item.story ? `...${kebabCaseName}.${capitalize(item.story)}.args` : "...{}";
8395
- return `${kebabCaseName}.default.component({...${kebabCaseName}.Basic.baseArgs, ${storyArgs}, ${componentProps}})`;
8418
+ const storyArgs = item.story ? `...${identifier}.${capitalize(item.story)}.args` : "...{}";
8419
+ return `${identifier}.default.component({...${identifier}.Basic.baseArgs, ${storyArgs}, ${componentProps}})`;
8396
8420
  };
8397
8421
  var renderImage = (item) => {
8398
8422
  const attrs = { ...item.attributes ?? {} };
@@ -8491,8 +8515,8 @@ var processPropsAttributes = (props) => {
8491
8515
 
8492
8516
  // src/generate/wrapperBuild.ts
8493
8517
  init_esm_shims();
8494
- import { existsSync as existsSync2, readdirSync as readdirSync2, readFileSync as readFileSync2 } from "fs";
8495
- import { join as join2 } from "path";
8518
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
8519
+ import { join as join3 } from "path";
8496
8520
 
8497
8521
  // src/renderer/wrapper.ts
8498
8522
  init_esm_shims();
@@ -8912,7 +8936,7 @@ init_esm_shims();
8912
8936
  function isObject(o) {
8913
8937
  return Object.prototype.toString.call(o) === "[object Object]";
8914
8938
  }
8915
- function isPlainObject(o) {
8939
+ function isPlainObject2(o) {
8916
8940
  var ctor, prot;
8917
8941
  if (isObject(o) === false) return false;
8918
8942
  ctor = o.constructor;
@@ -8936,7 +8960,7 @@ var acceptedArguments9 = [{ name: "glue", defaultValue: "" }];
8936
8960
 
8937
8961
  // node_modules/@christianwiedemann/drupal-twig-extensions/lib/filters/safe_join/twing.js
8938
8962
  function isTraversable(value) {
8939
- if (isPlainObject(value)) {
8963
+ if (isPlainObject2(value)) {
8940
8964
  return true;
8941
8965
  }
8942
8966
  if (value !== null && value !== void 0) {
@@ -10266,7 +10290,11 @@ function createTwigCore(iconPacks) {
10266
10290
  const ctx = buildIconContext(pack, iconId, settings || {});
10267
10291
  try {
10268
10292
  return twig3.twig({ data: pack.template }).render(ctx);
10269
- } catch {
10293
+ } catch (e) {
10294
+ console.error(
10295
+ '[SDC Icons] Error rendering icon "' + packId + ":" + iconId + '":',
10296
+ e
10297
+ );
10270
10298
  return "";
10271
10299
  }
10272
10300
  }
@@ -10274,20 +10302,10 @@ function createTwigCore(iconPacks) {
10274
10302
  twig3 = Twig2;
10275
10303
  if (Twig2.__sdcIconRegistered) return;
10276
10304
  Twig2.__sdcIconRegistered = true;
10277
- Twig2.extendFunction("icon", function(packId, iconId, settings) {
10278
- const pack = iconPacks[packId];
10279
- if (!pack || !iconId) return "";
10280
- const ctx = buildIconContext(pack, iconId, settings || {});
10281
- try {
10282
- return Twig2.twig({ data: pack.template }).render(ctx);
10283
- } catch (e) {
10284
- console.error(
10285
- '[SDC Icons] Error rendering icon "' + packId + ":" + iconId + '":',
10286
- e
10287
- );
10288
- return "";
10289
- }
10290
- });
10305
+ Twig2.extendFunction(
10306
+ "icon",
10307
+ (packId, iconId, settings) => renderIcon2(packId, iconId, settings)
10308
+ );
10291
10309
  }
10292
10310
  return { renderIcon: renderIcon2, registerCore, getTwig: () => twig3 };
10293
10311
  }
@@ -10402,8 +10420,8 @@ function twigWrapperEnv(opts) {
10402
10420
 
10403
10421
  // src/generate/iconPacks.ts
10404
10422
  init_esm_shims();
10405
- import { existsSync, readFileSync, readdirSync, statSync } from "fs";
10406
- import { join, resolve, basename, dirname as dirname2, extname, relative } from "path";
10423
+ import { existsSync, readFileSync, statSync } from "fs";
10424
+ import { join as join2, resolve, basename, dirname as dirname2, extname, relative as relative2 } from "path";
10407
10425
  import { parse as parseYaml } from "yaml";
10408
10426
  function parseSvgFile(raw) {
10409
10427
  const attrs = {};
@@ -10419,32 +10437,22 @@ function parseSvgFile(raw) {
10419
10437
  const content = innerMatch ? innerMatch[1].trim() : "";
10420
10438
  return { content, attrs };
10421
10439
  }
10422
- function scanDir(dir, baseDir, filterExt) {
10440
+ function scanDir(baseDir, filterExt) {
10423
10441
  const results = [];
10424
- let entries2;
10425
- try {
10426
- entries2 = readdirSync(dir, { withFileTypes: true });
10427
- } catch {
10428
- return results;
10429
- }
10430
- for (const entry of entries2) {
10431
- const fullPath = join(dir, entry.name);
10432
- if (entry.isDirectory()) {
10433
- results.push(...scanDir(fullPath, baseDir, filterExt));
10434
- } else if (entry.isFile()) {
10435
- const ext = extname(entry.name);
10436
- if (filterExt && ext.toLowerCase() !== filterExt.toLowerCase()) continue;
10437
- results.push({
10438
- absPath: fullPath,
10439
- iconId: basename(entry.name, ext),
10440
- group: relative(baseDir, dir)
10441
- });
10442
- }
10442
+ for (const entry of listDir(baseDir)) {
10443
+ if (entry.isDirectory) continue;
10444
+ const ext = extname(entry.name);
10445
+ if (filterExt && ext.toLowerCase() !== filterExt.toLowerCase()) continue;
10446
+ results.push({
10447
+ absPath: entry.path,
10448
+ iconId: basename(entry.name, ext),
10449
+ group: posixDirname(entry.relative)
10450
+ });
10443
10451
  }
10444
10452
  return results;
10445
10453
  }
10446
10454
  function resolveSourceEntry(rawSource, nsRoot) {
10447
- if (/^https?:\/\//.test(rawSource)) {
10455
+ if (isRemoteUrl(rawSource)) {
10448
10456
  return [{ absPath: rawSource, iconId: "*", group: "" }];
10449
10457
  }
10450
10458
  const absPath = resolve(nsRoot, rawSource);
@@ -10464,7 +10472,7 @@ function resolveSourceEntry(rawSource, nsRoot) {
10464
10472
  }
10465
10473
  }
10466
10474
  if (!existsSync(baseDir)) return [];
10467
- return scanDir(baseDir, baseDir, filterExt);
10475
+ return scanDir(baseDir, filterExt);
10468
10476
  }
10469
10477
  function loadIconPackFile(iconsFilePath, resolveIconSource) {
10470
10478
  const watchFiles = [iconsFilePath];
@@ -10479,7 +10487,7 @@ function loadIconPackFile(iconsFilePath, resolveIconSource) {
10479
10487
  return { packs, watchFiles };
10480
10488
  }
10481
10489
  if (!raw || typeof raw !== "object") return { packs, watchFiles };
10482
- const toUrl = (absPath) => `sdc-icons/${ns}/${relative(nsRoot, absPath).replace(/\\/g, "/")}`;
10490
+ const toUrl = (absPath) => `sdc-icons/${ns}/${relative2(nsRoot, absPath).replace(/\\/g, "/")}`;
10483
10491
  for (const [packId, packDef] of Object.entries(raw)) {
10484
10492
  if (!packDef || typeof packDef !== "object") continue;
10485
10493
  if (packDef.enabled === false) continue;
@@ -10491,7 +10499,7 @@ function loadIconPackFile(iconsFilePath, resolveIconSource) {
10491
10499
  const sources = [];
10492
10500
  const sourceUrls = [];
10493
10501
  for (const src of resolvedSources) {
10494
- if (/^https?:\/\//.test(src)) {
10502
+ if (isRemoteUrl(src)) {
10495
10503
  sources.push(src);
10496
10504
  sourceUrls.push(src);
10497
10505
  } else {
@@ -10572,7 +10580,7 @@ function collectIconIdsFromData(data, packId, out) {
10572
10580
  }
10573
10581
  }
10574
10582
  async function fetchRemoteSvgIcons(pack, usedIconIds, fetchSvg) {
10575
- const httpSources = pack.sources.filter((s) => /^https?:\/\//.test(s));
10583
+ const httpSources = pack.sources.filter((s) => isRemoteUrl(s));
10576
10584
  if (httpSources.length === 0) return;
10577
10585
  for (const iconId of usedIconIds) {
10578
10586
  if (pack.svgIcons[iconId]) continue;
@@ -10589,7 +10597,7 @@ async function fetchRemoteSvgIcons(pack, usedIconIds, fetchSvg) {
10589
10597
  }
10590
10598
  async function fetchRemoteSprite(pack, fetchSvg) {
10591
10599
  if (pack.extractor !== "svg_sprite") return null;
10592
- const remote = pack.sources.find((s) => /^https?:\/\//.test(s));
10600
+ const remote = pack.sources.find((s) => isRemoteUrl(s));
10593
10601
  if (!remote) return null;
10594
10602
  const content = await fetchSvg(remote);
10595
10603
  if (!content) return null;
@@ -10597,11 +10605,12 @@ async function fetchRemoteSprite(pack, fetchSvg) {
10597
10605
  pack.sourceUrls = [""];
10598
10606
  return content;
10599
10607
  }
10608
+ function iconPackFiles(namespaces) {
10609
+ return namespaces.entries().map(([ns, root]) => [ns, join2(root, `${ns}.icons.yml`)]).filter(([, file]) => existsSync(file));
10610
+ }
10600
10611
  function discoverIconPacks(namespaces, resolveIconSource) {
10601
10612
  const packs = {};
10602
- for (const [ns, nsRoot] of namespaces.entries()) {
10603
- const iconsFile = join(nsRoot, `${ns}.icons.yml`);
10604
- if (!existsSync(iconsFile)) continue;
10613
+ for (const [, iconsFile] of iconPackFiles(namespaces)) {
10605
10614
  const { packs: filePacks } = loadIconPackFile(iconsFile, resolveIconSource);
10606
10615
  Object.assign(packs, filePacks);
10607
10616
  }
@@ -10612,24 +10621,13 @@ function discoverIconPacks(namespaces, resolveIconSource) {
10612
10621
  function collectTemplates(namespaces) {
10613
10622
  const out = {};
10614
10623
  for (const [ns, root] of namespaces.entries()) {
10615
- const componentsRoot = join2(root, "components");
10624
+ const componentsRoot = join3(root, "components");
10616
10625
  const base = existsSync2(componentsRoot) ? componentsRoot : root;
10617
- const walk = (dir, prefix = "") => {
10618
- let entries2;
10619
- try {
10620
- entries2 = readdirSync2(dir, { withFileTypes: true });
10621
- } catch {
10622
- return;
10623
- }
10624
- for (const e of entries2) {
10625
- const full = join2(dir, e.name);
10626
- const rel = prefix ? `${prefix}/${e.name}` : e.name;
10627
- if (e.isDirectory()) walk(full, rel);
10628
- else if (/\.twig$/.test(e.name) || /\.svg/.test(e.name))
10629
- out[`@${ns}/${rel}`] = readFileSync2(full, "utf8");
10630
- }
10631
- };
10632
- walk(base);
10626
+ for (const entry of listDir(base)) {
10627
+ if (entry.isDirectory) continue;
10628
+ if (/\.twig$/.test(entry.name) || /\.svg/.test(entry.name))
10629
+ out[`@${ns}/${entry.relative}`] = readFileSync2(entry.path, "utf8");
10630
+ }
10633
10631
  }
10634
10632
  return out;
10635
10633
  }
@@ -10652,7 +10650,7 @@ async function createBuildWrapperEnv(namespaces, options39, resolveIconSource) {
10652
10650
  const twigLib = options39.twigLib === "twing" ? "twing" : "twig";
10653
10651
  const namespacesMap = {};
10654
10652
  for (const [ns, root] of namespaces.entries())
10655
- namespacesMap[ns] = [join2(root, "components")];
10653
+ namespacesMap[ns] = [join3(root, "components")];
10656
10654
  return createWrapperEnv(twigLib, {
10657
10655
  templates: collectTemplates(namespaces),
10658
10656
  namespaces: namespacesMap,
@@ -10686,12 +10684,12 @@ function renderWrapperStories(env, componentId, stories, fakerArgs) {
10686
10684
 
10687
10685
  // src/generate/componentMetadata.ts
10688
10686
  init_esm_shims();
10689
- import { dirname as dirname3, relative as relative2 } from "path";
10687
+ import { basename as basename2, dirname as dirname3, relative as relative3 } from "path";
10690
10688
  import { cwd } from "process";
10691
10689
  var componentMetadata_default = (id, content) => {
10692
10690
  return {
10693
- path: relative2(cwd(), dirname3(id)),
10694
- machineName: id,
10691
+ path: relative3(cwd(), dirname3(id)),
10692
+ machineName: basename2(id, ".component.yml"),
10695
10693
  status: content.status || "stable",
10696
10694
  name: content.name,
10697
10695
  group: content.group
@@ -10701,48 +10699,256 @@ var componentMetadata_default = (id, content) => {
10701
10699
  // src/generate/validate.ts
10702
10700
  init_esm_shims();
10703
10701
  import { Validator } from "jsonschema";
10704
- import fetch from "node-fetch";
10705
- var validator = new Validator();
10706
- var schemaCache = /* @__PURE__ */ new Map();
10707
- var fetchSchema = async (url) => {
10708
- if (schemaCache.has(url)) {
10709
- return schemaCache.get(url);
10702
+
10703
+ // src/constants.ts
10704
+ init_esm_shims();
10705
+ var DEFAULT_DEPENDENCY_MAP = {
10706
+ "system/base/hidden": [
10707
+ {
10708
+ type: "css",
10709
+ url: "https://cdn.jsdelivr.net/gh/drupal/drupal/core/modules/system/css/components/hidden.module.css"
10710
+ }
10711
+ ],
10712
+ "core/drupalSettings": [
10713
+ {
10714
+ type: "js",
10715
+ url: "https://cdn.jsdelivr.net/gh/drupal/drupal/core/misc/drupalSettingsLoader.js"
10716
+ }
10717
+ ],
10718
+ "core/drupal": [
10719
+ {
10720
+ type: "js",
10721
+ url: "https://cdn.jsdelivr.net/gh/drupal/drupal/core/misc/drupal.js"
10722
+ },
10723
+ {
10724
+ type: "js",
10725
+ url: "https://cdn.jsdelivr.net/gh/drupal/drupal/core/misc/drupal.init.js"
10726
+ }
10727
+ ],
10728
+ "core/once": [
10729
+ {
10730
+ type: "js",
10731
+ url: "https://cdn.jsdelivr.net/npm/@drupal/once@1.0.1/dist/once.min.js"
10732
+ }
10733
+ ]
10734
+ };
10735
+ var TWIG_FILE_RE = /\.twig(\?.*)?$/;
10736
+ var DEFAULT_SCHEMA_URL = "https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json";
10737
+ var DEFAULT_ADDON_OPTIONS = {
10738
+ sdcStorybookOptions: {
10739
+ useBasicArgsForStories: true,
10740
+ twigLib: "twig",
10741
+ validate: false
10742
+ },
10743
+ vitePluginTwingDrupalOptions: {
10744
+ include: TWIG_FILE_RE
10745
+ },
10746
+ vitePluginTwigDrupalOptions: {},
10747
+ jsonSchemaFakerOptions: {
10748
+ failOnInvalidTypes: false,
10749
+ useExamplesValue: true,
10750
+ useDefaultValue: true
10710
10751
  }
10711
- try {
10712
- const response = await fetch(url);
10713
- if (!response.ok) {
10714
- throw new Error(`Failed to fetch schema: ${response.statusText}`);
10752
+ };
10753
+
10754
+ // src/generate/draft-04.schema.json
10755
+ var draft_04_schema_default = {
10756
+ id: "http://json-schema.org/draft-04/schema#",
10757
+ $schema: "http://json-schema.org/draft-04/schema#",
10758
+ description: "Core schema meta-schema",
10759
+ definitions: {
10760
+ schemaArray: {
10761
+ type: "array",
10762
+ minItems: 1,
10763
+ items: { $ref: "#" }
10764
+ },
10765
+ positiveInteger: {
10766
+ type: "integer",
10767
+ minimum: 0
10768
+ },
10769
+ positiveIntegerDefault0: {
10770
+ allOf: [{ $ref: "#/definitions/positiveInteger" }, { default: 0 }]
10771
+ },
10772
+ simpleTypes: {
10773
+ enum: [
10774
+ "array",
10775
+ "boolean",
10776
+ "integer",
10777
+ "null",
10778
+ "number",
10779
+ "object",
10780
+ "string"
10781
+ ]
10782
+ },
10783
+ stringArray: {
10784
+ type: "array",
10785
+ items: { type: "string" },
10786
+ minItems: 1,
10787
+ uniqueItems: true
10715
10788
  }
10716
- const schema = await response.json();
10717
- schemaCache.set(url, schema);
10718
- return schema;
10719
- } catch (error) {
10720
- logger.error({ err: error }, "Error fetching schema");
10721
- throw new Error(`Could not fetch schema from ${url}`);
10789
+ },
10790
+ type: "object",
10791
+ properties: {
10792
+ id: {
10793
+ type: "string"
10794
+ },
10795
+ $schema: {
10796
+ type: "string"
10797
+ },
10798
+ title: {
10799
+ type: "string"
10800
+ },
10801
+ description: {
10802
+ type: "string"
10803
+ },
10804
+ default: {},
10805
+ multipleOf: {
10806
+ type: "number",
10807
+ minimum: 0,
10808
+ exclusiveMinimum: true
10809
+ },
10810
+ maximum: {
10811
+ type: "number"
10812
+ },
10813
+ exclusiveMaximum: {
10814
+ type: "boolean",
10815
+ default: false
10816
+ },
10817
+ minimum: {
10818
+ type: "number"
10819
+ },
10820
+ exclusiveMinimum: {
10821
+ type: "boolean",
10822
+ default: false
10823
+ },
10824
+ maxLength: { $ref: "#/definitions/positiveInteger" },
10825
+ minLength: { $ref: "#/definitions/positiveIntegerDefault0" },
10826
+ pattern: {
10827
+ type: "string",
10828
+ format: "regex"
10829
+ },
10830
+ additionalItems: {
10831
+ anyOf: [{ type: "boolean" }, { $ref: "#" }],
10832
+ default: {}
10833
+ },
10834
+ items: {
10835
+ anyOf: [{ $ref: "#" }, { $ref: "#/definitions/schemaArray" }],
10836
+ default: {}
10837
+ },
10838
+ maxItems: { $ref: "#/definitions/positiveInteger" },
10839
+ minItems: { $ref: "#/definitions/positiveIntegerDefault0" },
10840
+ uniqueItems: {
10841
+ type: "boolean",
10842
+ default: false
10843
+ },
10844
+ maxProperties: { $ref: "#/definitions/positiveInteger" },
10845
+ minProperties: { $ref: "#/definitions/positiveIntegerDefault0" },
10846
+ required: { $ref: "#/definitions/stringArray" },
10847
+ additionalProperties: {
10848
+ anyOf: [{ type: "boolean" }, { $ref: "#" }],
10849
+ default: {}
10850
+ },
10851
+ definitions: {
10852
+ type: "object",
10853
+ additionalProperties: { $ref: "#" },
10854
+ default: {}
10855
+ },
10856
+ properties: {
10857
+ type: "object",
10858
+ additionalProperties: { $ref: "#" },
10859
+ default: {}
10860
+ },
10861
+ patternProperties: {
10862
+ type: "object",
10863
+ additionalProperties: { $ref: "#" },
10864
+ default: {}
10865
+ },
10866
+ dependencies: {
10867
+ type: "object",
10868
+ additionalProperties: {
10869
+ anyOf: [{ $ref: "#" }, { $ref: "#/definitions/stringArray" }]
10870
+ }
10871
+ },
10872
+ enum: {
10873
+ type: "array",
10874
+ minItems: 1,
10875
+ uniqueItems: true
10876
+ },
10877
+ type: {
10878
+ anyOf: [
10879
+ { $ref: "#/definitions/simpleTypes" },
10880
+ {
10881
+ type: "array",
10882
+ items: { $ref: "#/definitions/simpleTypes" },
10883
+ minItems: 1,
10884
+ uniqueItems: true
10885
+ }
10886
+ ]
10887
+ },
10888
+ format: { type: "string" },
10889
+ allOf: { $ref: "#/definitions/schemaArray" },
10890
+ anyOf: { $ref: "#/definitions/schemaArray" },
10891
+ oneOf: { $ref: "#/definitions/schemaArray" },
10892
+ not: { $ref: "#" }
10893
+ },
10894
+ dependencies: {
10895
+ exclusiveMaximum: ["maximum"],
10896
+ exclusiveMinimum: ["minimum"]
10897
+ },
10898
+ default: {}
10899
+ };
10900
+
10901
+ // src/generate/validate.ts
10902
+ var DRAFT04_ID = "http://json-schema.org/draft-04/schema";
10903
+ var MAX_REF_ROUNDS = 20;
10904
+ var schemaCache = /* @__PURE__ */ new Map();
10905
+ var fetchSchema = (url) => {
10906
+ let pending = schemaCache.get(url);
10907
+ if (!pending) {
10908
+ pending = (async () => {
10909
+ const response = await fetch(url);
10910
+ if (!response.ok) {
10911
+ throw new Error(`Failed to fetch schema ${url}: ${response.statusText}`);
10912
+ }
10913
+ return await response.json();
10914
+ })();
10915
+ pending.catch(() => schemaCache.delete(url));
10916
+ schemaCache.set(url, pending);
10722
10917
  }
10918
+ return pending;
10919
+ };
10920
+ var schemaUrlFor = (content, validate) => {
10921
+ if (validate === true) return content.$schema || DEFAULT_SCHEMA_URL;
10922
+ if (typeof validate === "string" && validate)
10923
+ return content.$schema || validate;
10924
+ return void 0;
10723
10925
  };
10724
10926
  var validateJson = async (data, schemaUrl) => {
10927
+ const validator = new Validator();
10928
+ validator.addSchema(draft_04_schema_default, DRAFT04_ID);
10725
10929
  const rootSchema = await fetchSchema(schemaUrl);
10726
10930
  validator.addSchema(rootSchema, schemaUrl);
10727
- const unresolvedRefs = validator.unresolvedRefs;
10728
- while (unresolvedRefs.length > 0) {
10729
- const refUrl = unresolvedRefs.shift();
10730
- const schema = await fetchSchema(refUrl);
10731
- validator.addSchema(schema, refUrl);
10732
- }
10733
- const validationResult = validator.validate(data, rootSchema);
10734
- if (validationResult.errors.length > 0) {
10735
- logger.warn(`
10736
- ${data.name}.component.yml has validation errors:
10737
- ${validationResult.errors.map((error) => error.stack).join("\n")}
10738
- `);
10931
+ const loaded = /* @__PURE__ */ new Set([schemaUrl, DRAFT04_ID]);
10932
+ for (let round = 0; validator.unresolvedRefs.length > 0 && round < MAX_REF_ROUNDS; round++) {
10933
+ const ref = validator.unresolvedRefs.shift();
10934
+ const document = ref.split("#")[0];
10935
+ if (!document || loaded.has(document)) continue;
10936
+ loaded.add(document);
10937
+ validator.addSchema(await fetchSchema(document), document);
10938
+ }
10939
+ const result = validator.validate(data, rootSchema);
10940
+ if (result.errors.length > 0) {
10941
+ logger.warn(
10942
+ `${data.name}.component.yml has validation errors:
10943
+ ${result.errors.map((error) => error.stack).join("\n")}`
10944
+ );
10739
10945
  }
10740
10946
  };
10741
10947
 
10742
10948
  // src/generate/namespaces.ts
10743
10949
  init_esm_shims();
10744
- import { readdirSync as readdirSync3, existsSync as existsSync3 } from "fs";
10745
- import { basename as basename2, join as join3, resolve as resolve2, sep as sep2, relative as relative3 } from "path";
10950
+ import { existsSync as existsSync3 } from "fs";
10951
+ import { basename as basename3, join as join4, resolve as resolve2, sep as sep2, relative as relative4 } from "path";
10746
10952
  import { cwd as cwd2 } from "process";
10747
10953
  import { normalizePath } from "vite";
10748
10954
  var getProjectName = (p) => {
@@ -10754,37 +10960,20 @@ var getProjectName = (p) => {
10754
10960
  }
10755
10961
  return parts[i - 1];
10756
10962
  };
10757
- var getAllSubdirectoriesRecursive = (baseDir) => {
10758
- const result = [];
10759
- const scan = (dir) => {
10760
- try {
10761
- const entries2 = readdirSync3(dir, { withFileTypes: true });
10762
- for (const entry of entries2) {
10763
- if (entry.isDirectory()) {
10764
- const fullPath = join3(dir, entry.name);
10765
- result.push(fullPath);
10766
- scan(fullPath);
10767
- }
10768
- }
10769
- } catch (error) {
10770
- }
10771
- };
10772
- scan(baseDir);
10773
- return result;
10774
- };
10963
+ var getAllSubdirectoriesRecursive = (baseDir) => listDir(baseDir).filter((entry) => entry.isDirectory).map((entry) => entry.path);
10775
10964
  var resolveComponentPath = (namespace, component, namespaces) => {
10776
10965
  const baseDir = namespaces.findPath(namespace);
10777
10966
  if (!baseDir) return void 0;
10778
10967
  const componentFileName = `${component}.component.yml`;
10779
- const directPath = join3(baseDir, "components", component, componentFileName);
10968
+ const directPath = join4(baseDir, "components", component, componentFileName);
10780
10969
  if (existsSync3(directPath)) return directPath;
10781
- const componentsDir = join3(baseDir, "components");
10970
+ const componentsDir = join4(baseDir, "components");
10782
10971
  const directories = [
10783
10972
  componentsDir,
10784
10973
  ...getAllSubdirectoriesRecursive(componentsDir)
10785
10974
  ];
10786
10975
  for (const dir of directories) {
10787
- const possiblePath = join3(dir, component, componentFileName);
10976
+ const possiblePath = join4(dir, component, componentFileName);
10788
10977
  if (existsSync3(possiblePath)) return possiblePath;
10789
10978
  }
10790
10979
  return void 0;
@@ -10797,13 +10986,13 @@ var Namespaces = class {
10797
10986
  if (namespaceDefinition.namespace) {
10798
10987
  this.namespaces[namespaceDefinition.namespace] = cwd2();
10799
10988
  } else {
10800
- this.namespaces[basename2(cwd2())] = cwd2();
10989
+ this.namespaces[basename3(cwd2())] = cwd2();
10801
10990
  }
10802
10991
  logger.info(`REGISTER NAMESPACES: ${JSON.stringify(this.namespaces)}`);
10803
10992
  }
10804
10993
  // The namespace's components/ dir when present, else the root itself.
10805
10994
  componentsRoot(path2) {
10806
- const componentsPath = join3(path2, "components");
10995
+ const componentsPath = join4(path2, "components");
10807
10996
  return existsSync3(componentsPath) ? componentsPath : path2;
10808
10997
  }
10809
10998
  toViteAlias() {
@@ -10853,7 +11042,7 @@ var Namespaces = class {
10853
11042
  );
10854
11043
  }
10855
11044
  const rootPath = resolve2(this.namespaces[ns]);
10856
- const componentsDir = join3(rootPath, "components");
11045
+ const componentsDir = join4(rootPath, "components");
10857
11046
  if (existsSync3(componentsDir)) {
10858
11047
  const isExact = fsPath === componentsDir;
10859
11048
  const isChild = fsPath.startsWith(componentsDir + sep2);
@@ -10862,7 +11051,7 @@ var Namespaces = class {
10862
11051
  `Could not find 'components' folder in path: ${fsPath}, namespace: ${ns} (${Object.values(this.namespaces).join(", ")})`
10863
11052
  );
10864
11053
  }
10865
- let rel = relative3(componentsDir, fsPath);
11054
+ let rel = relative4(componentsDir, fsPath);
10866
11055
  if (sep2 !== "/") {
10867
11056
  rel = rel.split(sep2).join("/");
10868
11057
  }
@@ -10880,15 +11069,14 @@ var toNamespaces = (namespaceDefinition) => {
10880
11069
 
10881
11070
  // src/vite/sdcTwigRuntime.ts
10882
11071
  init_esm_shims();
10883
- import { existsSync as existsSync4, readdirSync as readdirSync4, readFileSync as readFileSync3 } from "fs";
10884
- import { join as join4 } from "path";
11072
+ import { readFileSync as readFileSync3 } from "fs";
11073
+ import { join as join5 } from "path";
10885
11074
  import { parse as parseYaml2 } from "yaml";
10886
- import fetch2 from "node-fetch";
10887
11075
  var remoteSvgCache = /* @__PURE__ */ new Map();
10888
11076
  async function fetchSvgFromUrl(url) {
10889
11077
  if (remoteSvgCache.has(url)) return remoteSvgCache.get(url) ?? null;
10890
11078
  try {
10891
- const res = await fetch2(url);
11079
+ const res = await fetch(url);
10892
11080
  if (!res.ok) {
10893
11081
  remoteSvgCache.set(url, null);
10894
11082
  return null;
@@ -10903,27 +11091,16 @@ async function fetchSvgFromUrl(url) {
10903
11091
  }
10904
11092
  function readNamespaceYamlData(namespaces) {
10905
11093
  const out = [];
10906
- const walk = (dir) => {
10907
- let entries2;
10908
- try {
10909
- entries2 = readdirSync4(dir, { withFileTypes: true });
10910
- } catch {
10911
- return;
10912
- }
10913
- for (const entry of entries2) {
10914
- const full = join4(dir, entry.name);
10915
- if (entry.isDirectory()) {
10916
- walk(full);
10917
- } else if (entry.name.endsWith(".story.yml") || entry.name.endsWith(".component.yml")) {
10918
- try {
10919
- out.push(parseYaml2(readFileSync3(full, "utf8")));
10920
- } catch {
10921
- }
11094
+ for (const [, root] of namespaces.entries()) {
11095
+ for (const entry of listDir(join5(root, "components"))) {
11096
+ if (entry.isDirectory) continue;
11097
+ if (!entry.name.endsWith(".story.yml") && !entry.name.endsWith(".component.yml"))
11098
+ continue;
11099
+ try {
11100
+ out.push(parseYaml2(readFileSync3(entry.path, "utf8")));
11101
+ } catch {
10922
11102
  }
10923
11103
  }
10924
- };
10925
- for (const [, root] of namespaces.entries()) {
10926
- walk(join4(root, "components"));
10927
11104
  }
10928
11105
  return out;
10929
11106
  }
@@ -10949,6 +11126,29 @@ export { PrintableArray } from 'storybook-addon-sdc/renderer/${lib}';
10949
11126
  export const { renderIcon, registerSdcRuntime } = ${factory}(${mergeExpr});
10950
11127
  `;
10951
11128
  }
11129
+ var TWING_ENV_ID = "virtual:twing-env";
11130
+ var TWING_ENV_LOADER_LINE = "const loader = createSDCLoader(allSources, twingNamespaces);";
11131
+ function twingEnvAliases(namespaces) {
11132
+ const pairs = [];
11133
+ for (const dirs of Object.values(namespaces.toTwingNamespaces() ?? {})) {
11134
+ for (const dir of dirs) {
11135
+ for (const entry of listDir(dir)) {
11136
+ if (entry.isDirectory) continue;
11137
+ if (!/\.(twig|svg)$/.test(entry.name)) continue;
11138
+ pairs.push([entry.path, entry.relative]);
11139
+ }
11140
+ }
11141
+ }
11142
+ return pairs;
11143
+ }
11144
+ function injectTwingEnvAliases(code, namespaces) {
11145
+ if (!code.includes(TWING_ENV_LOADER_LINE)) return code;
11146
+ const aliasCode = `for (const [abs, rel] of ${jsLiteral(twingEnvAliases(namespaces))}) {
11147
+ if (!(abs in allSources) && rel in allSources) allSources[abs] = allSources[rel];
11148
+ }
11149
+ ${TWING_ENV_LOADER_LINE}`;
11150
+ return code.replace(TWING_ENV_LOADER_LINE, aliasCode);
11151
+ }
10952
11152
  var TWIG_JS_MARKER = "from 'drupal-twig-extensions/twig'";
10953
11153
  var TWIG_JS_INJECT_AFTER = "addDrupalExtensions(Twig);";
10954
11154
  var TWING_MARKER = "createSynchronousEnvironment";
@@ -10964,7 +11164,7 @@ function sdcTwigRuntimePlugin(namespaces, resolveIconSource) {
10964
11164
  },
10965
11165
  async load(id) {
10966
11166
  if (id === RESOLVED_TWIG || id === RESOLVED_TWING) {
10967
- const packFilePaths = namespaces.entries().map(([ns, root]) => join4(root, `${ns}.icons.yml`)).filter((p) => existsSync4(p));
11167
+ const packFilePaths = iconPackFiles(namespaces).map(([, file]) => file);
10968
11168
  return generateRuntimeGlue(
10969
11169
  packFilePaths,
10970
11170
  id === RESOLVED_TWIG ? "twig" : "twing"
@@ -10978,7 +11178,7 @@ function sdcTwigRuntimePlugin(namespaces, resolveIconSource) {
10978
11178
  );
10979
11179
  watchFiles.forEach((f) => this.addWatchFile(f));
10980
11180
  const remotePacks = Object.values(packs).filter(
10981
- (p) => p.extractor === "svg" && p.sources.some((s) => /^https?:\/\//.test(s))
11181
+ (p) => p.extractor === "svg" && p.sources.some((s) => isRemoteUrl(s))
10982
11182
  );
10983
11183
  if (remotePacks.length > 0) {
10984
11184
  const yamlData = readNamespaceYamlData(namespaces);
@@ -10992,7 +11192,7 @@ function sdcTwigRuntimePlugin(namespaces, resolveIconSource) {
10992
11192
  }
10993
11193
  const sprites = {};
10994
11194
  for (const pack of Object.values(packs)) {
10995
- if (pack.extractor === "svg_sprite" && pack.sources.some((s) => /^https?:\/\//.test(s))) {
11195
+ if (pack.extractor === "svg_sprite" && pack.sources.some((s) => isRemoteUrl(s))) {
10996
11196
  const content = await fetchRemoteSprite(pack, fetchSvgFromUrl);
10997
11197
  if (content) sprites[pack.packId] = content;
10998
11198
  }
@@ -11026,8 +11226,10 @@ if (typeof document !== 'undefined') {
11026
11226
  }
11027
11227
  },
11028
11228
  transform(code, id) {
11029
- if (!id.match(/\.twig(\?.*)?$/)) return null;
11229
+ const isSharedEnv = id === TWING_ENV_ID;
11230
+ if (!isSharedEnv && !TWIG_FILE_RE.test(id)) return null;
11030
11231
  if (code.includes(INJECTED_GUARD)) return null;
11232
+ if (isSharedEnv) code = injectTwingEnvAliases(code, namespaces);
11031
11233
  const variants = [
11032
11234
  {
11033
11235
  marker: TWING_MARKER,
@@ -11070,13 +11272,18 @@ ${INJECTED_GUARD}(${v.arg});`),
11070
11272
 
11071
11273
  // src/vite/storybookYamlStories.ts
11072
11274
  var _wrapperEnv;
11073
- var readSDC = (filePath, defs, validate) => {
11275
+ var readSDC = async (filePath, defs, validate) => {
11074
11276
  const sdcSchema = {
11075
11277
  $defs: defs,
11076
11278
  ...parseYaml3(readFileSync4(filePath, "utf8"))
11077
11279
  };
11078
- if (typeof validate === "string" && validate.length > 0) {
11079
- validateJson(sdcSchema, sdcSchema["$schema"] || validate);
11280
+ const schemaUrl = schemaUrlFor(sdcSchema, validate);
11281
+ if (schemaUrl) {
11282
+ try {
11283
+ await validateJson(sdcSchema, schemaUrl);
11284
+ } catch (error) {
11285
+ logger.warn(`Could not validate ${filePath}: ${error}`);
11286
+ }
11080
11287
  }
11081
11288
  return sdcSchema;
11082
11289
  };
@@ -11099,6 +11306,9 @@ export async function injectAssets(assets) {
11099
11306
  if (asset.type === 'js') {
11100
11307
  const s = document.createElement('script')
11101
11308
  applyAttrs(s, asset.attributes)
11309
+ // Inserted scripts run in load order unless async is off; dependencies
11310
+ // (jquery before jquery-ui) must execute in the order they are listed.
11311
+ s.async = false
11102
11312
  s.src = asset.url; s.onload = res; s.onerror = rej; document.head.appendChild(s)
11103
11313
  } else {
11104
11314
  const l = document.createElement('link'); l.rel = 'stylesheet'
@@ -11119,9 +11329,9 @@ var dynamicImports = (stories, namespaces) => {
11119
11329
  componentName,
11120
11330
  namespaces
11121
11331
  );
11122
- const kebabCaseName = convertToKebabCase(item.component);
11332
+ const identifier = toIdentifier(item.component);
11123
11333
  if (resolvedPath) {
11124
- imports.add(`import * as ${kebabCaseName} from '${resolvedPath}';`);
11334
+ imports.add(`import * as ${identifier} from '${resolvedPath}';`);
11125
11335
  }
11126
11336
  };
11127
11337
  const extractComponentImports = (args) => {
@@ -11147,25 +11357,20 @@ var dynamicImports = (stories, namespaces) => {
11147
11357
  return Array.from(imports).join("\n");
11148
11358
  };
11149
11359
  var CSS_GROUPS = ["base", "layout", "component", "state", "theme"];
11150
- var isExternalUrl = (s) => s.startsWith("http://") || s.startsWith("https://");
11151
11360
  var isDisabled = (opts) => opts === false;
11152
11361
  var extractCssAssets = (library) => CSS_GROUPS.flatMap(
11153
- (group) => Object.entries(library.css?.[group] ?? {}).filter(([url, opts]) => isExternalUrl(url) && !isDisabled(opts)).map(
11154
- ([url, opts]) => ({
11155
- type: "css",
11156
- url,
11157
- media: opts.media,
11158
- attributes: opts.attributes
11159
- })
11160
- )
11161
- );
11162
- var extractJsAssets = (library) => Object.entries(library.js ?? {}).filter(([url, opts]) => isExternalUrl(url) && !isDisabled(opts)).map(
11163
- ([url, opts]) => ({
11164
- type: "js",
11362
+ (group) => Object.entries(library.css?.[group] ?? {}).filter(([url, opts]) => isRemoteUrl(url) && !isDisabled(opts)).map(([url, opts]) => ({
11363
+ type: "css",
11165
11364
  url,
11365
+ media: opts.media,
11166
11366
  attributes: opts.attributes
11167
- })
11367
+ }))
11168
11368
  );
11369
+ var extractJsAssets = (library) => Object.entries(library.js ?? {}).filter(([url, opts]) => isRemoteUrl(url) && !isDisabled(opts)).map(([url, opts]) => ({
11370
+ type: "js",
11371
+ url,
11372
+ attributes: opts.attributes
11373
+ }));
11169
11374
  var libraryOverridesImports = (content, dependencyMap = {}) => {
11170
11375
  const overrides = content.libraryOverrides;
11171
11376
  if (!overrides) return [];
@@ -11187,7 +11392,7 @@ var libraryOverridesLocalImports = (content) => {
11187
11392
  const seenCss = /* @__PURE__ */ new Set();
11188
11393
  for (const group of CSS_GROUPS) {
11189
11394
  for (const [url, opts] of Object.entries(overrides.css?.[group] ?? {})) {
11190
- if (isDisabled(opts) || isExternalUrl(url)) continue;
11395
+ if (isDisabled(opts) || isRemoteUrl(url)) continue;
11191
11396
  const path2 = normalizeLocalPath(url);
11192
11397
  if (isGlobCoveredCss(path2) || seenCss.has(path2)) continue;
11193
11398
  seenCss.add(path2);
@@ -11197,7 +11402,7 @@ var libraryOverridesLocalImports = (content) => {
11197
11402
  const js = [];
11198
11403
  const seenJs = /* @__PURE__ */ new Set();
11199
11404
  for (const [url, opts] of Object.entries(overrides.js ?? {})) {
11200
- if (isDisabled(opts) || isExternalUrl(url)) continue;
11405
+ if (isDisabled(opts) || isRemoteUrl(url)) continue;
11201
11406
  const path2 = normalizeLocalPath(url);
11202
11407
  if (isGlobCoveredJs(path2) || seenJs.has(path2)) continue;
11203
11408
  seenJs.add(path2);
@@ -11206,7 +11411,7 @@ var libraryOverridesLocalImports = (content) => {
11206
11411
  return { css, js };
11207
11412
  };
11208
11413
  var twigDependencyImports = (twigFilePath, namespaces) => {
11209
- if (!existsSync5(twigFilePath)) return "";
11414
+ if (!existsSync4(twigFilePath)) return "";
11210
11415
  const twigContent = readFileSync4(twigFilePath, "utf8");
11211
11416
  const imports = /* @__PURE__ */ new Set();
11212
11417
  const pattern = /{%-?\s*(?:include|embed|extends)\s+['"]([a-zA-Z0-9_-]+:[a-zA-Z0-9_/-]+)['"]/g;
@@ -11272,7 +11477,11 @@ var storybookYamlStories_default = ({
11272
11477
  }
11273
11478
  if (!id.endsWith("component.yml")) return;
11274
11479
  try {
11275
- const content = readSDC(id, globalDefs, sdcStorybookOptions.validate);
11480
+ const content = await readSDC(
11481
+ id,
11482
+ globalDefs,
11483
+ sdcStorybookOptions.validate
11484
+ );
11276
11485
  const externalAssets = libraryOverridesImports(
11277
11486
  content,
11278
11487
  sdcStorybookOptions.dependencyMap ?? {}
@@ -11288,9 +11497,9 @@ var storybookYamlStories_default = ({
11288
11497
  };
11289
11498
  registerCustomNodes(sdcStorybookOptions.customNodes);
11290
11499
  const storiesImports = dynamicImports(previewsStories, namespaces);
11291
- const componentBaseName = basename3(id, ".component.yml");
11500
+ const componentBaseName = basename4(id, ".component.yml");
11292
11501
  const namespace = namespaces.pathToNamespace(dirname4(id));
11293
- const twigFile = join5(dirname4(id), `${componentBaseName}.twig`);
11502
+ const twigFile = join6(dirname4(id), `${componentBaseName}.twig`);
11294
11503
  const twigImports = twigDependencyImports(twigFile, namespaces);
11295
11504
  const metadata = componentMetadata_default(id, content);
11296
11505
  const componentGlobals = content?.thirdPartySettings?.sdcStorybook?.globals ?? {};
@@ -11404,7 +11613,7 @@ var yamlStoriesIndexer = {
11404
11613
  test: /component\.yml$/,
11405
11614
  createIndex: async (fileName, { makeTitle }) => {
11406
11615
  try {
11407
- const content = readSDC(fileName);
11616
+ const content = await readSDC(fileName);
11408
11617
  const group = content.group || deriveGroupFromPath(fileName);
11409
11618
  const baseTitle = makeTitle(
11410
11619
  `${getProjectName(fileName)}/${capitalize(group)}/${content.name}`
@@ -11435,30 +11644,13 @@ var yamlStoriesIndexer = {
11435
11644
  }
11436
11645
  };
11437
11646
  var collectStoryFilesSync = (rootDir) => {
11438
- const out = [];
11439
- const walk = (dir, isRoot) => {
11440
- let entries2;
11441
- try {
11442
- entries2 = readdirSync5(dir, { withFileTypes: true });
11443
- } catch {
11444
- return;
11445
- }
11446
- if (!isRoot && entries2.some(
11447
- (entry) => entry.isFile() && entry.name.endsWith(".component.yml")
11448
- )) {
11449
- return;
11450
- }
11451
- for (const entry of entries2) {
11452
- const full = join5(dir, entry.name);
11453
- if (entry.isDirectory()) {
11454
- walk(full, false);
11455
- } else if (entry.name.endsWith(".story.yml")) {
11456
- out.push(full);
11457
- }
11458
- }
11459
- };
11460
- walk(rootDir, true);
11461
- return out;
11647
+ const files = listDir(rootDir).filter((entry) => !entry.isDirectory);
11648
+ const foreign = files.filter(
11649
+ (entry) => entry.name.endsWith(".component.yml") && entry.relative.includes("/")
11650
+ ).map((entry) => posixDirname(entry.relative) + "/");
11651
+ return files.filter(
11652
+ (entry) => entry.name.endsWith(".story.yml") && !foreign.some((dir) => entry.relative.startsWith(dir))
11653
+ ).map((entry) => entry.path);
11462
11654
  };
11463
11655
  var loadStoryFilesSync = (fileName) => {
11464
11656
  const folderPath = dirname4(fileName);
@@ -11466,7 +11658,7 @@ var loadStoryFilesSync = (fileName) => {
11466
11658
  return storyFiles.reduce(
11467
11659
  (acc, file) => {
11468
11660
  const content = readFileSync4(file, "utf8");
11469
- const rawKey = basename3(file).split(".")[1];
11661
+ const rawKey = basename4(file).split(".")[1];
11470
11662
  const key = sanitizeStoryKey(rawKey);
11471
11663
  if (Object.prototype.hasOwnProperty.call(acc, key)) {
11472
11664
  logger.warn(
@@ -11489,11 +11681,10 @@ import { mergeConfig } from "vite";
11489
11681
  init_esm_shims();
11490
11682
  import { parse } from "yaml";
11491
11683
  import { readFileSync as readFileSync5 } from "fs";
11492
- import fetch3 from "node-fetch";
11493
11684
  async function loadExternalDef(defPath) {
11494
11685
  try {
11495
- if (defPath.startsWith("http://") || defPath.startsWith("https://")) {
11496
- const response = await fetch3(defPath);
11686
+ if (isRemoteUrl(defPath)) {
11687
+ const response = await fetch(defPath);
11497
11688
  if (!response.ok) {
11498
11689
  throw new Error(`Failed to fetch ${defPath}: ${response.statusText}`);
11499
11690
  }
@@ -11533,61 +11724,9 @@ async function loadAndMergeDefinitions(externalDefs, customDefs) {
11533
11724
  return globalDefs;
11534
11725
  }
11535
11726
 
11536
- // src/constants.ts
11537
- init_esm_shims();
11538
- var DEFAULT_DEPENDENCY_MAP = {
11539
- "system/base/hidden": [
11540
- {
11541
- type: "css",
11542
- url: "https://cdn.jsdelivr.net/gh/drupal/drupal/core/modules/system/css/components/hidden.module.css"
11543
- }
11544
- ],
11545
- "core/drupalSettings": [
11546
- {
11547
- type: "js",
11548
- url: "https://cdn.jsdelivr.net/gh/drupal/drupal/core/misc/drupalSettingsLoader.js"
11549
- }
11550
- ],
11551
- "core/drupal": [
11552
- {
11553
- type: "js",
11554
- url: "https://cdn.jsdelivr.net/gh/drupal/drupal/core/misc/drupal.js"
11555
- },
11556
- {
11557
- type: "js",
11558
- url: "https://cdn.jsdelivr.net/gh/drupal/drupal/core/misc/drupal.init.js"
11559
- }
11560
- ],
11561
- "core/once": [
11562
- {
11563
- type: "js",
11564
- url: "https://cdn.jsdelivr.net/npm/@drupal/once@1.0.1/dist/once.min.js"
11565
- }
11566
- ]
11567
- };
11568
- var DEFAULT_ADDON_OPTIONS = {
11569
- sdcStorybookOptions: {
11570
- useBasicArgsForStories: true,
11571
- twigLib: "twig",
11572
- validate: false
11573
- // validate:
11574
- // 'https://git.drupalcode.org/project/drupal/-/raw/HEAD/core/assets/schemas/v1/metadata.schema.json',
11575
- },
11576
- vitePluginTwingDrupalOptions: {
11577
- include: /\.twig(\?.*)?$/
11578
- },
11579
- vitePluginTwigDrupalOptions: {},
11580
- jsonSchemaFakerOptions: {
11581
- failOnInvalidTypes: false,
11582
- useExamplesValue: true,
11583
- useDefaultValue: true
11584
- }
11585
- };
11586
-
11587
11727
  // src/preset.ts
11588
- import { merge as lodashMerge } from "lodash-es";
11589
- async function viteFinal(config, options39) {
11590
- options39 = lodashMerge({}, DEFAULT_ADDON_OPTIONS, options39);
11728
+ async function viteFinal(config, userOptions) {
11729
+ const options39 = mergeOptions(DEFAULT_ADDON_OPTIONS, userOptions);
11591
11730
  const {
11592
11731
  sdcStorybookOptions,
11593
11732
  vitePluginTwigDrupalOptions,
@@ -11656,23 +11795,21 @@ var experimental_indexers = async (existingIndexers) => [
11656
11795
  yamlStoriesIndexer
11657
11796
  ];
11658
11797
  var staticDirs = async (existing, options39) => {
11659
- const merged = lodashMerge({}, DEFAULT_ADDON_OPTIONS, options39);
11798
+ const merged = mergeOptions(DEFAULT_ADDON_OPTIONS, options39);
11660
11799
  const namespaces = toNamespaces(merged.sdcStorybookOptions);
11661
11800
  const iconDirs = [];
11662
- for (const [ns, nsRoot] of namespaces.entries()) {
11663
- const iconsFile = join6(nsRoot, `${ns}.icons.yml`);
11664
- if (!existsSync6(iconsFile)) continue;
11801
+ for (const [ns, iconsFile] of iconPackFiles(namespaces)) {
11802
+ const nsRoot = dirname5(iconsFile);
11665
11803
  const { packs } = loadIconPackFile(iconsFile);
11666
11804
  const seen = /* @__PURE__ */ new Set();
11667
11805
  for (const pack of Object.values(packs)) {
11668
11806
  if (pack.extractor === "svg") continue;
11669
11807
  for (const src of pack.sources) {
11670
- if (src.startsWith("http")) continue;
11671
- if (!existsSync6(src)) continue;
11808
+ if (isRemoteUrl(src) || !existsSync5(src)) continue;
11672
11809
  const dir = statSync2(src).isDirectory() ? src : dirname5(src);
11673
11810
  if (seen.has(dir)) continue;
11674
11811
  seen.add(dir);
11675
- const relDir = relative4(nsRoot, dir).replace(/\\/g, "/");
11812
+ const relDir = relative5(nsRoot, dir).replace(/\\/g, "/");
11676
11813
  iconDirs.push({ from: dir, to: `/sdc-icons/${ns}/${relDir}` });
11677
11814
  }
11678
11815
  }
@@ -104,7 +104,11 @@ function createTwigCore(iconPacks) {
104
104
  const ctx = buildIconContext(pack, iconId, settings || {});
105
105
  try {
106
106
  return twig.twig({ data: pack.template }).render(ctx);
107
- } catch {
107
+ } catch (e) {
108
+ console.error(
109
+ '[SDC Icons] Error rendering icon "' + packId + ":" + iconId + '":',
110
+ e
111
+ );
108
112
  return "";
109
113
  }
110
114
  }
@@ -112,20 +116,10 @@ function createTwigCore(iconPacks) {
112
116
  twig = Twig;
113
117
  if (Twig.__sdcIconRegistered) return;
114
118
  Twig.__sdcIconRegistered = true;
115
- Twig.extendFunction("icon", function(packId, iconId, settings) {
116
- const pack = iconPacks[packId];
117
- if (!pack || !iconId) return "";
118
- const ctx = buildIconContext(pack, iconId, settings || {});
119
- try {
120
- return Twig.twig({ data: pack.template }).render(ctx);
121
- } catch (e) {
122
- console.error(
123
- '[SDC Icons] Error rendering icon "' + packId + ":" + iconId + '":',
124
- e
125
- );
126
- return "";
127
- }
128
- });
119
+ Twig.extendFunction(
120
+ "icon",
121
+ (packId, iconId, settings) => renderIcon(packId, iconId, settings)
122
+ );
129
123
  }
130
124
  return { renderIcon, registerCore, getTwig: () => twig };
131
125
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "storybook-addon-sdc",
3
- "version": "0.25.1",
3
+ "version": "0.26.0",
4
4
  "description": "Drupal Single Directory Components as stories",
5
5
  "keywords": [
6
6
  "SDC",
@@ -38,18 +38,15 @@
38
38
  "storybook": "storybook dev -p 6006",
39
39
  "build-storybook": "storybook build",
40
40
  "serve": "npx http-server ./storybook-static",
41
- "format": "prettier --write ."
41
+ "format": "prettier --write .",
42
+ "test:e2e": "vitest run --config vitest.e2e.config.ts"
42
43
  },
43
44
  "dependencies": {
44
- "json-schema-faker": "^0.6.2",
45
+ "json-schema-faker": "^0.6.4",
45
46
  "jsonschema": "^1.5.0",
46
- "lodash-es": "^4.18.1",
47
- "node-fetch": "^3.3.2",
48
- "pino": "^10.3.1",
49
- "pino-pretty": "^13.1.3",
50
47
  "vite-plugin-twig-drupal": "^1.7.0",
51
- "vite-plugin-twing-drupal": "^1.1.2",
52
- "yaml": "^2.8.4"
48
+ "vite-plugin-twing-drupal": "^1.1.4",
49
+ "yaml": "^2.9.1"
53
50
  },
54
51
  "peerDependencies": {
55
52
  "@storybook/html-vite": "^10.4.6 || ^11.0.0-beta.0",
@@ -58,28 +55,27 @@
58
55
  "twing": "^7.3.1"
59
56
  },
60
57
  "devDependencies": {
61
- "@storybook/addon-a11y": "^11.0.0-beta.0",
62
- "@storybook/addon-docs": "^11.0.0-beta.0",
63
- "@storybook/html-vite": "^11.0.0-beta.0",
58
+ "@storybook/addon-a11y": "^11.0.0-beta.1",
59
+ "@storybook/addon-docs": "^11.0.0-beta.1",
60
+ "@storybook/html-vite": "^11.0.0-beta.1",
64
61
  "@types/json-schema": "^7.0.15",
65
- "@types/lodash-es": "^4.17.12",
66
62
  "@types/node": "^24.19.2",
67
- "@types/node-fetch": "^2.6.13",
68
63
  "@types/twig": "^1.12.17",
69
64
  "auto": "^11.3.6",
70
65
  "boxen": "^9.0.0",
71
66
  "dedent": "^1.7.2",
72
67
  "drupal-attribute": "^1.2.1",
73
- "prettier": "^3.8.3",
68
+ "playwright": "^1.65.0",
69
+ "prettier": "^3.9.10",
74
70
  "prompts": "^2.4.2",
75
- "react": "^19.2.6",
76
- "react-dom": "^19.2.6",
77
- "storybook": "^11.0.0-beta.0",
71
+ "react": "^19.3.1",
72
+ "react-dom": "^19.3.1",
73
+ "storybook": "^11.0.0-beta.1",
78
74
  "tsup": "^9.0.0",
79
75
  "twing": "^7.3.1",
80
- "typescript": "^5.9.3",
81
- "vite": "^7.3.3",
82
- "vitest": "^4.1.5",
76
+ "typescript": "^6.0.3",
77
+ "vite": "^7.3.8",
78
+ "vitest": "^5.1.0",
83
79
  "zx": "^8.8.5"
84
80
  },
85
81
  "publishConfig": {