storyblok 4.21.2 → 4.22.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/dist/index.mjs CHANGED
@@ -10,7 +10,7 @@ import chalk from 'chalk';
10
10
  import { MultiBar, Presets } from 'cli-progress';
11
11
  import { Spinner } from '@topcli/spinner';
12
12
  import { readPackageUp } from 'read-package-up';
13
- import fs, { mkdir, writeFile, readdir, readFile as readFile$1, appendFile, access, constants, unlink } from 'node:fs/promises';
13
+ import fs, { mkdir, writeFile, readdir, readFile as readFile$1, appendFile, access, constants, unlink, stat } from 'node:fs/promises';
14
14
  import filenamify from 'filenamify';
15
15
  import { createManagementApiClient, normalizeAssetUrl } from '@storyblok/management-api-client';
16
16
  import { select, password, input, confirm } from '@inquirer/prompts';
@@ -136,11 +136,12 @@ const SUPPORTED_ASSET_EXTENSIONS = /* @__PURE__ */ new Set([
136
136
  ".wma",
137
137
  ".m4a",
138
138
  ".opus",
139
- // Documents: application/msword, text/plain, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document
139
+ // Documents: application/msword, text/plain, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document, text/vtt
140
140
  ".pdf",
141
141
  ".doc",
142
142
  ".docx",
143
- ".txt"
143
+ ".txt",
144
+ ".vtt"
144
145
  ]);
145
146
  const directories = {
146
147
  assets: "assets",
@@ -166,6 +167,9 @@ const chunk = (items, size) => {
166
167
  function isPlainObject(value) {
167
168
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
168
169
  }
170
+ function isRecord(value) {
171
+ return typeof value === "object" && value !== null && !Array.isArray(value);
172
+ }
169
173
  function mergeDeep(target, source) {
170
174
  if (!isPlainObject(source)) {
171
175
  return target;
@@ -930,6 +934,20 @@ function createRegexFromGlob(pattern) {
930
934
  return new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*")}$`);
931
935
  }
932
936
 
937
+ let stdoutEpipeGuarded = false;
938
+ function guardStdoutEpipe(ui) {
939
+ if (stdoutEpipeGuarded) {
940
+ return;
941
+ }
942
+ stdoutEpipeGuarded = true;
943
+ process.stdout.on("error", (error) => {
944
+ if (error.code === "EPIPE") {
945
+ return;
946
+ }
947
+ ui.error(`Failed to write to stdout: ${error.message}`);
948
+ process.exitCode = 1;
949
+ });
950
+ }
933
951
  const noopProgressBar = {
934
952
  increment: () => {
935
953
  },
@@ -1038,6 +1056,16 @@ class UI {
1038
1056
  log(message) {
1039
1057
  this.console?.log(message);
1040
1058
  }
1059
+ /**
1060
+ * Writes machine-readable output straight to stdout, bypassing the UI enable
1061
+ * gate. Decorative output is suppressed alongside it (see `--format json`), so
1062
+ * stdout stays a single pipeable document even with `--no-ui-enabled`.
1063
+ */
1064
+ writeMachineOutput(payload) {
1065
+ guardStdoutEpipe(this);
1066
+ process.stdout.write(`${payload}
1067
+ `);
1068
+ }
1041
1069
  list(items) {
1042
1070
  for (const item of items) {
1043
1071
  this.console?.log(` ${item}`);
@@ -4171,6 +4199,7 @@ generateCmd$1.action(async (componentName, options, command) => {
4171
4199
  });
4172
4200
 
4173
4201
  const normalizeFullSlug = (slug) => slug.replace(/\/$/, "");
4202
+ const normalizeStartsWith = (prefix) => prefix.replace(/^\/+/, "");
4174
4203
 
4175
4204
  const fetchStories = async (spaceId, params) => {
4176
4205
  try {
@@ -10215,7 +10244,7 @@ transferCmd.action(async (assetIds, options, command) => {
10215
10244
  const program$2 = getProgram();
10216
10245
  const storiesCommand = program$2.command(commands.STORIES).description(`Manage your space's stories`);
10217
10246
 
10218
- const pullCmd = storiesCommand.command("pull").option("-s, --space <space>", "space ID").option("-d, --dry-run", "Preview changes without applying them to Storyblok").option("-q, --query <query>", 'Filter stories by content attributes using Storyblok filter query syntax. Example: --query="[highlighted][in]=true"').option("--starts-with <path>", 'Filter stories by path. Example: --starts-with="/en/blog/"').description(`Download your space's stories as separate json files.`);
10247
+ const pullCmd = storiesCommand.command("pull").option("-s, --space <space>", "space ID").option("-d, --dry-run", "Preview changes without applying them to Storyblok").option("-q, --query <query>", 'Filter stories by content attributes using Storyblok filter query syntax. Example: --query="[highlighted][in]=true"').option("--starts-with <path>", 'Filter stories by path. Example: --starts-with="en/blog/"').description(`Download your space's stories as separate json files.`);
10219
10248
  pullCmd.action(async (options, command) => {
10220
10249
  const ui = getUI();
10221
10250
  const logger = getLogger();
@@ -10250,7 +10279,9 @@ pullCmd.action(async (options, command) => {
10250
10279
  spaceId: space,
10251
10280
  params: {
10252
10281
  filter_query: options.query ? parseFilterQuery(options.query) : void 0,
10253
- starts_with: options.startsWith
10282
+ // A `full_slug` never starts with a slash and MAPI matches the prefix
10283
+ // literally, so `/en/blog/` would pull nothing at all.
10284
+ starts_with: options.startsWith === void 0 ? void 0 : normalizeStartsWith(options.startsWith) || void 0
10254
10285
  },
10255
10286
  setTotalPages: (totalPages) => {
10256
10287
  summary.fetchStoryPages.total = totalPages;
@@ -10718,12 +10749,481 @@ pushCmd.action(async (options, command) => {
10718
10749
  }
10719
10750
  });
10720
10751
 
10752
+ function isComponent(value) {
10753
+ return isRecord(value) && typeof value.name === "string" && Array.isArray(value.fields);
10754
+ }
10755
+ function isDatasource(value) {
10756
+ return isRecord(value) && typeof value.name === "string" && typeof value.slug === "string" && !Array.isArray(value.fields);
10757
+ }
10758
+ function isFolder(value) {
10759
+ return isRecord(value) && typeof value.name === "string" && typeof value.path === "string" && !Array.isArray(value.fields) && !("slug" in value);
10760
+ }
10761
+ function isFieldPlugin(value) {
10762
+ return isRecord(value) && typeof value.fieldType === "string" && "value" in value;
10763
+ }
10764
+ function isSchemaObject(value) {
10765
+ return isRecord(value) && ("blocks" in value || "datasources" in value || "folders" in value || "fieldPlugins" in value);
10766
+ }
10767
+ function collectSchemaExports(moduleExports) {
10768
+ const components = [];
10769
+ const datasources = [];
10770
+ const folders = [];
10771
+ const fieldPlugins = [];
10772
+ const seen = /* @__PURE__ */ new Set();
10773
+ function collect(value) {
10774
+ if (isComponent(value)) {
10775
+ if (seen.has(value)) {
10776
+ return;
10777
+ }
10778
+ seen.add(value);
10779
+ components.push(value);
10780
+ } else if (isFolder(value)) {
10781
+ if (seen.has(value)) {
10782
+ return;
10783
+ }
10784
+ seen.add(value);
10785
+ folders.push(value);
10786
+ } else if (isDatasource(value)) {
10787
+ if (seen.has(value)) {
10788
+ return;
10789
+ }
10790
+ seen.add(value);
10791
+ datasources.push(value);
10792
+ } else if (isFieldPlugin(value)) {
10793
+ if (seen.has(value)) {
10794
+ return;
10795
+ }
10796
+ seen.add(value);
10797
+ fieldPlugins.push(value);
10798
+ }
10799
+ }
10800
+ for (const value of Object.values(moduleExports)) {
10801
+ if (isSchemaObject(value)) {
10802
+ for (const group of Object.values(value)) {
10803
+ if (isRecord(group)) {
10804
+ for (const entity of Object.values(group)) {
10805
+ collect(entity);
10806
+ }
10807
+ }
10808
+ }
10809
+ } else {
10810
+ collect(value);
10811
+ }
10812
+ }
10813
+ return { components, datasources, folders, fieldPlugins };
10814
+ }
10815
+ async function loadSchemaModule(entryPath) {
10816
+ const entryAbs = resolve(entryPath);
10817
+ try {
10818
+ await stat(entryAbs);
10819
+ } catch {
10820
+ throw new CommandError(`Schema entry file not found at "${entryPath}".`);
10821
+ }
10822
+ const { createJiti } = await import('jiti');
10823
+ const jiti = createJiti(import.meta.url, { interopDefault: true });
10824
+ return await jiti.import(entryAbs);
10825
+ }
10826
+
10827
+ async function validateSchema(schema) {
10828
+ const schemaPkg = await import('@storyblok/schema');
10829
+ return schemaPkg.validateSchema(schema);
10830
+ }
10831
+ async function validateStory(story, schema) {
10832
+ const schemaPkg = await import('@storyblok/schema');
10833
+ return schemaPkg.validateStory(story, schema);
10834
+ }
10835
+ async function loadSchemaEntry(entryPath, options = {}) {
10836
+ const entryMod = await loadSchemaModule(entryPath);
10837
+ const { components, datasources, fieldPlugins } = collectSchemaExports(entryMod);
10838
+ if (components.length === 0 && datasources.length === 0) {
10839
+ throw new CommandError(
10840
+ "No blocks or datasources found in the schema entry file. Verify the file exports schema definitions."
10841
+ );
10842
+ }
10843
+ if (options.requireBlocks && components.length === 0) {
10844
+ throw new CommandError(
10845
+ "No blocks found in the schema entry file. Story content cannot be validated against a schema that defines no blocks."
10846
+ );
10847
+ }
10848
+ const schema = { blocks: components, datasources, fieldPlugins };
10849
+ return { schema, entityCount: components.length + datasources.length };
10850
+ }
10851
+
10852
+ function filterIssuesByLevel(issues, level) {
10853
+ if (level === "warning") {
10854
+ return [...issues];
10855
+ }
10856
+ return issues.filter((issue) => issue.severity === "error");
10857
+ }
10858
+ function unitsInGroup(group) {
10859
+ if (group.ref.kind !== "schema") {
10860
+ return 1;
10861
+ }
10862
+ const definitions = /* @__PURE__ */ new Set();
10863
+ for (const issue of group.issues) {
10864
+ const [collection, index] = issue.path;
10865
+ definitions.add(
10866
+ typeof collection === "string" && index !== void 0 ? `${collection}.${index}` : "schema"
10867
+ );
10868
+ }
10869
+ return definitions.size;
10870
+ }
10871
+ function countIssues(result) {
10872
+ let errors = 0;
10873
+ let warnings = 0;
10874
+ let unitsWithIssues = 0;
10875
+ for (const group of result.groups) {
10876
+ for (const issue of group.issues) {
10877
+ if (issue.severity === "error") {
10878
+ errors += 1;
10879
+ } else {
10880
+ warnings += 1;
10881
+ }
10882
+ }
10883
+ unitsWithIssues += unitsInGroup(group);
10884
+ }
10885
+ return { errors, warnings, unitsWithIssues };
10886
+ }
10887
+
10888
+ function formatJson(result, level) {
10889
+ const { errors, warnings, unitsWithIssues } = countIssues(result);
10890
+ const fetchFailures = result.fetchFailures ?? 0;
10891
+ const listFailed = result.listFailed ?? false;
10892
+ const report = {
10893
+ ok: errors === 0 && fetchFailures === 0 && !listFailed,
10894
+ unit: result.unitNoun,
10895
+ unitsTotal: result.unitsTotal,
10896
+ unitsWithIssues,
10897
+ ...result.filter ? { filter: result.filter } : {},
10898
+ // Only stated when it is the whole story: a listing that failed already
10899
+ // explains the empty population through `listFailed`.
10900
+ ...result.filter && result.unitsTotal === 0 && !listFailed ? { noMatches: true } : {},
10901
+ errors,
10902
+ warnings,
10903
+ fetchFailures,
10904
+ // Only present when they carry information: an empty array or a null reason
10905
+ // is noise in a document a machine reads.
10906
+ ...result.fetchErrors?.length ? { fetchErrors: result.fetchErrors } : {},
10907
+ listFailed,
10908
+ ...listFailed && result.listError ? { listError: result.listError } : {},
10909
+ groups: result.groups.map((group) => ({ ...group, issues: filterIssuesByLevel(group.issues, level) })).filter((group) => group.issues.length > 0)
10910
+ };
10911
+ return JSON.stringify(report, null, 2);
10912
+ }
10913
+
10914
+ const SYMBOL = {
10915
+ error: chalk.red("\u2716"),
10916
+ warning: chalk.yellow("\u26A0")
10917
+ };
10918
+ function pluralize(count, noun) {
10919
+ return `${count} ${count === 1 ? noun : `${noun}s`}`;
10920
+ }
10921
+ function formatPretty(result, level) {
10922
+ const lines = [];
10923
+ for (const group of result.groups) {
10924
+ const visible = filterIssuesByLevel(group.issues, level);
10925
+ if (visible.length === 0) {
10926
+ continue;
10927
+ }
10928
+ lines.push(group.header);
10929
+ const codeWidth = Math.max(...visible.map((issue) => issue.code.length));
10930
+ for (const issue of visible) {
10931
+ const location = issue.path.length > 0 ? `${issue.path.join(".")}: ${issue.message}` : issue.message;
10932
+ lines.push(` ${SYMBOL[issue.severity]} ${issue.code.padEnd(codeWidth)} ${location}`);
10933
+ }
10934
+ }
10935
+ const { errors, warnings, unitsWithIssues } = countIssues(result);
10936
+ const summarySymbol = errors > 0 ? chalk.red("\u2716") : warnings > 0 ? chalk.yellow("\u26A0") : chalk.green("\u2714");
10937
+ const unitNoun = result.unitsTotal === 1 ? result.unitNounSingular : result.unitNoun;
10938
+ const hidden = level === "error" && warnings > 0 ? chalk.dim(` (${pluralize(warnings, "warning")} hidden by --level error)`) : "";
10939
+ lines.push(
10940
+ `${summarySymbol} ${pluralize(errors, "error")}, ${pluralize(warnings, "warning")} across ${unitsWithIssues} of ${result.unitsTotal} ${unitNoun}${hidden}`
10941
+ );
10942
+ return lines.join("\n");
10943
+ }
10944
+
10945
+ function entityToHeader(entity) {
10946
+ const separator = entity.indexOf(":");
10947
+ if (separator === -1) {
10948
+ return entity;
10949
+ }
10950
+ const type = entity.slice(0, separator);
10951
+ const name = entity.slice(separator + 1);
10952
+ if (name === "") {
10953
+ return `<unnamed ${type}>`;
10954
+ }
10955
+ return `${name} (${type})`;
10956
+ }
10957
+ function entityToRef(entity) {
10958
+ const separator = entity.indexOf(":");
10959
+ const type = separator === -1 ? entity : entity.slice(0, separator);
10960
+ const name = separator === -1 ? void 0 : entity.slice(separator + 1);
10961
+ if (type === "block" || type === "datasource") {
10962
+ return { kind: type, ...name ? { name } : {} };
10963
+ }
10964
+ return { kind: "schema" };
10965
+ }
10966
+ function groupIssuesByEntity(issues) {
10967
+ const byEntity = /* @__PURE__ */ new Map();
10968
+ for (const issue of issues) {
10969
+ const existing = byEntity.get(issue.entity);
10970
+ if (existing) {
10971
+ existing.push(issue);
10972
+ } else {
10973
+ byEntity.set(issue.entity, [issue]);
10974
+ }
10975
+ }
10976
+ return [...byEntity].map(([entity, entityIssues]) => ({
10977
+ header: entityToHeader(entity),
10978
+ ref: entityToRef(entity),
10979
+ issues: entityIssues
10980
+ }));
10981
+ }
10982
+
10983
+ function writeValidationReport(reporter, result) {
10984
+ const { errors, warnings, unitsWithIssues } = countIssues(result);
10985
+ reporter.addSummary("validation", {
10986
+ total: result.unitsTotal,
10987
+ succeeded: result.unitsTotal - unitsWithIssues,
10988
+ failed: unitsWithIssues
10989
+ });
10990
+ reporter.addMeta("validation", {
10991
+ unitNoun: result.unitNoun,
10992
+ errors,
10993
+ warnings,
10994
+ unitsWithIssues,
10995
+ unitsTotal: result.unitsTotal,
10996
+ groups: result.groups
10997
+ });
10998
+ }
10999
+
11000
+ const LEVEL_OPTIONS = ["error", "warning"];
11001
+ const FORMAT_OPTIONS = ["pretty", "json"];
11002
+ function parseLevel(value) {
11003
+ if (!LEVEL_OPTIONS.includes(value)) {
11004
+ throw new CommandError(`Invalid --level "${value}". Expected one of: ${LEVEL_OPTIONS.join(", ")}.`);
11005
+ }
11006
+ return value;
11007
+ }
11008
+ function parseFormat(value) {
11009
+ if (!FORMAT_OPTIONS.includes(value)) {
11010
+ throw new CommandError(`Invalid --format "${value}". Expected one of: ${FORMAT_OPTIONS.join(", ")}.`);
11011
+ }
11012
+ return value;
11013
+ }
11014
+
11015
+ function storyHeader(story) {
11016
+ const slug = story.full_slug ?? story.slug ?? String(story.id);
11017
+ return `${slug} (story #${story.id})`;
11018
+ }
11019
+ function storyRef(story) {
11020
+ return {
11021
+ kind: "story",
11022
+ id: story.id,
11023
+ ...story.full_slug ? { slug: story.full_slug } : {},
11024
+ ...story.name ? { name: story.name } : {}
11025
+ };
11026
+ }
11027
+ storiesCommand.command("validate").description("Validate every story's draft content in a space against a local code-defined schema.").option("-s, --space <space>", "space ID").option("--schema <entry-file>", "Path to the TypeScript schema entry file").option("--starts-with <path>", 'Only validate stories whose path starts with this prefix. Example: --starts-with="en/blog/"').option("--level <level>", "Display threshold: error|warning", "warning").option("--format <format>", "Output format: pretty|json", "pretty").action(async (options, command) => {
11028
+ const { schema: schemaEntry } = options;
11029
+ const startsWith = options.startsWith === void 0 ? void 0 : normalizeStartsWith(options.startsWith) || void 0;
11030
+ const ui = getUI();
11031
+ const logger = getLogger();
11032
+ const reporter = getReporter();
11033
+ const { space, verbose } = command.optsWithGlobals();
11034
+ const { state } = session();
11035
+ const failFatal = (message) => {
11036
+ reporter.addSummary("validation", { total: 1, succeeded: 0, failed: 1 });
11037
+ handleError(new CommandError(message), verbose);
11038
+ };
11039
+ try {
11040
+ let level;
11041
+ let format;
11042
+ try {
11043
+ level = parseLevel(options.level);
11044
+ format = parseFormat(options.format);
11045
+ } catch (maybeError) {
11046
+ failFatal(toError(maybeError).message);
11047
+ return;
11048
+ }
11049
+ const isJson = format === "json";
11050
+ logger.info("Stories validate started", { space, schemaEntry, startsWith, level, format });
11051
+ if (!requireAuthentication(state, verbose)) {
11052
+ reporter.addSummary("validation", { total: 1, succeeded: 0, failed: 1 });
11053
+ return;
11054
+ }
11055
+ if (!space) {
11056
+ failFatal("Please provide the space as argument --space YOUR_SPACE_ID.");
11057
+ return;
11058
+ }
11059
+ if (!schemaEntry) {
11060
+ failFatal("Please provide the schema entry file with --schema <entry-file>.");
11061
+ return;
11062
+ }
11063
+ let schema;
11064
+ try {
11065
+ ({ schema } = await loadSchemaEntry(schemaEntry, { requireBlocks: true }));
11066
+ } catch (maybeError) {
11067
+ failFatal(toError(maybeError).message);
11068
+ return;
11069
+ }
11070
+ const groups = [];
11071
+ let totalStories = 0;
11072
+ const fetchErrors = [];
11073
+ let listFailed = false;
11074
+ let listError;
11075
+ let progress;
11076
+ let listedTotal = 0;
11077
+ let foldersSkipped = 0;
11078
+ const startProgress = () => {
11079
+ if (isJson) {
11080
+ return void 0;
11081
+ }
11082
+ progress ??= ui.createProgressBar({ title: "Validating Stories...".padEnd(23) });
11083
+ return progress;
11084
+ };
11085
+ const syncProgressTotal = () => {
11086
+ const total = Math.max(listedTotal - foldersSkipped, 0);
11087
+ if (total === 0 && progress === void 0) {
11088
+ return;
11089
+ }
11090
+ startProgress()?.setTotal(total);
11091
+ };
11092
+ const stopProgress = () => {
11093
+ progress?.stop();
11094
+ ui.stopAllProgressBars();
11095
+ };
11096
+ if (!isJson) {
11097
+ ui.title(`${commands.STORIES}`, colorPalette.STORIES, "Validating stories...");
11098
+ }
11099
+ try {
11100
+ await pipeline$1(
11101
+ fetchStoriesStream({
11102
+ spaceId: space,
11103
+ params: { starts_with: startsWith },
11104
+ setTotalStories: (total) => {
11105
+ listedTotal = total;
11106
+ syncProgressTotal();
11107
+ },
11108
+ onPageError: (error, page, total) => {
11109
+ listFailed = true;
11110
+ listError = error.message;
11111
+ stopProgress();
11112
+ logger.error("Failed to list stories", { error: error.message, page, total });
11113
+ handleError(error, verbose, { page, total });
11114
+ }
11115
+ }),
11116
+ // Skip folders: they carry no content to validate, and are not part of
11117
+ // the population the summary counts.
11118
+ new Transform({
11119
+ objectMode: true,
11120
+ transform(story, _encoding, callback) {
11121
+ if (story.is_folder) {
11122
+ foldersSkipped += 1;
11123
+ syncProgressTotal();
11124
+ callback();
11125
+ return;
11126
+ }
11127
+ totalStories += 1;
11128
+ this.push(story);
11129
+ callback();
11130
+ }
11131
+ }),
11132
+ fetchStoryStream({
11133
+ spaceId: space,
11134
+ onStoryError: (error, story) => {
11135
+ fetchErrors.push({
11136
+ id: story.id,
11137
+ ...story.full_slug ? { slug: story.full_slug } : {},
11138
+ message: error.message
11139
+ });
11140
+ progress?.increment();
11141
+ logger.error("Failed to fetch story", { error: error.message, storyId: story.id });
11142
+ handleError(error, verbose, { storyId: story.id });
11143
+ }
11144
+ }),
11145
+ new Writable({
11146
+ objectMode: true,
11147
+ async write(story, _encoding, callback) {
11148
+ try {
11149
+ const { issues } = await validateStory(story, schema);
11150
+ if (issues.length > 0) {
11151
+ groups.push({ header: storyHeader(story), ref: storyRef(story), issues });
11152
+ }
11153
+ progress?.increment();
11154
+ callback();
11155
+ } catch (maybeError) {
11156
+ callback(toError(maybeError));
11157
+ }
11158
+ }
11159
+ })
11160
+ );
11161
+ } catch (maybeError) {
11162
+ stopProgress();
11163
+ failFatal(toError(maybeError).message);
11164
+ return;
11165
+ }
11166
+ stopProgress();
11167
+ groups.sort((a, b) => {
11168
+ const left = a.ref.slug ?? a.header;
11169
+ const right = b.ref.slug ?? b.header;
11170
+ if (left !== right) {
11171
+ return left < right ? -1 : 1;
11172
+ }
11173
+ return (a.ref.id ?? 0) - (b.ref.id ?? 0);
11174
+ });
11175
+ const fetchFailures = fetchErrors.length;
11176
+ const result = {
11177
+ unitNoun: "stories",
11178
+ unitNounSingular: "story",
11179
+ unitsTotal: totalStories,
11180
+ groups,
11181
+ // Travels with the result so both formatters can say the population was
11182
+ // narrowed, rather than only the pretty one knowing.
11183
+ ...startsWith === void 0 ? {} : { filter: { option: "--starts-with", value: startsWith } },
11184
+ fetchFailures,
11185
+ fetchErrors,
11186
+ listFailed,
11187
+ listError
11188
+ };
11189
+ writeValidationReport(reporter, result);
11190
+ reporter.addSummary("fetch", {
11191
+ total: totalStories,
11192
+ succeeded: totalStories - fetchFailures,
11193
+ failed: fetchFailures
11194
+ });
11195
+ if (listFailed) {
11196
+ reporter.addSummary("list", { total: 1, succeeded: 0, failed: 1 });
11197
+ }
11198
+ const { errors, warnings } = countIssues(result);
11199
+ logger.info("Stories validate finished", { errors, warnings, stories: totalStories, fetchFailures, listFailed });
11200
+ if (isJson) {
11201
+ ui.writeMachineOutput(formatJson(result, level));
11202
+ }
11203
+ if (listFailed) {
11204
+ if (!isJson) {
11205
+ ui.error("Listing stories failed; the space was not fully validated.");
11206
+ }
11207
+ return;
11208
+ }
11209
+ if (!isJson) {
11210
+ ui.log(formatPretty(result, level));
11211
+ if (result.filter && totalStories === 0) {
11212
+ ui.warn(`No stories matched ${result.filter.option} "${result.filter.value}"; nothing was validated.`);
11213
+ }
11214
+ if (fetchFailures > 0) {
11215
+ ui.warn(`${fetchFailures} story(s) could not be fetched and were not validated.`);
11216
+ }
11217
+ }
11218
+ process.exitCode = errors > 0 || fetchFailures > 0 ? 1 : 0;
11219
+ } finally {
11220
+ reporter.finalize();
11221
+ }
11222
+ });
11223
+
10721
11224
  const program$1 = getProgram();
10722
11225
  const schemaCommand = program$1.command(commands.SCHEMA).description(`Manage your space's schema from code`);
10723
11226
 
10724
- function isRecord(value) {
10725
- return typeof value === "object" && value !== null && !Array.isArray(value);
10726
- }
10727
11227
  const COMPONENT_STRIP_KEYS = /* @__PURE__ */ new Set([
10728
11228
  "id",
10729
11229
  "created_at",
@@ -10931,15 +11431,6 @@ function mapDatasourceToWire(datasource) {
10931
11431
  return datasource;
10932
11432
  }
10933
11433
 
10934
- function isComponent(value) {
10935
- return isRecord(value) && typeof value.name === "string" && Array.isArray(value.fields);
10936
- }
10937
- function isDatasource(value) {
10938
- return isRecord(value) && typeof value.name === "string" && typeof value.slug === "string" && !Array.isArray(value.fields);
10939
- }
10940
- function isFolder(value) {
10941
- return isRecord(value) && typeof value.name === "string" && typeof value.path === "string" && !Array.isArray(value.fields) && !("slug" in value);
10942
- }
10943
11434
  function buildLocalFolders(registered, derived) {
10944
11435
  const byPath = /* @__PURE__ */ new Map();
10945
11436
  const add = (displayPath, registeredLeaf) => {
@@ -10980,24 +11471,42 @@ function buildLocalFolders(registered, derived) {
10980
11471
  }
10981
11472
  return folders;
10982
11473
  }
10983
- function isSchemaObject(value) {
10984
- return isRecord(value) && ("blocks" in value || "datasources" in value || "folders" in value);
10985
- }
10986
- function emptySchemaData() {
10987
- return { components: [], folders: [], datasources: [] };
11474
+ function assertUniqueIdentities(components, datasources) {
11475
+ const collisions = [];
11476
+ const collect = (label, values) => {
11477
+ const seen = /* @__PURE__ */ new Set();
11478
+ const reported = /* @__PURE__ */ new Set();
11479
+ for (const value of values) {
11480
+ if (typeof value !== "string") {
11481
+ continue;
11482
+ }
11483
+ if (seen.has(value) && !reported.has(value)) {
11484
+ reported.add(value);
11485
+ collisions.push(`${label} "${value}"`);
11486
+ }
11487
+ seen.add(value);
11488
+ }
11489
+ };
11490
+ collect("block name", components.map((component) => component.name));
11491
+ collect("datasource name", datasources.map((datasource) => datasource.name));
11492
+ collect("datasource slug", datasources.map((datasource) => datasource.slug));
11493
+ if (collisions.length > 0) {
11494
+ throw new CommandError(
11495
+ `Duplicate schema definitions: ${collisions.join(", ")}. Each block name, datasource name, and datasource slug must be unique; rename or remove the duplicate before pushing.`
11496
+ );
11497
+ }
10988
11498
  }
10989
11499
  function classifyExports(moduleExports) {
10990
- const data = emptySchemaData();
10991
- const seenComponents = /* @__PURE__ */ new Set();
10992
- const seenDatasources = /* @__PURE__ */ new Set();
10993
- const registered = [];
11500
+ const { components, datasources, folders } = collectSchemaExports(moduleExports);
11501
+ assertUniqueIdentities(components, datasources);
11502
+ const registered = folders.map((folder) => folder.path);
10994
11503
  const derived = [];
10995
- function harvestComponentPaths(value) {
10996
- if (typeof value.folder === "string") {
10997
- derived.push(value.folder);
11504
+ for (const component of components) {
11505
+ if (typeof component.folder === "string") {
11506
+ derived.push(component.folder);
10998
11507
  }
10999
- if (Array.isArray(value.fields)) {
11000
- for (const field of value.fields) {
11508
+ if (Array.isArray(component.fields)) {
11509
+ for (const field of component.fields) {
11001
11510
  if (!isRecord(field) || !Array.isArray(field.allow)) {
11002
11511
  continue;
11003
11512
  }
@@ -11009,46 +11518,14 @@ function classifyExports(moduleExports) {
11009
11518
  }
11010
11519
  }
11011
11520
  }
11012
- function collect(value) {
11013
- if (isComponent(value)) {
11014
- harvestComponentPaths(value);
11015
- if (seenComponents.has(value.name)) {
11016
- return;
11017
- }
11018
- seenComponents.add(value.name);
11019
- data.components.push(mapBlockToWire(value));
11020
- } else if (isFolder(value)) {
11021
- registered.push(value.path);
11022
- } else if (isDatasource(value)) {
11023
- if (seenDatasources.has(value.name)) {
11024
- return;
11025
- }
11026
- seenDatasources.add(value.name);
11027
- data.datasources.push(mapDatasourceToWire(value));
11028
- }
11029
- }
11030
- for (const value of Object.values(moduleExports)) {
11031
- if (isSchemaObject(value)) {
11032
- for (const group of Object.values(value)) {
11033
- if (isRecord(group)) {
11034
- for (const entity of Object.values(group)) {
11035
- collect(entity);
11036
- }
11037
- }
11038
- }
11039
- } else {
11040
- collect(value);
11041
- }
11042
- }
11043
- data.folders = buildLocalFolders(registered, derived);
11044
- return data;
11521
+ return {
11522
+ components: components.map(mapBlockToWire),
11523
+ folders: buildLocalFolders(registered, derived),
11524
+ datasources: datasources.map(mapDatasourceToWire)
11525
+ };
11045
11526
  }
11046
11527
  async function loadSchema(entryPath) {
11047
- const { createJiti } = await import('jiti');
11048
- const jiti = createJiti(import.meta.url, { interopDefault: true });
11049
- const { resolve } = await import('pathe');
11050
- const entryAbs = resolve(entryPath);
11051
- const entryMod = await jiti.import(entryAbs);
11528
+ const entryMod = await loadSchemaModule(entryPath);
11052
11529
  return classifyExports(entryMod);
11053
11530
  }
11054
11531
 
@@ -13071,6 +13548,56 @@ schemaCommand.command("rollback [changeset-file]").description("Roll back a Stor
13071
13548
  }
13072
13549
  });
13073
13550
 
13551
+ schemaCommand.command("validate <entry-file>").description("Validate a local TypeScript schema definition. Static and fully offline \u2014 no login, no space, no API calls.").option("--level <level>", "Display threshold: error|warning", "warning").option("--format <format>", "Output format: pretty|json", "pretty").action(async (entryFile, options, command) => {
13552
+ const ui = getUI();
13553
+ const logger = getLogger();
13554
+ const reporter = getReporter();
13555
+ const { verbose } = command.optsWithGlobals();
13556
+ try {
13557
+ let level;
13558
+ let format;
13559
+ try {
13560
+ level = parseLevel(options.level);
13561
+ format = parseFormat(options.format);
13562
+ } catch (maybeError) {
13563
+ reporter.addSummary("validation", { total: 1, succeeded: 0, failed: 1 });
13564
+ handleError(toError(maybeError), verbose);
13565
+ return;
13566
+ }
13567
+ const isJson = format === "json";
13568
+ logger.info("Schema validate started", { entryFile, level, format });
13569
+ let loaded;
13570
+ try {
13571
+ loaded = await loadSchemaEntry(entryFile);
13572
+ } catch (maybeError) {
13573
+ const error = toError(maybeError);
13574
+ reporter.addSummary("validation", { total: 1, succeeded: 0, failed: 1 });
13575
+ handleError(error, verbose);
13576
+ logger.error("Schema validate failed to load entry file", { error: error.message });
13577
+ return;
13578
+ }
13579
+ const { issues } = await validateSchema(loaded.schema);
13580
+ const result = {
13581
+ unitNoun: "entities",
13582
+ unitNounSingular: "entity",
13583
+ unitsTotal: loaded.entityCount,
13584
+ groups: groupIssuesByEntity(issues)
13585
+ };
13586
+ if (isJson) {
13587
+ ui.writeMachineOutput(formatJson(result, level));
13588
+ } else {
13589
+ ui.title(commands.SCHEMA, colorPalette.SCHEMA, "Validating schema...");
13590
+ ui.log(formatPretty(result, level));
13591
+ }
13592
+ writeValidationReport(reporter, result);
13593
+ const { errors, warnings } = countIssues(result);
13594
+ logger.info("Schema validate finished", { errors, warnings, entities: result.unitsTotal });
13595
+ process.exitCode = errors > 0 ? 1 : 0;
13596
+ } finally {
13597
+ reporter.finalize();
13598
+ }
13599
+ });
13600
+
13074
13601
  const program = getProgram();
13075
13602
  const ui = getUI();
13076
13603
  ui.br();