{"version":3,"file":"index.mjs","sources":["../src/constants.ts","../src/utils/array.ts","../src/utils/object.ts","../src/lib/config/defaults.ts","../src/lib/config/loader.ts","../src/lib/config/helpers.ts","../src/lib/config/commander.ts","../src/lib/config/options.ts","../src/lib/config/resolver.ts","../src/lib/config/store.ts","../src/utils/fetch.ts","../src/utils/error/api-error.ts","../src/utils/error/command-error.ts","../src/lib/logger/logger.ts","../src/utils/error/filesystem-error.ts","../src/utils/error/error.ts","../src/utils/auth.ts","../src/utils/format.ts","../src/utils/konsola.ts","../src/utils/package.ts","../src/utils/index.ts","../src/utils/ui.ts","../src/utils/filesystem.ts","../src/lib/reporter/reporter.ts","../src/lib/logger/logger-transport-file.ts","../src/lib/logger/logger-transport-console.ts","../src/creds.ts","../src/session.ts","../src/api.ts","../src/program.ts","../src/utils/api-routes.ts","../src/commands/user/actions.ts","../src/commands/login/actions.ts","../src/commands/login/helpers.ts","../src/commands/login/index.ts","../src/commands/logout/index.ts","../src/commands/signup/actions.ts","../src/commands/signup/index.ts","../src/commands/user/index.ts","../src/commands/components/command.ts","../src/commands/components/loader.ts","../src/commands/components/constants.ts","../src/utils/pagination.ts","../src/commands/components/pull/actions.ts","../src/commands/components/push/actions.ts","../src/commands/components/pull/index.ts","../src/commands/components/push/graph-operations/dependency-graph.ts","../src/commands/components/push/utils.ts","../src/commands/components/push/progress-display.ts","../src/commands/components/push/graph-operations/resource-processor.ts","../src/commands/components/push/graph-operations/index.ts","../src/commands/components/push/index.ts","../src/commands/languages/constants.ts","../src/commands/spaces/actions.ts","../src/commands/languages/actions.ts","../src/commands/languages/index.ts","../src/commands/migrations/command.ts","../src/commands/migrations/generate/actions.ts","../src/commands/migrations/generate/index.ts","../src/commands/stories/constants.ts","../src/commands/stories/actions.ts","../src/commands/migrations/run/constants.ts","../src/commands/migrations/run/streams/stories-stream.ts","../src/commands/migrations/run/actions.ts","../src/commands/migrations/rollback/actions.ts","../src/commands/migrations/run/streams/migrations-transform.ts","../src/commands/stories/utils.ts","../src/commands/migrations/run/streams/update-stream.ts","../src/commands/migrations/run/index.ts","../src/commands/migrations/rollback/index.ts","../src/commands/types/command.ts","../src/utils/storyblok-schemas.ts","../src/commands/types/generate/utils.ts","../src/commands/types/generate/actions.ts","../src/commands/datasources/push/actions.ts","../src/commands/types/generate/index.ts","../src/commands/datasources/command.ts","../src/commands/datasources/constants.ts","../src/commands/datasources/pull/actions.ts","../src/commands/datasources/pull/index.ts","../src/commands/datasources/push/index.ts","../src/commands/datasources/delete/actions.ts","../src/commands/datasources/delete/index.ts","../src/github.ts","../src/commands/create/constants.ts","../src/commands/create/actions.ts","../src/commands/create/index.ts","../src/commands/logs/command.ts","../src/commands/logs/list/index.ts","../src/commands/logs/prune/index.ts","../src/commands/reports/command.ts","../src/commands/reports/list/index.ts","../src/commands/reports/prune/index.ts","../src/commands/assets/command.ts","../src/commands/assets/actions.ts","../src/commands/assets/utils.ts","../src/commands/assets/streams.ts","../src/commands/assets/pull/index.ts","../src/commands/stories/ref-mapper.ts","../src/commands/stories/streams.ts","../src/commands/stories/richtext.ts","../src/commands/stories/validate-story.ts","../src/commands/assets/pipelines.ts","../src/commands/assets/push/index.ts","../src/commands/stories/command.ts","../src/commands/stories/pull/index.ts","../src/commands/stories/push/failure-report.ts","../src/commands/stories/push/index.ts","../src/index.ts"],"sourcesContent":["// Please do not change the casing of the commands, it's used for the CLI commands definition\nexport const commands = {\n  LOGIN: 'login',\n  LOGOUT: 'logout',\n  SIGNUP: 'signup',\n  USER: 'user',\n  COMPONENTS: 'components',\n  LANGUAGES: 'languages',\n  MIGRATIONS: 'migrations',\n  TYPES: 'types',\n  DATASOURCES: 'datasources',\n  CREATE: 'create',\n  LOGS: 'logs',\n  REPORTS: 'reports',\n  ASSETS: 'assets',\n  STORIES: 'stories',\n} as const;\n\nexport const colorPalette = {\n  PRIMARY: '#8d60ff',\n  LOGIN: '#dad4ff',\n  LOGOUT: '#6d6d6d',\n  SIGNUP: '#b6ff6d',\n  USER: '#71d300',\n  COMPONENTS: '#a185ff',\n  LANGUAGES: '#f5c003',\n  MIGRATIONS: '#8CE2FF',\n  TYPES: '#3178C6',\n  CREATE: '#ffb3ba',\n  GROUPS: '#4ade80',\n  TAGS: '#fbbf24',\n  PRESETS: '#a855f7',\n  DATASOURCES: '#4ade80',\n  LOGS: '#4ade80',\n  REPORTS: '#4ade80',\n  ASSETS: '#f97316',\n  STORIES: '#a185ff',\n} as const;\n\nexport interface ReadonlyArray<T> {\n  includes: (searchElement: any, fromIndex?: number) => searchElement is T;\n}\nexport const regionCodes = ['eu', 'us', 'cn', 'ca', 'ap'] as const;\nexport type RegionCode = typeof regionCodes[number];\n\nexport const regions: Record<Uppercase<RegionCode>, RegionCode> = {\n  EU: 'eu',\n  US: 'us',\n  CN: 'cn',\n  CA: 'ca',\n  AP: 'ap',\n} as const;\n\nexport const regionsDomain: Record<RegionCode, string> = {\n  eu: 'api.storyblok.com',\n  us: 'api-us.storyblok.com',\n  cn: 'app.storyblokchina.cn',\n  ca: 'api-ca.storyblok.com',\n  ap: 'api-ap.storyblok.com',\n} as const;\n\nexport const managementApiRegions: Record<RegionCode, string> = {\n  eu: 'mapi.storyblok.com',\n  us: 'api-us.storyblok.com',\n  cn: 'app.storyblokchina.cn',\n  ca: 'api-ca.storyblok.com',\n  ap: 'api-ap.storyblok.com',\n} as const;\n\nexport const appDomains: Record<RegionCode, string> = {\n  eu: 'app.storyblok.com',\n  us: 'app-us.storyblok.com',\n  cn: 'app.storyblokchina.cn',\n  ca: 'app-ca.storyblok.com',\n  ap: 'app-ap.storyblok.com',\n} as const;\n\nexport const regionNames: Record<RegionCode, string> = {\n  eu: 'Europe',\n  us: 'United States',\n  cn: 'China',\n  ca: 'Canada',\n  ap: 'Australia',\n} as const;\n\nexport const DEFAULT_AGENT = {\n  SB_Agent: 'SB-CLI',\n  SB_Agent_Version: process.env.npm_package_version || '4.x',\n} as const;\n\nexport interface SpaceOptions {\n  spaceId: string;\n}\n\n/**\n * Supported asset file extensions based on Storyblok's accepted MIME types.\n * @see https://www.storyblok.com/docs/concepts/assets\n * @see https://www.storyblok.com/faq/are-there-asset-type-upload-limitations\n */\nexport const SUPPORTED_ASSET_EXTENSIONS = new Set([\n  // Images: image/png, image/x-png, image/gif, image/jpeg, image/avif, image/svg+xml, image/webp\n  '.jpg',\n  '.jpeg',\n  '.png',\n  '.gif',\n  '.webp',\n  '.avif',\n  '.svg',\n  // Video: video/*, application/mp4, application/x-mpegurl, application/vnd.apple.mpegurl\n  '.mp4',\n  '.mov',\n  '.avi',\n  '.webm',\n  '.wmv',\n  '.mkv',\n  '.flv',\n  '.ogv',\n  '.3gp',\n  '.m4v',\n  '.mpg',\n  '.mpeg',\n  '.m3u8',\n  // Audio: audio/*\n  '.mp3',\n  '.wav',\n  '.ogg',\n  '.aac',\n  '.flac',\n  '.wma',\n  '.m4a',\n  '.opus',\n  // Documents: application/msword, text/plain, application/pdf, application/vnd.openxmlformats-officedocument.wordprocessingml.document\n  '.pdf',\n  '.doc',\n  '.docx',\n  '.txt',\n]);\n\nexport const directories = {\n  assets: 'assets',\n  components: 'components',\n  datasources: 'datasources',\n  logs: 'logs',\n  reports: 'reports',\n  stories: 'stories',\n} as const;\n","/**\n * Splits an iterable into batches of at most `size` items, preserving order.\n * Returns `[]` for empty input. If `size <= 0`, returns the full input as a single batch.\n */\nexport const chunk = <T>(items: Iterable<T>, size: number): T[][] => {\n  const all = Array.from(items);\n  if (all.length === 0) {\n    return [];\n  }\n  if (size <= 0) {\n    return [all];\n  }\n  const chunks: T[][] = [];\n  for (let i = 0; i < all.length; i += size) {\n    chunks.push(all.slice(i, i + size));\n  }\n  return chunks;\n};\n","export type PlainObject = Record<string, any>;\n\nexport function isPlainObject(value: unknown): value is PlainObject {\n  return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n}\n\nexport function mergeDeep<T extends PlainObject>(target: T, source?: PlainObject): T {\n  if (!isPlainObject(source)) {\n    return target;\n  }\n\n  const targetRecord = target as PlainObject;\n\n  for (const [key, value] of Object.entries(source)) {\n    if (isPlainObject(value)) {\n      const existing = targetRecord[key];\n      const base = isPlainObject(existing) ? existing : {};\n      targetRecord[key] = mergeDeep(base, value);\n    }\n    else {\n      targetRecord[key] = value;\n    }\n  }\n\n  return target;\n}\n\nexport function isEmptyObject(obj: object): boolean {\n  return Object.keys(obj).length === 0;\n}\n","import type { GlobalConfig, ResolvedCliConfig } from './types';\n\nconst BASE_GLOBAL_CONFIG: GlobalConfig = {\n  region: undefined,\n  space: undefined,\n  path: undefined,\n  api: {\n    maxRetries: 3,\n    maxConcurrency: 6,\n  },\n  log: {\n    console: {\n      enabled: false,\n      level: 'info',\n    },\n    file: {\n      enabled: true,\n      level: 'info',\n      maxFiles: 10,\n    },\n  },\n  report: {\n    enabled: true,\n    maxFiles: 10,\n  },\n  ui: {\n    enabled: true,\n  },\n  verbose: false,\n};\n\n/**\n * Shared immutable default global config for read-only operations.\n * Use this when you only need to read default values without mutation.\n *\n * @export\n * @constant\n */\nexport const DEFAULT_GLOBAL_CONFIG: Readonly<ResolvedCliConfig> = Object.freeze(\n  structuredClone(BASE_GLOBAL_CONFIG),\n) as Readonly<ResolvedCliConfig>;\n\n/**\n * Create a new mutable resolved config with default values.\n * Use this when you need to mutate the config.\n *\n * @export\n * @return {ResolvedCliConfig}\n */\nexport function createDefaultResolvedConfig(): ResolvedCliConfig {\n  return structuredClone(BASE_GLOBAL_CONFIG) as ResolvedCliConfig;\n}\n","import { loadConfig as c12LoadConfig, SUPPORTED_EXTENSIONS } from 'c12';\n\nexport { SUPPORTED_EXTENSIONS };\n\n/**\n * Load configuration using c12\n * This encapsulates the c12 dependency so it's only referenced within lib/config\n */\nexport async function loadConfig(options: {\n  name: string;\n  cwd?: string;\n  configFile?: string;\n  defaults?: Record<string, any>;\n}): Promise<{ config: Record<string, any> | null }> {\n  return c12LoadConfig({\n    name: options.name,\n    cwd: options.cwd,\n    configFile: options.configFile,\n    defaults: options.defaults || {},\n    rcFile: false,\n    globalRc: false,\n    dotenv: false,\n    packageJson: false,\n  });\n}\n","import { resolve as resolvePath } from 'pathe';\nimport { existsSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { isPlainObject } from '../../utils/object';\n\nimport { DEFAULT_GLOBAL_CONFIG } from './defaults';\nimport { loadConfig, SUPPORTED_EXTENSIONS } from './loader';\nimport type {\n  ApiConfig,\n  CommanderCommand,\n  CommanderOption,\n  ConfigLocation,\n  GlobalConfig,\n  LogConfig,\n  LogConsoleConfig,\n  LogFileConfig,\n  PlainObject,\n  ReportConfig,\n  ResolvedCliConfig,\n} from './types';\n\n// Type representing any level of the config hierarchy during path traversal\ntype ConfigLevel = GlobalConfig | ApiConfig | LogConfig | LogConsoleConfig | LogFileConfig | ReportConfig | Record<string, unknown>;\n\nexport const CONFIG_FILE_NAME = 'storyblok.config';\nexport const HIDDEN_CONFIG_DIR = '.storyblok';\nexport const HIDDEN_CONFIG_FILE_NAME = 'config';\n\n// Writes a value into a nested object by following the option path (creating objects along the way).\nexport function setValueAtPath(target: PlainObject, path: string[], value: unknown): void {\n  if (!path.length) {\n    return;\n  }\n  let current: PlainObject = target;\n  path.forEach((key, index) => {\n    if (index === path.length - 1) {\n      current[key] = value;\n      return;\n    }\n    if (!isPlainObject(current[key])) {\n      current[key] = {};\n    }\n    current = current[key];\n  });\n}\n\n// Reads a nested value described by the option path. Returns undefined when any segment is missing.\nexport function getValueAtPath(source: Record<string, any>, path: string[]): unknown {\n  return path.reduce<unknown>((accumulator, key) => {\n    if (accumulator === null || typeof accumulator !== 'object') {\n      return undefined;\n    }\n    return (accumulator as Record<string, any>)[key];\n  }, source);\n}\n\n// Pick only the direct scalar fields at a module level (nested objects belong to child commands).\nexport function extractDirectValues(input: PlainObject): PlainObject {\n  const direct: PlainObject = {};\n  for (const [key, value] of Object.entries(input)) {\n    if (isPlainObject(value)) {\n      continue;\n    }\n    direct[key] = value;\n  }\n  return direct;\n}\n\n// Builds the chain of commands from root to the current command (used for scoping defaults/overrides).\nexport function getCommandAncestry(command: CommanderCommand): CommanderCommand[] {\n  const chain: CommanderCommand[] = [];\n  let current: CommanderCommand | null = command;\n  while (current) {\n    chain.unshift(current);\n    current = current.parent;\n  }\n  return chain;\n}\n\nexport function getOptionPath(option: CommanderOption): string[] {\n  const longFlag = option.long || option.flags.split(',').pop()?.trim();\n  if (!longFlag) {\n    return [option.attributeName()];\n  }\n\n  // Remove the -- prefix and check for --no-* negation prefix\n  let normalized = longFlag.replace(/^--/, '');\n  const isNegated = normalized.startsWith('no-');\n\n  // Remove the no- prefix if present (Commander uses --no-* for boolean negation)\n  if (isNegated) {\n    normalized = normalized.replace(/^no-/, '');\n  }\n\n  // Split on hyphens to get all segments\n  const segments = normalized.split('-');\n  const path: string[] = [];\n\n  // Dynamically determine path vs property by checking if partial path is an object in DEFAULT_GLOBAL_CONFIG\n  // For example, for --log-file-max-files:\n  // - Check if 'log' is an object → yes, add to path\n  // - Check if 'log.file' is an object → yes, add to path\n  // - Check if 'log.file.max' is an object → no, so 'max-files' becomes property 'maxFiles'\n  let currentConfig: ConfigLevel = DEFAULT_GLOBAL_CONFIG as ConfigLevel;\n  let i = 0;\n\n  while (i < segments.length) {\n    const segment = segments[i];\n\n    // Check if this segment exists as an object in the current config level\n    const currentAsRecord = currentConfig as Record<string, unknown>;\n    if (currentConfig && isPlainObject(currentAsRecord[segment])) {\n      path.push(segment);\n      currentConfig = currentAsRecord[segment] as ConfigLevel;\n      i++;\n    }\n    else {\n      // Remaining segments form the property name - convert to camelCase\n      const remainingSegments = segments.slice(i);\n      const camelCased = remainingSegments\n        .map((seg, idx) => idx === 0 ? seg : seg.charAt(0).toUpperCase() + seg.slice(1))\n        .join('');\n      path.push(camelCased);\n      break;\n    }\n  }\n\n  return path;\n}\n\nfunction resolveConfigFilePath(cwd: string, configFile: string): string | null {\n  for (const ext of SUPPORTED_EXTENSIONS) {\n    const candidate = resolvePath(cwd, `${configFile}${ext}`);\n    if (existsSync(candidate)) {\n      return candidate;\n    }\n  }\n  return null;\n}\n\nasync function loadConfigLayer({ cwd, configFile }: ConfigLocation): Promise<Record<string, any> | null> {\n  if (!existsSync(cwd)) {\n    return null;\n  }\n  const filePath = resolveConfigFilePath(cwd, configFile);\n  if (!filePath) {\n    return null;\n  }\n\n  // Config loading happens before logger initialization, so we skip logging here\n  // The resolved config will be logged later in the process\n\n  const { config } = await loadConfig({\n    name: 'storyblok',\n    cwd,\n    configFile,\n  });\n  return config ?? null;\n}\n\nexport async function loadConfigLayers(): Promise<Record<string, any>[]> {\n  const cwd = process.cwd();\n\n  // Order: most general (home) first so workspace configs override during merging.\n  const locations: ConfigLocation[] = [\n    {\n      cwd: resolvePath(homedir(), HIDDEN_CONFIG_DIR),\n      configFile: HIDDEN_CONFIG_FILE_NAME,\n    },\n    {\n      cwd: resolvePath(cwd, HIDDEN_CONFIG_DIR),\n      configFile: HIDDEN_CONFIG_FILE_NAME,\n    },\n    {\n      cwd,\n      configFile: CONFIG_FILE_NAME,\n    },\n  ];\n\n  const layers: Record<string, any>[] = [];\n  for (const location of locations) {\n    const layer = await loadConfigLayer(location);\n    if (layer) {\n      layers.push(layer);\n    }\n  }\n  // Config loading happens before logger initialization, so we skip logging here\n  // The resolved config will be logged later in the process\n  return layers;\n}\n\nexport function formatConfigForDisplay(config: ResolvedCliConfig): string {\n  return JSON.stringify(config, null, 2);\n}\n","import type { CommanderCommand, PlainObject, ResolvedCliConfig } from './types';\nimport { getOptionPath, getValueAtPath, setValueAtPath } from './helpers';\n\n// Sets defaults. If, at Commander flag-level, some options has defauls, they'll override\n// the ones from the config file defaults\nexport function collectGlobalDefaults(root: CommanderCommand, baseDefaults: PlainObject): PlainObject {\n  const defaults = baseDefaults;\n  for (const option of root.options) {\n    if (option.defaultValue === undefined) {\n      continue;\n    }\n    // Nested global options (api.*, log.*, etc.) are projected into the config tree via path segments.\n    setValueAtPath(defaults, getOptionPath(option), option.defaultValue);\n  }\n  return defaults;\n}\n\nexport function collectLocalDefaults(commands: CommanderCommand[]): PlainObject {\n  const defaults: PlainObject = {};\n  for (const command of commands) {\n    for (const option of command.options) {\n      if (option.defaultValue === undefined) {\n        continue;\n      }\n      const attrName = option.attributeName();\n      if (!(attrName in defaults)) {\n        defaults[attrName] = option.defaultValue;\n      }\n    }\n  }\n  return defaults;\n}\n\n// Translate explicit CLI flags into config objects: root options mutate the global tree,\n// nested commands only patch their own local option bag (no deep paths involved).\nexport function applyCliOverrides(commandChain: CommanderCommand[], globalResolved: PlainObject, localResolved: PlainObject): void {\n  const [root] = commandChain;\n  for (const command of commandChain) {\n    const isRoot = command === root;\n    for (const option of command.options) {\n      const attrName = option.attributeName();\n      const source = command.getOptionValueSource(attrName);\n      // Skip commander defaults/config hydration so we only react to explicit CLI input.\n      if (!source || source === 'default' || source === 'config') {\n        continue;\n      }\n      const value = command.getOptionValue(attrName);\n      if (isRoot) {\n        setValueAtPath(globalResolved, getOptionPath(option), value);\n        // Global CLI overrides must also win over module-level config that may have\n        // set the same key in localResolved (e.g. --path overriding modules.*.path).\n        delete localResolved[attrName];\n      }\n      else {\n        localResolved[attrName] = value;\n      }\n    }\n  }\n}\n\n// Hydrate Commander options with resolved config so downstream logic can rely on option values.\nexport function applyConfigToCommander(commandChain: CommanderCommand[], resolved: ResolvedCliConfig): void {\n  for (const command of commandChain) {\n    for (const option of command.options) {\n      const attrName = option.attributeName();\n      const source = command.getOptionValueSource(attrName);\n      // Never overwrite explicit CLI flags; only hydrate values that still come from defaults.\n      if (source && source !== 'default' && source !== 'config') {\n        continue;\n      }\n      const value = getValueAtPath(resolved, getOptionPath(option));\n      if (value === undefined) {\n        continue;\n      }\n      command.setOptionValueWithSource(attrName, value, 'config');\n    }\n  }\n}\n","import { DEFAULT_GLOBAL_CONFIG } from './defaults';\nimport type { GlobalOptionDefinition } from './types';\n\nexport function parseNumber(value: string): number {\n  const parsed = Number.parseInt(value, 10);\n  if (Number.isNaN(parsed)) {\n    throw new TypeError(`Invalid number value \"${value}\".`);\n  }\n  return parsed;\n}\n\nexport const GLOBAL_OPTION_DEFINITIONS: GlobalOptionDefinition[] = [\n  {\n    flags: '-p, --path <path>',\n    description: 'Base directory for file storage (default: .storyblok)',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.path,\n  },\n  {\n    flags: '--verbose',\n    description: 'Enable verbose output',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.verbose,\n  },\n  {\n    flags: '--region <region>',\n    description: 'Storyblok region used for API requests',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.region,\n  },\n  {\n    flags: '--api-max-retries <number>',\n    description: 'Maximum retry attempts for HTTP requests',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.api.maxRetries,\n    parser: parseNumber,\n  },\n  {\n    flags: '--api-max-concurrency <number>',\n    description: 'Maximum concurrent API requests executed by the CLI',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.api.maxConcurrency,\n    parser: parseNumber,\n  },\n  // Boolean flags that default to true need both positive and negative forms\n  {\n    flags: '--log-console-enabled',\n    description: 'Enable console logging output',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.log.console.enabled,\n  },\n  {\n    flags: '--no-log-console-enabled',\n    description: 'Disable console logging output',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.log.console.enabled,\n  },\n  {\n    flags: '--log-console-level <level>',\n    description: 'Console log level threshold',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.log.console.level,\n  },\n  {\n    flags: '--log-file-enabled',\n    description: 'Enable file logging output',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.log.file.enabled,\n  },\n  {\n    flags: '--no-log-file-enabled',\n    description: 'Disable file logging output',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.log.file.enabled,\n  },\n  {\n    flags: '--log-file-level <level>',\n    description: 'File log level threshold',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.log.file.level,\n  },\n  {\n    flags: '--log-file-max-files <number>',\n    description: 'Maximum amount of log files to keep on disk',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.log.file.maxFiles,\n    parser: parseNumber,\n  },\n  {\n    flags: '--ui-enabled',\n    description: 'Enable UI output',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.ui.enabled,\n  },\n  {\n    flags: '--no-ui-enabled',\n    description: 'Disable UI output',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.ui.enabled,\n  },\n  {\n    flags: '--report-enabled',\n    description: 'Enable report generation after command execution',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.report.enabled,\n  },\n  {\n    flags: '--no-report-enabled',\n    description: 'Disable report generation after command execution',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.report.enabled,\n  },\n  {\n    flags: '--report-max-files <number>',\n    description: 'Maximum number of report files to keep',\n    defaultValue: DEFAULT_GLOBAL_CONFIG.report.maxFiles,\n    parser: parseNumber,\n  },\n];\n","import type { CommanderCommand, PlainObject, ResolvedCliConfig } from './types';\nimport { createDefaultResolvedConfig } from './defaults';\nimport {\n  applyCliOverrides,\n  collectGlobalDefaults,\n  collectLocalDefaults,\n} from './commander';\nimport {\n  extractDirectValues,\n  getCommandAncestry,\n  loadConfigLayers,\n} from './helpers';\nimport { isPlainObject, mergeDeep } from '../../utils/object';\n\n// Modules are root subcommands that have their own subcommands (e.g. \"components\" has \"pull\"/\"push\").\n// Leaf root commands like \"login\" or \"logout\" are not modules.\nfunction getModuleNames(root: CommanderCommand): Set<string> {\n  return new Set(\n    root.commands\n      .filter(cmd => cmd.commands.length > 0)\n      .map(cmd => cmd.name()),\n  );\n}\n\nfunction warnUnknownModuleKeys(modules: Record<string, any>, knownKeys: Set<string>): void {\n  for (const key of Object.keys(modules)) {\n    if (!knownKeys.has(key)) {\n      console.warn(`[storyblok] Unknown module \"${key}\" in config file. Known modules: ${[...knownKeys].join(', ')}`);\n    }\n  }\n}\n\n// Walks the command chain (excluding root) and applies module-specific overrides at each level.\nfunction mergeModuleConfig(target: PlainObject, modulesConfig: Record<string, any>, commands: CommanderCommand[]): void {\n  let currentLevel: any = modulesConfig;\n  for (const command of commands) {\n    if (!isPlainObject(currentLevel)) {\n      return;\n    }\n    const segment = currentLevel[command.name()];\n    if (segment === undefined) {\n      return;\n    }\n    if (isPlainObject(segment)) {\n      Object.assign(target, extractDirectValues(segment));\n      currentLevel = segment;\n    }\n    else {\n      Object.assign(target, { [command.name()]: segment });\n      return;\n    }\n  }\n}\n\nexport async function resolveConfig(\n  thisCommand: CommanderCommand,\n  ancestry?: CommanderCommand[] | CommanderCommand,\n): Promise<ResolvedCliConfig> {\n  // Build the command hierarchy so we can split global vs local defaults and apply overrides in order.\n  let commandChain: CommanderCommand[];\n  if (Array.isArray(ancestry)) {\n    commandChain = ancestry;\n  }\n  else if (ancestry) {\n    commandChain = getCommandAncestry(ancestry);\n  }\n  else {\n    commandChain = getCommandAncestry(thisCommand);\n  }\n  const [root, ...rest] = commandChain;\n\n  // Create default config once and reuse it\n  const defaultConfig = createDefaultResolvedConfig();\n  const globalResolved = collectGlobalDefaults(root, defaultConfig);\n  const localResolved = collectLocalDefaults(rest);\n\n  const layers = await loadConfigLayers();\n  const knownModuleKeys = getModuleNames(root);\n  for (const layer of layers) {\n    const { modules, ...globalLayer } = layer;\n    // Later layers overwrite earlier ones because loadConfigLayers orders them from general to specific.\n    mergeDeep(globalResolved, globalLayer);\n    if (modules && isPlainObject(modules)) {\n      warnUnknownModuleKeys(modules, knownModuleKeys);\n      mergeModuleConfig(localResolved, modules, rest);\n    }\n  }\n\n  applyCliOverrides(commandChain, globalResolved, localResolved);\n\n  const resolved = structuredClone(defaultConfig);\n  mergeDeep(resolved as PlainObject, globalResolved);\n  Object.assign(resolved, localResolved);\n\n  if (resolved.space != null) {\n    resolved.space = String(resolved.space);\n  }\n\n  return resolved;\n}\n","import type { ResolvedCliConfig } from './types';\nimport { createDefaultResolvedConfig } from './defaults';\n\n// Singleton snapshot that exposes the last resolved config\nlet activeConfig: ResolvedCliConfig = createDefaultResolvedConfig();\n\nexport function getActiveConfig(): ResolvedCliConfig {\n  return activeConfig;\n}\n\nexport function setActiveConfig(config: ResolvedCliConfig): void {\n  activeConfig = structuredClone(config);\n}\n\nexport function resetActiveConfig(): void {\n  activeConfig = createDefaultResolvedConfig();\n}\n","import { getActiveConfig } from '../lib/config';\n\nexport interface FetchErrorRequest {\n  url?: string;\n  method?: string;\n}\n\nexport class FetchError extends Error {\n  response: {\n    status: number;\n    statusText: string;\n    data?: Record<string, unknown> | null;\n  };\n\n  request: FetchErrorRequest;\n\n  constructor(\n    message: string,\n    response: { status: number; statusText: string; data?: Record<string, unknown> | null },\n    request: FetchErrorRequest = {},\n  ) {\n    super(message);\n    this.name = 'FetchError';\n    this.response = response;\n    this.request = request;\n  }\n}\n\nexport const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));\n\nexport interface FetchOptions {\n  headers?: Record<string, string>;\n  method?: string;\n  body?: any;\n  maxRetries?: number;\n  baseDelay?: number;\n}\n\nexport async function customFetch<T>(url: string, options: FetchOptions = {}): Promise<T & { perPage: number; total: number }> {\n  const { api } = getActiveConfig(); // live config includes CLI overrides (maxRetries, maxConcurrency, etc.)\n  const maxRetries = options.maxRetries ?? api.maxRetries;\n  const baseDelay = options.baseDelay ?? 500; // 500ms base delay\n  const requestContext: FetchErrorRequest = { url, method: options.method ?? 'GET' };\n  let attempt = 0;\n\n  while (attempt <= maxRetries) {\n    try {\n      const headers = {\n        'Content-Type': 'application/json',\n        ...options.headers,\n      };\n\n      // Handle JSON body\n      const fetchOptions: FetchOptions = {\n        ...options,\n        headers,\n      };\n\n      if (options.body) {\n        fetchOptions.body = typeof options.body === 'string'\n          ? options.body\n          : JSON.stringify(options.body);\n      }\n\n      const response = await fetch(url, fetchOptions);\n      let data;\n      try {\n        // We try to parse the response as JSON\n        data = await response.json();\n      }\n      catch {\n        // If it fails, we throw an error\n        throw new FetchError(`Non-JSON response`, {\n          status: response.status,\n          statusText: response.statusText,\n          data: null,\n        }, requestContext);\n      }\n\n      if (!response.ok) {\n        // If we hit rate limit and have retries left\n        if ((response.status === 429) && (attempt < maxRetries)) {\n          const waitTime = baseDelay * 2 ** attempt;\n          await delay(waitTime);\n          attempt++;\n          continue;\n        }\n\n        throw new FetchError(`HTTP error! status: ${response.status}`, {\n          status: response.status,\n          statusText: response.statusText,\n          data,\n        }, requestContext);\n      }\n\n      return {\n        ...data,\n        perPage: Number(response.headers.get('Per-Page')),\n        total: Number(response.headers.get('Total')),\n      };\n    }\n    catch (error) {\n      if (error instanceof FetchError) {\n        throw error;\n      }\n      // For network errors or other non-HTTP errors, create a FetchError\n      throw new FetchError(error instanceof Error ? error.message : String(error), {\n        status: 0,\n        statusText: 'Network Error',\n        data: null,\n      }, requestContext);\n    }\n  }\n\n  throw new FetchError('Max retries exceeded', {\n    status: 429,\n    statusText: 'Rate Limit Exceeded',\n    data: null,\n  }, requestContext);\n}\n","import { FetchError } from '../fetch';\n\nexport const API_ACTIONS = {\n  login: 'login',\n  login_with_token: 'Failed to log in with token',\n  login_with_otp: 'Failed to log in with email, password and otp',\n  login_email_password: 'Failed to log in with email and password',\n  get_user: 'Failed to get user',\n  pull_languages: 'Failed to pull languages',\n  pull_components: 'Failed to pull components',\n  pull_component_groups: 'Failed to pull component groups',\n  pull_component_presets: 'Failed to pull component presets',\n  pull_component_internal_tags: 'Failed to pull component internal tags',\n  push_component: 'Failed to push component',\n  push_component_group: 'Failed to push component group',\n  push_component_preset: 'Failed to push component preset',\n  push_component_internal_tag: 'Failed to push component internal tag',\n  update_component: 'Failed to update component',\n  update_component_internal_tag: 'Failed to update component internal tag',\n  update_component_group: 'Failed to update component group',\n  update_component_preset: 'Failed to update component preset',\n  delete_component_preset: 'Failed to delete component preset',\n  pull_stories: 'Failed to pull stories',\n  pull_story: 'Failed to pull story',\n  create_story: 'Failed to create story',\n  update_story: 'Failed to update story',\n  pull_asset: 'Failed to pull asset',\n  pull_assets: 'Failed to pull assets',\n  pull_asset_folder: 'Failed to pull asset folder',\n  pull_asset_folders: 'Failed to pull asset folders',\n  push_asset_folder: 'Failed to push asset folder',\n  push_asset_create: 'Failed to create asset',\n  push_asset_update: 'Failed to update asset',\n  pull_datasources: 'Failed to pull datasources',\n  push_datasource: 'Failed to push datasource',\n  update_datasource: 'Failed to update datasource',\n  delete_datasource: 'Failed to delete datasource',\n  delete_datasource_entry: 'Failed to delete datasource entry',\n  create_space: 'Failed to create space',\n  pull_spaces: 'Failed to pull spaces',\n  fetch_blueprints: 'Failed to fetch blueprints from GitHub',\n} as const;\n\nexport const API_ERRORS = {\n  unauthorized: 'The user is not authorized to access the API',\n  network_error: 'No response from server, please check if you are correctly connected to internet',\n  server_error: 'The server returned an error',\n  invalid_credentials: 'The provided credentials are invalid',\n  timeout: 'The API request timed out',\n  generic: 'Error fetching data from the API',\n  not_found: 'The requested resource was not found',\n  unprocessable_entity: 'The request was well-formed but was unable to be followed due to semantic errors',\n} as const;\n\nfunction getErrorId(status: number): keyof typeof API_ERRORS {\n  switch (status) {\n    case 401:\n      return 'unauthorized';\n    case 404:\n      return 'not_found';\n    case 422:\n      return 'unprocessable_entity';\n    default:\n      return status >= 500 ? 'server_error' : 'generic';\n  }\n}\n\nexport function handleAPIError(action: keyof typeof API_ACTIONS, error: unknown, customMessage?: string): never {\n  if (error instanceof FetchError) {\n    const errorId = getErrorId(error.response.status);\n    throw new APIError(errorId, action, error, customMessage);\n  }\n\n  // Handle non-FetchError objects that have a response property (e.g. mapi-client ClientError).\n  // ClientError itself doesn't carry request context, but some wrappers attach\n  // a `request` field — forward it best-effort so verbose output can show it.\n  const response = (error as any)?.response;\n  if (response?.status) {\n    const reqCandidate = (error as any)?.request;\n    const wrappedError = new FetchError(\n      response.statusText ?? (error as Error).message,\n      { status: response.status, statusText: response.statusText ?? '', data: response.data },\n      {\n        url: typeof reqCandidate?.url === 'string' ? reqCandidate.url : undefined,\n        method: typeof reqCandidate?.method === 'string' ? reqCandidate.method : undefined,\n      },\n    );\n    const errorId = getErrorId(response.status);\n    throw new APIError(errorId, action, wrappedError, customMessage);\n  }\n\n  throw new APIError('generic', action, error as FetchError, customMessage);\n}\n\nexport class APIError extends Error {\n  errorId: string;\n  cause: string;\n  code: number;\n  messageStack: string[];\n  error: FetchError | undefined;\n  response: FetchError['response'] | undefined;\n  constructor(errorId: keyof typeof API_ERRORS, action: keyof typeof API_ACTIONS, error?: FetchError, customMessage?: string) {\n    super(customMessage || API_ERRORS[errorId]);\n    this.name = 'API Error';\n    this.errorId = errorId;\n    this.cause = API_ERRORS[errorId];\n    this.code = error?.response?.status || 0;\n    this.messageStack = [];\n    this.error = error;\n    this.response = error?.response;\n\n    if (!customMessage) {\n      this.messageStack.push(API_ACTIONS[action]);\n    }\n    this.messageStack.push(customMessage || API_ERRORS[errorId]);\n\n    if (this.code === 422) {\n      const responseData = this.response?.data as { [key: string]: string[] } | undefined;\n      if (responseData?.name?.[0] === 'has already been taken') {\n        this.message = 'A component with this name already exists';\n      }\n      Object.entries(responseData || {}).forEach(([key, errors]) => {\n        if (Array.isArray(errors)) {\n          errors.forEach((e) => {\n            this.messageStack.push(`${key}: ${e}`);\n          });\n        }\n      });\n    }\n  }\n\n  getInfo() {\n    const request = this.error?.request;\n    const hasRequestContext = Boolean(request && (request.url || request.method));\n    return {\n      name: this.name,\n      message: this.message,\n      httpCode: this.code,\n      cause: this.cause,\n      errorId: this.errorId,\n      stack: this.stack,\n      responseData: this.response?.data,\n      ...(hasRequestContext ? { request: { url: request!.url, method: request!.method } } : {}),\n    };\n  }\n}\n","export class CommandError extends Error {\n  constructor(message: string) {\n    super(message);\n    this.name = 'Command Error';\n  }\n\n  getInfo() {\n    return {\n      name: this.name,\n      message: this.message,\n      stack: this.stack,\n    };\n  }\n}\n","export type LogLevel = 'error' | 'warn' | 'info' | 'debug';\n\nexport type LogContextValue =\n  | string\n  | number\n  | boolean\n  | null\n  | undefined\n  | Error\n  | LogContextValue[]\n  | { [key: string]: LogContextValue };\n\nexport interface LogContext {\n  [key: string]: LogContextValue;\n}\n\nexport interface LogRecord {\n  timestamp?: Date;\n  level: LogLevel;\n  message: string;\n  context?: LogContext;\n}\n\nexport interface LogTransport {\n  enabled?: boolean;\n  level?: LogLevel;\n  log: (record: LogRecord) => void;\n}\n\nexport interface LoggerOptions {\n  context?: LogContext;\n  transports?: LogTransport[];\n}\n\nexport class Logger {\n  public transports: LogTransport[] = [];\n  public context: LogContext = {};\n\n  constructor(options?: LoggerOptions) {\n    if (options?.transports) { this.transports = options.transports; }\n    if (options?.context) { this.context = options.context; }\n  }\n\n  public log(level: LogLevel, message: string, context?: LogContext): void {\n    const timestamp = new Date();\n    const mergedContext = context\n      ? { ...this.context, ...context }\n      : this.context;\n\n    const record: LogRecord = {\n      timestamp,\n      level,\n      message,\n      context: Object.keys(mergedContext).length ? mergedContext : undefined,\n    };\n\n    for (const transport of this.transports) {\n      transport.log(record);\n    }\n  }\n\n  public error(message: string, context?: LogContext): void {\n    this.log('error', message, context);\n  }\n\n  public warn(message: string, context?: LogContext): void {\n    this.log('warn', message, context);\n  }\n\n  public info(message: string, context?: LogContext): void {\n    this.log('info', message, context);\n  }\n\n  public debug(message: string, context?: LogContext): void {\n    this.log('debug', message, context);\n  }\n}\n\nlet loggerInstance: Logger | null = null;\n\nexport function getLogger(options?: LoggerOptions) {\n  if (!loggerInstance) {\n    loggerInstance = new Logger(options);\n  }\n\n  return loggerInstance;\n}\n\nexport function setLoggerTransports(transports: LogTransport[]) {\n  if (loggerInstance) {\n    loggerInstance.transports = transports;\n  }\n}\n\nexport function resetLogger() {\n  loggerInstance = null;\n}\n","const FS_ERRORS = {\n  file_not_found: 'The file requested was not found',\n  permission_denied: 'Permission denied while accessing the file',\n  operation_on_directory: 'The operation is not allowed on a directory',\n  not_a_directory: 'The path provided is not a directory',\n  file_already_exists: 'The file already exists',\n  directory_not_empty: 'The directory is not empty',\n  too_many_open_files: 'Too many open files',\n  no_space_left: 'No space left on the device',\n  invalid_argument: 'An invalid argument was provided',\n  unknown_error: 'An unknown error occurred',\n} as const;\n\nconst FS_ACTIONS = {\n  read: 'Failed to read/parse file:',\n  write: 'Writing file',\n  delete: 'Deleting file',\n  mkdir: 'Creating directory',\n  rmdir: 'Removing directory',\n  authorization_check: 'Failed to check authorization in .netrc file:',\n} as const;\n\nexport function handleFileSystemError(action: keyof typeof FS_ACTIONS, error: NodeJS.ErrnoException): void {\n  if (error.code) {\n    switch (error.code) {\n      case 'ENOENT':\n        throw new FileSystemError('file_not_found', action, error);\n      case 'EACCES':\n      case 'EPERM':\n        throw new FileSystemError('permission_denied', action, error);\n      case 'EISDIR':\n        throw new FileSystemError('operation_on_directory', action, error);\n      case 'ENOTDIR':\n        throw new FileSystemError('not_a_directory', action, error);\n      case 'EEXIST':\n        throw new FileSystemError('file_already_exists', action, error);\n      case 'ENOTEMPTY':\n        throw new FileSystemError('directory_not_empty', action, error);\n      case 'EMFILE':\n        throw new FileSystemError('too_many_open_files', action, error);\n      case 'ENOSPC':\n        throw new FileSystemError('no_space_left', action, error);\n      case 'EINVAL':\n        throw new FileSystemError('invalid_argument', action, error);\n      default:\n        throw new FileSystemError('unknown_error', action, error);\n    }\n  }\n  else {\n    // In case the error does not have a known `fs` error code, throw a general error\n    throw new FileSystemError('unknown_error', action, error);\n  }\n}\n\nexport class FileSystemError extends Error {\n  errorId: string;\n  cause: string;\n  code: string | undefined;\n  messageStack: string[];\n  error: NodeJS.ErrnoException | undefined;\n\n  constructor(errorId: keyof typeof FS_ERRORS, action: keyof typeof FS_ACTIONS, error: NodeJS.ErrnoException, customMessage?: string) {\n    super(customMessage || FS_ERRORS[errorId]);\n    this.name = 'File System Error';\n    this.errorId = errorId;\n    this.cause = FS_ERRORS[errorId];\n    this.code = error.code;\n    this.messageStack = [];\n    this.error = error;\n\n    if (!customMessage) {\n      this.messageStack.push(FS_ACTIONS[action]);\n    }\n    this.messageStack.push(customMessage || FS_ERRORS[errorId]);\n  }\n\n  getInfo() {\n    return {\n      name: this.name,\n      message: this.message,\n      code: this.code,\n      cause: this.cause,\n      errorId: this.errorId,\n      stack: this.stack,\n    };\n  }\n}\n","import type { LogContext } from '../../lib/logger/logger';\nimport { getLogger } from '../../lib/logger/logger';\nimport { konsola } from '..';\nimport type { FetchError } from '../fetch';\nimport { APIError } from './api-error';\nimport { CommandError } from './command-error';\nimport { FileSystemError } from './filesystem-error';\n\ninterface ErrorWithMessage {\n  message: string;\n}\n\nfunction hasMessage(error: unknown): error is ErrorWithMessage {\n  return (\n    typeof error === 'object'\n    && error !== null\n    && 'message' in error\n    && typeof (error as Record<string, unknown>).message === 'string'\n  );\n}\n\nexport function toError(maybeError: unknown) {\n  if (maybeError instanceof Error) { return maybeError; }\n  if (typeof maybeError === 'string') { return new Error(maybeError); }\n  if (hasMessage(maybeError)) { return new Error(maybeError.message); }\n\n  try {\n    return new Error(JSON.stringify(maybeError));\n  }\n  catch {\n    // fallback in case there's an error stringifying the maybeError\n    // like with circular references for example.\n    return new Error(String(maybeError));\n  }\n}\n\nfunction handleVerboseError(error: unknown): void {\n  if (error instanceof CommandError || error instanceof APIError || error instanceof FileSystemError) {\n    const errorDetails = 'getInfo' in error ? error.getInfo() : {};\n    if (error instanceof CommandError) {\n      konsola.error(`Command Error: ${error.getInfo().message}`, errorDetails);\n    }\n    else if (error instanceof APIError) {\n      konsola.error(`API Error: ${error.getInfo().cause}`, errorDetails);\n    }\n    else if (error instanceof FileSystemError) {\n      konsola.error(`File System Error: ${error.getInfo().cause}`, errorDetails);\n    }\n    else {\n      konsola.error(`Unexpected Error: ${error}`, errorDetails);\n    }\n  }\n  else {\n    konsola.error(`Unexpected Error`, error);\n  }\n}\n\nexport function handleError(error: Error | FetchError, verbose = false, context?: LogContext): void {\n  // Print the message stack if it exists\n  if (error instanceof APIError || error instanceof FileSystemError) {\n    const messageStack = (error).messageStack;\n    messageStack.forEach((message: string, index: number) => {\n      konsola.error(message, null, {\n        header: index === 0,\n        margin: false,\n      });\n    });\n  }\n  else {\n    konsola.error(error.message, null, {\n      header: true,\n    });\n  }\n  if (verbose) {\n    handleVerboseError(error);\n  }\n  else {\n    konsola.br();\n    konsola.info('For more information about the error, run the command with the `--verbose` flag');\n  }\n\n  if (!process.env.VITEST) {\n    console.log(''); // Add a line break for readability\n  }\n  getLogger().error(error.message, { error, errorCode: 'code' in error ? String(error.code) : 'UNKNOWN_ERROR', context });\n}\n\nexport function logOnlyError(error: Error | FetchError, context?: LogContext): void {\n  getLogger().error(error.message, { error, errorCode: 'code' in error ? String(error.code) : 'UNKNOWN_ERROR', context });\n}\n","import { colorPalette } from '../constants';\nimport type { SessionState } from '../session';\nimport { CommandError, handleError } from './error';\nimport chalk from 'chalk';\n\ntype AuthenticatedSessionState = SessionState & {\n  isLoggedIn: true;\n  password: NonNullable<SessionState['password']>;\n  region: NonNullable<SessionState['region']>;\n};\n\n/**\n * Check if user is authenticated and handle error if not\n * @param state - Session state object\n * @param verbose - Whether to show verbose error output\n * @returns true if authenticated, false if not (and error is handled)\n */\nexport function requireAuthentication(state: SessionState, verbose = false): state is AuthenticatedSessionState {\n  if (!state.isLoggedIn || !state.password || !state.region) {\n    handleError(\n      new CommandError(`You are currently not logged in. Please run ${chalk.hex(colorPalette.PRIMARY)('storyblok login')} to authenticate, or ${chalk.hex(colorPalette.PRIMARY)('storyblok signup')} to sign up.`),\n      verbose,\n    );\n    return false;\n  }\n  return true;\n}\n","export const toCamelCase = (str: string) => {\n  return str\n    // First replace snake_case\n    .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())\n    .replace(/_/g, '')\n    // Then replace kebab-case\n    .replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())\n  // Capitalize letters after special characters\n    .replace(/[^a-z0-9]([a-z])/gi, (_, letter) => letter.toUpperCase())\n    // Remove special characters\n    .replace(/[^a-z0-9]/gi, '');\n};\n\nexport const toPascalCase = (str: string) => {\n  const camelCase = toCamelCase(str);\n  return camelCase ? camelCase[0].toUpperCase() + camelCase.slice(1) : camelCase;\n};\n\nexport const toSnakeCase = (str: string) => {\n  return str\n    .replace(/([A-Z])/g, (_, char) => `_${char.toLowerCase()}`)\n    .replace(/^_/, '');\n};\n\nexport const capitalize = (str: string) => {\n  return str.charAt(0).toUpperCase() + str.slice(1);\n};\n\n/**\n * Converts kebab-case, snake_case, or camelCase strings to human-readable title case\n * @param str - The string to convert (e.g., \"my-blog-website\", \"my_blog_website\", \"myBlogWebsite\")\n * @returns A human-readable string (e.g., \"My Blog Website\")\n *\n * @example\n * toHumanReadable(\"my-blog-website\") // \"My Blog Website\"\n * toHumanReadable(\"my_react_app\") // \"My React App\"\n * toHumanReadable(\"myVueProject\") // \"My Vue Project\"\n * toHumanReadable(\"simple\") // \"Simple\"\n */\nexport const toHumanReadable = (str: string): string => {\n  return str\n    // Replace kebab-case and snake_case with spaces\n    .replace(/[-_]/g, ' ')\n    // Insert space before uppercase letters (for camelCase)\n    .replace(/([a-z])([A-Z])/g, '$1 $2')\n    // Split into words and capitalize each word\n    .split(' ')\n    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n    .join(' ')\n    // Clean up any extra spaces\n    .replace(/\\s+/g, ' ')\n    .trim();\n};\n\nexport function maskToken(token: string): string {\n  // Show only the first 4 characters and replace the rest with asterisks\n  if (token.length <= 4) {\n    // If the token is too short, just return it as is\n    return token;\n  }\n  const visiblePart = token.slice(0, 4);\n  const maskedPart = '*'.repeat(token.length - 4);\n  return `${visiblePart}${maskedPart}`;\n}\n\nexport const slugify = (text: string): string =>\n  text\n    .toString()\n    .toLowerCase()\n    .replace(/\\s+/g, '-') // Replace spaces with -\n    .replace(/[^\\w-]+/g, '') // Remove all non-word chars\n    .replace(/-{2,}/g, '-') // Replace multiple - with single -\n    .replace(/^-+/, '') // Trim - from start of text\n    .replace(/-+$/, '');\n\nexport const removePropertyRecursively = (obj: Record<string, any>, property: string): Record<string, any> => {\n  if (typeof obj !== 'object' || obj === null) {\n    return obj;\n  }\n\n  if (Array.isArray(obj)) {\n    return obj.map(item => removePropertyRecursively(item, property));\n  }\n\n  const result: Record<string, any> = {};\n  for (const [key, value] of Object.entries(obj)) {\n    if (key !== property) {\n      result[key] = removePropertyRecursively(value, property);\n    }\n  }\n  return result;\n};\n\n/**\n * Converts an object with potential non-string values to an object with string values\n * for use with URLSearchParams\n *\n * @param obj - The object to convert\n * @returns An object with all values converted to strings\n */\nexport const objectToStringParams = (obj: Record<string, any>): Record<string, string> => {\n  return Object.entries(obj).reduce((acc, [key, value]) => {\n    // Skip undefined values\n    if (value === undefined) {\n      return acc;\n    }\n\n    // Convert objects/arrays to JSON strings\n    if (typeof value === 'object' && value !== null) {\n      acc[key] = JSON.stringify(value);\n    }\n    else {\n      // Convert other types to strings\n      acc[key] = String(value);\n    }\n    return acc;\n  }, {} as Record<string, string>);\n};\n\n/**\n * Creates a regex pattern from a glob pattern\n * @param pattern - The glob pattern to convert\n * @returns A regex that matches the glob pattern\n */\nexport function createRegexFromGlob(pattern: string): RegExp {\n  // Add ^ and $ to ensure exact match, escape the pattern to handle special characters\n  return new RegExp(`^${pattern.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&').replace(/\\\\\\*/g, '.*')}$`);\n}\n","/**\n * DEPRECATED!\n * Use `getUI()` instead.\n */\nimport chalk from 'chalk';\nimport { capitalize } from './format';\n\nexport interface KonsolaFormatOptions {\n  header?: boolean;\n  margin?: boolean;\n}\n\nexport function formatHeader(title: string) {\n  return `${title}`;\n}\nexport const konsola = {\n  title: (message: string, color: string, subtitle?: string) => {\n    if (subtitle) {\n      console.log(`${formatHeader(chalk.bgHex(color).bold(` ${capitalize(message)} `))} ${subtitle}`);\n    }\n    else {\n      console.log(formatHeader(chalk.bgHex(color).bold(` ${capitalize(message)} `)));\n    }\n    console.log(''); // Add a line break\n    console.log(''); // Add a line break\n  },\n  br: () => {\n    console.log(''); // Add a line break\n  },\n  ok: (message?: string, header: boolean = false) => {\n    if (header) {\n      console.log(''); // Add a line break\n      const successHeader = chalk.bgGreen.bold.white(` Success `);\n      console.log(formatHeader(successHeader));\n      console.log(''); // Add a line break\n    }\n\n    console.log(message ? `${chalk.green('✔')} ${message}` : '');\n  },\n  info: (message: string, options: KonsolaFormatOptions = {\n    header: false,\n    margin: true,\n  }) => {\n    if (options.header) {\n      console.log(''); // Add a line break\n      const infoHeader = chalk.bgBlue.bold.white(` Info `);\n      console.log(formatHeader(infoHeader));\n    }\n\n    console.log(message ? `${chalk.blue('ℹ')} ${message}` : '');\n    if (options.margin) {\n      console.error(''); // Add a line break\n    }\n  },\n  warn: (message?: string, header: boolean = false) => {\n    if (header) {\n      console.log(''); // Add a line break\n      const warnHeader = chalk.bgYellow.bold.black(` Warning `);\n      console.warn(formatHeader(warnHeader));\n    }\n\n    console.warn(message ? `${chalk.yellow('⚠️ ')} ${message}` : '');\n  },\n  error: (message: string, info?: unknown, options?: KonsolaFormatOptions) => {\n    if (options?.header) {\n      const errorHeader = chalk.bgRed.bold.white(` Error `);\n      console.error(formatHeader(errorHeader));\n      console.log(''); // Add a line break\n    }\n\n    console.error(`${chalk.red.bold('▲ error')} ${message}`, info || '');\n    if (options?.margin) {\n      console.error(''); // Add a line break\n    }\n  },\n};\n","import { fileURLToPath } from 'node:url';\nimport { dirname } from 'pathe';\nimport type { NormalizedPackageJson } from 'read-package-up';\nimport { readPackageUp } from 'read-package-up';\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Read package.json for metadata\nconst result = await readPackageUp({\n  cwd: __dirname,\n});\n\nconst packageJson: NormalizedPackageJson = result\n  ? result.packageJson\n  : ({\n      name: 'storyblok',\n      description: 'Storyblok CLI',\n      version: '0.0.0',\n    } as NormalizedPackageJson);\n\nif (!result) {\n  console.debug('Metadata not found');\n}\n\n/**\n * Get the package.json metadata\n *\n * @export\n * @return {NormalizedPackageJson}\n */\nexport function getPackageJson(): NormalizedPackageJson {\n  return packageJson;\n}\n\nexport { packageJson as pkg };\n","import { fileURLToPath } from 'node:url';\nimport { dirname } from 'pathe';\nimport type { RegionCode } from '../constants';\nimport { regions } from '../constants';\n\nexport * from './array';\nexport * from './auth';\nexport * from './error/';\nexport * from './format';\nexport * from './konsola';\nexport * from './object';\nexport * from './package';\nexport * from './types';\n\nexport const __filename = fileURLToPath(import.meta.url);\nexport const __dirname = dirname(__filename);\n\nexport function isRegion(value: RegionCode): value is RegionCode {\n  return Object.values(regions).includes(value);\n}\n\nexport const isVitest = process.env.VITEST === 'true';\n","import chalk from 'chalk';\nimport { MultiBar, Presets } from 'cli-progress';\nimport { Spinner } from '@topcli/spinner';\nimport { colorPalette } from '../constants';\nimport { capitalize } from './format';\nimport { isVitest } from './';\n\ninterface InfoOptions {\n  header?: boolean;\n  margin?: boolean;\n}\n\ninterface ErrorOptions {\n  header?: boolean;\n  margin?: boolean;\n}\n\ninterface ProgressBar {\n  increment: (count?: number) => void;\n  setTotal: (total: number) => void;\n  stop: () => void;\n}\n\nconst noopProgressBar: ProgressBar = {\n  increment: () => {},\n  setTotal: () => {},\n  stop: () => {},\n};\n\nconst noopSpinner = {\n  failed: (_title: string) => {},\n  succeed: (_title: string) => {},\n  elapsedTime: 0,\n};\n\nexport class UI {\n  private console: typeof console | null;\n  private enabled: boolean;\n  private multiBar: MultiBar | null;\n\n  constructor({ enabled }: { enabled: boolean }) {\n    this.console = enabled ? console : null;\n    this.enabled = enabled;\n    this.multiBar = enabled\n      ? new MultiBar({\n        clearOnComplete: false,\n        format: `${chalk.bold(' {title} ')} ${chalk.hex(colorPalette.PRIMARY)('[{bar}]')} {percentage}% | {eta_formatted} | {value}/{total} processed`,\n        etaBuffer: 60,\n      }, Presets.rect)\n      : null;\n  }\n\n  title(message: string, color: string, subtitle?: string) {\n    if (subtitle) {\n      this.console?.log(`${chalk.bgHex(color).bold(` ${capitalize(message)} `)} ${subtitle}`);\n    }\n    else {\n      this.console?.log(chalk.bgHex(color).bold(` ${capitalize(message)} `));\n    }\n    this.br();\n    this.br();\n  }\n\n  br() {\n    this.console?.log('');\n  }\n\n  ok(message?: string, header: boolean = false) {\n    if (header) {\n      this.br();\n      const successHeader = chalk.bgGreen.bold.white(` Success `);\n      this.console?.log(successHeader);\n      this.br();\n    }\n\n    this.console?.log(message ? `${chalk.green('✔')} ${message}` : '');\n  }\n\n  info(message: string, options: InfoOptions = {}) {\n    const { header = false, margin = true } = options;\n    if (header) {\n      this.br();\n      const infoHeader = chalk.bgBlue.bold.white(` Info `);\n      this.console?.info(infoHeader);\n    }\n\n    this.console?.info(message ? `${chalk.blue('ℹ')} ${message}` : '');\n    if (margin) {\n      this.br();\n    }\n  }\n\n  warn(message?: string, header: boolean = false) {\n    if (header) {\n      this.br();\n      const warnHeader = chalk.bgYellow.bold.black(` Warning `);\n      this.console?.warn(warnHeader);\n    }\n\n    this.console?.warn(message ? `${chalk.yellow('⚠️ ')} ${message}` : '');\n  }\n\n  error(message: string, info?: unknown, options: ErrorOptions = {}) {\n    const { header = false, margin = false } = options;\n    if (header) {\n      const errorHeader = chalk.bgRed.bold.white(` Error `);\n      this.console?.error(errorHeader);\n      this.br();\n    }\n\n    this.console?.error(`${chalk.red.bold('▲ error')} ${message}`, info || '');\n    if (margin) {\n      this.br();\n    }\n  }\n\n  list(items: string[]) {\n    for (const item of items) {\n      this.console?.log(`  ${item}`);\n    }\n  }\n\n  createProgressBar(options: { title: string }): ProgressBar {\n    const bar = this.multiBar?.create(0, 0, options);\n    if (!bar) { return noopProgressBar; }\n    return {\n      increment: (count = 1) => bar.increment(count),\n      // cli-progress renders `{eta_formatted}` as \"LLs\" when total is 0.\n      // Floor at 1 so an empty phase stays a clean 0/1 instead.\n      setTotal: total => bar.setTotal(Math.max(total, 1)),\n      stop: () => bar.stop(),\n    };\n  }\n\n  stopAllProgressBars() {\n    this.multiBar?.stop();\n  }\n\n  createSpinner(title: string) {\n    return this.enabled\n      ? new Spinner({\n          verbose: !isVitest,\n        }).start(title)\n      : noopSpinner;\n  }\n}\n\nlet uiInstance: UI | null = null;\n\nexport function getUI(options: { enabled: boolean } = { enabled: false }) {\n  if (!uiInstance) {\n    uiInstance = new UI(options);\n  }\n\n  return uiInstance;\n}\n","import { join, parse, resolve } from 'pathe';\nimport { pathToFileURL } from 'node:url';\nimport { access, appendFile, constants, mkdir, readdir, readFile as readFileImpl, writeFile } from 'node:fs/promises';\nimport { handleFileSystemError } from './error/filesystem-error';\nimport type { FileReaderResult } from '../types';\nimport filenamify from 'filenamify';\nimport { appendFileSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { toError } from './error';\n\n// Default working folder for commands that do not pass --path explicitly.\nexport const DEFAULT_STORAGE_DIR = '.storyblok';\n\nexport interface FileOptions {\n  mode?: number;\n}\n\nexport const getStoryblokGlobalPath = () => {\n  const homeDirectory = process.env[\n    process.platform.startsWith('win') ? 'USERPROFILE' : 'HOME'\n  ] || process.cwd();\n\n  return join(homeDirectory, '.storyblok');\n};\n\nexport const saveToFile = async (filePath: string, data: string | NodeJS.ArrayBufferView, options?: FileOptions) => {\n  // Get the directory path\n  const resolvedPath = parse(filePath).dir;\n\n  // Ensure the directory exists\n  try {\n    await mkdir(resolvedPath, { recursive: true });\n  }\n  catch (mkdirError) {\n    handleFileSystemError('mkdir', mkdirError as Error);\n    return; // Exit early if the directory creation fails\n  }\n\n  // Write the file\n  try {\n    await writeFile(filePath, data, options);\n  }\n  catch (writeError) {\n    handleFileSystemError('write', writeError as Error);\n  }\n};\n\nexport const saveToFileSync = (filePath: string, data: string | NodeJS.ArrayBufferView, options?: FileOptions) => {\n  const resolvedPath = parse(filePath).dir;\n\n  // Only attempt to create a directory if there's a directory part\n  if (resolvedPath) {\n    try {\n      mkdirSync(resolvedPath, { recursive: true });\n    }\n    catch (mkdirError) {\n      handleFileSystemError('mkdir', mkdirError as Error);\n      return; // Exit early if the directory creation fails\n    }\n  }\n\n  try {\n    writeFileSync(filePath, data, options as any);\n  }\n  catch (writeError) {\n    handleFileSystemError('write', writeError as Error);\n  }\n};\n\nexport const appendToFile = async (filePath: string, data: string, options?: any) => {\n  const dataWithNewline = data.endsWith('\\n') ? data : `${data}\\n`;\n  try {\n    await appendFile(filePath, dataWithNewline, options);\n  }\n  catch (maybeError) {\n    const error = toError(maybeError);\n    // If the directory doesn't exist, create it and retry\n    if ('code' in error && error.code === 'ENOENT') {\n      const dir = parse(filePath).dir;\n      await mkdir(dir, { recursive: true });\n      // Retry the append\n      await appendFile(filePath, dataWithNewline, options);\n    }\n    else {\n      handleFileSystemError(\n        'syscall' in error && error.syscall === 'mkdir' ? 'mkdir' : 'write',\n        error,\n      );\n    }\n  }\n};\n\nexport const appendToFileSync = (filePath: string, data: string, options?: FileOptions) => {\n  const resolvedPath = parse(filePath).dir;\n\n  // Ensure the directory exists\n  try {\n    mkdirSync(resolvedPath, { recursive: true });\n  }\n  catch (mkdirError) {\n    handleFileSystemError('mkdir', mkdirError as Error);\n    return;\n  }\n\n  try {\n    const dataWithNewline = data.endsWith('\\n') ? data : `${data}\\n`;\n    appendFileSync(filePath, dataWithNewline, options);\n  }\n  catch (writeError) {\n    handleFileSystemError('write', writeError as Error);\n  }\n};\n\nexport const readFile = async (filePath: string) => {\n  try {\n    return await readFileImpl(filePath, 'utf8');\n  }\n  catch (error) {\n    handleFileSystemError('read', error as Error);\n    return '';\n  }\n};\n\nexport interface ManifestEntry {\n  old_id: string | number;\n  new_id: string | number;\n  old_filename?: string;\n  new_filename?: string;\n  created_at?: string;\n}\n\nexport const loadManifest = async (manifestFile: string): Promise<ManifestEntry[]> => {\n  return readFileImpl(manifestFile, 'utf8')\n    .then(manifest => manifest.split('\\n').filter(Boolean).map(entry => JSON.parse(entry)))\n    .catch((error: NodeJS.ErrnoException) => {\n      if (error && error.code === 'ENOENT') {\n        return [];\n      }\n      throw error;\n    });\n};\n\n/**\n * Saves an array of manifest entries to a JSONL file.\n */\nexport const saveManifest = async (manifestFile: string, entries: ManifestEntry[]): Promise<void> => {\n  const content = entries.map(entry => JSON.stringify(entry)).join('\\n');\n  await saveToFile(manifestFile, content ? `${content}\\n` : '');\n};\n\n/**\n * Deduplicates a manifest file by keeping only the latest entry for each `old_id`.\n */\nexport const deduplicateManifest = async (manifestFile: string): Promise<void> => {\n  const entries = await loadManifest(manifestFile);\n  if (entries.length === 0) {\n    return;\n  }\n\n  const uniqueEntries = new Map<string | number, ManifestEntry>();\n  for (const entry of entries) {\n    uniqueEntries.set(entry.old_id, entry);\n  }\n\n  await saveManifest(manifestFile, Array.from(uniqueEntries.values()));\n};\n\nexport const resolvePath = (path: string | undefined, folder: string) => {\n  const basePath = path ?? DEFAULT_STORAGE_DIR;\n  // Keeps honoring relative paths by anchoring everything on the current workspace root.\n  return resolve(process.cwd(), basePath, folder);\n};\n\n/**\n * Resolves the absolute path for a specific command directory.\n *\n * If a `space` is provided, it is appended to the `commandPath` before resolution.\n *\n * @param commandPath - The relative path or name of the command category.\n * @param space - (Optional).\n * @param baseDir - (Optional) The base directory to resolve against.\n * @returns The fully resolved absolute path string.\n */\nexport function resolveCommandPath(commandPath: string, space?: string, baseDir?: string) {\n  if (space) {\n    return resolvePath(baseDir, join(commandPath, space));\n  }\n  return resolvePath(baseDir, commandPath);\n}\n\n/**\n * Extracts the component name from a migration filename\n * @param filename - The migration filename (e.g., \"simple_component.js\")\n * @returns The component name (e.g., \"simple_component\")\n */\nexport const getComponentNameFromFilename = (filename: string): string => {\n  // Remove the .js extension\n  return filename.replace(/\\.js$/, '');\n};\n\n/**\n * Sanitizes a string to be safe for use as a filename by removing/replacing problematic characters\n * https://github.com/parshap/node-sanitize-filename/blob/master/index.js\n * @param filename - The filename to sanitize\n * @returns A safe filename string\n */\nexport const sanitizeFilename = (filename: string): string => {\n  return filenamify(filename, {\n    replacement: '_',\n  });\n};\n\nexport async function readDirectory(directoryPath: string) {\n  try {\n    const files = await readdir(directoryPath);\n    return files;\n  }\n  catch (maybeError) {\n    handleFileSystemError('read', toError(maybeError));\n    return [];\n  }\n}\n\nexport async function readJsonFile<T>(filePath: string): Promise<FileReaderResult<T>> {\n  try {\n    const content = (await readFile(filePath)).toString();\n    if (!content) {\n      return { data: [] };\n    }\n    const parsed = JSON.parse(content);\n    return { data: Array.isArray(parsed) ? parsed : [parsed] };\n  }\n  catch (error) {\n    return { data: [], error: error as Error };\n  }\n}\n\nexport function importModule(filePath: string) {\n  return import(pathToFileURL(filePath).href);\n}\n\nexport async function fileExists(path: string) {\n  try {\n    await access(path, constants.F_OK);\n    return true;\n  }\n  catch {\n    return false;\n  }\n}\n\n/**\n * Filters a list of filenames to only include JSON files matching the suffix convention.\n *\n * When `suffix` is set (e.g. \"dev\"), only `*.dev.json` files are included.\n * When unset, all `.json` files are included — use `suffix` to target a specific\n * environment subset.\n */\nexport function filterJsonBySuffix(files: string[], suffix?: string): string[] {\n  return files.filter((file) => {\n    if (!file.endsWith('.json')) {\n      return false;\n    }\n    if (suffix) {\n      return file.endsWith(`.${suffix}.json`);\n    }\n    return true;\n  });\n}\n","import { saveToFileSync } from '../../utils/filesystem';\nimport { existsSync, readdirSync, unlinkSync } from 'node:fs';\nimport { dirname, extname, join, relative } from 'pathe';\n\nexport const REPORT_STATUS = {\n  unfinished: 'UNFINISHED',\n  success: 'SUCCESS',\n  partialSuccess: 'PARTIAL_SUCCESS',\n  failure: 'FAILURE',\n} as const;\n\nexport interface Report {\n  status: typeof REPORT_STATUS[keyof typeof REPORT_STATUS];\n  meta: {\n    command?: string;\n    cliVersion?: string;\n    startedAt?: string;\n    endedAt?: string;\n    durationMs?: number;\n    config?: Record<string, unknown>;\n  } & Record<string, unknown>;\n  summary: Record<string, {\n    total: number;\n    succeeded: number;\n    skipped?: number;\n    failed: number;\n  }>;\n}\n\nexport interface ReporterOptions {\n  enabled?: boolean;\n  filePath?: string;\n  maxFiles?: number;\n}\n\nexport class Reporter {\n  public filePath: string;\n  private enabled: boolean;\n  private startedAt: Date = new Date();\n  private maxFiles?: number;\n  private report: Report = {\n    status: REPORT_STATUS.unfinished,\n    meta: {\n      startedAt: this.startedAt.toISOString(),\n    },\n    summary: {},\n  };\n\n  constructor(options?: ReporterOptions) {\n    this.enabled = options?.enabled || false;\n    this.filePath = options?.filePath ?? `./${Date.now()}.json`;\n    this.maxFiles = options?.maxFiles;\n  }\n\n  public addMeta(key: keyof Report['meta'], value: Report['meta'][typeof key]) {\n    this.report.meta[key] = value;\n    return this;\n  }\n\n  public addSummary(key: keyof Report['summary'], value: Report['summary'][typeof key]) {\n    this.report.summary[key] = value;\n    return this;\n  }\n\n  public finalize() {\n    if (!this.enabled) {\n      return;\n    }\n\n    const endedAt = new Date();\n    this.report.meta.endedAt = endedAt.toISOString();\n    this.report.meta.durationMs = endedAt.getTime() - this.startedAt.getTime();\n    this.updateStatus();\n\n    saveToFileSync(this.filePath, JSON.stringify(this.report, null, 2));\n\n    if (this.maxFiles !== undefined) {\n      this.pruneOldFiles();\n    }\n  }\n\n  private updateStatus() {\n    let succeededTotal = 0;\n    let failedTotal = 0;\n\n    for (const item of Object.values(this.report.summary)) {\n      succeededTotal += item.succeeded;\n      failedTotal += item.failed;\n    }\n\n    if (failedTotal === 0) {\n      this.report.status = REPORT_STATUS.success;\n    }\n    else if (succeededTotal > 0) {\n      this.report.status = REPORT_STATUS.partialSuccess;\n    }\n    else {\n      this.report.status = REPORT_STATUS.failure;\n    }\n  }\n\n  private pruneOldFiles(): void {\n    if (this.maxFiles === undefined) {\n      return;\n    }\n\n    const dir = dirname(this.filePath);\n    const ext = extname(this.filePath);\n\n    Reporter.pruneReportFiles(dir, this.maxFiles, ext);\n  }\n\n  public static pruneReportFiles(\n    directory: string,\n    keep: number,\n    extension = '.json',\n  ) {\n    if (!existsSync(directory)) {\n      return 0;\n    }\n\n    const files = readdirSync(directory)\n      .filter(file => extname(file) === extension)\n      .sort();\n\n    const filesToDelete = files.length - keep;\n    if (filesToDelete <= 0) {\n      return 0;\n    }\n\n    for (const file of files.slice(0, filesToDelete)) {\n      unlinkSync(join(directory, file));\n    }\n\n    return filesToDelete;\n  }\n\n  public static listReportFiles(\n    directory: string,\n    extension = '.json',\n  ) {\n    if (!existsSync(directory)) {\n      return [];\n    }\n\n    return readdirSync(directory)\n      .filter(file => extname(file) === extension)\n      .map(f => relative(process.cwd(), join(directory, f)))\n      .sort();\n  }\n}\n\nlet reporterInstance: Reporter | null = null;\n\nexport function getReporter(options?: ReporterOptions) {\n  if (!reporterInstance) {\n    reporterInstance = new Reporter(options);\n  }\n\n  return reporterInstance;\n}\n\nexport function resetReporter() {\n  reporterInstance = null;\n}\n","import type { LogContext, LogLevel, LogRecord, LogTransport } from './logger';\nimport { appendToFileSync } from '../../utils/filesystem';\nimport { existsSync, readdirSync, unlinkSync } from 'node:fs';\nimport { dirname, extname, join } from 'pathe';\nimport { APIError } from '../../utils/error/api-error';\n\nexport interface FileTransportOptions {\n  filePath?: string;\n  level?: LogLevel;\n  maxFiles?: number;\n}\n\nexport class FileTransport implements LogTransport {\n  public filePath: string;\n  public level: LogLevel;\n  private maxFiles?: number;\n  private hasPruned = false;\n\n  constructor(options?: FileTransportOptions) {\n    this.filePath = options?.filePath ?? `./${Date.now()}.jsonl`;\n    this.level = options?.level ?? 'info';\n    this.maxFiles = options?.maxFiles;\n  }\n\n  public log(record: LogRecord): void {\n    if (!this.shouldLog(record.level)) {\n      return;\n    }\n\n    const line = this.format(record);\n    appendToFileSync(this.filePath, line);\n\n    if (!this.hasPruned && this.maxFiles !== undefined) {\n      // A log file is only created if logged at least once so we only prune old\n      // files if at least one log was written and not when initializing the\n      // transport.\n      this.hasPruned = true;\n      this.pruneOldFiles();\n    }\n  }\n\n  private pruneOldFiles(): void {\n    if (this.maxFiles === undefined) {\n      return;\n    }\n\n    const dir = dirname(this.filePath);\n    const ext = extname(this.filePath);\n\n    FileTransport.pruneLogFiles(dir, this.maxFiles, ext);\n  }\n\n  public static pruneLogFiles(\n    directory: string,\n    keep: number,\n    extension = '.jsonl',\n  ) {\n    if (!existsSync(directory)) {\n      return 0;\n    }\n\n    const files = readdirSync(directory)\n      .filter(file => extname(file) === extension)\n      .sort();\n\n    const filesToDelete = files.length - keep;\n    if (filesToDelete <= 0) {\n      return 0;\n    }\n\n    for (const file of files.slice(0, filesToDelete)) {\n      unlinkSync(join(directory, file));\n    }\n\n    return filesToDelete;\n  }\n\n  public static listLogFiles(\n    directory: string,\n    extension = '.jsonl',\n  ) {\n    if (!existsSync(directory)) {\n      return [];\n    }\n\n    const files = readdirSync(directory)\n      .filter(file => extname(file) === extension)\n      .sort();\n\n    return files.map(f => join(directory, f).replace(process.cwd(), '.'));\n  }\n\n  private levelRank(level: LogLevel): number {\n    switch (level) {\n      case 'error':\n        return 0;\n      case 'warn':\n        return 1;\n      case 'info':\n        return 2;\n      case 'debug':\n        return 3;\n      default:\n        return 3;\n    }\n  }\n\n  private shouldLog(level: LogLevel): boolean {\n    return this.levelRank(level) <= this.levelRank(this.level);\n  }\n\n  private format(record: LogRecord): string {\n    const timestamp = (record.timestamp ?? new Date()).toISOString();\n    const level = record.level.toUpperCase();\n    const message = record.message.replaceAll('\\n', '\\\\n');\n    const contextNormalized = record.context && this.formatContext(record.context);\n\n    return JSON.stringify({ timestamp, level, message, context: contextNormalized });\n  }\n\n  private formatContext(context: LogContext) {\n    const contextNormalized: LogContext = {};\n    for (const [key, value] of Object.entries(context)) {\n      if (value instanceof APIError) {\n        contextNormalized[key] = {\n          name: value.name,\n          message: value.message,\n          httpCode: value.code,\n          httpStatusText: value.error?.response?.statusText,\n          stack: value.stack,\n        };\n        continue;\n      }\n      if (value instanceof Error) {\n        contextNormalized[key] = {\n          name: value.name,\n          message: value.message,\n          stack: value.stack,\n        };\n        continue;\n      }\n      contextNormalized[key] = value;\n    }\n\n    return contextNormalized;\n  }\n}\n","import { APIError } from '../../utils/error';\nimport type { LogContext, LogLevel, LogRecord, LogTransport } from './logger';\n\nexport interface ConsoleTransportOptions {\n  level?: LogLevel;\n}\n\nexport class ConsoleTransport implements LogTransport {\n  public level: LogLevel;\n\n  constructor(options?: ConsoleTransportOptions) {\n    this.level = options?.level ?? 'info';\n  }\n\n  public log(record: LogRecord): void {\n    if (!this.shouldLog(record.level)) {\n      return;\n    }\n\n    const line = this.format(record);\n    switch (record.level) {\n      case 'error':\n        (console.error ?? console.log).call(console, line);\n        break;\n      case 'warn':\n        (console.warn ?? console.log).call(console, line);\n        break;\n      case 'info':\n        (console.info ?? console.log).call(console, line);\n        break;\n      case 'debug':\n        (console.debug ?? console.log).call(console, line);\n        break;\n    }\n  }\n\n  private levelRank(level: LogLevel): number {\n    switch (level) {\n      case 'error':\n        return 0;\n      case 'warn':\n        return 1;\n      case 'info':\n        return 2;\n      case 'debug':\n        return 3;\n      default:\n        return 3;\n    }\n  }\n\n  private shouldLog(level: LogLevel): boolean {\n    return this.levelRank(level) <= this.levelRank(this.level);\n  }\n\n  private format(record: LogRecord): string {\n    const timestamp = this.formatTimestamp(record.timestamp ?? new Date());\n    const level = record.level.toUpperCase().padEnd(5, ' ');\n    const message = record.message.replaceAll('\\n', '\\\\n');\n    const context = record.context ? this.formatContext(record.context) : '';\n    return `[${timestamp}]  ${level}  ${message}${context}`;\n  }\n\n  private formatTimestamp(date: Date): string {\n    const pad2 = (n: number) => String(n).padStart(2, '0');\n    const pad3 = (n: number) => String(n).padStart(3, '0');\n    const h = pad2(date.getHours());\n    const m = pad2(date.getMinutes());\n    const s = pad2(date.getSeconds());\n    const ms = pad3(date.getMilliseconds());\n    return `${h}:${m}:${s}.${ms}`;\n  }\n\n  private formatContext(context: LogContext): string {\n    const entries = Object.entries(context);\n    if (entries.length === 0) { return ''; }\n    const parts = entries.map(([k, v]) => `${k}: ${this.stringify(v)}`);\n    return `  (${parts.join(', ')})`;\n  }\n\n  private stringify(value: unknown): string {\n    try {\n      if (value instanceof APIError) {\n        return JSON.stringify({\n          name: value.name,\n          message: value.message,\n          httpCode: value.code,\n          httpStatusText: value.error?.response?.statusText,\n          stack: value.stack,\n        });\n      }\n      if (value instanceof Error) {\n        return JSON.stringify({\n          name: value.name,\n          message: value.message,\n          stack: value.stack,\n        });\n      }\n      if (value && typeof value === 'object') {\n        return JSON.stringify(value);\n      }\n\n      return String(value);\n    }\n    catch {\n      return '[unserializable]';\n    }\n  }\n}\n","import { access } from 'node:fs/promises';\nimport { join } from 'pathe';\nimport { FileSystemError, handleFileSystemError } from './utils';\nimport { getStoryblokGlobalPath, readFile, saveToFile } from './utils/filesystem';\nimport type { StoryblokCredentials } from './types';\n\nexport const getCredentials = async (filePath = join(getStoryblokGlobalPath(), 'credentials.json')): Promise<StoryblokCredentials | null> => {\n  try {\n    await access(filePath);\n    const content = await readFile(filePath);\n    const parsedContent = JSON.parse(content);\n\n    // Return null if the parsed content is an empty object\n    if (Object.keys(parsedContent).length === 0) {\n      return null;\n    }\n\n    return parsedContent;\n  }\n  catch (error) {\n    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n      // File doesn't exist, create it with empty credentials\n      await saveToFile(filePath, JSON.stringify({}, null, 2), { mode: 0o600 });\n      return null;\n    }\n    handleFileSystemError('read', error as NodeJS.ErrnoException);\n    return null;\n  }\n};\n\nexport const addCredentials = async ({\n  filePath = join(getStoryblokGlobalPath(), 'credentials.json'),\n  machineName,\n  login,\n  password,\n  region,\n}: Record<string, string>) => {\n  const credentials = {\n    ...await getCredentials(filePath),\n    [machineName]: {\n      login,\n      password,\n      region,\n    },\n  };\n\n  try {\n    await saveToFile(filePath, JSON.stringify(credentials, null, 2), { mode: 0o600 });\n  }\n  catch (error) {\n    throw new FileSystemError('invalid_argument', 'write', error as NodeJS.ErrnoException, `Error adding/updating entry for machine ${machineName} in credentials.json file`);\n  }\n};\n\nexport const removeAllCredentials = async (filepath: string = getStoryblokGlobalPath()) => {\n  const filePath = join(filepath, 'credentials.json');\n  await saveToFile(filePath, JSON.stringify({}, null, 2), { mode: 0o600 });\n};\n","// session.ts\nimport { type RegionCode, regionsDomain } from './constants';\nimport { addCredentials, getCredentials } from './creds';\n\nexport interface SessionState {\n  isLoggedIn: boolean;\n  login?: string;\n  password?: string;\n  region?: RegionCode;\n  envLogin?: boolean;\n}\n\nlet sessionInstance: ReturnType<typeof createSession> | null = null;\n\nfunction createSession() {\n  const state: SessionState = {\n    isLoggedIn: false,\n  };\n\n  async function initializeSession() {\n    // First, check for environment variables\n    const envCredentials = getEnvCredentials();\n    if (envCredentials) {\n      state.isLoggedIn = true;\n      state.login = envCredentials.login;\n      state.password = envCredentials.password;\n      state.region = envCredentials.region as RegionCode;\n      state.envLogin = true;\n      return;\n    }\n\n    // If no environment variables, fall back to .storyblok/credentials.json\n    const credentials = await getCredentials();\n    if (credentials) {\n      // Todo: evaluate this in future when we want to support multiple regions\n      const creds = Object.values(credentials)[0];\n      state.isLoggedIn = true;\n      state.login = creds.login;\n      state.password = creds.password;\n      state.region = creds.region as RegionCode;\n    }\n    else {\n      // No credentials found; set state to logged out\n      state.isLoggedIn = false;\n      state.login = undefined;\n      state.password = undefined;\n      state.region = undefined;\n    }\n    state.envLogin = false;\n  }\n\n  function getEnvCredentials() {\n    const envLogin = process.env.STORYBLOK_LOGIN || process.env.TRAVIS_STORYBLOK_LOGIN;\n    const envPassword = process.env.STORYBLOK_TOKEN || process.env.TRAVIS_STORYBLOK_TOKEN;\n    const envRegion = process.env.STORYBLOK_REGION || process.env.TRAVIS_STORYBLOK_REGION;\n\n    if (envLogin && envPassword && envRegion) {\n      return {\n        login: envLogin,\n        password: envPassword,\n        region: envRegion,\n      };\n    }\n    return null;\n  }\n\n  async function persistCredentials(region: RegionCode) {\n    if (state.isLoggedIn && state.login && state.password && state.region) {\n      await addCredentials({\n        machineName: regionsDomain[region] || 'mapi.storyblok.com',\n        login: state.login,\n        password: state.password,\n        region: state.region,\n      });\n    }\n    else {\n      throw new Error('No credentials to save.');\n    }\n  }\n\n  function updateSession(login: string, password: string, region: RegionCode) {\n    state.isLoggedIn = true;\n    state.login = login;\n    state.password = password;\n    state.region = region;\n  }\n\n  function logout() {\n    state.isLoggedIn = false;\n    state.login = undefined;\n    state.password = undefined;\n    state.region = undefined;\n  }\n\n  return {\n    state,\n    initializeSession,\n    updateSession,\n    persistCredentials,\n    logout,\n  };\n}\n\nexport function session() {\n  if (!sessionInstance) {\n    sessionInstance = createSession();\n  }\n  return sessionInstance;\n}\n","import { createManagementApiClient, type ManagementApiClient, type ManagementApiClientConfig } from '@storyblok/management-api-client';\n\nimport { getActiveConfig } from './lib/config';\n\nlet instance: ManagementApiClient | null = null;\nlet storedConfig: ManagementApiClientConfig | null = null;\n\nfunction configsAreEqual(config1: ManagementApiClientConfig, config2: ManagementApiClientConfig): boolean {\n  return JSON.stringify(config1) === JSON.stringify(config2);\n}\n\nexport function createMapiClient(options: ManagementApiClientConfig) {\n  const { api } = getActiveConfig();\n  return createManagementApiClient({\n    ...options,\n    rateLimit: options.rateLimit ?? (api.maxConcurrency > 0 ? { maxConcurrency: api.maxConcurrency } : false),\n  });\n}\n\nexport function getMapiClient(options?: ManagementApiClientConfig) {\n  if (!instance && options) {\n    instance = createMapiClient(options);\n    storedConfig = options;\n  }\n  else if (!instance) {\n    throw new Error('MAPI client not initialized. Call getMapiClient with configuration first.');\n  }\n  else if (options && storedConfig && !configsAreEqual(options, storedConfig)) {\n    // Create new instance if options differ from stored config\n    instance = createMapiClient(options);\n    storedConfig = options;\n  }\n  return instance;\n}\n","import { Command } from 'commander';\nimport { join } from 'pathe';\nimport { getPackageJson, handleError } from './utils';\n\nimport type { LogLevel, LogTransport } from './lib/logger/logger';\nimport { getLogger, setLoggerTransports } from './lib/logger/logger';\nimport { getUI } from './utils/ui';\nimport { getReporter } from './lib/reporter/reporter';\nimport { FileTransport } from './lib/logger/logger-transport-file';\nimport { ConsoleTransport } from './lib/logger/logger-transport-console';\nimport { resolveCommandPath } from './utils/filesystem';\nimport { directories } from './constants';\nimport { session } from './session';\nimport { getMapiClient } from './api';\nimport {\n  applyConfigToCommander,\n  getCommandAncestry,\n  GLOBAL_OPTION_DEFINITIONS,\n  resolveConfig,\n  setActiveConfig,\n} from './lib/config';\n\nconst packageJson = getPackageJson();\n\n// Declare a variable to hold the singleton instance\nlet programInstance: Command | null = null;\n\n/**\n * Get the shared program singleton instance\n *\n * @export getProgram\n * @return {*}  {Command}\n */\nexport function getProgram(): Command {\n  if (!programInstance) {\n    programInstance = new Command();\n\n    // Basic program setup\n    programInstance\n      .name(packageJson.name)\n      .description(packageJson.description || '')\n      .version(packageJson.version, '-v, --vers', 'Output the current version')\n      .helpOption('-h, --help', 'Display help for command');\n\n    // Register all global config options\n    for (const option of GLOBAL_OPTION_DEFINITIONS) {\n      if (option.parser) {\n        programInstance.option(\n          option.flags,\n          option.description,\n          option.parser as (value: string, previous: unknown) => unknown,\n          option.defaultValue as string | boolean | number,\n        );\n      }\n      else {\n        programInstance.option(\n          option.flags,\n          option.description,\n          option.defaultValue as string | boolean | string[],\n        );\n      }\n    }\n\n    // Unified preAction hook: handles config resolution, then logging/reporting setup\n    programInstance.hook('preAction', async (thisCommand, actionCommand) => {\n      const targetCommand = actionCommand ?? thisCommand;\n\n      // Step 1: Resolve and apply configuration\n      const ancestry = getCommandAncestry(targetCommand);\n      const resolvedConfig = await resolveConfig(targetCommand, ancestry);\n      applyConfigToCommander(ancestry, resolvedConfig);\n      setActiveConfig(resolvedConfig);\n\n      // Initialize mapiClient\n      const { state, initializeSession } = session();\n      await initializeSession();\n      if (state.password) {\n        getMapiClient({\n          personalAccessToken: state.password,\n          region: state.region ?? resolvedConfig.region,\n        });\n      }\n\n      // Step 2: Setup logging, UI, and reporting with resolved config\n      const options = targetCommand.optsWithGlobals();\n      const commandPieces: string[] = [];\n      for (\n        let c: Command | null = targetCommand;\n        c;\n        c = c.parent as Command | null\n      ) {\n        commandPieces.unshift(c.name());\n      }\n      const command = commandPieces.join(' ');\n\n      const runId = Date.now();\n\n      // Initialize logger with transports based on config\n      let logFilePath: string | undefined;\n\n      const transports: LogTransport[] = [];\n\n      // Add console transport if enabled\n      if (resolvedConfig.log.console.enabled) {\n        transports.push(\n          new ConsoleTransport({\n            level: resolvedConfig.log.console.level as LogLevel,\n          }),\n        );\n      }\n\n      // Add file transport if enabled\n      if (resolvedConfig.log.file.enabled) {\n        const logsPath = resolveCommandPath(\n          directories.logs,\n          options.space,\n          options.path,\n        );\n        const logFilename = `${commandPieces.join('-')}-${runId}.jsonl`;\n        logFilePath = join(logsPath, logFilename);\n        transports.push(\n          new FileTransport({\n            filePath: logFilePath,\n            level: resolvedConfig.log.file.level as LogLevel,\n            maxFiles: resolvedConfig.log.file.maxFiles,\n          }),\n        );\n      }\n\n      // Initialize logger with configured transports\n      const logger = getLogger({\n        context: { runId, command, options, cliVersion: packageJson.version },\n        transports,\n      });\n\n      // If logger already existed (created before preAction), update its transports\n      if (logger.transports.length === 0 && transports.length > 0) {\n        setLoggerTransports(transports);\n      }\n\n      // Initialize UI\n      getUI({ enabled: resolvedConfig.ui.enabled });\n\n      // Initialize reporter based on config\n      if (resolvedConfig.report.enabled) {\n        const reportPath = resolveCommandPath(\n          directories.reports,\n          options.space,\n          options.path,\n        );\n        const reportFilename = `${commandPieces.join('-')}-${runId}.json`;\n        const reportFilePath = join(reportPath, reportFilename);\n        const reporter = getReporter({\n          enabled: true,\n          filePath: reportFilePath,\n          maxFiles: resolvedConfig.report.maxFiles,\n        });\n\n        // Add metadata to reporter\n        reporter\n          .addMeta('command', command)\n          .addMeta('cliVersion', packageJson.version)\n          .addMeta('runId', String(runId))\n          .addMeta('config', options);\n\n        // Add logPath if file logging is enabled\n        if (logFilePath) {\n          reporter.addMeta('logPath', logFilePath);\n        }\n      }\n    });\n\n    // Global error handling\n    programInstance.configureOutput({\n      writeErr: str => handleError(new Error(str)),\n    });\n  }\n\n  return programInstance;\n}\n","import type { RegionCode } from '../constants';\nimport { managementApiRegions } from '../constants';\n\nconst API_VERSION = 'v1';\n\nexport const getStoryblokUrl = (region: RegionCode = 'eu') => {\n  return `https://${managementApiRegions[region]}/${API_VERSION}`;\n};\n","import chalk from 'chalk';\nimport { handleAPIError, maskToken } from '../../utils';\nimport { createMapiClient } from '../../api';\nimport type { RegionCode } from '../../constants';\n\nexport type { User } from '../../types';\n\nexport const getUser = async (token: string, region: RegionCode) => {\n  try {\n    const client = createMapiClient({\n      personalAccessToken: token,\n      region,\n    });\n\n    const { data } = await client.users.me({\n      throwOnError: true,\n    });\n\n    return data?.user;\n  }\n  catch (error) {\n    const status = (error as any)?.response?.status;\n    const customMessage = status === 401\n      ? `The token provided ${chalk.bold(maskToken(token))} is invalid.\n        Please make sure you are using the correct token and try again.`\n      : undefined;\n    handleAPIError('get_user', error, customMessage);\n  }\n};\n","import type { RegionCode } from '../../constants';\nimport { customFetch } from '../../utils/fetch';\nimport { APIError, handleAPIError } from '../../utils';\nimport { getStoryblokUrl } from '../../utils/api-routes';\nimport type { StoryblokLoginResponse, StoryblokLoginWithOtpResponse } from '../../types';\nimport { getUser } from '../user/actions';\n\nexport const loginWithToken = async (token: string, region: RegionCode) => {\n  try {\n    return await getUser(token, region);\n  }\n  catch (error) {\n    // If getUser already threw an APIError, just re-throw it\n    if (error instanceof APIError) {\n      throw error;\n    }\n\n    handleAPIError('login_with_token', error);\n  }\n};\n\nexport const loginWithEmailAndPassword = async (email: string, password: string, region: RegionCode) => {\n  try {\n    // TODO: we cant use the getMapiClient for now here because token is required for its instantiation\n    const url = getStoryblokUrl(region);\n    return await customFetch<StoryblokLoginResponse>(`${url}/users/login`, {\n      method: 'POST',\n      body: { email, password },\n    });\n  }\n  catch (error) {\n    handleAPIError('login_email_password', error, 'The provided credentials are invalid');\n  }\n};\n\nexport const loginWithOtp = async (email: string, password: string, otp: string, region: RegionCode) => {\n  try {\n    const url = getStoryblokUrl(region);\n    return await customFetch<StoryblokLoginWithOtpResponse>(`${url}/users/login`, {\n      method: 'POST',\n      body: { email, password, otp_attempt: otp },\n    });\n  }\n  catch (error) {\n    handleAPIError('login_with_otp', error as Error);\n  }\n};\n","import { Spinner } from '@topcli/spinner';\nimport chalk from 'chalk';\nimport { input, password, select } from '@inquirer/prompts';\nimport type { RegionCode } from '../../constants';\nimport { colorPalette, regionNames, regions } from '../../constants';\nimport { handleError, isVitest, konsola } from '../../utils';\nimport { loginWithEmailAndPassword, loginWithOtp, loginWithToken } from './actions';\nimport { session } from '../../session';\n\n/**\n * Performs interactive login flow with email/password or token\n * @param options - Options for the login flow\n * @param options.verbose - Whether to show verbose error output\n * @param options.preSelectedRegion - Pre-selected region to skip region selection\n * @param options.showWelcomeMessage - Whether to show welcome message after login\n * @returns Object with token and region, or null if cancelled/failed\n */\nexport async function performInteractiveLogin(options?: {\n  verbose?: boolean;\n  preSelectedRegion?: RegionCode;\n  showWelcomeMessage?: boolean;\n}): Promise<{ token: string; region: RegionCode } | null> {\n  const { verbose = false, preSelectedRegion, showWelcomeMessage = true } = options || {};\n  const spinner = new Spinner({\n    verbose: !isVitest,\n  });\n\n  try {\n    const strategy = await select({\n      message: 'How would you like to login?',\n      choices: [\n        {\n          name: 'With email',\n          value: 'login-with-email',\n          short: 'Email',\n        },\n        {\n          name: 'With Token (Personal Access Token – works also for SSO accounts)',\n          value: 'login-with-token',\n          short: 'Token',\n        },\n      ],\n    });\n\n    let userToken: string;\n    let userRegion: RegionCode;\n\n    if (strategy === 'login-with-token') {\n      konsola.info([\n        '🔑 You can use a Personal Access Token to log in.',\n        'This works for all accounts, including SSO accounts.',\n        `Generate one in your Storyblok account settings: ${chalk.underline.blue('https://app.storyblok.com/#/me/account?tab=token')}`,\n      ].join('\\n'));\n\n      userToken = await password({\n        message: 'Please enter your Personal Access Token:',\n        validate: (value: string) => {\n          return value.length > 0;\n        },\n      });\n\n      userRegion = preSelectedRegion || await select({\n        message: 'Please select the region you would like to work in:',\n        choices: Object.values(regions).map((region: RegionCode) => ({\n          name: regionNames[region],\n          value: region,\n        })),\n        default: regions.EU,\n      });\n\n      spinner.start(`Logging in with token`);\n      const user = await loginWithToken(userToken, userRegion);\n      spinner.succeed();\n\n      if (user) {\n        const { updateSession, persistCredentials } = session();\n        updateSession(user.email, userToken, userRegion);\n        await persistCredentials(userRegion);\n        if (showWelcomeMessage) {\n          konsola.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(user.friendly_name)}.`, true);\n        }\n        return { token: userToken, region: userRegion };\n      }\n    }\n    else {\n      const userEmail = await input({\n        message: 'Please enter your email address:',\n        required: true,\n        validate: (value: string) => {\n          const emailRegex = /^[^\\s@]+@[^\\s@][^\\s.@]*\\.[^\\s@]+$/;\n          return emailRegex.test(value);\n        },\n      });\n      const userPassword = await password({\n        message: 'Please enter your password:',\n      });\n\n      userRegion = preSelectedRegion || await select({\n        message: 'Please select the region you would like to work in:',\n        choices: Object.values(regions).map((region: RegionCode) => ({\n          name: regionNames[region],\n          value: region,\n        })),\n        default: regions.EU,\n      });\n\n      spinner.start(`Logging in with email`);\n      spinner.succeed();\n      const response = await loginWithEmailAndPassword(userEmail, userPassword, userRegion);\n\n      if (response?.otp_required) {\n        const otp = await input({\n          message: 'Add the code from your Authenticator app, or the one we sent to your e-mail / phone:',\n          required: true,\n        });\n\n        const otpResponse = await loginWithOtp(userEmail, userPassword, otp, userRegion);\n        if (otpResponse?.access_token) {\n          userToken = otpResponse.access_token;\n        }\n      }\n      else if (response?.access_token) {\n        userToken = response.access_token;\n      }\n\n      if (userToken!) {\n        const { updateSession, persistCredentials } = session();\n        updateSession(userEmail, userToken, userRegion);\n        await persistCredentials(userRegion);\n        if (showWelcomeMessage) {\n          konsola.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(userEmail)}.`, true);\n        }\n        return { token: userToken, region: userRegion };\n      }\n    }\n\n    return null;\n  }\n  catch (error) {\n    spinner.failed();\n    konsola.br();\n    handleError(error as Error, verbose);\n    return null;\n  }\n}\n","import { Spinner } from '@topcli/spinner';\nimport chalk from 'chalk';\nimport { select } from '@inquirer/prompts';\nimport type { RegionCode } from '../../constants';\nimport { colorPalette, commands, regionNames, regions } from '../../constants';\nimport { getProgram } from '../../program';\nimport { CommandError, handleError, isRegion, isVitest, konsola } from '../../utils';\nimport { loginWithToken } from './actions';\nimport { session } from '../../session';\nimport { performInteractiveLogin } from './helpers';\n\nconst program = getProgram(); // Get the shared singleton instance\n\nconst allRegionsText = Object.values(regions).join(',');\n\nexport const loginCommand = program\n  .command(commands.LOGIN)\n  .description('Login to the Storyblok CLI')\n  .option('-t, --token <token>', 'Token to login directly without questions, like for CI environments')\n  .option(\n    '-r, --region <region>',\n    `The region you would like to work in. Please keep in mind that the region must match the region of your space. This region flag will be used for the other cli's commands. You can use the values: ${allRegionsText}.`,\n  )\n  .action(async (options: {\n    token: string;\n    region: RegionCode;\n  }) => {\n    konsola.title(`${commands.LOGIN}`, colorPalette.LOGIN);\n    // Global options\n    const verbose = program.opts().verbose;\n    // Command options\n    const { token, region } = options;\n\n    const { state, updateSession, persistCredentials } = session();\n\n    if (state.isLoggedIn && !state.envLogin) {\n      konsola.ok(`You are already logged in. If you want to login with a different account, please logout first.`);\n      return;\n    }\n\n    if (region && !isRegion(region)) {\n      handleError(new CommandError(`The provided region: ${region} is not valid. Please use one of the following values: ${Object.values(regions).join(' | ')}`));\n      return;\n    }\n\n    if (token) {\n      const spinner = new Spinner({\n        verbose: !isVitest,\n      });\n      try {\n        let userRegion = region;\n        if (!userRegion) {\n          userRegion = await select({\n            message: 'Please select the region you would like to work in:',\n            choices: Object.values(regions).map((region: RegionCode) => ({\n              name: regionNames[region],\n              value: region,\n            })),\n            default: regions.EU,\n          });\n        }\n        spinner.start(`Logging in with token`);\n        const user = await loginWithToken(token, userRegion);\n        if (user) {\n          updateSession(user.email, token, userRegion);\n\n          await persistCredentials(userRegion);\n          spinner.succeed();\n\n          konsola.ok(`Successfully logged in to region ${chalk.hex(colorPalette.PRIMARY)(`${regionNames[userRegion]} (${userRegion})`)}. Welcome ${chalk.hex(colorPalette.PRIMARY)(user.friendly_name)}.`, true);\n        }\n      }\n      catch (error) {\n        spinner.failed();\n        konsola.br();\n        handleError(error as Error, verbose);\n      }\n    }\n    else {\n      try {\n        const result = await performInteractiveLogin({\n          verbose,\n          preSelectedRegion: region,\n          showWelcomeMessage: true,\n        });\n\n        if (!result) {\n          konsola.warn('Login cancelled or failed.');\n        }\n      }\n      catch (error) {\n        konsola.br();\n        handleError(error as Error, verbose);\n      }\n    }\n\n    konsola.br();\n  });\n","import { removeAllCredentials } from '../../creds';\nimport { colorPalette, commands } from '../../constants';\nimport { getProgram } from '../../program';\nimport { handleError, konsola } from '../../utils';\nimport { session } from '../../session';\n\nconst program = getProgram(); // Get the shared singleton instance\n\nexport const logoutCommand = program\n  .command(commands.LOGOUT)\n  .description('Logout from the Storyblok CLI')\n  .action(async () => {\n    konsola.title(`${commands.LOGOUT}`, colorPalette.LOGOUT);\n\n    const verbose = program.opts().verbose;\n    try {\n      const { state } = session();\n      if (!state.isLoggedIn || !state.password || !state.region) {\n        konsola.warn(`You are already logged out. If you want to login, please use the login command.`);\n        konsola.br();\n        return;\n      }\n      await removeAllCredentials();\n\n      konsola.ok(`Successfully logged out.`, true);\n      konsola.br();\n    }\n    catch (error) {\n      handleError(error as Error, verbose);\n    }\n    konsola.br();\n  });\n","import { exec } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execAsync = promisify(exec);\n\n/**\n * Build the signup URL with UTM parameters\n */\nexport function buildSignupUrl(): string {\n  const baseUrl = 'https://app.storyblok.com';\n\n  const utmParams = new URLSearchParams({\n    utm_source: 'storyblok-cli',\n    utm_medium: 'cli',\n    utm_campaign: 'signup',\n  });\n\n  return `${baseUrl}/#/signup?${utmParams.toString()}`;\n}\n\n/**\n * Open the signup URL in the default browser\n */\nexport async function openSignupInBrowser(url: string): Promise<void> {\n  let command: string;\n\n  switch (process.platform) {\n    case 'darwin':\n      command = `open \"${url}\"`;\n      break;\n    case 'win32':\n      command = `start \"\" \"${url}\"`;\n      break;\n    default:\n      command = `xdg-open \"${url}\"`;\n      break;\n  }\n\n  try {\n    await execAsync(command);\n  }\n  catch (error) {\n    throw new Error(`Failed to open browser: ${error}`);\n  }\n}\n","import chalk from 'chalk';\nimport { colorPalette, commands } from '../../constants';\nimport { getProgram } from '../../program';\nimport { handleError, konsola } from '../../utils';\nimport { buildSignupUrl, openSignupInBrowser } from './actions';\nimport { session } from '../../session';\n\nconst program = getProgram(); // Get the shared singleton instance\n\nexport const signupCommand = program\n  .command(commands.SIGNUP)\n  .description('Sign up for Storyblok')\n  .action(async () => {\n    konsola.title(`${commands.SIGNUP}`, colorPalette.SIGNUP);\n    // Global options\n    const verbose = program.opts().verbose;\n    const { state } = session();\n\n    if (state.isLoggedIn && !state.envLogin) {\n      konsola.ok(`You are already logged in. If you want to signup with a different account, please logout first.`);\n      return;\n    }\n\n    try {\n      // Build the signup URL with UTM parameters\n      const signupUrl = buildSignupUrl();\n\n      konsola.info(`Opening Storyblok signup page...`);\n      konsola.info(`URL: ${chalk.dim(signupUrl)}`);\n\n      // Open the browser\n      await openSignupInBrowser(signupUrl);\n\n      konsola.ok(`Browser opened! Please complete the signup process.`);\n      konsola.br();\n      konsola.info(`Once you've completed signup, run ${chalk.hex(colorPalette.PRIMARY)('storyblok login')} to authenticate with the CLI.`);\n    }\n    catch (error) {\n      konsola.br();\n      handleError(error as Error, verbose);\n    }\n\n    konsola.br();\n  });\n","import chalk from 'chalk';\nimport { colorPalette, commands } from '../../constants';\nimport { getProgram } from '../../program';\nimport { handleError, isVitest, konsola, requireAuthentication } from '../../utils';\nimport { getUser } from './actions';\nimport { session } from '../../session';\nimport { Spinner } from '@topcli/spinner';\n\nconst program = getProgram(); // Get the shared singleton instance\n\nexport const userCommand = program\n  .command(commands.USER)\n  .description('Get the current user')\n  .action(async () => {\n    konsola.title(`${commands.USER}`, colorPalette.USER);\n    const verbose = program.opts().verbose;\n    const { state } = session();\n\n    if (!requireAuthentication(state)) {\n      return;\n    }\n\n    const spinner = new Spinner({\n      verbose: !isVitest,\n    }).start(`Fetching user info`);\n    try {\n      const { password, region } = state;\n      if (!password || !region) {\n        throw new Error('No password or region found');\n      }\n\n      const user = await getUser(password, region);\n\n      if (user) {\n        if (verbose) {\n          konsola.info(JSON.stringify(user, null, 2));\n        }\n        spinner.succeed();\n        konsola.ok(`Hi ${chalk.bold(user.friendly_name)}, you are currently logged in with ${chalk.hex(colorPalette.PRIMARY)(user.email)} on ${chalk.bold(region)} region`, true);\n      }\n    }\n    catch (error) {\n      spinner.failed();\n      handleError(error as Error, true);\n    }\n    konsola.br();\n  });\n","import { commands } from '../../constants';\nimport { getProgram } from '../../program';\n\nconst program = getProgram(); // Get the shared singleton instance\n\n// Components root command\nexport const componentsCommand = program\n  .command(commands.COMPONENTS)\n  .alias('comp')\n  .description(`Manage your space's block schema`);\n","import { join } from 'pathe';\nimport { FileSystemError, handleFileSystemError } from '../../utils';\nimport type { Component, ComponentFolder, InternalTag, Preset } from './constants';\nimport { filterJsonBySuffix, readDirectory, readJsonFile } from '../../utils/filesystem';\n\nexport interface ComponentsData {\n  components: Component[];\n  groups: ComponentFolder[];\n  presets: Preset[];\n  internalTags: InternalTag[];\n}\n\n// Content-based entity discriminators — classify items by their data shape, not filename\nfunction isComponent(item: Record<string, unknown>): item is Component {\n  return 'schema' in item;\n}\n\nfunction isPreset(item: Record<string, unknown>): item is Preset {\n  return 'component_id' in item && 'preset' in item;\n}\n\nfunction isInternalTag(item: Record<string, unknown>): item is InternalTag {\n  return 'object_type' in item;\n}\n\nfunction isComponentGroup(item: Record<string, unknown>): item is ComponentFolder {\n  return 'uuid' in item && !('schema' in item);\n}\n\n/**\n * Loads component entities from a directory by reading all matching JSON files\n * and classifying items by their data shape.\n *\n * Throws on duplicate components (same name found in multiple files).\n */\nexport async function loadComponents(\n  directoryPath: string,\n  options?: { suffix?: string },\n): Promise<ComponentsData> {\n  const files = await readDirectory(directoryPath);\n  const { suffix } = options ?? {};\n\n  const componentMap = new Map<string, { component: Component; file: string }>();\n  const groupMap = new Map<number, ComponentFolder>();\n  const tagMap = new Map<number, InternalTag>();\n  const presets: Preset[] = [];\n  const duplicates: string[] = [];\n\n  for (const file of filterJsonBySuffix(files, suffix)) {\n    const { data, error } = await readJsonFile<Record<string, unknown>>(join(directoryPath, file));\n    if (error) {\n      handleFileSystemError('read', error);\n      continue;\n    }\n\n    for (const item of data) {\n      if (isPreset(item)) {\n        presets.push(item);\n      }\n      else if (isInternalTag(item)) {\n        if (!item.id) {\n          throw new Error('Internal tag is missing \"id\"!');\n        }\n        tagMap.set(item.id, item);\n      }\n      else if (isComponent(item)) {\n        const existing = componentMap.get(item.name);\n        if (existing) {\n          duplicates.push(`Component \"${item.name}\" found in both \"${existing.file}\" and \"${file}\"`);\n        }\n        componentMap.set(item.name, { component: item, file });\n      }\n      else if (isComponentGroup(item)) {\n        groupMap.set(item.id, item);\n      }\n    }\n  }\n\n  if (duplicates.length) {\n    throw new FileSystemError(\n      'invalid_argument',\n      'read',\n      new Error('Duplicate components detected'),\n      `Duplicate components found in ${directoryPath}:\\n\\n${duplicates.join('\\n')}\\n\\nThis can happen when multiple environment snapshots (e.g. components.json and components.dev.json) or mixed formats coexist in the same directory.\\n\\nTo fix this, either:\\n  - Use --suffix <env> to target a specific environment (e.g. --suffix dev)\\n  - Clean up the directory and pull components again in the format you intend`,\n    );\n  }\n\n  return {\n    components: [...componentMap.values()].map(({ component }) => component),\n    groups: [...groupMap.values()],\n    presets,\n    internalTags: [...tagMap.values()],\n  };\n}\n","import type { SpaceDatasource } from '../datasources/constants';\n\nimport type { Component, ComponentFolder, InternalTag, Preset } from '../../types';\n\nexport type { Component, ComponentFolder, InternalTag, Preset };\n\nexport const DEFAULT_COMPONENTS_FILENAME = 'components';\nexport const DEFAULT_GROUPS_FILENAME = 'groups';\nexport const DEFAULT_PRESETS_FILENAME = 'presets';\nexport const DEFAULT_TAGS_FILENAME = 'tags';\n\n// There is no create or update type for internal tags\n\nexport interface SpaceComponentsData {\n  components: Component[];\n  groups: ComponentFolder[];\n  presets: Preset[];\n  internalTags: InternalTag[];\n  datasources: SpaceDatasource[];\n}\n\nexport interface SpaceComponentsDataState {\n  local: SpaceComponentsData;\n  target: {\n    components: Map<string, Component>;\n    tags: Map<string, InternalTag>;\n    groups: Map<string, ComponentFolder>;\n    presets: Map<string, Preset>;\n    datasources: Map<string, SpaceDatasource>;\n  };\n}\n","/**\n * Fetches every page of a list endpoint and returns the combined items.\n * Stops when the `total` response header is reached, when a page returns\n * no items, or immediately if the header is absent (treats the response\n * as un-paginated).\n *\n * @param fetchFunction - Fetches a single page; receives the 1-based page number\n * @param extractDataFunction - Extracts the items array from a page's response data\n */\nexport async function fetchAllPages<T, R>(\n  fetchFunction: (page: number) => Promise<{ data: T; response: Response }>,\n  extractDataFunction: (data: T) => R[],\n): Promise<R[]> {\n  const items: R[] = [];\n  let page = 1;\n\n  while (true) {\n    const { data, response } = await fetchFunction(page);\n    const totalHeader = response.headers.get('total');\n    const fetchedItems = extractDataFunction(data);\n    items.push(...fetchedItems);\n\n    if (!totalHeader) {\n      return items;\n    }\n    const total = Number(totalHeader);\n    if (Number.isNaN(total) || items.length >= total || fetchedItems.length === 0) {\n      return items;\n    }\n    page++;\n  }\n}\n","import { join, resolve } from 'pathe';\nimport type { Component, ComponentFolder, InternalTag, Preset, SpaceComponentsData } from '../constants';\nimport { DEFAULT_COMPONENTS_FILENAME, DEFAULT_GROUPS_FILENAME, DEFAULT_PRESETS_FILENAME, DEFAULT_TAGS_FILENAME } from '../constants';\nimport type { SaveComponentsOptions } from './constants';\nimport { handleAPIError, handleFileSystemError } from '../../../utils';\nimport { resolvePath, sanitizeFilename, saveToFile } from '../../../utils/filesystem';\nimport { fetchAllPages } from '../../../utils/pagination';\nimport { getMapiClient } from '../../../api';\n\n// Components\nexport const fetchComponents = async (spaceId: string): Promise<Component[] | undefined> => {\n  try {\n    const client = getMapiClient();\n    return await fetchAllPages(\n      (page: number) => client.components.list({\n        path: {\n          space_id: Number(spaceId),\n        },\n        query: {\n          page,\n        },\n        throwOnError: true,\n      }),\n      data => data?.components ?? [],\n    );\n  }\n  catch (error) {\n    handleAPIError('pull_components', error as Error);\n  }\n};\n\nexport const fetchComponent = async (spaceId: string, componentName: string): Promise<Component | undefined> => {\n  try {\n    const client = getMapiClient();\n    const matches = await fetchAllPages(\n      (page: number) => client.components.list({\n        path: {\n          space_id: Number(spaceId),\n        },\n        query: {\n          page,\n          search: componentName,\n        },\n        throwOnError: true,\n      }),\n      data => data?.components ?? [],\n    );\n    return matches.find((c: Component) => c.name === componentName);\n  }\n  catch (error) {\n    handleAPIError('pull_components', error as Error, `Failed to fetch component ${componentName}`);\n  }\n};\n\n// Component group actions\nexport const fetchComponentGroups = async (spaceId: string): Promise<ComponentFolder[] | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.componentFolders.list({\n      path: {\n        space_id: Number(spaceId),\n      },\n    });\n\n    return data?.component_groups;\n  }\n  catch (error) {\n    handleAPIError('pull_component_groups', error as Error);\n  }\n};\n\n// Component preset actions\nexport const fetchComponentPresets = async (spaceId: string): Promise<Preset[] | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.presets.list({\n      path: {\n        space_id: Number(spaceId),\n      },\n    });\n\n    return data?.presets;\n  }\n  catch (error) {\n    handleAPIError('pull_component_presets', error as Error);\n  }\n};\n\n// Component internal tags\nexport const fetchComponentInternalTags = async (spaceId: string): Promise<InternalTag[] | undefined> => {\n  try {\n    const client = getMapiClient();\n    return await fetchAllPages(\n      (page: number) => client.internalTags.list({\n        path: {\n          space_id: Number(spaceId),\n        },\n        query: {\n          page,\n          by_object_type: 'component',\n        },\n        throwOnError: true,\n      }),\n      data => data?.internal_tags ?? [],\n    );\n  }\n  catch (error) {\n    handleAPIError('pull_component_internal_tags', error as Error);\n  }\n};\n\n// Filesystem actions\n\nexport const saveComponentsToFiles = async (\n  space: string,\n  spaceData: SpaceComponentsData,\n  options: SaveComponentsOptions,\n) => {\n  const { components = [], groups = [], presets = [], internalTags = [] } = spaceData;\n  const { filename = DEFAULT_COMPONENTS_FILENAME, suffix, path, separateFiles } = options;\n  // Ensure we always include the components/space folder structure regardless of custom path\n  const resolvedPath = path\n    ? resolve(process.cwd(), path, 'components', space)\n    : resolvePath(path, `components/${space}`);\n\n  try {\n    if (separateFiles) {\n      // Save in separate files without nested structure\n      for (const component of components) {\n        const sanitizedName = sanitizeFilename(component.name || '');\n        const componentFilePath = join(resolvedPath, suffix ? `${sanitizedName}.${suffix}.json` : `${sanitizedName}.json`);\n        await saveToFile(componentFilePath, JSON.stringify(component, null, 2));\n\n        // Find and save associated presets\n        const componentPresets = presets.filter(preset => preset.component_id === component.id);\n        if (componentPresets.length > 0) {\n          const presetsFilePath = join(resolvedPath, suffix ? `${sanitizedName}.${DEFAULT_PRESETS_FILENAME}.${suffix}.json` : `${sanitizedName}.${DEFAULT_PRESETS_FILENAME}.json`);\n          await saveToFile(presetsFilePath, JSON.stringify(componentPresets, null, 2));\n        }\n        // Always save groups in a consolidated file\n        const groupsFilePath = join(resolvedPath, suffix ? `${DEFAULT_GROUPS_FILENAME}.${suffix}.json` : `${DEFAULT_GROUPS_FILENAME}.json`);\n        await saveToFile(groupsFilePath, JSON.stringify(groups, null, 2));\n\n        // Always save internal tags in a consolidated file\n        const internalTagsFilePath = join(resolvedPath, suffix ? `${DEFAULT_TAGS_FILENAME}.${suffix}.json` : `${DEFAULT_TAGS_FILENAME}.json`);\n        await saveToFile(internalTagsFilePath, JSON.stringify(internalTags, null, 2));\n      }\n      return;\n    }\n\n    // Default to saving consolidated files\n    const componentsFilePath = join(resolvedPath, suffix ? `${filename}.${suffix}.json` : `${filename}.json`);\n    await saveToFile(componentsFilePath, JSON.stringify(components, null, 2));\n\n    if (groups.length > 0) {\n      const groupsFilePath = join(resolvedPath, suffix ? `${DEFAULT_GROUPS_FILENAME}.${suffix}.json` : `${DEFAULT_GROUPS_FILENAME}.json`);\n      await saveToFile(groupsFilePath, JSON.stringify(groups, null, 2));\n    }\n\n    if (presets.length > 0) {\n      const presetsFilePath = join(resolvedPath, suffix ? `${DEFAULT_PRESETS_FILENAME}.${suffix}.json` : `${DEFAULT_PRESETS_FILENAME}.json`);\n      await saveToFile(presetsFilePath, JSON.stringify(presets, null, 2));\n    }\n\n    if (internalTags.length > 0) {\n      const internalTagsFilePath = join(resolvedPath, suffix ? `${DEFAULT_TAGS_FILENAME}.${suffix}.json` : `${DEFAULT_TAGS_FILENAME}.json`);\n      await saveToFile(internalTagsFilePath, JSON.stringify(internalTags, null, 2));\n    }\n  }\n  catch (error) {\n    handleFileSystemError('write', error as Error);\n  }\n};\n","import { FileSystemError, handleAPIError } from '../../../utils';\nimport type { Component, ComponentFolder, InternalTag, Preset } from '../constants';\nimport type { ComponentCreate, ComponentUpdate } from '../../../types';\nimport type { ReadComponentsOptions } from './constants';\nimport { resolvePath } from '../../../utils/filesystem';\nimport chalk from 'chalk';\nimport { getMapiClient } from '../../../api';\nimport { type ComponentsData, loadComponents } from '../loader';\n\nexport type { ComponentsData };\n\n// Component actions\nexport const pushComponent = async (space: string, component: ComponentCreate): Promise<Component | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.components.create({\n      path: {\n        space_id: Number(space),\n      },\n      body: {\n        component,\n      },\n    });\n\n    return data?.component;\n  }\n  catch (error) {\n    handleAPIError('push_component', error as Error, `Failed to push component ${component.name}`);\n  }\n};\n\nexport const updateComponent = async (space: string, componentId: number, component: ComponentUpdate): Promise<Component | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.components.update(componentId, {\n      path: {\n        space_id: Number(space),\n      },\n      body: {\n        component,\n      },\n      throwOnError: true,\n    });\n\n    return data?.component;\n  }\n  catch (error) {\n    handleAPIError('update_component', error as Error, `Failed to update component ${component.name}`);\n  }\n};\n\nexport const upsertComponent = async (\n  space: string,\n  component: ComponentCreate,\n  existingId?: number,\n): Promise<Component | undefined> => {\n  if (existingId) {\n    // We know it exists, update directly\n    return await updateComponent(space, existingId, component);\n  }\n  else {\n    // New resource, create directly\n    return await pushComponent(space, component);\n  }\n};\n\n// Component group actions\n\nexport const pushComponentGroup = async (space: string, componentGroup: ComponentFolder): Promise<ComponentFolder | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.componentFolders.create({\n      path: {\n        space_id: Number(space),\n      },\n      body: {\n        component_group: componentGroup,\n      },\n      throwOnError: true,\n    });\n\n    return data?.component_group;\n  }\n  catch (error) {\n    handleAPIError('push_component_group', error as Error, `Failed to push component group ${componentGroup.name}`);\n  }\n};\n\nexport const updateComponentGroup = async (space: string, groupId: number, componentGroup: ComponentFolder): Promise<ComponentFolder | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.componentFolders.update(groupId, {\n      path: {\n        space_id: Number(space),\n      },\n      body: {\n        component_group: componentGroup,\n      },\n      throwOnError: true,\n    });\n\n    return data?.component_group;\n  }\n  catch (error) {\n    handleAPIError('update_component_group', error as Error, `Failed to update component group ${componentGroup.name}`);\n  }\n};\n\nexport const upsertComponentGroup = async (\n  space: string,\n  group: ComponentFolder,\n  existingId?: number,\n): Promise<ComponentFolder | undefined> => {\n  if (existingId) {\n    // We know it exists, update directly\n    return await updateComponentGroup(space, existingId, group);\n  }\n  else {\n    // New resource, create directly\n    return await pushComponentGroup(space, group);\n  }\n};\n\n// Component preset actions\nexport const pushComponentPreset = async (space: string, preset: Preset): Promise<Preset | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.presets.create({\n      path: {\n        space_id: Number(space),\n      },\n      body: {\n        preset,\n      },\n      throwOnError: true,\n    });\n\n    return data?.preset;\n  }\n  catch (error) {\n    handleAPIError('push_component_preset', error as Error, `Failed to push component preset ${preset.name}`);\n  }\n};\n\nexport const updateComponentPreset = async (space: string, presetId: number, preset: Preset): Promise<Preset | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.presets.update(presetId, {\n      path: {\n        space_id: Number(space),\n      },\n      body: {\n        preset,\n      },\n      throwOnError: true,\n    });\n\n    return data?.preset;\n  }\n  catch (error) {\n    handleAPIError('update_component_preset', error as Error, `Failed to update component preset ${preset.name}`);\n  }\n};\n\nexport const upsertComponentPreset = async (\n  space: string,\n  preset: Preset,\n  existingId?: number,\n): Promise<Preset | undefined> => {\n  if (existingId) {\n    // We know it exists, update directly\n    return await updateComponentPreset(space, existingId, preset);\n  }\n  else {\n    // New resource, create directly\n    return await pushComponentPreset(space, preset);\n  }\n};\n\n// Component preset deletion\nexport const deleteComponentPreset = async (space: string, presetId: number): Promise<void> => {\n  try {\n    const client = getMapiClient();\n\n    await client.presets.delete(presetId, {\n      path: { space_id: Number(space) },\n      throwOnError: true,\n    });\n  }\n  catch (error) {\n    handleAPIError('delete_component_preset', error as Error, `Failed to delete component preset ${presetId}`);\n  }\n};\n\n// Component internal tag actions\n\nexport const pushComponentInternalTag = async (space: string, componentInternalTag: InternalTag): Promise<InternalTag | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.internalTags.create({\n      path: {\n        space_id: Number(space),\n      },\n      body: componentInternalTag,\n      throwOnError: true,\n    });\n\n    return data.internal_tag;\n  }\n  catch (error) {\n    handleAPIError('push_component_internal_tag', error as Error, `Failed to push component internal tag ${componentInternalTag.name}`);\n  }\n};\n\nexport const updateComponentInternalTag = async (space: string, tagId: number, componentInternalTag: InternalTag): Promise<InternalTag | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.internalTags.update(tagId, {\n      path: {\n        space_id: Number(space),\n      },\n      body: componentInternalTag,\n      throwOnError: true,\n    });\n\n    return data.internal_tag;\n  }\n  catch (error) {\n    handleAPIError('update_component_internal_tag', error as Error, `Failed to update component internal tag ${componentInternalTag.name}`);\n  }\n};\n\nexport const upsertComponentInternalTag = async (\n  space: string,\n  tag: InternalTag,\n  existingId?: number,\n): Promise<InternalTag | undefined> => {\n  if (existingId) {\n    // We know it exists, update directly\n    return await updateComponentInternalTag(space, existingId, tag);\n  }\n  else {\n    // New resource, create directly\n    return await pushComponentInternalTag(space, tag);\n  }\n};\n\nexport const readComponentsFiles = async (\n  options: ReadComponentsOptions): Promise<ComponentsData> => {\n  const { from, path, suffix } = options;\n  const resolvedPath = resolvePath(path, `components/${from}`);\n\n  let result: ComponentsData;\n  try {\n    result = await loadComponents(resolvedPath, { suffix });\n  }\n  catch (error) {\n    if (error instanceof FileSystemError && error.code !== 'ENOENT') {\n      throw error;\n    }\n    const message = `No local components found for space ${chalk.bold(from)}. To push components, you need to pull them first:\n\n1. Pull the components from your source space:\n   ${chalk.cyan(`storyblok components pull --space ${from}`)}\n\n2. Then try pushing again:\n   ${chalk.cyan(`storyblok components push --space <target_space> --from ${from}`)}`;\n\n    throw new FileSystemError(\n      'file_not_found',\n      'read',\n      error as Error,\n      message,\n    );\n  }\n\n  if (!result.components.length) {\n    throw new FileSystemError(\n      'file_not_found',\n      'read',\n      new Error('No component data found'),\n      `No components found in ${resolvedPath}. Please make sure you have pulled the components first.`,\n    );\n  }\n\n  return result;\n};\n","import type { PullComponentsOptions } from './constants';\nimport type { Command } from 'commander';\n\nimport { colorPalette, commands, directories } from '../../../constants';\nimport { CommandError, handleError, requireAuthentication } from '../../../utils';\nimport { session } from '../../../session';\nimport { fetchComponent, fetchComponentGroups, fetchComponentInternalTags, fetchComponentPresets, fetchComponents, saveComponentsToFiles } from '../actions';\nimport { componentsCommand } from '../command';\nimport chalk from 'chalk';\nimport { isAbsolute, join, relative } from 'pathe';\nimport { resolveCommandPath } from '../../../utils/filesystem';\nimport { DEFAULT_COMPONENTS_FILENAME } from '../constants';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\n\nconst pullCmd = componentsCommand\n  .command('pull [componentName]')\n  .option('-f, --filename <filename>', 'custom name to be used in file(s) name instead of space id')\n  .option('--sf, --separate-files', 'Argument to create a single file for each component')\n  .option('--su, --suffix <suffix>', 'suffix to add to the file name (e.g. components.<suffix>.json)')\n  .option('-s, --space <space>', 'space ID')\n  .description(`Download your space's components schema as json. Optionally specify a component name to pull a single component.`);\n\npullCmd\n  .action(async (componentName: string | undefined, options: PullComponentsOptions, command: Command) => {\n    const ui = getUI();\n    const logger = getLogger();\n\n    ui.title(`${commands.COMPONENTS}`, colorPalette.COMPONENTS, componentName ? `Pulling component ${componentName}...` : 'Pulling components...');\n\n    const { space, path, verbose } = command.optsWithGlobals();\n    const {\n      separateFiles = false,\n      suffix,\n      filename,\n    } = options;\n\n    // Use default filename when not provided\n    const actualFilename = filename ?? DEFAULT_COMPONENTS_FILENAME;\n    // `--path` overrides remain command-scoped; fallback keeps the historic .storyblok output.\n    const componentsOutputDir = resolveCommandPath(directories.components, space, path);\n\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n    if (!space) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      return;\n    }\n\n    logger.info('Pulling components started', { space, componentName });\n\n    const spinnerGroups = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.COMPONENTS)('components groups')}`);\n    const spinnerPresets = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.COMPONENTS)('components presets')}`);\n    const spinnerInternalTags = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.COMPONENTS)('components internal tags')}`);\n    const spinnerComponents = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.COMPONENTS)('components')}`);\n\n    try {\n      // Fetch components groups\n      const groups = await fetchComponentGroups(space);\n      spinnerGroups.succeed(`${chalk.hex(colorPalette.COMPONENTS)('Groups')} - Completed in ${spinnerGroups.elapsedTime.toFixed(2)}ms`);\n\n      // Fetch components presets\n      const presets = await fetchComponentPresets(space);\n      spinnerPresets.succeed(`${chalk.hex(colorPalette.COMPONENTS)('Presets')} - Completed in ${spinnerPresets.elapsedTime.toFixed(2)}ms`);\n\n      // Fetch components internal tags\n      const internalTags = await fetchComponentInternalTags(space);\n      spinnerInternalTags.succeed(`${chalk.hex(colorPalette.COMPONENTS)('Tags')} - Completed in ${spinnerInternalTags.elapsedTime.toFixed(2)}ms`);\n\n      // Save everything using the new structure\n      let components;\n\n      if (componentName) {\n        const component = await fetchComponent(space, componentName);\n        if (!component) {\n          spinnerComponents.failed(`No component found with name \"${componentName}\"`);\n          return;\n        }\n        components = [component];\n      }\n      else {\n        components = await fetchComponents(space);\n        if (!components || components.length === 0) {\n          spinnerComponents.failed(`No components found in the space ${space}`);\n          return;\n        }\n      }\n      spinnerComponents.succeed(`${chalk.hex(colorPalette.COMPONENTS)('Components')} - Completed in ${spinnerComponents.elapsedTime.toFixed(2)}ms`);\n      await saveComponentsToFiles(\n        space,\n        { components, groups: groups || [], presets: presets || [], internalTags: internalTags || [], datasources: [] },\n        { ...options, path, separateFiles: separateFiles || !!componentName },\n      );\n      ui.br();\n      if (separateFiles) {\n        if (filename && filename !== DEFAULT_COMPONENTS_FILENAME) {\n          ui.warn(`The --filename option is ignored when using --separate-files`);\n        }\n        const filePath = `${componentsOutputDir}/`;\n        // Only show relative path if the base path wasn't absolute\n        const displayPath = (path && isAbsolute(path)) ? filePath : `${relative(process.cwd(), componentsOutputDir)}/`;\n\n        ui.ok(`Components downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);\n      }\n      else if (componentName) {\n        const fileName = suffix ? `${actualFilename}.${suffix}.json` : `${componentName}.json`;\n        const filePath = join(componentsOutputDir, fileName);\n        // Only show relative path if the base path wasn't absolute\n        const displayPath = (path && isAbsolute(path)) ? filePath : relative(process.cwd(), filePath);\n        ui.ok(`Component ${chalk.hex(colorPalette.PRIMARY)(componentName)} downloaded successfully in ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);\n      }\n      else {\n        const fileName = suffix ? `${actualFilename}.${suffix}.json` : `${actualFilename}.json`;\n        const filePath = join(componentsOutputDir, fileName);\n        // Only show relative path if the base path wasn't absolute\n        const displayPath = (path && isAbsolute(path)) ? filePath : relative(process.cwd(), filePath);\n\n        ui.ok(`Components downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);\n      }\n      ui.br();\n    }\n    catch (error) {\n      spinnerGroups.failed(`Pulling ${chalk.hex(colorPalette.COMPONENTS)('Groups')} - Failed`);\n      spinnerPresets.failed(`Pulling ${chalk.hex(colorPalette.COMPONENTS)('Presets')} - Failed`);\n      spinnerInternalTags.failed(`Pulling ${chalk.hex(colorPalette.COMPONENTS)('Tags')} - Failed`);\n      spinnerComponents.failed(`Pulling ${chalk.hex(colorPalette.COMPONENTS)('Components')} - Failed`);\n      ui.br();\n      handleError(error as Error, verbose);\n    }\n    finally {\n      logger.info('Pulling components finished', { space, componentName });\n    }\n  });\n","import type {\n  Component,\n  ComponentFolder,\n  InternalTag,\n  Preset,\n} from '../../constants';\nimport type { DependencyGraph, GraphBuildingContext, NodeData, NodeType, ProcessingLevel, SchemaDependencies, TargetResourceInfo, UnifiedNode } from './types';\nimport { upsertComponent, upsertComponentGroup, upsertComponentInternalTag, upsertComponentPreset } from '../actions';\n\n// =============================================================================\n// HELPER FUNCTIONS\n// =============================================================================\n\n/**\n * Field types that support component whitelists (group, tag, and component whitelists)\n */\nconst fieldTypesWithDependencies = ['bloks', 'richtext'] as const;\n\n// =============================================================================\n// GRAPH BUILDING\n// =============================================================================\n\n/**\n * Builds a complete dependency graph from the space data with colocated target data.\n * Each node in the graph represents a resource (component, group, or tag) and\n * maintains bidirectional links to its dependencies and dependents.\n * Target data is colocated with each node for efficient upsert operations.\n */\nexport function buildDependencyGraph(context: GraphBuildingContext): DependencyGraph {\n  const { spaceState } = context;\n  const graph: DependencyGraph = { nodes: new Map() };\n\n  // Helper function to establish bidirectional dependencies\n  function addDependency(dependentId: string, dependencyId: string) {\n    const dependent = graph.nodes.get(dependentId);\n    const dependency = graph.nodes.get(dependencyId);\n\n    if (dependent && dependency) {\n      dependent.dependencies.add(dependencyId);\n      dependency.dependents.add(dependentId);\n    }\n  }\n\n  // Note: Datasource dependencies are not processed by the components push command.\n  // Datasources should be managed using the dedicated 'storyblok datasources push' command.\n\n  // Create nodes for all tags with colocated target data\n  spaceState.local.internalTags.forEach((tag) => {\n    const nodeId = `tag:${tag.id}`;\n    const targetTag = spaceState.target.tags.get(tag.name);\n    const node = new TagNode(nodeId, tag, targetTag);\n    graph.nodes.set(nodeId, node);\n  });\n\n  // Create nodes for all groups with colocated target data\n  spaceState.local.groups.forEach((group) => {\n    const nodeId = `group:${group.uuid}`;\n    const targetGroup = spaceState.target.groups.get(group.name);\n    const node = new GroupNode(nodeId, group, targetGroup);\n    graph.nodes.set(nodeId, node);\n  });\n\n  // Create nodes for all components with colocated target data\n  spaceState.local.components.forEach((component) => {\n    const nodeId = `component:${component.name}`;\n    const targetComponent = spaceState.target.components.get(component.name);\n    const node = new ComponentNode(nodeId, component, targetComponent);\n    graph.nodes.set(nodeId, node);\n  });\n\n  // Create nodes for all presets with colocated target data\n  // Since presets are nested resources under components, create a component map for efficient lookups\n  const componentMap = new Map(spaceState.local.components.map(c => [c.id, c]));\n\n  spaceState.local.presets.forEach((preset) => {\n    const nodeId = `preset:${preset.id}`;\n\n    // Find the parent component for this nested preset resource\n    const sourceComponent = componentMap.get(preset.component_id);\n    if (!sourceComponent) {\n      // Skip presets whose parent components are not available in local data\n      console.warn(`Warning: Preset \"${preset.name}\" (ID: ${preset.id}) references component ID ${preset.component_id} which is not available in local data. Skipping preset.`);\n      return;\n    }\n\n    // Use hierarchical key: component.name:preset.name (parent:child)\n    const compositeKey = `${sourceComponent.name}:${preset.name}`;\n    const targetPreset = spaceState.target.presets.get(compositeKey);\n\n    if (targetPreset && targetPreset.id === undefined) {\n      throw new Error(`Target preset \"${preset.name}\" is missing an id`);\n    }\n    const targetData = targetPreset\n      ? {\n          resource: targetPreset,\n          id: targetPreset.id,\n        }\n      : undefined;\n    const node = new PresetNode(preset, targetData);\n    graph.nodes.set(nodeId, node);\n  });\n\n  // Add group parent dependencies\n  spaceState.local.groups.forEach((group) => {\n    // Skip if parent_id is null/undefined (no parent) or if parent_uuid points to itself (self-reference)\n    if (group.parent_uuid && group.parent_id && group.parent_uuid !== group.uuid) {\n      const childId = `group:${group.uuid}`;\n      const parentId = `group:${group.parent_uuid}`;\n      addDependency(childId, parentId);\n    }\n  });\n\n  // Add component dependencies based on schema analysis\n  spaceState.local.components.forEach((component) => {\n    const componentId = `component:${component.name}`;\n\n    // Add dependencies on internal_tag_ids (direct component tag references)\n    if (component.internal_tag_ids && component.internal_tag_ids.length > 0) {\n      component.internal_tag_ids.forEach((tagId) => {\n        const tagNodeId = `tag:${tagId}`;\n        addDependency(componentId, tagNodeId);\n      });\n    }\n\n    // Add dependencies on component_group_uuid (component group assignment)\n    if (component.component_group_uuid) {\n      const groupId = `group:${component.component_group_uuid}`;\n      addDependency(componentId, groupId);\n    }\n\n    // Add dependencies on preset_id (component preset reference)\n    if (component.preset_id) {\n      // Find the preset by ID and create dependency\n      const preset = spaceState.local.presets.find(p => p.id === component.preset_id);\n      if (preset) {\n        const presetId = `preset:${preset.id}`;\n        addDependency(componentId, presetId);\n      }\n    }\n\n    if (component.schema) {\n      const dependencies = collectWhitelistDependencies(component.schema);\n\n      // Add dependencies on groups (from schema whitelists)\n      dependencies.groupUuids.forEach((groupUuid) => {\n        const groupId = `group:${groupUuid}`;\n        addDependency(componentId, groupId);\n      });\n\n      // Add dependencies on tags (from schema whitelists)\n      dependencies.tagIds.forEach((tagId) => {\n        const tagNodeId = `tag:${tagId}`;\n        addDependency(componentId, tagNodeId);\n      });\n\n      // Add dependencies on other components\n      dependencies.componentNames.forEach((componentName) => {\n        const dependencyId = `component:${componentName}`;\n        addDependency(componentId, dependencyId);\n      });\n    }\n  });\n\n  // Add preset dependencies on components\n  spaceState.local.presets.forEach((preset) => {\n    const presetId = `preset:${preset.id}`;\n\n    // Find the component this preset belongs to\n    const component = spaceState.local.components.find(c => c.id === preset.component_id);\n    if (component) {\n      const componentId = `component:${component.name}`;\n      addDependency(presetId, componentId);\n    }\n  });\n\n  return graph;\n}\n\n// =============================================================================\n// DEPENDENCY EXTRACTION\n// =============================================================================\n\n/**\n * Extracts dependency information from a component schema.\n * Traverses the schema to find references to groups, tags, and other components.\n */\nexport function collectWhitelistDependencies(schema: Record<string, any>): SchemaDependencies {\n  const groupUuids = new Set<string>();\n  const tagIds = new Set<number>();\n  const componentNames = new Set<string>();\n  const datasourceNames = new Set<string>();\n\n  function traverseField(field: Record<string, any>) {\n    if (fieldTypesWithDependencies.includes(field.type)) {\n      // Collect group dependencies\n      if (field.component_group_whitelist && Array.isArray(field.component_group_whitelist)) {\n        field.component_group_whitelist.forEach((uuid: string) => groupUuids.add(uuid));\n      }\n\n      // Collect tag dependencies\n      if (field.component_tag_whitelist && Array.isArray(field.component_tag_whitelist)) {\n        field.component_tag_whitelist.forEach((tagId: number) => tagIds.add(tagId));\n      }\n\n      // Collect component dependencies\n      if (field.component_whitelist && Array.isArray(field.component_whitelist)) {\n        field.component_whitelist.forEach((name: string) => componentNames.add(name));\n      }\n    }\n\n    // Collect datasource dependencies from option/options fields with internal source\n    if ((field.type === 'option' || field.type === 'options') && field.source === 'internal') {\n      // For option/options fields with internal source, the datasource name is typically\n      // specified in the datasource_slug field or can be inferred from other properties\n      if (field.datasource_slug && typeof field.datasource_slug === 'string') {\n        datasourceNames.add(field.datasource_slug);\n      }\n    }\n\n    // Recursively traverse nested fields\n    Object.values(field).forEach((value) => {\n      if (Array.isArray(value)) {\n        value.forEach((item) => {\n          if (typeof item === 'object' && item !== null) {\n            traverseField(item);\n          }\n        });\n      }\n      else if (typeof value === 'object' && value !== null) {\n        traverseField(value);\n      }\n    });\n  }\n\n  // Traverse all fields in the schema\n  Object.values(schema).forEach((field) => {\n    if (typeof field === 'object' && field !== null) {\n      traverseField(field);\n    }\n  });\n\n  return { groupUuids, tagIds, componentNames, datasourceNames };\n}\n\n// =============================================================================\n// GRAPH VALIDATION\n// =============================================================================\n\n/**\n * Detects problematic cycles in the dependency graph.\n * Returns an array of cycle descriptions that would prevent successful processing.\n */\nexport function detectProblematicCycles(graph: DependencyGraph): string[] {\n  const problematicCycles: string[] = [];\n  const visited = new Set<string>();\n  const recursionStack = new Set<string>();\n\n  function dfs(nodeId: string, path: string[]): boolean {\n    if (recursionStack.has(nodeId)) {\n      // Found a cycle - check if it's problematic\n      const cycleStart = path.indexOf(nodeId);\n      const cycle = path.slice(cycleStart).concat(nodeId);\n\n      // Cycles involving groups or tags are always problematic\n      const hasGroupOrTag = cycle.some(id => id.startsWith('group:') || id.startsWith('tag:'));\n      if (hasGroupOrTag) {\n        problematicCycles.push(`Problematic cycle: ${cycle.join(' → ')}`);\n      }\n\n      return true;\n    }\n\n    if (visited.has(nodeId)) {\n      return false;\n    }\n\n    visited.add(nodeId);\n    recursionStack.add(nodeId);\n    path.push(nodeId);\n\n    const node = graph.nodes.get(nodeId);\n    if (node) {\n      for (const dependencyId of node.dependencies) {\n        if (dfs(dependencyId, [...path])) {\n          return true;\n        }\n      }\n    }\n\n    recursionStack.delete(nodeId);\n    path.pop();\n    return false;\n  }\n\n  // Check each node for cycles\n  for (const nodeId of graph.nodes.keys()) {\n    if (!visited.has(nodeId)) {\n      dfs(nodeId, []);\n    }\n  }\n\n  return problematicCycles;\n}\n\n/**\n * Detects circular component whitelists (which are allowed but worth noting).\n */\nexport function detectCircularWhitelists(graph: DependencyGraph): string[] {\n  const circularWhitelists: string[] = [];\n  const visited = new Set<string>();\n  const recursionStack = new Set<string>();\n\n  function dfs(nodeId: string, path: string[]): boolean {\n    if (recursionStack.has(nodeId)) {\n      // Found a cycle - check if it's just component whitelists\n      const cycleStart = path.indexOf(nodeId);\n      const cycle = path.slice(cycleStart).concat(nodeId);\n\n      // Only report if it's purely component-to-component cycles\n      const isComponentOnly = cycle.every(id => id.startsWith('component:'));\n      if (isComponentOnly) {\n        circularWhitelists.push(cycle.join(' → '));\n      }\n\n      return true;\n    }\n\n    if (visited.has(nodeId)) {\n      return false;\n    }\n\n    visited.add(nodeId);\n    recursionStack.add(nodeId);\n    path.push(nodeId);\n\n    const node = graph.nodes.get(nodeId);\n    if (node) {\n      for (const dependencyId of node.dependencies) {\n        if (dfs(dependencyId, [...path])) {\n          return true;\n        }\n      }\n    }\n\n    recursionStack.delete(nodeId);\n    path.pop();\n    return false;\n  }\n\n  // Check each component node for circular whitelists\n  for (const nodeId of graph.nodes.keys()) {\n    if (nodeId.startsWith('component:') && !visited.has(nodeId)) {\n      dfs(nodeId, []);\n    }\n  }\n\n  return circularWhitelists;\n}\n\n/**\n * Detects strongly connected components using Tarjan's algorithm.\n * Returns an array of SCCs, where each SCC is an array of node IDs.\n */\nexport function detectStronglyConnectedComponents(nodeIds: string[], graph: DependencyGraph): string[][] {\n  const index = new Map<string, number>();\n  const lowLink = new Map<string, number>();\n  const onStack = new Set<string>();\n  const stack: string[] = [];\n  const sccs: string[][] = [];\n  let currentIndex = 0;\n\n  function strongConnect(nodeId: string) {\n    // Set the depth index for this node to the smallest unused index\n    index.set(nodeId, currentIndex);\n    lowLink.set(nodeId, currentIndex);\n    currentIndex++;\n    stack.push(nodeId);\n    onStack.add(nodeId);\n\n    // Consider successors of this node\n    const node = graph.nodes.get(nodeId);\n    if (node) {\n      for (const dependencyId of node.dependencies) {\n        if (nodeIds.includes(dependencyId)) { // Only consider nodes in the remaining set\n          if (!index.has(dependencyId)) {\n            // Successor has not yet been visited; recurse on it\n            strongConnect(dependencyId);\n            lowLink.set(nodeId, Math.min(lowLink.get(nodeId)!, lowLink.get(dependencyId)!));\n          }\n          else if (onStack.has(dependencyId)) {\n            // Successor is in stack and hence in the current SCC\n            lowLink.set(nodeId, Math.min(lowLink.get(nodeId)!, index.get(dependencyId)!));\n          }\n        }\n      }\n    }\n\n    // If this is a root node, pop the stack and create an SCC\n    if (lowLink.get(nodeId) === index.get(nodeId)) {\n      const scc: string[] = [];\n      let w: string;\n      do {\n        w = stack.pop()!;\n        onStack.delete(w);\n        scc.push(w);\n      } while (w !== nodeId);\n      sccs.push(scc);\n    }\n  }\n\n  // Run the algorithm for all unvisited nodes\n  for (const nodeId of nodeIds) {\n    if (!index.has(nodeId)) {\n      strongConnect(nodeId);\n    }\n  }\n\n  return sccs;\n}\n\n/**\n * Determines the processing order using topological sorting with SCC handling.\n * Returns an array of ProcessingLevels, which can be either regular or cyclic levels.\n */\nexport function determineProcessingOrder(graph: DependencyGraph): ProcessingLevel[] {\n  const levels: ProcessingLevel[] = [];\n  const inDegree = new Map<string, number>();\n\n  // Calculate in-degrees for all nodes\n  for (const [nodeId, node] of graph.nodes) {\n    inDegree.set(nodeId, node.dependencies.size);\n  }\n\n  // Process nodes level by level\n  while (inDegree.size > 0) {\n    // Find all nodes with no remaining dependencies\n    const currentLevel: string[] = [];\n    for (const [nodeId, degree] of inDegree) {\n      if (degree === 0) {\n        currentLevel.push(nodeId);\n      }\n    }\n\n    if (currentLevel.length === 0) {\n      // If no nodes can be processed, we have cycles - detect SCCs\n      const remainingNodes = Array.from(inDegree.keys());\n      const sccs = detectStronglyConnectedComponents(remainingNodes, graph);\n\n      for (const scc of sccs) {\n        // Validate that SCCs only contain components (not groups/tags)\n        const hasNonComponent = scc.some(nodeId =>\n          nodeId.startsWith('group:') || nodeId.startsWith('tag:'),\n        );\n\n        if (hasNonComponent) {\n          throw new Error(`Unsupported circular dependency involving groups, tags, or presets: ${scc.join(' → ')}`);\n        }\n\n        // Add as cyclic level - these will need special processing\n        levels.push({ nodes: scc, isCyclic: true });\n\n        // Remove SCC nodes from processing\n        scc.forEach(nodeId => inDegree.delete(nodeId));\n      }\n\n      continue; // Continue with remaining nodes after handling cycles\n    }\n\n    // Add regular level\n    levels.push({ nodes: currentLevel, isCyclic: false });\n\n    // Remove processed nodes and update in-degrees\n    for (const nodeId of currentLevel) {\n      inDegree.delete(nodeId);\n      const node = graph.nodes.get(nodeId)!;\n\n      // Decrease in-degree for all dependents\n      for (const dependentId of node.dependents) {\n        const currentDegree = inDegree.get(dependentId);\n        if (currentDegree !== undefined) {\n          inDegree.set(dependentId, currentDegree - 1);\n        }\n      }\n    }\n  }\n\n  return levels;\n}\n\n// =============================================================================\n// GRAPH VALIDATION\n// =============================================================================\n\n/**\n * Validates the dependency graph and throws errors for critical issues.\n */\nexport function validateGraph(graph: DependencyGraph): void {\n  console.log(`📊 Built dependency graph with ${graph.nodes.size} nodes`);\n\n  // Check for problematic cycles\n  const problematicCycles = detectProblematicCycles(graph);\n  if (problematicCycles.length > 0) {\n    throw new Error(`❌ Problematic cycles detected:\\n${problematicCycles.join('\\n')}`);\n  }\n\n  // Report circular whitelists (informational)\n  const circularWhitelists = detectCircularWhitelists(graph);\n  if (circularWhitelists.length > 0) {\n    console.log(`ℹ️  Circular component whitelists detected (allowed): ${circularWhitelists.join(', ')}`);\n  }\n\n  console.log(`✅ Graph validation passed`);\n}\n\n// =============================================================================\n// CONCRETE NODE IMPLEMENTATIONS\n// =============================================================================\n\nclass GraphNode<TSource extends NodeData> implements UnifiedNode<TSource> {\n  id: string;\n  type: NodeType;\n  name: string;\n  sourceData: TSource;\n  targetData?: TargetResourceInfo<TSource>;\n  dependencies: Set<string>;\n  dependents: Set<string>;\n\n  constructor(id: string, type: NodeType, name: string, sourceData: TSource, targetResource?: TSource) {\n    this.id = id;\n    this.type = type;\n    this.name = name;\n    this.sourceData = sourceData;\n    this.dependencies = new Set();\n    this.dependents = new Set();\n\n    // Set target data if target resource exists\n    if (targetResource) {\n      this.targetData = {\n        resource: targetResource,\n        id: (targetResource as any).id,\n      };\n    }\n  }\n\n  getName(): string {\n    return this.name;\n  }\n\n  resolveReferences(_graph: DependencyGraph): void {\n    // Base implementation does nothing - override in derived classes if needed\n  }\n\n  async upsert(_space: string): Promise<TSource> {\n    throw new Error('upsert must be implemented by derived classes');\n  }\n\n  updateTargetData(result: TSource): void {\n    this.targetData = {\n      resource: result,\n      id: (result as any).id,\n    };\n  }\n}\n\nexport class TagNode extends GraphNode<InternalTag> {\n  constructor(id: string, data: InternalTag, targetTag?: InternalTag) {\n    super(id, 'tag', data.name, data, targetTag);\n  }\n\n  resolveReferences(_graph: DependencyGraph): void {\n    // Tags don't have references to resolve\n  }\n\n  async upsert(space: string): Promise<InternalTag> {\n    const existingId = this.targetData?.id;\n    const result = await upsertComponentInternalTag(space, this.sourceData, existingId as number | undefined);\n    if (!result) {\n      throw new Error(`Failed to upsert tag ${this.name}`);\n    }\n    return result;\n  }\n}\n\nexport class GroupNode extends GraphNode<ComponentFolder> {\n  constructor(id: string, data: ComponentFolder, targetGroup?: ComponentFolder) {\n    super(id, 'group', data.name, data, targetGroup);\n  }\n\n  resolveReferences(graph: DependencyGraph): void {\n    // Resolve parent group reference if it exists\n    if (this.sourceData.parent_uuid) {\n      const parentNodeId = `group:${this.sourceData.parent_uuid}`;\n      const parentNode = graph.nodes.get(parentNodeId) as GroupNode;\n\n      if (parentNode?.targetData) {\n        // Update the source data to use the target space parent ID\n        this.sourceData = {\n          ...this.sourceData,\n          parent_id: parentNode.targetData.id as number,\n        };\n      }\n    }\n  }\n\n  async upsert(space: string): Promise<ComponentFolder> {\n    const existingId = this.targetData?.id;\n    const result = await upsertComponentGroup(space, this.sourceData, existingId as number | undefined);\n    if (!result) {\n      throw new Error(`Failed to upsert group ${this.name}`);\n    }\n    return result;\n  }\n}\n\nexport class ComponentNode extends GraphNode<Component> {\n  constructor(id: string, data: Component, targetComponent?: Component) {\n    super(id, 'component', data.name, data, targetComponent);\n  }\n\n  resolveReferences(graph: DependencyGraph): void {\n    // Create a copy of source data to modify\n    const updatedData = { ...this.sourceData };\n\n    // Resolve component group reference\n    if (this.sourceData.component_group_uuid) {\n      const groupNodeId = `group:${this.sourceData.component_group_uuid}`;\n      const groupNode = graph.nodes.get(groupNodeId) as GroupNode;\n\n      if (groupNode?.targetData) {\n        updatedData.component_group_uuid = groupNode.targetData.resource.uuid;\n      }\n    }\n\n    // Resolve internal tag references\n    if (this.sourceData.internal_tag_ids && this.sourceData.internal_tag_ids.length > 0) {\n      const resolvedTagIds: string[] = [];\n\n      for (const tagId of this.sourceData.internal_tag_ids) {\n        const tagNodeId = `tag:${tagId}`;\n        const tagNode = graph.nodes.get(tagNodeId) as TagNode;\n\n        if (tagNode?.targetData) {\n          resolvedTagIds.push(String(tagNode.targetData.id));\n        }\n        else {\n          // Keep original ID if not found in graph (might be a tag that already exists in target)\n          resolvedTagIds.push(tagId);\n        }\n      }\n\n      updatedData.internal_tag_ids = resolvedTagIds;\n    }\n\n    // Resolve preset reference\n    if (this.sourceData.preset_id) {\n      // Find the preset by ID and resolve to target preset ID\n      const preset = this.findPresetById(this.sourceData.preset_id, graph);\n      if (preset) {\n        const presetNodeId = `preset:${preset.id}`;\n        const presetNode = graph.nodes.get(presetNodeId);\n\n        if (presetNode?.targetData) {\n          updatedData.preset_id = presetNode.targetData.id as number;\n        }\n      }\n    }\n\n    // Resolve schema references (component whitelists, group whitelists, tag whitelists)\n    if (this.sourceData.schema) {\n      updatedData.schema = this.resolveSchemaReferences(this.sourceData.schema, graph);\n    }\n\n    // Update the source data with resolved references\n    this.sourceData = updatedData;\n  }\n\n  private findPresetById(presetId: number, graph: DependencyGraph): Preset | null {\n    // Find preset by matching source preset_id\n    for (const [_nodeId, node] of graph.nodes) {\n      if (node.type === 'preset' && (node.sourceData as Preset).id === presetId) {\n        return node.sourceData as Preset;\n      }\n    }\n    return null;\n  }\n\n  private resolveSchemaReferences(schema: Record<string, any>, graph: DependencyGraph): Record<string, any> {\n    const resolvedSchema = JSON.parse(JSON.stringify(schema)); // Deep copy\n\n    function resolveField(field: any): any {\n      if (typeof field !== 'object' || field === null) {\n        return field;\n      }\n\n      if (Array.isArray(field)) {\n        return field.map(resolveField);\n      }\n\n      const resolvedField = { ...field };\n\n      // Resolve bloks and richtext field references (both support component whitelists)\n      if (fieldTypesWithDependencies.includes(resolvedField.type)) {\n        // Resolve component group whitelist\n        if (resolvedField.component_group_whitelist && Array.isArray(resolvedField.component_group_whitelist)) {\n          resolvedField.component_group_whitelist = resolvedField.component_group_whitelist.map((groupUuid: string) => {\n            const groupNodeId = `group:${groupUuid}`;\n            const groupNode = graph.nodes.get(groupNodeId) as GroupNode;\n            return groupNode?.targetData?.resource.uuid || groupUuid;\n          });\n        }\n\n        // Resolve component tag whitelist\n        if (resolvedField.component_tag_whitelist && Array.isArray(resolvedField.component_tag_whitelist)) {\n          resolvedField.component_tag_whitelist = resolvedField.component_tag_whitelist.map((tagId: number) => {\n            const tagNodeId = `tag:${tagId}`;\n            const tagNode = graph.nodes.get(tagNodeId) as TagNode;\n            return tagNode?.targetData?.id || tagId;\n          });\n        }\n\n        // Component whitelist doesn't need ID resolution as it uses names\n      }\n\n      // Note: Datasource references are not resolved by the components push command.\n      // Components that reference datasources will work correctly if the datasources\n      // already exist in the target space with the same slug names.\n\n      // Recursively resolve nested fields\n      Object.keys(resolvedField).forEach((key) => {\n        if (typeof resolvedField[key] === 'object' && resolvedField[key] !== null) {\n          resolvedField[key] = resolveField(resolvedField[key]);\n        }\n      });\n\n      return resolvedField;\n    }\n\n    const result: Record<string, any> = {};\n    Object.keys(resolvedSchema).forEach((key) => {\n      result[key] = resolveField(resolvedSchema[key]);\n    });\n\n    return result;\n  }\n\n  async upsert(space: string): Promise<Component> {\n    const existingId = this.targetData?.id;\n    const result = await upsertComponent(space, this.sourceData, existingId as number | undefined);\n    if (!result) {\n      throw new Error(`Failed to upsert component ${this.name}`);\n    }\n    return result;\n  }\n}\n\n/**\n * Preset node implementation\n * Presets depend on components (via component_id)\n */\nclass PresetNode implements UnifiedNode<Preset> {\n  public readonly id: string;\n  public readonly name: string;\n  public readonly type: NodeType = 'preset';\n  public readonly sourceData: Preset;\n  public targetData?: TargetResourceInfo<Preset>;\n  public readonly dependencies = new Set<string>();\n  public readonly dependents = new Set<string>();\n\n  constructor(preset: Preset, targetData?: TargetResourceInfo<Preset>) {\n    this.sourceData = preset;\n    this.targetData = targetData;\n    this.id = `preset:${preset.id}`;\n    this.name = preset.name;\n  }\n\n  getName(): string {\n    return this.name;\n  }\n\n  resolveReferences(graph: DependencyGraph): void {\n    // Find the component this preset belongs to and update component_id\n    const componentName = this.findComponentNameById(this.sourceData.component_id, graph);\n    if (componentName) {\n      const componentNode = graph.nodes.get(`component:${componentName}`);\n      if (componentNode?.targetData) {\n        this.sourceData.component_id = componentNode.targetData.id as number;\n      }\n    }\n  }\n\n  private findComponentNameById(componentId: number, graph: DependencyGraph): string | null {\n    // Find component by matching source component_id\n    for (const [_nodeId, node] of graph.nodes) {\n      if (node.type === 'component' && (node.sourceData as Component).id === componentId) {\n        return node.name;\n      }\n    }\n    return null;\n  }\n\n  async upsert(space: string): Promise<Preset> {\n    const existingId = this.targetData?.id as number | undefined;\n    const result = await upsertComponentPreset(space, this.sourceData, existingId);\n    if (!result) {\n      throw new Error(`Failed to upsert preset: ${this.name}`);\n    }\n    return result;\n  }\n\n  updateTargetData(result: Preset): void {\n    if (result.id === undefined) {\n      throw new Error(`Preset \"${this.name}\" is missing an id after upsert`);\n    }\n    this.targetData = {\n      resource: result,\n      id: result.id,\n    };\n  }\n}\n\n// Note: DatasourceNode class removed as datasources are not managed\n// by the components push command. Use 'storyblok datasources push' instead.\n","import type { SpaceComponentsData } from '../constants';\nimport { minimatch } from 'minimatch';\nimport { collectWhitelistDependencies } from './graph-operations/dependency-graph';\n\n/**\n * Collects all dependencies (groups, tags, and components) for a set of components\n */\nfunction collectAllDependencies(\n  components: SpaceComponentsData['components'],\n  allComponents: SpaceComponentsData['components'],\n  allGroups: SpaceComponentsData['groups'],\n  allTags: SpaceComponentsData['internalTags'],\n) {\n  const requiredComponents = new Set<string>();\n  const requiredGroupUuids = new Set<string>();\n  const requiredTagIds = new Set<number>();\n\n  // Add initial components\n  components.forEach(component => requiredComponents.add(component.name));\n\n  // Recursively collect component dependencies\n  function collectComponentDeps(componentName: string, visited = new Set<string>()) {\n    if (visited.has(componentName)) { return; } // Prevent infinite loops\n    visited.add(componentName);\n\n    const component = allComponents.find(c => c.name === componentName);\n    if (!component) { return; }\n\n    // Collect direct component group assignment\n    if (component.component_group_uuid) {\n      requiredGroupUuids.add(component.component_group_uuid);\n    }\n\n    // Collect direct internal tag assignments\n    if (component.internal_tag_ids && component.internal_tag_ids.length > 0) {\n      component.internal_tag_ids.forEach((tagId) => {\n        // Handle both string and number tag IDs\n        const numericTagId = typeof tagId === 'string' ? Number.parseInt(tagId, 10) : tagId;\n        if (!Number.isNaN(numericTagId)) {\n          requiredTagIds.add(numericTagId);\n        }\n      });\n    }\n\n    // Collect schema whitelist dependencies\n    if (component.schema) {\n      const schemaDeps = collectWhitelistDependencies(component.schema);\n\n      // Add schema group dependencies\n      schemaDeps.groupUuids.forEach((groupUuid) => {\n        requiredGroupUuids.add(groupUuid);\n      });\n\n      // Add schema tag dependencies\n      schemaDeps.tagIds.forEach((tagId) => {\n        requiredTagIds.add(tagId);\n      });\n\n      // Add schema component dependencies (recursive)\n      schemaDeps.componentNames.forEach((componentName) => {\n        if (!requiredComponents.has(componentName)) {\n          requiredComponents.add(componentName);\n          collectComponentDeps(componentName, visited);\n        }\n      });\n    }\n  }\n\n  // Collect dependencies for all components\n  components.forEach(component => collectComponentDeps(component.name));\n\n  // Collect parent groups for hierarchical dependencies\n  function collectParentGroups(groupUuid: string, visited = new Set<string>()) {\n    if (visited.has(groupUuid)) { return; } // Prevent infinite loops\n    visited.add(groupUuid);\n\n    const group = allGroups.find(g => g.uuid === groupUuid);\n    if (group && group.parent_uuid) {\n      requiredGroupUuids.add(group.parent_uuid);\n      collectParentGroups(group.parent_uuid, visited);\n    }\n  }\n\n  // Ensure we include parent groups for all required groups\n  const initialGroupUuids = Array.from(requiredGroupUuids);\n  initialGroupUuids.forEach(groupUuid => collectParentGroups(groupUuid));\n\n  // Filter to only include required resources\n  const filteredComponents = allComponents.filter(component => requiredComponents.has(component.name));\n  const filteredGroups = allGroups.filter(group => group.uuid !== undefined && requiredGroupUuids.has(group.uuid));\n  const filteredTags = allTags.filter(tag => tag.id !== undefined && requiredTagIds.has(tag.id));\n\n  return { filteredComponents, filteredGroups, filteredTags };\n}\n\n/**\n * Filters space data to only include a specific component and its dependencies\n */\nexport function filterSpaceDataByComponent(spaceData: SpaceComponentsData, componentName: string): SpaceComponentsData {\n  // Find the target component\n  const targetComponent = spaceData.components.find(component => component.name === componentName);\n  if (!targetComponent) {\n    return {\n      components: [],\n      groups: [],\n      internalTags: [],\n      presets: [],\n      datasources: [],\n    };\n  }\n\n  // Collect all dependencies for this component\n  const { filteredComponents, filteredGroups, filteredTags } = collectAllDependencies(\n    [targetComponent],\n    spaceData.components,\n    spaceData.groups,\n    spaceData.internalTags,\n  );\n\n  // Find presets for all included components\n  const componentIds = filteredComponents.map(component => component.id);\n  const filteredPresets = spaceData.presets.filter(\n    preset => componentIds.includes(preset.component_id),\n  );\n\n  return {\n    components: filteredComponents,\n    groups: filteredGroups,\n    internalTags: filteredTags,\n    presets: filteredPresets,\n    datasources: [],\n  };\n}\n\n/**\n * Filters space data to only include components matching a glob pattern and their dependencies\n */\nexport function filterSpaceDataByPattern(spaceData: SpaceComponentsData, pattern: string): SpaceComponentsData {\n  // Filter components by pattern\n  const matchingComponents = spaceData.components.filter(component =>\n    minimatch(component.name, pattern),\n  );\n\n  if (matchingComponents.length === 0) {\n    return {\n      components: [],\n      groups: [],\n      internalTags: [],\n      presets: [],\n      datasources: [],\n    };\n  }\n\n  // Collect all dependencies for matching components\n  const { filteredComponents, filteredGroups, filteredTags } = collectAllDependencies(\n    matchingComponents,\n    spaceData.components,\n    spaceData.groups,\n    spaceData.internalTags,\n  );\n\n  // Find presets for all included components\n  const componentIds = filteredComponents.map(component => component.id);\n  const filteredPresets = spaceData.presets.filter(\n    preset => componentIds.includes(preset.component_id),\n  );\n\n  return {\n    components: filteredComponents,\n    groups: filteredGroups,\n    internalTags: filteredTags,\n    presets: filteredPresets,\n    datasources: [],\n  };\n}\n","import chalk from 'chalk';\nimport { konsola } from '../../../utils/konsola';\n\nexport type ProcessingEvent =\n  | { type: 'start'; total: number }\n  | { type: 'success'; name: string; resourceType: string; color: string; elapsedMs?: number }\n  | { type: 'skip'; name: string; resourceType: string; elapsedMs?: number }\n  | { type: 'error'; name: string; resourceType: string; error: unknown; elapsedMs?: number }\n  | { type: 'complete'; summary: { updated: number; unchanged: number; failed: number } };\n\nexport class ProgressDisplay {\n  public total = 0;\n  private processed = 0;\n  private updated = 0;\n  private unchanged = 0;\n  private failed = 0;\n  private currentProgressLine = '';\n  // Track start time for calculating elapsed time on completion\n  private startTime: number | null = null;\n\n  start(total: number) {\n    this.total = total;\n    this.processed = 0;\n    this.updated = 0;\n    this.unchanged = 0;\n    this.failed = 0;\n    // Record the start time when processing begins\n    this.startTime = Date.now();\n    konsola.br();\n    console.log(`Processing ${total} resources...`);\n    this.updateProgress();\n  }\n\n  handleEvent(event: ProcessingEvent) {\n    switch (event.type) {\n      case 'start':\n        this.start(event.total);\n        break;\n\n      case 'success': {\n        this.processed++;\n        this.updated++;\n        this.clearProgress();\n        const successTimeString = event.elapsedMs ? chalk.dim(` (${this.formatElapsedTime(event.elapsedMs)})`) : '';\n        console.log(`${chalk.green('✓')} ${this.capitalize(event.resourceType)}→ ${chalk.hex(event.color)(event.name)} - Updated${successTimeString}`);\n        this.updateProgress();\n        break;\n      }\n\n      case 'skip': {\n        this.processed++;\n        this.unchanged++;\n        // Optionally show timing for skipped items if they take longer than expected\n        const skipTimeString = event.elapsedMs && event.elapsedMs > 10 ? chalk.dim(` (${this.formatElapsedTime(event.elapsedMs)})`) : '';\n        if (skipTimeString) {\n          this.clearProgress();\n          console.log(`${chalk.dim('—')} ${this.capitalize(event.resourceType)}→ ${chalk.dim(event.name)} - Skipped${skipTimeString}`);\n        }\n        this.updateProgress();\n        break;\n      }\n\n      case 'error': {\n        this.processed++;\n        this.failed++;\n        this.clearProgress();\n        const errorTimeString = event.elapsedMs ? chalk.dim(` (${this.formatElapsedTime(event.elapsedMs)})`) : '';\n        console.log(`${chalk.red('✗')} ${this.capitalize(event.resourceType)}→ ${chalk.red(event.name)} - Failed${errorTimeString}`);\n        this.updateProgress();\n        break;\n      }\n\n      case 'complete': {\n        this.clearProgress();\n        const { updated, unchanged, failed } = event.summary;\n\n        // Calculate elapsed time if startTime was recorded\n        const elapsedTime = this.startTime ? Date.now() - this.startTime : null;\n        const timeString = elapsedTime ? this.formatElapsedTime(elapsedTime) : '';\n\n        konsola.ok(`Completed: ${updated} updated, ${unchanged} unchanged, ${failed} failed${timeString ? ` in ${timeString}` : ''}`, true);\n        konsola.br();\n        // Show summary of skipped items when there are many\n        if (unchanged > 5) {\n          console.log(chalk.dim(`   (${unchanged} resources were already up-to-date)`));\n        }\n        break;\n      }\n    }\n  }\n\n  private updateProgress() {\n    this.currentProgressLine = `[${this.processed}/${this.total}] ${this.updated} updated, ${this.unchanged} unchanged, ${this.failed} failed`;\n    process.stdout.write(`\\r${this.currentProgressLine}`);\n  }\n\n  clearProgress() {\n    if (this.currentProgressLine) {\n      process.stdout.write(`\\r${' '.repeat(this.currentProgressLine.length)}\\r`);\n    }\n  }\n\n  private capitalize(str: string): string {\n    return str.charAt(0).toUpperCase() + str.slice(1);\n  }\n\n  /**\n   * Formats elapsed time in milliseconds to a human-readable string\n   * @param ms - Time in milliseconds\n   * @returns Formatted time string (e.g., \"1.2s\", \"2m 30s\", \"1h 5m\")\n   */\n  private formatElapsedTime(ms: number): string {\n    if (ms < 1000) {\n      return `${ms}ms`;\n    }\n\n    const seconds = Math.floor(ms / 1000);\n    const minutes = Math.floor(seconds / 60);\n    const hours = Math.floor(minutes / 60);\n\n    if (hours > 0) {\n      const remainingMinutes = minutes % 60;\n      return remainingMinutes > 0 ? `${hours}h ${remainingMinutes}m` : `${hours}h`;\n    }\n\n    if (minutes > 0) {\n      const remainingSeconds = seconds % 60;\n      return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;\n    }\n\n    // For times under a minute, show decimal precision for seconds\n    const preciseSeconds = (ms / 1000).toFixed(1);\n    return `${preciseSeconds}s`;\n  }\n}\n\n// Global display instance - single source of truth for terminal output\nexport const progressDisplay = new ProgressDisplay();\n","import { colorPalette } from '../../../../constants';\nimport type { DependencyGraph, NodeProcessingResult, ProcessingLevel, PushResults } from './types';\nimport { determineProcessingOrder } from './dependency-graph';\nimport { progressDisplay } from '../progress-display';\nimport { pushComponent } from '../actions';\nimport type { ComponentCreate } from '../../../../types';\nimport chalk from 'chalk';\nimport { getActiveConfig } from '../../../../lib/config';\n\n// =============================================================================\n// RESOURCE PROCESSING\n// =============================================================================\n\n/**\n * Processes all resources with 2-pass per level approach.\n */\nexport async function processAllResources(\n  graph: DependencyGraph,\n  space: string,\n\n  maxConcurrency: number = getActiveConfig().api.maxConcurrency,\n): Promise<PushResults> {\n  const levels = determineProcessingOrder(graph);\n  const results: PushResults = { successful: [], failed: [] };\n\n  // Calculate total resources for progress tracking\n  const totalResources = levels.reduce((sum, level) => sum + level.nodes.length, 0);\n\n  // Initialize progress display\n  progressDisplay.start(totalResources);\n\n  for (const level of levels) {\n    if (level.isCyclic) {\n      // Handle circular dependencies with stub creation\n      const cyclicResults = await processCyclicLevel(level, graph, space, maxConcurrency);\n      mergeResults(results, cyclicResults);\n    }\n    else {\n      // Handle regular level\n      const levelResults = await processLevel(level.nodes, graph, space, maxConcurrency);\n      mergeResults(results, levelResults);\n    }\n  }\n\n  // Show completion summary using progress display\n  progressDisplay.handleEvent({\n    type: 'complete',\n    summary: {\n      updated: results.successful.length,\n      unchanged: 0, // No longer skip resources - all are processed\n      failed: results.failed.length,\n    },\n  });\n\n  return results;\n}\n\n/**\n * Processes a cyclic level with circular dependency handling.\n * Creates stub components for missing components in the cycle, then processes normally.\n */\nasync function processCyclicLevel(\n  level: ProcessingLevel,\n  graph: DependencyGraph,\n  space: string,\n  maxConcurrency: number,\n): Promise<PushResults> {\n  // Clear current progress display and show circular dependency message\n  progressDisplay.clearProgress();\n  console.log(`\\n🔄 Detected circular dependencies: ${level.nodes.map(id => id.replace('component:', '')).join(', ')}`);\n\n  // STEP 1: Create stub components for any missing components in the cycle\n  await createStubComponents(level.nodes, graph, space);\n\n  // STEP 2: Process the cyclic level normally (references can now resolve)\n  return await processLevel(level.nodes, graph, space, maxConcurrency);\n}\n\n/**\n * Creates stub components for missing components in circular dependencies.\n */\nasync function createStubComponents(\n  nodeIds: string[],\n  graph: DependencyGraph,\n  space: string,\n): Promise<void> {\n  const missingComponents: string[] = [];\n\n  for (const nodeId of nodeIds) {\n    const node = graph.nodes.get(nodeId);\n    if (node && node.type === 'component' && !node.targetData) {\n      missingComponents.push(node.name);\n    }\n  }\n\n  if (missingComponents.length === 0) {\n    return; // No missing components to create stubs for\n  }\n\n  console.log(`📝 Creating stub components for circular dependencies: ${missingComponents.join(', ')}`);\n\n  // Create minimal stub components\n  for (const nodeId of nodeIds) {\n    const node = graph.nodes.get(nodeId);\n    if (node && node.type === 'component' && !node.targetData) {\n      try {\n        const stubComponent = createMinimalStubComponent(node.name);\n        const result = await pushComponent(space, stubComponent);\n\n        if (result) {\n          // Update the node's target data so future references can resolve\n          node.updateTargetData(result);\n          console.log(`${chalk.green('✓')} Created stub component: ${node.name}`);\n        }\n      }\n      catch (error) {\n        console.error(`✗ Failed to create stub component ${node.name}:`, error);\n        throw error;\n      }\n    }\n  }\n\n  // Add a blank line before resuming normal processing\n  console.log('');\n}\n\n/**\n * Creates a minimal stub component with only required fields.\n */\nfunction createMinimalStubComponent(name: string): ComponentCreate {\n  return {\n    name,\n    display_name: name,\n    schema: {}, // Minimal empty schema\n  };\n}\n\n/**\n * Processes a single level of nodes using 2-pass approach:\n * Pass 1: Resolve references (dependencies from previous levels exist)\n * Pass 2: Process all resources with resolved references\n */\nasync function processLevel(\n  level: string[],\n  graph: DependencyGraph,\n  space: string,\n  maxConcurrency: number,\n): Promise<PushResults> {\n  // PASS 1: Resolve references for this level (now that dependencies from previous levels exist)\n  for (const nodeId of level) {\n    const node = graph.nodes.get(nodeId)!;\n    node.resolveReferences(graph);\n  }\n\n  // PASS 2: Process all nodes in this level with resolved references\n  const semaphore: Array<Promise<NodeProcessingResult> | null> = Array.from({ length: maxConcurrency }, () => null);\n  const promises: Promise<NodeProcessingResult>[] = [];\n\n  for (let i = 0; i < level.length; i++) {\n    const nodeId = level[i];\n\n    // Wait for an available slot\n    const slotIndex = i % maxConcurrency;\n    if (i >= maxConcurrency && semaphore[slotIndex]) {\n      await semaphore[slotIndex];\n    }\n\n    // Start processing the node\n    const promise = processNode(nodeId, graph, space);\n    promises.push(promise);\n    semaphore[slotIndex] = promise;\n  }\n\n  const results = await Promise.all(promises);\n  return aggregateResults(results);\n}\n\n/**\n * Process node with resolved references\n */\nasync function processNode(\n  nodeId: string,\n  graph: DependencyGraph,\n  space: string,\n): Promise<NodeProcessingResult> {\n  const node = graph.nodes.get(nodeId)!;\n  // Track start time for individual process timing\n  const startTime = Date.now();\n\n  try {\n    // Always perform upsert - change detection removed due to unstable ID issues\n    // Create/update the resource with resolved references\n    const result = await node.upsert(space);\n    node.updateTargetData(result);\n\n    const elapsedMs = Date.now() - startTime;\n    progressDisplay.handleEvent({\n      type: 'success',\n      name: node.getName(),\n      resourceType: getResourceTypeName(node.type),\n      color: getResourceTypeColor(node.type),\n      elapsedMs,\n    });\n\n    return { name: node.getName() };\n  }\n  catch (error) {\n    const elapsedMs = Date.now() - startTime;\n    progressDisplay.handleEvent({\n      type: 'error',\n      name: node.getName(),\n      resourceType: getResourceTypeName(node.type),\n      error,\n      elapsedMs,\n    });\n    return { name: node.getName(), error };\n  }\n}\n\n/**\n * Aggregates results from multiple node processing operations\n */\nfunction aggregateResults(results: NodeProcessingResult[]): PushResults {\n  const aggregated: PushResults = { successful: [], failed: [] };\n\n  for (const result of results) {\n    if (result.error) {\n      aggregated.failed.push({ name: result.name, error: result.error });\n    }\n    else {\n      aggregated.successful.push(result.name);\n    }\n  }\n\n  return aggregated;\n}\n\n/**\n * Merges results from multiple operations\n */\nfunction mergeResults(target: PushResults, source: PushResults): void {\n  target.successful.push(...source.successful);\n  target.failed.push(...source.failed);\n}\n\n/**\n * Gets display name for a resource type\n */\nfunction getResourceTypeName(type: string): string {\n  switch (type) {\n    case 'component': return 'component';\n    case 'group': return 'group';\n    case 'tag': return 'tag';\n    case 'preset': return 'preset';\n    default: return type;\n  }\n}\n\n/**\n * Gets color for a resource type\n */\nfunction getResourceTypeColor(type: string): string {\n  switch (type) {\n    case 'component': return colorPalette.COMPONENTS;\n    case 'group': return colorPalette.GROUPS;\n    case 'tag': return colorPalette.TAGS;\n    case 'preset': return colorPalette.PRESETS;\n    default: return colorPalette.COMPONENTS;\n  }\n}\n","import type { SpaceComponentsDataState } from '../../constants';\nimport type { GraphBuildingContext, PushResults } from './types';\n\nimport { buildDependencyGraph, validateGraph } from './dependency-graph';\nimport { processAllResources } from './resource-processor';\nimport { getActiveConfig } from '../../../../lib/config';\n\n// Re-export commonly used utilities\nexport type { PushResults } from './types';\n\n// =============================================================================\n// MAIN COORDINATOR\n// =============================================================================\n\n/**\n * Main function to push components using graph-based dependency resolution.\n *\n * Architecture:\n * - Build dependency graph with colocated target data\n * - For each level: resolve references then process resources\n * - Target data is embedded in each graph node for efficient upserts\n *\n * Benefits:\n * - Deterministic processing order\n * - References resolved when dependencies exist\n * - Clean behavioral node abstraction with colocated data\n * - Robust error handling and progress tracking\n */\nexport async function pushWithDependencyGraph(\n  space: string,\n  spaceState: SpaceComponentsDataState,\n\n  maxConcurrency: number = getActiveConfig().api.maxConcurrency,\n): Promise<PushResults> {\n  // Build and validate the dependency graph with colocated target data\n  const context: GraphBuildingContext = { spaceState };\n  const graph = buildDependencyGraph(context);\n  validateGraph(graph);\n\n  // Process all resources using the dependency graph\n  const results = await processAllResources(graph, space, maxConcurrency);\n\n  return results;\n}\n","import type { PushComponentsOptions } from './constants';\nimport type { Command } from 'commander';\n\nimport { colorPalette, commands } from '../../../constants';\nimport { CommandError, handleError, requireAuthentication } from '../../../utils';\nimport { session } from '../../../session';\nimport { deleteComponentPreset, readComponentsFiles } from './actions';\nimport { componentsCommand } from '../command';\nimport { filterSpaceDataByComponent, filterSpaceDataByPattern } from './utils';\nimport { pushWithDependencyGraph } from './graph-operations';\nimport chalk from 'chalk';\nimport { getMapiClient } from '../../../api';\nimport { fetchComponentGroups, fetchComponentInternalTags, fetchComponentPresets, fetchComponents } from '../actions';\nimport type { Component, ComponentFolder, InternalTag, Preset, SpaceComponentsData, SpaceComponentsDataState } from '../constants';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\n\nconst pushCmd = componentsCommand\n  .command('push [componentName]')\n  .description(`Push your space's components schema as json`)\n  .option('-f, --from <from>', 'source space id')\n  .option('--fi, --filter <filter>', 'glob filter to apply to the components before pushing')\n  .option('--sf, --separate-files', 'Read from separate files instead of consolidated files', false)\n  .option('--su, --suffix <suffix>', 'Load only files matching *.<suffix>.json (e.g. components.dev.json)')\n  .option('-s, --space <space>', 'space ID');\n\npushCmd\n  .action(async (componentName: string | undefined, options: PushComponentsOptions, command: Command) => {\n    const ui = getUI();\n    const logger = getLogger();\n\n    ui.title(`${commands.COMPONENTS}`, colorPalette.COMPONENTS, componentName ? `Pushing component ${componentName}...` : 'Pushing components...');\n\n    const { space, path, verbose } = command.optsWithGlobals();\n\n    const { filter } = options;\n    const fromSpace = options.from || space;\n\n    // Check if the user is logged in\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n\n    // Check if the space is provided\n    if (!space) {\n      handleError(new CommandError(`Please provide the target space as argument --space TARGET_SPACE_ID.`), verbose);\n      return;\n    }\n\n    logger.info('Pushing components started', { space, fromSpace, componentName });\n\n    ui.info(`Attempting to push components ${chalk.bold('from')} space ${chalk.hex(colorPalette.COMPONENTS)(fromSpace)} ${chalk.bold('to')} ${chalk.hex(colorPalette.COMPONENTS)(space)}`);\n    ui.br();\n\n    let requestCount = 0;\n\n    const client = getMapiClient();\n\n    client.interceptors.request.use((config) => {\n      requestCount++;\n      return config;\n    });\n\n    try {\n      // Read components data from source space (from option or target space)\n      const componentsData = await readComponentsFiles({\n        ...options,\n        path,\n        from: fromSpace,\n      });\n\n      // Combine into the expected structure\n      // Note: Datasources are not managed by the components push command\n      const localData: SpaceComponentsData = {\n        ...componentsData,\n        datasources: [],\n      };\n\n      const spaceState: SpaceComponentsDataState = {\n        local: localData,\n        target: {\n          components: new Map(),\n          groups: new Map(),\n          tags: new Map(),\n          presets: new Map(),\n          datasources: new Map(),\n        },\n      };\n\n      // Target space data\n      const promises = [\n        fetchComponents(space),\n        fetchComponentGroups(space),\n        fetchComponentPresets(space),\n        fetchComponentInternalTags(space),\n      ];\n      const [components, groups, presets, internalTags] = await Promise.all(promises);\n\n      if (components) {\n        (components as Component[]).forEach((component) => {\n          spaceState.target.components.set(component.name, component);\n        });\n      }\n\n      if (groups) {\n        (groups as ComponentFolder[]).forEach((group) => {\n          spaceState.target.groups.set(group.name, group);\n        });\n      }\n\n      if (presets) {\n        (presets as Preset[]).forEach((preset) => {\n          // Find the parent component for this nested preset resource\n          const targetComponent = (components as Component[])?.find(c => c.id === preset.component_id);\n          if (targetComponent) {\n            // Store presets using hierarchical key: component.name:preset.name (parent:child)\n            // This reflects the nested resource relationship where presets are scoped to components\n            const compositeKey = `${targetComponent.name}:${preset.name}`;\n            spaceState.target.presets.set(compositeKey, preset);\n          }\n        });\n      }\n\n      if (internalTags) {\n        (internalTags as InternalTag[]).forEach((tag) => {\n          spaceState.target.tags.set(tag.name, tag);\n        });\n      }\n\n      // If componentName is provided, filter space data to only include related resources\n      if (componentName) {\n        spaceState.local = filterSpaceDataByComponent(spaceState.local, componentName);\n        if (!spaceState.local.components.length) {\n          handleError(new CommandError(`Component \"${componentName}\" not found.`), verbose);\n          return;\n        }\n      }\n      // If filter pattern is provided, filter space data to match the pattern\n      else if (filter) {\n        spaceState.local = filterSpaceDataByPattern(spaceState.local, filter);\n        if (!spaceState.local.components.length) {\n          handleError(new CommandError(`No components found matching pattern \"${filter}\".`), verbose);\n          return;\n        }\n        ui.info(`Filter applied: ${filter}`);\n      }\n\n      if (!spaceState.local.components.length) {\n        ui.warn('No components found. Please make sure you have pulled the components first.');\n        return;\n      }\n\n      const results = {\n        successful: [] as string[],\n        failed: [] as Array<{ name: string; error: unknown }>,\n      };\n\n      // Build local preset keys BEFORE graph processing (which mutates component_id references)\n      const localComponentById = new Map(spaceState.local.components.map(c => [c.id, c.name]));\n      const localPresetKeys = new Set<string>();\n      for (const preset of spaceState.local.presets) {\n        const componentName = localComponentById.get(preset.component_id);\n        if (componentName) {\n          localPresetKeys.add(`${componentName}:${preset.name}`);\n        }\n      }\n\n      // Use optimized graph-based dependency resolution with colocated target data\n      ui.info('Using graph-based dependency resolution');\n      const graphResults = await pushWithDependencyGraph(space, spaceState);\n      results.successful.push(...graphResults.successful);\n      results.failed.push(...graphResults.failed);\n\n      // Reconcile presets: delete stale presets only for components that were pushed successfully\n      const successfulNames = new Set(results.successful);\n      for (const [compositeKey, targetPreset] of spaceState.target.presets) {\n        const separatorIndex = compositeKey.indexOf(':');\n        const componentName = compositeKey.substring(0, separatorIndex);\n\n        if (successfulNames.has(componentName) && !localPresetKeys.has(compositeKey)) {\n          try {\n            await deleteComponentPreset(space, targetPreset.id);\n            ui.info(`Deleted stale preset: ${chalk.hex(colorPalette.PRESETS)(compositeKey)}`);\n          }\n          catch (error) {\n            results.failed.push({ name: compositeKey, error });\n          }\n        }\n      }\n\n      if (results.failed.length > 0) {\n        if (!verbose) {\n          ui.br();\n          ui.info('For more information about the error, run the command with the `--verbose` flag');\n        }\n        else {\n          results.failed.forEach((failed) => {\n            handleError(failed.error as Error, verbose);\n          });\n        }\n      }\n      console.log(`${requestCount} requests made`);\n\n      // Check if components reference datasources and inform user\n      const referencedDatasources = new Set<string>();\n      spaceState.local.components.forEach((component) => {\n        if (component.schema) {\n          const fields = JSON.stringify(component.schema);\n          const datasourceMatches = fields.match(/\"datasource_slug\"\\s*:\\s*\"([^\"]+)\"/g);\n          if (datasourceMatches) {\n            datasourceMatches.forEach((match) => {\n              const slug = match.match(/\"([^\"]+)\"$/)?.[1];\n              if (slug) {\n                referencedDatasources.add(slug);\n              }\n            });\n          }\n        }\n      });\n\n      if (referencedDatasources.size > 0) {\n        ui.br();\n        ui.info(`Components reference datasources: ${chalk.yellow(Array.from(referencedDatasources).join(', '))}`);\n        ui.info(`To manage datasources, use: ${chalk.cyan('storyblok datasources push')}`);\n      }\n    }\n    catch (error) {\n      handleError(error as Error, verbose);\n    }\n    finally {\n      logger.info('Pushing components finished', { space, fromSpace, componentName });\n    }\n  });\n","import type { CommandOptions } from '../../types';\n\nexport const DEFAULT_LANGUAGES_FILENAME = 'languages';\n\n/**\n * Interface representing the options for the `pull-languages` command.\n */\nexport interface PullLanguagesOptions extends CommandOptions {\n  /**\n   * The path to save the languages file to.\n   * Defaults to `.storyblok/languages`.\n   * @default `.storyblok/languages`\n   */\n  path?: string;\n  /**\n   * The space ID.\n   * @required true\n   */\n  space: string;\n  /**\n   * The filename to save the file as.\n   * Defaults to `DEFAULT_LANGUAGES_FILENAME`. The file will be saved as `<filename>.<space>.json`.\n   * @default DEFAULT_LANGUAGES_FILENAME\n   */\n  filename?: string;\n  /**\n   * The suffix to add to the filename.\n   * Defaults to the space ID.\n   * @default space\n   */\n  suffix?: string;\n}\n","import type { Space, SpaceCreate, SpaceUpdate } from '../../types';\nimport { handleAPIError } from '../../utils';\nimport { getMapiClient } from '../../api';\n\nexport type { Space, SpaceCreate, SpaceUpdate };\n\nexport const fetchSpace = async (spaceId: string): Promise<Space | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.spaces.get({\n      path: {\n        space_id: Number(spaceId),\n      },\n      throwOnError: true,\n    });\n\n    return data?.space;\n  }\n  catch (error) {\n    handleAPIError('pull_spaces', error as Error, `Failed to fetch space ${spaceId}`);\n  }\n};\n\n/**\n * Creates a new space using the Storyblok Management API\n * @param space - The space creation request data\n * @returns Promise<Space> - The created space data\n */\nexport const createSpace = async (space: SpaceCreate): Promise<Space | undefined> => {\n  try {\n    const client = getMapiClient();\n    const { data } = await client.spaces.create({\n      body: {\n        space,\n      },\n    });\n\n    return data?.space;\n  }\n  catch (error) {\n    handleAPIError('create_space', error as Error, `Failed to create space ${space.name}`);\n  }\n};\n","import { join } from 'pathe';\nimport { handleAPIError, handleFileSystemError } from '../../utils';\nimport { resolvePath, saveToFile } from '../../utils/filesystem';\nimport type { PullLanguagesOptions } from './constants';\nimport { DEFAULT_LANGUAGES_FILENAME } from './constants';\nimport type { SpaceInternationalization } from '../../types';\nimport { fetchSpace } from '../spaces';\n\nexport const fetchLanguages = async (spaceId: string): Promise<SpaceInternationalization | undefined> => {\n  try {\n    const space = await fetchSpace(spaceId);\n    if (space?.default_lang_name !== undefined && space?.languages?.length) {\n      return {\n        default_lang_name: space?.default_lang_name,\n        languages: space?.languages,\n      };\n    }\n  }\n  catch (error) {\n    handleAPIError('pull_languages', error);\n  }\n};\n\nexport const saveLanguagesToFile = async (space: string, internationalizationOptions: SpaceInternationalization, options: PullLanguagesOptions) => {\n  try {\n    const { filename = DEFAULT_LANGUAGES_FILENAME, suffix, path } = options;\n    const data = JSON.stringify(internationalizationOptions, null, 2);\n    const name = suffix ? `${filename}.${suffix}.json` : `${filename}.json`;\n    const resolvedPath = resolvePath(path, `languages/${space}/`);\n    const filePath = join(resolvedPath, name);\n\n    await saveToFile(filePath, data);\n  }\n  catch (error) {\n    handleFileSystemError('write', error as Error);\n  }\n};\n","import type { Command } from 'commander';\nimport { colorPalette, commands } from '../../constants';\nimport { CommandError, handleError, isVitest, konsola, requireAuthentication } from '../../utils';\nimport { getProgram } from '../../program';\nimport { session } from '../../session';\nimport { fetchLanguages, saveLanguagesToFile } from './actions';\nimport chalk from 'chalk';\nimport type { PullLanguagesOptions } from './constants';\nimport { Spinner } from '@topcli/spinner';\nimport { isAbsolute, join, relative } from 'pathe';\nimport { resolveCommandPath } from '../../utils/filesystem';\n\nconst program = getProgram(); // Get the shared singleton instance\n\nexport const languagesCommand = program\n  .command(commands.LANGUAGES)\n  .alias('lang')\n  .description(`Manage your space's languages`);\n\nconst pullCmd = languagesCommand\n  .command('pull')\n  .description(`Download your space's languages schema as json`)\n  .option('-f, --filename <filename>', 'filename to save the file as <filename>.<suffix>.json')\n  .option('--su, --suffix <suffix>', 'suffix to add to the file name (e.g. languages.<suffix>.json). By default, the space ID is used.')\n  .option('-s, --space <space>', 'space ID');\n\npullCmd\n  .action(async (options: PullLanguagesOptions, command: Command) => {\n    konsola.title(`${commands.LANGUAGES}`, colorPalette.LANGUAGES);\n\n    const { space, path, verbose } = command.optsWithGlobals();\n    const { filename = 'languages', suffix = options.space } = options;\n\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n    if (!space) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      return;\n    }\n\n    const spinner = new Spinner({\n      verbose: !isVitest,\n    });\n    try {\n      spinner.start(`Fetching ${chalk.hex(colorPalette.LANGUAGES)('languages')}`);\n\n      const internationalization = await fetchLanguages(space);\n\n      if (!internationalization || internationalization.languages?.length === 0) {\n        spinner.failed();\n\n        konsola.warn(`No languages found in the space ${space}`, true);\n        konsola.br();\n        return;\n      }\n      await saveLanguagesToFile(space, internationalization, {\n        ...options,\n        path,\n        filename,\n        suffix,\n      });\n      const languagesOutputDir = resolveCommandPath('languages', space, path);\n      const fileName = suffix ? `${filename}.${suffix}.json` : `${filename}.json`;\n      const filePath = join(languagesOutputDir, fileName);\n      const displayPath = (path && isAbsolute(path)) ? filePath : relative(process.cwd(), filePath);\n      spinner.succeed();\n      konsola.ok(`Languages schema downloaded successfully at ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`, true);\n    }\n    catch (error) {\n      spinner.failed();\n      konsola.br();\n      handleError(error as Error, verbose);\n    }\n    konsola.br();\n  });\n","import { commands } from '../../constants';\nimport { getProgram } from '../../program';\n\nconst program = getProgram(); // Get the shared singleton instance\n\n// Components root command\nexport const migrationsCommand = program\n  .command(commands.MIGRATIONS)\n  .alias('mig')\n  .description(`Manage your space's migrations`);\n","import { resolvePath, saveToFile } from '../../../utils/filesystem';\nimport type { Component } from '../../components/constants';\nimport { join } from 'pathe';\nimport { handleFileSystemError } from '../../../utils';\n\nconst getMigrationTemplate = () => {\n  return `export default function (block) {\n  // Example to change a string to boolean\n  // block.field_name = !!(block.field_name)\n\n  // Example to transfer content from other field\n  // block.target_field = block.source_field\n\n  // Example to transform an array\n  // block.array_field = block.array_field.map(item => ({ ...item, new_prop: 'value' }))\n\n  return block;\n}\n`;\n};\n\nexport const generateMigration = async (space: string, path: string | undefined, component: Component, suffix?: string) => {\n  const resolvedPath = resolvePath(path, `migrations/${space}`);\n\n  const fileName = suffix ? `${component.name}.${suffix}.js` : `${component.name}.js`;\n  const migrationPath = join(resolvedPath, fileName);\n\n  try {\n    await saveToFile(migrationPath, getMigrationTemplate());\n  }\n  catch (error) {\n    handleFileSystemError('write', error as Error);\n  }\n};\n","import type { Command } from 'commander';\nimport chalk from 'chalk';\n\nimport type { MigrationsGenerateOptions } from './constants';\nimport { colorPalette, commands } from '../../../constants';\nimport { CommandError, handleError, requireAuthentication } from '../../../utils';\nimport { session } from '../../../session';\nimport { fetchComponent } from '../../../commands/components';\nimport { migrationsCommand } from '../command';\nimport { generateMigration } from './actions';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\n\nconst generateCmd = migrationsCommand\n  .command('generate [componentName]')\n  .description('Generate a migration file')\n  .option('--su, --suffix <suffix>', 'suffix to add to the file name (e.g. {component-name}.<suffix>.js)')\n  .option('-s, --space <space>', 'space ID');\n\ngenerateCmd\n  .action(async (componentName: string | undefined, options: MigrationsGenerateOptions, command: Command) => {\n    const ui = getUI();\n    const logger = getLogger();\n\n    ui.title(`${commands.MIGRATIONS}`, colorPalette.MIGRATIONS, componentName ? `Generating migration for component ${componentName}...` : 'Generating migrations...');\n\n    const { space, path, verbose } = command.optsWithGlobals();\n    const { suffix } = options;\n\n    logger.info('Migration generation started', {\n      componentName,\n      space,\n      suffix,\n    });\n\n    if (!componentName) {\n      handleError(new CommandError(`Please provide the component name as argument ${chalk.hex(colorPalette.MIGRATIONS)('storyblok migrations generate YOUR_COMPONENT_NAME.')}`), verbose);\n      return;\n    }\n\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n    if (!space) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      return;\n    }\n\n    const spinner = ui.createSpinner(`Generating migration for component ${componentName}...`);\n    try {\n      const component = await fetchComponent(space, componentName);\n\n      if (!component) {\n        spinner.failed(`Failed to fetch component ${componentName}. Make sure the component exists in your space.`);\n        handleError(new CommandError(`No component found with name \"${componentName}\"`), verbose);\n        return;\n      }\n\n      await generateMigration(space, path, component, suffix);\n\n      spinner.succeed(`Migration generated for component ${chalk.hex(colorPalette.MIGRATIONS)(componentName)} - Completed in ${spinner.elapsedTime.toFixed(2)}ms`);\n\n      const fileName = suffix ? `${component.name}.${suffix}.js` : `${component.name}.js`;\n      const migrationPath = path ? `${path}/migrations/${space}/${fileName}` : `.storyblok/migrations/${space}/${fileName}`;\n      ui.ok(`You can find the migration file in ${chalk.hex(colorPalette.MIGRATIONS)(migrationPath)}`);\n\n      logger.info('Migration generation finished', {\n        componentName: component.name,\n        migrationPath,\n        space,\n        suffix,\n      });\n    }\n    catch (error) {\n      spinner.failed(`Failed to generate migration for component ${componentName}`);\n      handleError(error as Error, verbose);\n    }\n  });\n","import type { Story, StoryContent, StoryListQuery } from '../../types';\n\nexport type { Story, StoryContent };\n\n/**\n * Query parameters for retrieving multiple stories from the Management API.\n * Extends the MAPI StoryListQuery with an index signature to allow CLI-specific\n * ad-hoc parameters (e.g. filter_query[...] expansions).\n * @see https://www.storyblok.com/docs/api/management/core-resources/stories/retrieve-multiple-stories\n */\nexport type StoriesQueryParams = StoryListQuery & {\n  // Allow string indexing for dynamic filter_query parameters\n  [key: string]: string | number | boolean | undefined;\n};\n\nexport interface FetchStoriesResult {\n  stories: Story[];\n  headers: Headers;\n}\n\nexport type TargetStoryRef = Pick<Story, 'id' | 'uuid' | 'is_folder'>;\n\nexport interface ExistingTargetStories {\n  // folders and start_page can have the same slug, we need TargetStoryRef[]\n  bySlug: Map<string, TargetStoryRef[]>;\n  byId: Map<number, TargetStoryRef>;\n}\n\nexport interface StoryIndexEntry {\n  filename: string;\n  id: number | string;\n  uuid: string;\n  slug: string;\n  name: string;\n  full_slug: string;\n  is_folder: boolean;\n  is_startpage: boolean;\n  parent_id: number | string | null;\n  component?: string;\n}\n\nexport const normalizeFullSlug = (slug: string): string => slug.replace(/\\/$/, '');\n","import type { StoryCreate, StoryUpdate } from '../../types';\nimport type { ExistingTargetStories, FetchStoriesResult, StoriesQueryParams, Story, TargetStoryRef } from './constants';\nimport { normalizeFullSlug } from './constants';\nimport { getMapiClient } from '../../api';\nimport { chunk } from '../../utils/array';\nimport { handleAPIError } from '../../utils/error/api-error';\n\n/**\n * Fetches a single page of stories from Storyblok Management API\n * @param spaceId - The space ID\n * @param params - Optional query parameters for filtering stories\n * @returns Promise with an array of stories and response headers or undefined if error occurs\n */\nexport const fetchStories = async (\n  spaceId: string,\n  params?: StoriesQueryParams,\n): Promise<FetchStoriesResult | undefined> => {\n  try {\n    const client = getMapiClient();\n    const { data, response } = await client.stories.list({\n      path: {\n        space_id: Number(spaceId),\n      },\n      query: {\n        ...params,\n        per_page: params?.per_page || 100,\n        page: params?.page || 1,\n      },\n      throwOnError: true,\n    });\n\n    return {\n      stories: data.stories || [],\n      headers: response.headers,\n    };\n  }\n  catch (error) {\n    handleAPIError('pull_stories', error as Error);\n  }\n};\n\nexport const fetchStory = async (\n  spaceId: string,\n  storyId: string | number,\n) => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.stories.get(storyId, {\n      path: {\n        space_id: Number(spaceId),\n      },\n      throwOnError: true,\n    });\n\n    return data.story;\n  }\n  catch (error) {\n    handleAPIError('pull_story', error as Error);\n  }\n};\n\nexport const createStory = async (\n  spaceId: string,\n  payload: {\n    story: StoryCreate;\n    publish?: number;\n  },\n): Promise<Story | void> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.stories.create({\n      path: {\n        space_id: Number(spaceId),\n      },\n      body: {\n        story: {\n          ...payload.story,\n          // StoryCreate2 expects `parent_id?: number`; normalize null → undefined.\n          parent_id: payload.story.parent_id ?? undefined,\n        },\n        ...(payload.publish ? { publish: payload.publish } : {}),\n      },\n      throwOnError: true,\n    });\n\n    return data?.story;\n  }\n  catch (error) {\n    handleAPIError('create_story', error);\n  }\n};\n\n/**\n * Updates a story in Storyblok with new content\n * @param spaceId - The space ID\n * @param storyId - The ID of the story to update\n * @param payload - The payload containing story data and update options\n * @param payload.story - The story data to update\n * @param payload.force_update - Whether to force the update (optional)\n * @param payload.publish - Whether to publish the story (optional)\n * @returns Promise with the updated story\n */\nexport const updateStory = async (\n  spaceId: string,\n  storyId: number,\n  payload: {\n    story: StoryUpdate;\n    force_update?: string;\n    publish?: number;\n  },\n) => {\n  try {\n    const client = getMapiClient();\n    const { data } = await client.stories.update(storyId, {\n      path: {\n        space_id: Number(spaceId),\n      },\n      body: {\n        story: {\n          ...payload.story,\n          // StoryUpdate2 expects `parent_id?: number`; normalize null → undefined.\n          parent_id: payload.story.parent_id ?? undefined,\n        },\n        force_update: payload.force_update === '1' ? '1' : '0',\n        ...(payload.publish ? { publish: payload.publish } : {}),\n      },\n      throwOnError: true,\n    });\n\n    const story = data?.story;\n    if (!story) {\n      throw new Error('Failed to update story');\n    }\n\n    return story;\n  }\n  catch (error) {\n    if (error instanceof Error && error.message === 'Failed to update story') {\n      throw error;\n    }\n    handleAPIError('update_story', error);\n  }\n};\n\n// 100 keys per chunk: matches MAPI's `per_page=100` so id queries fill a page\n// exactly (1 result per id) and slug queries paginate when folder + startpage\n// pairs push the result count above one page. At ~30 char slugs, 100 entries\n// ≈ 3 KB — well below typical URL length limits.\nconst PREFETCH_CHUNK_SIZE = 100;\nconst PREFETCH_PER_PAGE = 100;\n\nconst addRef = (result: ExistingTargetStories, story: Story): void => {\n  const ref: TargetStoryRef = { id: story.id, uuid: story.uuid, is_folder: story.is_folder };\n  if (story.full_slug) {\n    const key = normalizeFullSlug(story.full_slug);\n    const existing = result.bySlug.get(key);\n    if (existing) {\n      // Avoid duplicates if the same story comes back via both by_slugs and by_ids.\n      if (!existing.some(r => r.id === ref.id)) {\n        existing.push(ref);\n      }\n    }\n    else {\n      result.bySlug.set(key, [ref]);\n    }\n  }\n  result.byId.set(story.id, ref);\n};\n\n/**\n * Fetches every page of a single chunk query (`by_slugs` / `by_ids`).\n * A 100-id chunk returns ≤100 stories and resolves in one page; a 100-slug\n * chunk may exceed 100 results when slugs match folder + startpage pairs.\n */\nconst fetchChunkAllPages = async (\n  spaceId: string,\n  params: StoriesQueryParams,\n  onPageStories: (stories: Story[]) => void,\n): Promise<void> => {\n  let page = 1;\n  while (true) {\n    const response = await fetchStories(spaceId, { ...params, page, per_page: PREFETCH_PER_PAGE });\n    if (!response) {\n      return;\n    }\n    onPageStories(response.stories);\n    const total = Number(response.headers.get('Total'));\n    const perPage = Number(response.headers.get('Per-Page')) || PREFETCH_PER_PAGE;\n    if (!Number.isFinite(total) || total <= page * perPage) {\n      return;\n    }\n    page++;\n  }\n};\n\n/**\n * Targeted prefetch: fetches only the remote stories that match the local push set,\n * either by `full_slug` (cross-space duplicate matching, same-space slug fallback)\n * or by numeric id (resume against a same-space manifest).\n *\n * Slug and id batches are dispatched concurrently through the MAPI client's\n * existing throttle (default `maxConcurrency = 6`, adapts to the server's\n * `X-RateLimit-Policy` header, auto-retries 429).\n */\nexport const prefetchTargetStoriesByKeys = async (\n  spaceId: string,\n  keys: { slugs: Iterable<string>; ids: Iterable<number> },\n  options?: {\n    onTotal?: (total: number) => void;\n    onIncrement?: (count: number) => void;\n  },\n): Promise<ExistingTargetStories> => {\n  const result: ExistingTargetStories = {\n    bySlug: new Map(),\n    byId: new Map(),\n  };\n\n  const slugSet = new Set<string>();\n  for (const slug of keys.slugs) {\n    if (slug) {\n      slugSet.add(normalizeFullSlug(slug));\n    }\n  }\n  const idSet = new Set<number>();\n  for (const id of keys.ids) {\n    if (typeof id === 'number' && Number.isFinite(id)) {\n      idSet.add(id);\n    }\n  }\n\n  options?.onTotal?.(slugSet.size + idSet.size);\n\n  if (slugSet.size === 0 && idSet.size === 0) {\n    return result;\n  }\n\n  const slugChunks = chunk(slugSet, PREFETCH_CHUNK_SIZE);\n  const idChunks = chunk(idSet, PREFETCH_CHUNK_SIZE);\n\n  const requests: Array<Promise<void>> = [];\n\n  for (const slugs of slugChunks) {\n    requests.push((async () => {\n      await fetchChunkAllPages(spaceId, { by_slugs: slugs.join(',') }, (stories) => {\n        for (const story of stories) {\n          addRef(result, story);\n        }\n      });\n      options?.onIncrement?.(slugs.length);\n    })());\n  }\n\n  for (const ids of idChunks) {\n    requests.push((async () => {\n      await fetchChunkAllPages(spaceId, { by_ids: ids.join(',') }, (stories) => {\n        for (const story of stories) {\n          addRef(result, story);\n        }\n      });\n      options?.onIncrement?.(ids.length);\n    })());\n  }\n\n  await Promise.all(requests);\n  return result;\n};\n","import type { CommandOptions } from '../../../types';\nimport type { StoryContent } from '../../stories/constants';\n\nexport interface MigrationsRunOptions extends CommandOptions {\n  dryRun?: boolean;\n  filter?: string;\n  /**\n   * The source space id to read migration files from.\n   */\n  from?: string;\n  query?: string;\n  startsWith?: string;\n  publish?: 'all' | 'published' | 'published-with-changes';\n}\n\nexport interface ReadMigrationFilesOptions {\n  space: string;\n  path: string;\n  filter?: string;\n}\n\nexport interface MigrationFile {\n  name: string;\n}\n\nexport interface MigrationResult {\n  successful: SuccessfulMigration[];\n  failed: FailedMigration[];\n  skipped: SkippedMigration[];\n}\n\nexport interface SuccessfulMigration {\n  storyId: number;\n  name: string | undefined;\n  migrationNames: string[];\n  content: StoryContent;\n}\n\nexport interface FailedMigration {\n  storyId: number;\n  migrationNames: string[];\n  error: unknown;\n}\n\nexport interface SkippedMigration {\n  storyId: number;\n  name: string | undefined;\n  migrationNames: string[];\n  reason: string;\n}\n\nexport const ERROR_CODES = {\n  MIGRATION_APPLY_TO_STORY_ERROR: 'MIGRATION_APPLY_TO_STORY_ERROR',\n  MIGRATION_CREATE_STORIES_PIPELINE_ERROR: 'MIGRATION_CREATE_STORIES_PIPELINE_ERROR',\n  MIGRATION_FILE_NO_DEFAULT_EXPORT: 'MIGRATION_FILE_NO_DEFAULT_EXPORT',\n  MIGRATION_FILE_NOT_FOUND: 'MIGRATION_FILE_NOT_FOUND',\n  MIGRATION_LOAD_ERROR: 'MIGRATION_LOAD_ERROR',\n  MIGRATION_STORY_CONTENT_MISSING: 'MIGRATION_STORY_CONTENT_MISSING',\n  MIGRATION_STORY_FETCH_ERROR: 'MIGRATION_STORY_FETCH_ERROR',\n  MIGRATION_STORY_UPDATE_ERROR: 'MIGRATION_STORY_UPDATE_ERROR',\n  MIGRATION_STORY_UPDATE_NULL: 'MIGRATION_STORY_UPDATE_NULL',\n};\n","import { pipeline, Readable, Transform } from 'node:stream';\nimport { Sema } from 'async-sema';\nimport { fetchStories, fetchStory } from '../../../stories/actions';\nimport type { StoriesQueryParams, Story } from '../../../stories/constants';\nimport { handleAPIError, toError } from '../../../../utils/error';\nimport { getLogger } from '../../../../lib/logger/logger';\nimport { ERROR_CODES } from '../constants';\n\n/**\n * Iterator that fetches stories\n */\nexport async function* storiesIterator(\n  spaceId: string,\n  params?: StoriesQueryParams,\n  onTotal?: (total: number) => void,\n) {\n  try {\n    let perPage = 500;\n\n    // Apply the same parameter transformations as fetchAllStoriesByComponent\n    const transformedParams: StoriesQueryParams = {\n      ...params,\n    };\n\n    // Handle component filter - convert componentName to contain_component\n    if (params?.componentName && typeof params.componentName === 'string') {\n      transformedParams.contain_component = params.componentName;\n      delete transformedParams.componentName;\n    }\n\n    // Handle query string if provided - add filter_query prefix\n    if (params?.query && typeof params.query === 'string') {\n      transformedParams.filter_query = params.query.startsWith('filter_query')\n        ? params.query\n        : `filter_query${params.query}`;\n      delete transformedParams.query;\n    }\n\n    // Fetch first page to get total pages\n    const result = await fetchStories(spaceId, {\n      ...transformedParams,\n      per_page: perPage,\n      page: 1,\n      story_only: true,\n    });\n    getLogger().info(`Fetched stories page 1 of ${perPage}`);\n\n    if (!result) {\n      return;\n    }\n\n    const { headers } = result;\n    const total = Number(headers.get('Total'));\n    perPage = Number(headers.get('Per-Page'));\n    const totalPages = Math.ceil(Number(total) / perPage);\n\n    if (onTotal) {\n      onTotal(total);\n    }\n\n    for (let page = 1; page <= totalPages; page++) {\n      const result = await fetchStories(spaceId, {\n        ...transformedParams,\n        per_page: perPage,\n        page,\n        story_only: true,\n      });\n      getLogger().info(`Fetched stories page ${page} of ${perPage}`);\n\n      if (!result) {\n        return;\n      }\n\n      const { stories } = result;\n      for (const story of stories) {\n        yield story;\n      }\n    }\n  }\n  catch (error) {\n    handleAPIError('pull_stories', error as Error);\n  }\n}\n\n/**\n * Given a stream of stories, fetches the content for each story and streams the full story.\n * This is necessary because the content is not included in the stories stream.\n */\nclass StoriesStream extends Transform {\n  private semaphore: Sema;\n\n  constructor(private spaceId: string, private batchSize: number, private onProgress?: () => void) {\n    super({\n      objectMode: true,\n    });\n\n    this.semaphore = new Sema(this.batchSize);\n  }\n\n  async _transform(chunk: Omit<Story, 'content'>, _encoding: string, callback: (error?: Error | null, data?: any) => void) {\n    try {\n      await this.semaphore.acquire();\n      const story = await fetchStory(this.spaceId, chunk.id.toString());\n      this.push(story);\n      this.onProgress?.();\n      getLogger().info('Fetched story', { storyId: chunk.id });\n      callback();\n    }\n    catch (maybeError) {\n      const error = toError(maybeError);\n      getLogger().error(error.message, { storyId: chunk.id, error, errorCode: ERROR_CODES.MIGRATION_STORY_FETCH_ERROR });\n      callback(error);\n    }\n    finally {\n      this.semaphore.release();\n    }\n  }\n\n  _flush(callback: (error?: Error | null) => void) {\n    // Process any remaining stories in the batch\n    this.semaphore.drain().then(() => {\n      callback();\n    });\n  }\n}\n\n/**\n * Creates a stream of stories\n */\nexport const createStoriesStream = async ({\n  spaceId,\n  params,\n  batchSize = 100,\n  onTotal,\n  onProgress,\n}: {\n  spaceId: string;\n  params: StoriesQueryParams;\n  batchSize: number;\n  onTotal: (total: number) => void;\n  onProgress: () => void;\n}): Promise<Readable> => {\n  const iterator = storiesIterator(spaceId, params, onTotal);\n  const listStoriesStream = Readable.from(iterator);\n  return pipeline(listStoriesStream, new StoriesStream(spaceId, batchSize, onProgress), (err) => {\n    if (err) {\n      console.error(err);\n      getLogger().error(err.message, { errorCode: ERROR_CODES.MIGRATION_CREATE_STORIES_PIPELINE_ERROR });\n    }\n  });\n};\n","import { readdir } from 'node:fs/promises';\nimport { importModule, resolvePath } from '../../../utils/filesystem';\nimport { FileSystemError, toError } from '../../../utils/error';\nimport { join } from 'pathe';\nimport { ERROR_CODES, type MigrationFile, type ReadMigrationFilesOptions } from './constants';\nimport { createRegexFromGlob } from '../../../utils';\nimport type { StoryContent } from '../../stories/constants';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\n\nexport async function readMigrationFiles(options: ReadMigrationFilesOptions): Promise<MigrationFile[]> {\n  const { space, path, filter } = options;\n  const resolvedPath = resolvePath(path, `migrations/${space}`);\n\n  try {\n    const dirFiles = await readdir(resolvedPath);\n    const migrationFiles: MigrationFile[] = [];\n    const filterRegex = filter ? createRegexFromGlob(filter) : null;\n\n    if (dirFiles.length > 0) {\n      for (const file of dirFiles) {\n        if (!file.endsWith('.js')) {\n          continue;\n        }\n\n        // Apply glob filter if provided\n        if (filterRegex && !filterRegex.test(file)) {\n          continue;\n        }\n\n        migrationFiles.push({\n          name: file,\n        });\n      }\n    }\n\n    return migrationFiles;\n  }\n  catch (error) {\n    const message = `No directory found for space \"${space}\". Please make sure you have generated migrations first by running:\\n\\n  storyblok migrations generate YOUR_COMPONENT_NAME --space ${space}`;\n    throw new FileSystemError(\n      'file_not_found',\n      'read',\n      error as Error,\n      message,\n    );\n  }\n}\n\n/**\n * Loads a migration function from a file using dynamic import\n * @param fileName - The name of the migration file\n * @param space - The space ID\n * @param basePath - The base path for migrations\n * @returns The migration function or null if loading failed\n */\nexport async function getMigrationFunction(fileName: string, space: string, basePath: string): Promise<((block: any) => any) | null> {\n  try {\n    const resolvedPath = resolvePath(basePath, `migrations/${space}`);\n    const filePath = join(resolvedPath, fileName);\n    const migrationModule = await importModule(filePath);\n\n    // Get the default export which should be the migration function\n    if (typeof migrationModule.default === 'function') {\n      return migrationModule.default;\n    }\n\n    getUI().error(`Migration file \"${fileName}\" does not export a default function.`);\n    getLogger().error('Migration file does not export a default function', {\n      fileName,\n      errorCode: ERROR_CODES.MIGRATION_FILE_NO_DEFAULT_EXPORT,\n    });\n    return null;\n  }\n  catch (maybeError) {\n    const error = toError(maybeError);\n    getUI().error(`Error loading migration function from \"${fileName}\": ${error.message}`);\n    getLogger().error('Couldn\\'t load migration function', {\n      fileName,\n      error,\n      errorCode: ERROR_CODES.MIGRATION_LOAD_ERROR,\n    });\n    return null;\n  }\n}\n\n/**\n * Recursively applies a migration function to all blocks in a content object that match the target component\n * @param content - The content object to process\n * @param migrationFunction - The migration function to apply\n * @param targetComponent - The component name to target for migration\n * @returns Whether any blocks were modified\n */\nexport function applyMigrationToAllBlocks(content: StoryContent, migrationFunction: (block: StoryContent) => StoryContent, targetComponent: string): boolean {\n  let processed = false;\n\n  if (!content || typeof content !== 'object') {\n    return processed;\n  }\n\n  // Get the base component name (everything before the first dot)\n  const baseTargetComponent = targetComponent.split('.')[0];\n\n  // If the content has a component property and it matches the base component name\n  let migratedContent = null;\n  if (content.component === baseTargetComponent) {\n    migratedContent = migrationFunction({ ...content });\n    processed = true;\n  }\n\n  const uniqueKeys = new Set([...Object.keys(content), ...Object.keys(migratedContent || {})]);\n  for (const key of uniqueKeys) {\n    if (migratedContent) {\n      if (!(key in migratedContent)) {\n        delete content[key];\n        continue;\n      }\n      content[key] = migratedContent[key];\n    }\n\n    // Recursively process all properties that might contain nested blocks\n    // Process arrays (might contain blocks)\n    if (Array.isArray(content[key])) {\n      for (const value of content[key]) {\n        if (value && typeof value === 'object' && '_uid' in value && 'component' in value) {\n          const blockProcessed = applyMigrationToAllBlocks(value as StoryContent, migrationFunction, targetComponent);\n          processed = processed || blockProcessed;\n        }\n      }\n    }\n    // Process nested objects (might be blocks)\n    else if (content[key] && typeof content[key] === 'object' && '_uid' in (content[key] as object) && 'component' in (content[key] as object)) {\n      const blockProcessed = applyMigrationToAllBlocks(content[key] as unknown as StoryContent, migrationFunction, targetComponent);\n      processed = processed || blockProcessed;\n    }\n  }\n\n  return processed;\n}\n","import { join } from 'pathe';\nimport { appendToFile, getComponentNameFromFilename, resolvePath } from '../../../utils/filesystem';\nimport type { StoryContent } from '../../stories/constants';\nimport { readFile } from 'node:fs/promises';\nimport { CommandError } from '../../../utils';\n\nexport interface RollbackDataStory {\n  storyId: number;\n  name: string;\n  content: StoryContent;\n  published?: boolean;\n  unpublished_changes?: boolean;\n}\n\nexport interface RollbackData {\n  stories: RollbackDataStory[];\n}\n\n/**\n * Save the rollback data for a migration\n * @param options - Options for saving rollback data\n * @param options.space - The space ID\n * @param options.path - Base path for saving rollback data\n * @param options.story - Story with their original content\n * @param options.story.id - Story ID\n * @param options.story.name - Story name\n * @param options.story.content - Story content\n * @param options.story.published - Story publication status\n * @param options.story.unpublished_changes - Story unpublished changes status\n * @param options.migrationTimestamp - The timestamp when the migration started\n * @param options.migrationNames - Names of the migration files being applied\n */\nexport async function saveRollbackData({\n  space,\n  path,\n  story,\n  migrationTimestamp,\n  migrationNames,\n}: {\n  space: string;\n  path: string;\n  story: { id: number; name: string; content: StoryContent; published?: boolean; unpublished_changes?: boolean };\n  migrationTimestamp: number;\n  migrationNames: string[];\n}): Promise<void> {\n  const rollbackData: RollbackDataStory = {\n    storyId: story.id,\n    name: story.name,\n    content: story.content,\n    published: story.published,\n    unpublished_changes: story.unpublished_changes,\n  };\n\n  // Resolve the path for rollbacks\n  const rollbacksPath = resolvePath(path, `migrations/${space}/rollbacks`);\n  const componentNames = migrationNames.map(n => getComponentNameFromFilename(n));\n  // Deduplicate component names and join the component names for final rollback name\n  const rollbackName = [...new Set(componentNames)].join('~');\n  const rollbackFileName = `${rollbackName}.${migrationTimestamp}.jsonl`;\n  const rollbackFilePath = join(rollbacksPath, rollbackFileName);\n\n  // Save the rollback data as JSONL\n  await appendToFile(\n    rollbackFilePath,\n    JSON.stringify(rollbackData),\n  );\n}\n\n/**\n * Read rollback data from a file\n * @param options - Options for reading rollback data\n * @param options.space - The space ID\n * @param options.path - Base path for rollback files\n * @param options.migrationFile - Name of the migration file to rollback\n * @returns The rollback data containing stories to restore\n */\nexport async function readRollbackFile({\n  space,\n  path,\n  migrationFile,\n}: {\n  space: string;\n  path: string;\n  migrationFile: string;\n}): Promise<RollbackData> {\n  try {\n    const resolvedPath = resolvePath(path, `migrations/${space}/rollbacks`);\n    const rollbackFilePath = join(resolvedPath, migrationFile);\n\n    // Read the rollback file\n    const filePath = rollbackFilePath.endsWith('.jsonl')\n      ? rollbackFilePath\n      : `${rollbackFilePath}.jsonl`;\n\n    return {\n      stories: (await readFile(filePath, 'utf-8')).trim().split('\\n').filter(Boolean).map(x => JSON.parse(x)),\n    };\n  }\n  catch (error) {\n    throw new CommandError(`Failed to read rollback file: ${(error as Error).message}`);\n  }\n}\n","import { Transform } from 'node:stream';\nimport type { Story, StoryContent } from '../../../stories/constants';\nimport { ERROR_CODES, type FailedMigration, type MigrationFile, type SkippedMigration, type SuccessfulMigration } from '../constants';\nimport { applyMigrationToAllBlocks, getMigrationFunction } from '../actions';\nimport { getComponentNameFromFilename } from '../../../../utils/filesystem';\nimport { hash } from 'ohash';\nimport { saveRollbackData } from '../../rollback/actions';\nimport { getLogger } from '../../../../lib/logger/logger';\nimport { toError } from '../../../../utils/error';\n\nexport interface MigrationStreamOptions {\n  migrationFiles: MigrationFile[];\n  space: string;\n  /** Space id to read migration files from. Defaults to `space` when not set. */\n  sourceSpace: string;\n  path: string;\n  componentName?: string;\n  onProgress: (current: number) => void;\n  onTotal: (total: number) => void;\n}\n\nexport interface MigrationStreamResult {\n  successful: SuccessfulMigration[];\n  failed: FailedMigration[];\n  skipped: SkippedMigration[];\n  totalProcessed: number;\n}\n\n/**\n * Transform stream that processes stories and applies migrations to them\n * Outputs successful migration results for further processing by update streams\n */\nexport class MigrationStream extends Transform {\n  private timestamp: number = Date.now();\n  private results: MigrationStreamResult;\n  private migrationFunctions: Map<string, ((block: any) => any) | null> = new Map();\n  private totalProcessed: number = 0;\n\n  constructor(private options: MigrationStreamOptions) {\n    super({\n      objectMode: true,\n    });\n\n    this.results = {\n      successful: [],\n      failed: [],\n      skipped: [],\n      totalProcessed: 0,\n    };\n  }\n\n  async _transform(chunk: Story, _encoding: string, callback: (error?: Error | null, data?: any) => void) {\n    try {\n      const results = await this.processStory(chunk);\n\n      this.results.totalProcessed++;\n      this.options.onProgress?.(this.results.totalProcessed);\n\n      // Output successful migration results for further processing\n      if (results.length > 0) {\n        this.totalProcessed += results.length;\n        this.options.onTotal?.(this.totalProcessed);\n        for (const result of results) {\n          this.push(result);\n        }\n      }\n\n      callback();\n    }\n    catch (error) {\n      callback(error as Error);\n    }\n  }\n\n  private async getOrLoadMigrationFunction(migrationFile: MigrationFile) {\n    if (this.migrationFunctions.has(migrationFile.name)) {\n      return this.migrationFunctions.get(migrationFile.name);\n    }\n\n    const migrationFunction = await getMigrationFunction(\n      migrationFile.name,\n      this.options.sourceSpace,\n      this.options.path,\n    );\n    this.migrationFunctions.set(migrationFile.name, migrationFunction);\n\n    return migrationFunction;\n  }\n\n  private async processStory(story: Story): Promise<Array<{ storyId: number; name: string | undefined; content: StoryContent; published?: boolean; unpublished_changes?: boolean }>> {\n    // Filter migrations based on component name if provided\n    const relevantMigrations = this.options.componentName\n      ? this.options.migrationFiles.filter((file) => {\n          const targetComponent = getComponentNameFromFilename(file.name);\n          return targetComponent.split('.')[0] === this.options.componentName;\n        })\n      : this.options.migrationFiles;\n\n    if (!story.content) {\n      this.results.failed.push({\n        storyId: story.id,\n        migrationNames: relevantMigrations.map(m => m.name),\n        error: new Error('Story content is missing'),\n      });\n      getLogger().error('Failed to process story: Content is missing', {\n        storyId: story.id,\n        errorCode: ERROR_CODES.MIGRATION_STORY_CONTENT_MISSING,\n      });\n      return [];\n    }\n\n    const successfulResults: Array<{ storyId: number; name: string | undefined; content: StoryContent; published?: boolean; unpublished_changes?: boolean }> = [];\n\n    // Process each relevant migration\n    const result = await this.applyMigrationsToStory(story, relevantMigrations);\n    if (result) {\n      successfulResults.push(result);\n    }\n\n    return successfulResults;\n  }\n\n  private async applyMigrationsToStory(story: Story, migrationFiles: MigrationFile[]): Promise<{ storyId: number; name: string | undefined; content: StoryContent; published?: boolean; unpublished_changes?: boolean } | null> {\n    const migrationNames = migrationFiles.map(f => f.name);\n\n    try {\n      const storyContent = structuredClone(story.content) as StoryContent;\n      const originalContentHash = hash(storyContent);\n\n      let processed = false;\n      for (const migrationFile of migrationFiles) {\n        const migrationFunction = await this.getOrLoadMigrationFunction(migrationFile);\n        if (!migrationFunction) {\n          const error = new Error(`Failed to load migration function from file \"${migrationFile.name}\"`);\n          this.results.failed.push({\n            storyId: story.id,\n            migrationNames,\n            error,\n          });\n          getLogger().error(error.message, {\n            errorCode: ERROR_CODES.MIGRATION_FILE_NOT_FOUND,\n          });\n          return null;\n        }\n\n        const targetComponent = this.options.componentName || getComponentNameFromFilename(migrationFile.name);\n        const migrationProcessed = applyMigrationToAllBlocks(storyContent, migrationFunction, targetComponent);\n        processed = processed || migrationProcessed;\n      }\n\n      const newContentHash = hash(storyContent);\n      const contentChanged = originalContentHash !== newContentHash;\n\n      if (processed && contentChanged) {\n        // Save rollback data before applying migration\n        await saveRollbackData({\n          space: this.options.space,\n          path: this.options.path,\n          story: {\n            id: story.id,\n            name: story.name || '',\n            content: story.content as StoryContent,\n            published: story.published,\n            unpublished_changes: story.unpublished_changes,\n          },\n          migrationTimestamp: this.timestamp,\n          migrationNames,\n        });\n\n        this.results.successful.push({\n          storyId: story.id,\n          name: story.name,\n          migrationNames,\n          content: storyContent,\n        });\n        getLogger().info('Applied migration', { storyId: story.id, migrationNames });\n\n        return {\n          storyId: story.id,\n          name: story.name,\n          content: storyContent,\n          published: story.published,\n          unpublished_changes: story.unpublished_changes,\n        };\n      }\n      else if (processed && !contentChanged) {\n        this.results.skipped.push({\n          storyId: story.id,\n          name: story.name,\n          migrationNames,\n          reason: 'No changes detected after migration',\n        });\n        getLogger().info('Skipped migration: No changes detected', { storyId: story.id, migrationNames });\n        return null;\n      }\n      else {\n        const reason = migrationFiles.map((migrationFile) => {\n          const targetComponent = this.options.componentName || getComponentNameFromFilename(migrationFile.name);\n          const baseComponent = targetComponent.split('.')[0];\n          return baseComponent === this.options.componentName ? `No matching components found for ${migrationFile.name}` : `Different component target ${migrationFile.name}`;\n        }).join('\\n');\n\n        this.results.skipped.push({\n          storyId: story.id,\n          name: story.name,\n          migrationNames,\n          reason,\n        });\n        getLogger().info(`Skipped migration: ${reason}`, { storyId: story.id, migrationNames });\n        return null;\n      }\n    }\n    catch (maybeError) {\n      const error = toError(maybeError);\n      this.results.failed.push({\n        storyId: story.id,\n        migrationNames,\n        error,\n      });\n      getLogger().error(error.message, {\n        storyId: story.id,\n        migrationNames,\n        error,\n        errorCode: ERROR_CODES.MIGRATION_APPLY_TO_STORY_ERROR,\n      });\n      return null;\n    }\n  }\n\n  _flush(callback: (error?: Error | null) => void) {\n    callback();\n  }\n\n  /**\n   * Get the migration results\n   */\n  getResults(): MigrationStreamResult {\n    return this.results;\n  }\n\n  /**\n   * Get a summary of the migration results\n   */\n  getSummary(): string {\n    const { successful, failed, skipped } = this.results;\n\n    const successfulStoryIds = new Set(successful.map(result => result.storyId));\n\n    let summary = `Migration Results: ${successfulStoryIds.size} stories updated, ${skipped.length} stories skipped`;\n\n    if (skipped.length > 0) {\n      const skippedByReason = skipped.reduce((acc, item) => {\n        if (!acc[item.reason]) {\n          acc[item.reason] = 0;\n        }\n        acc[item.reason]++;\n        return acc;\n      }, {} as Record<string, number>);\n      const skippedReasons = Object.entries(skippedByReason)\n        .map(([reason, count]) => `${reason}: ${count}`)\n        .join(', ');\n\n      summary += ` (${skippedReasons})`;\n    }\n\n    if (failed.length > 0) {\n      const failedStoryIds = new Set(failed.map(result => result.storyId));\n      summary += `, ${failedStoryIds.size} stories failed`;\n    }\n\n    summary += `.`;\n    return summary;\n  }\n}\n","import type { Component } from '../components/constants';\nimport type { Story } from './constants';\nimport { loadComponents } from '../components/loader';\nimport { FileSystemError } from '../../utils/error/filesystem-error';\n\n/**\n * @method isStoryPublishedWithoutChanges\n * @param  {object} story\n * @return {boolean}\n */\nexport const isStoryPublishedWithoutChanges = (story: Partial<Story>) => {\n  return story.published && !story.unpublished_changes;\n};\n\n/**\n * @method isStoryWithUnpublishedChanges\n * @param  {object} story\n * @return {boolean}\n */\nexport const isStoryWithUnpublishedChanges = (story: Partial<Story>) => {\n  return story.published && story.unpublished_changes;\n};\n\nexport const findComponentSchemas = async (directoryPath: string) => {\n  try {\n    const { components } = await loadComponents(directoryPath);\n    const schemas: Record<Component['name'], Component['schema']> = {};\n    for (const component of components) {\n      schemas[component.name] = component.schema;\n    }\n    return schemas;\n  }\n  catch (error) {\n    if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n      return {};\n    }\n    if (error instanceof FileSystemError) {\n      error.message = `Failed to load component schemas for content validation.\\n\\n${error.message}`;\n      throw error;\n    }\n    throw error;\n  }\n};\n\n/**\n * @method getStoryFilename\n * @param  {object} story - Story object with slug and uuid\n * @return {string} Filename in the format {slug}_{uuid}.json\n */\nexport const getStoryFilename = (story: Pick<Story, 'slug' | 'uuid'>) => {\n  return `${story.slug}_${story.uuid}.json`;\n};\n","import { Writable } from 'node:stream';\nimport { Sema } from 'async-sema';\nimport type { StoryUpdate } from '../../../../types';\nimport type { StoryContent } from '../../../stories/constants';\nimport { updateStory } from '../../../stories/actions';\nimport { isStoryPublishedWithoutChanges, isStoryWithUnpublishedChanges } from '../../../stories/utils';\nimport { getLogger } from '../../../../lib/logger/logger';\nimport { ERROR_CODES } from '../constants';\nimport { toError } from '../../../../utils/error';\n\nexport interface UpdateStreamOptions {\n  space: string;\n  publish?: 'all' | 'published' | 'published-with-changes';\n  dryRun?: boolean;\n  batchSize?: number;\n  onProgress?: (current: number) => void;\n  onTotal?: (total: number) => void;\n}\n\nexport interface UpdateStreamResult {\n  successful: Array<{ storyId: number; name: string }>;\n  failed: Array<{ storyId: number; name: string; error: Error }>;\n  totalProcessed: number;\n}\n\n/**\n * Writable stream that updates stories in Storyblok with migrated content\n * This stream accepts successful migration results and applies them to Storyblok\n */\nexport class UpdateStream extends Writable {\n  private results: UpdateStreamResult;\n  private readonly batchSize: number;\n  private semaphore: Sema;\n\n  constructor(private options: UpdateStreamOptions) {\n    super({\n      objectMode: true,\n    });\n\n    this.batchSize = options.batchSize || 10;\n    this.results = {\n      successful: [],\n      failed: [],\n      totalProcessed: 0,\n    };\n\n    this.semaphore = new Sema(this.batchSize);\n  }\n\n  async _write(chunk: { storyId: number; name: string | undefined; content: StoryContent; published?: boolean; unpublished_changes?: boolean }, _encoding: string, callback: (error?: Error | null) => void) {\n    try {\n      await this.semaphore.acquire();\n\n      this.updateStory(chunk).finally(() => {\n        this.semaphore.release();\n      });\n\n      callback();\n    }\n    catch (error) {\n      callback(error as Error);\n    }\n  }\n\n  private async updateStory(migrationResult: { storyId: number; name: string | undefined; content: StoryContent; published?: boolean; unpublished_changes?: boolean }): Promise<void> {\n    const { storyId, name, content, published, unpublished_changes } = migrationResult;\n    const storyName = name || storyId.toString();\n\n    try {\n      const payload: {\n        story: StoryUpdate;\n        force_update?: string;\n        publish?: number;\n      } = {\n        story: {\n          content,\n          id: storyId,\n          name: storyName,\n        },\n        force_update: '1',\n      };\n\n      // Determine if we should publish based on options using actual story data\n      if (this.options.publish === 'published' && isStoryPublishedWithoutChanges({ published, unpublished_changes })) {\n        payload.publish = 1;\n      }\n      else if (this.options.publish === 'published-with-changes' && isStoryWithUnpublishedChanges({ published, unpublished_changes })) {\n        payload.publish = 1;\n      }\n      else if (this.options.publish === 'all') {\n        payload.publish = 1;\n      }\n\n      const updatedStory = !this.options.dryRun && await updateStory(this.options.space, storyId, payload);\n      const isStoryUpdated = Boolean(updatedStory);\n      if (isStoryUpdated || this.options.dryRun) {\n        this.results.successful.push({ storyId, name: storyName });\n        this.results.totalProcessed++;\n        this.options.onProgress?.(this.results.totalProcessed);\n        getLogger().info('Updated story', { storyId });\n      }\n      else {\n        const error = new Error('Update returned null');\n        this.results.failed.push({\n          storyId,\n          name: storyName,\n          error,\n        });\n        this.results.totalProcessed++;\n        this.options.onProgress?.(this.results.totalProcessed);\n        getLogger().error(`Failed to update story: ${error.message}`, {\n          storyId,\n          errorCode: ERROR_CODES.MIGRATION_STORY_UPDATE_NULL,\n        });\n      }\n    }\n    catch (maybeError) {\n      const error = toError(maybeError);\n      this.results.failed.push({\n        storyId,\n        name: storyName,\n        error,\n      });\n      this.results.totalProcessed++;\n      this.options.onProgress?.(this.results.totalProcessed);\n      getLogger().error(error.message, {\n        storyId,\n        error,\n        errorCode: ERROR_CODES.MIGRATION_STORY_UPDATE_ERROR,\n      });\n    }\n  }\n\n  async _destroy(error: Error | null, callback: (error?: Error | null) => void) {\n    try {\n      // Process any remaining items\n      await this.semaphore.drain();\n      callback();\n    }\n    catch (batchError) {\n      callback(batchError as Error);\n      return;\n    }\n\n    callback(error);\n  }\n\n  /**\n   * Get the update results\n   */\n  getResults(): UpdateStreamResult {\n    return this.results;\n  }\n\n  /**\n   * Get a summary of the update results\n   */\n  getSummary(): string {\n    const { successful, failed, totalProcessed } = this.results;\n\n    if (totalProcessed === 0) {\n      return `No stories required updates.`;\n    }\n\n    let summary = `Update Results: ${successful.length} stories updated`;\n\n    if (failed.length > 0) {\n      summary += `, ${failed.length} stories failed`;\n    }\n\n    summary += `.`;\n    return summary;\n  }\n}\n","import type { Command } from 'commander';\nimport chalk from 'chalk';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\nimport { getReporter } from '../../../lib/reporter/reporter';\nimport { colorPalette, commands } from '../../../constants';\nimport { CommandError, handleError, requireAuthentication } from '../../../utils';\nimport { session } from '../../../session';\nimport type { MigrationsRunOptions } from './constants';\nimport { migrationsCommand } from '../command';\nimport { createStoriesStream } from './streams/stories-stream';\nimport { readMigrationFiles } from './actions';\nimport { MigrationStream } from './streams/migrations-transform';\nimport { UpdateStream } from './streams/update-stream';\nimport { pipeline } from 'node:stream';\n\nconst runCmd = migrationsCommand.command('run [componentName]')\n  .description('Run migrations')\n  .option('--fi, --filter <filter>', 'glob filter to apply to the components before pushing')\n  .option('-d, --dry-run', 'Preview changes without applying them to Storyblok')\n  .option('-q, --query <query>', 'Filter stories by content attributes using Storyblok filter query syntax. Example: --query=\"[highlighted][in]=true\"')\n  .option('--starts-with <path>', 'Filter stories by path. Example: --starts-with=\"/en/blog/\"')\n  .option('--publish <publish>', 'Options for publication mode: all | published | published-with-changes')\n  .option('-f, --from <from>', 'source space id')\n  .option('-s, --space <space>', 'space ID');\n\nrunCmd\n  .action(async (componentName: string | undefined, options: MigrationsRunOptions, command: Command) => {\n    const ui = getUI();\n    const logger = getLogger();\n    const reporter = getReporter();\n\n    ui.title(`${commands.MIGRATIONS}`, colorPalette.MIGRATIONS, componentName ? `Running migrations for component ${componentName}...` : 'Running migrations...');\n    logger.info('Migration started');\n\n    if (options.dryRun) {\n      ui.warn(`DRY RUN MODE ENABLED: No changes will be made.\\n`);\n      logger.warn('Dry run mode enabled');\n    }\n\n    const { space, path, verbose } = command.optsWithGlobals();\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n    if (!space) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      return;\n    }\n\n    const { filter, from, dryRun = false, query, startsWith, publish } = options;\n    const fromSpace = from || space;\n\n    if (from) {\n      ui.info(`Running migrations ${chalk.bold('from')} space ${chalk.hex(colorPalette.MIGRATIONS)(fromSpace)} ${chalk.bold('on')} space ${chalk.hex(colorPalette.MIGRATIONS)(space)}`);\n      ui.br();\n    }\n\n    try {\n      const spinner = ui.createSpinner(`Fetching migration files and stories...`);\n\n      const migrationFiles = await readMigrationFiles({\n        space: fromSpace,\n        path,\n        filter,\n      });\n      const filteredMigrations = componentName\n        ? migrationFiles.filter((file) => {\n          // Match any migration file that starts with the component name and is followed by either\n          // the end of the filename or a dot\n            return file.name.match(new RegExp(`^${componentName}(\\\\..*)?\\.js$`));\n          })\n        : migrationFiles;\n\n      if (filteredMigrations.length === 0) {\n        spinner.failed(`No migration files found${componentName ? ` for component \"${componentName}\"` : ''}${filter ? ` matching filter \"${filter}\"` : ''} in space \"${fromSpace}\".`);\n        logger.warn('No migration files found');\n        logger.info('Migration finished');\n        return;\n      }\n\n      // Spinner doesn't have update method, so we'll stop and start a new one\n      spinner.succeed(`Found ${filteredMigrations.length} migration files.`);\n      const storiesProgress = ui.createProgressBar({ title: 'Fetching Stories...'.padEnd(19) });\n      const migrationsProgress = ui.createProgressBar({ title: 'Applying Migrations'.padEnd(19) });\n      const updateProgress = ui.createProgressBar({ title: 'Updating Stories...'.padEnd(19) });\n\n      const storiesStream = await createStoriesStream({\n        spaceId: space,\n        params: {\n          componentName,\n          query,\n          starts_with: startsWith,\n        },\n        batchSize: 12,\n        onTotal: (total) => {\n          storiesProgress.setTotal(total);\n          migrationsProgress.setTotal(total);\n        },\n        onProgress: () => {\n          storiesProgress.increment();\n        },\n      });\n\n      const migrationStream = new MigrationStream({\n        migrationFiles: filteredMigrations,\n        space,\n        sourceSpace: fromSpace,\n        path,\n        componentName,\n        onTotal: (total) => {\n          updateProgress.setTotal(total);\n        },\n        onProgress: () => {\n          migrationsProgress.increment();\n        },\n      });\n\n      const updateStream = new UpdateStream({\n        space,\n        publish,\n        dryRun,\n        batchSize: 12,\n        onProgress: () => {\n          updateProgress.increment();\n        },\n      });\n\n      await new Promise<void>((resolve, reject) => {\n        pipeline(\n          storiesStream,\n          migrationStream,\n          updateStream,\n          (err) => {\n            if (err) {\n              reject(err);\n              return;\n            }\n            resolve();\n          },\n        );\n      });\n\n      ui.stopAllProgressBars();\n\n      // Show migration summary\n      const migrationSummary = migrationStream.getSummary();\n      ui.info(migrationSummary);\n\n      // Show update summary\n      const updateSummary = updateStream.getSummary();\n      ui.info(updateSummary);\n\n      const migrationStreamResults = migrationStream.getResults();\n      const migrationResults = {\n        total: migrationStreamResults.totalProcessed,\n        succeeded: migrationStreamResults.successful.length,\n        skipped: migrationStreamResults.skipped.length,\n        failed: migrationStreamResults.failed.length,\n      };\n      const updateStreamResults = updateStream.getResults();\n      const updateResults = {\n        total: updateStreamResults.totalProcessed,\n        succeeded: updateStreamResults.successful.length,\n        failed: updateStreamResults.failed.length,\n      };\n\n      logger.info('Migration finished', {\n        migrationResults,\n        updateResults,\n      });\n      reporter.addSummary('migrationResults', migrationResults);\n      reporter.addSummary('updateResults', updateResults);\n      reporter.finalize();\n    }\n    catch (error) {\n      handleError(error as Error, verbose);\n    }\n  });\n","import type { Command } from 'commander';\nimport type { StoryUpdate } from '../../../types';\nimport { colorPalette, commands } from '../../../constants';\nimport { CommandError, handleError, requireAuthentication, toError } from '../../../utils';\nimport { migrationsCommand } from '../command';\nimport { session } from '../../../session';\nimport { readRollbackFile } from './actions';\nimport { updateStory } from '../../stories/actions';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\nimport chalk from 'chalk';\n\nconst rollbackCmd = migrationsCommand.command('rollback [migrationFile]')\n  .description('Rollback a migration')\n  .option('-s, --space <space>', 'space ID');\n\nrollbackCmd\n  .action(async (migrationFile: string, _options: unknown, command: Command) => {\n    const ui = getUI();\n    const logger = getLogger();\n\n    ui.title(\n      `${commands.MIGRATIONS}`,\n      colorPalette.MIGRATIONS,\n      migrationFile\n        ? `Rolling back migration ${chalk.hex(colorPalette.MIGRATIONS)(migrationFile)}...`\n        : 'Rolling back migration...',\n    );\n\n    const { space, path, verbose } = command.optsWithGlobals();\n\n    logger.info('Migration rollback started', {\n      migrationFile,\n      space,\n      path,\n    });\n\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n\n    if (!space) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      return;\n    }\n\n    try {\n      // Read the rollback data\n      const rollbackData = await readRollbackFile({\n        space,\n        path,\n        migrationFile,\n      });\n\n      const rollbackSummary = {\n        total: rollbackData.stories.length,\n        succeeded: 0,\n        failed: 0,\n      };\n\n      // Restore each story to its original state\n      for (const story of rollbackData.stories) {\n        const spinner = ui.createSpinner(`Restoring story ${chalk.hex(colorPalette.PRIMARY)(story.name || story.storyId)}...`);\n        try {\n          const payload: { story: StoryUpdate; force_update?: string; publish?: number } = {\n            story: {\n              content: story.content,\n              id: story.storyId,\n              name: story.name,\n            },\n            force_update: '1',\n          };\n\n          // Only restore publication status if it was saved in the rollback data\n          // For backwards compatibility, we check if the published status exists in the rollback data\n          if (story.published !== undefined && story.unpublished_changes !== undefined) {\n            // If the story was originally published without changes, publish it\n            if (story.published && !story.unpublished_changes) {\n              payload.publish = 1;\n            }\n            // Otherwise, don't publish (let it remain as draft or with unpublished changes)\n          }\n\n          await updateStory(space, story.storyId, payload);\n          rollbackSummary.succeeded += 1;\n          spinner.succeed(`Restored story ${chalk.hex(colorPalette.PRIMARY)(story.name || story.storyId)} - Completed in ${spinner.elapsedTime.toFixed(2)}ms`);\n\n          logger.info('Story restored', {\n            storyId: story.storyId,\n            migrationFile,\n            space,\n          });\n        }\n        catch (maybeError) {\n          const error = toError(maybeError);\n          rollbackSummary.failed += 1;\n          spinner.failed(`Failed to restore story ${chalk.hex(colorPalette.PRIMARY)(story.name || story.storyId)}: ${(error as Error).message}`);\n          logger.error('Failed to restore story', {\n            storyId: story.storyId,\n            migrationFile,\n            space,\n            error,\n          });\n        }\n      }\n\n      logger.info('Migration rollback finished', {\n        migrationFile,\n        space,\n        results: rollbackSummary,\n      });\n    }\n    catch (error) {\n      handleError(new CommandError(`Failed to rollback migration: ${(error as Error).message}`), verbose);\n    }\n  });\n","import { commands } from '../../constants';\nimport { getProgram } from '../../program';\n\nconst program = getProgram(); // Get the shared singleton instance\n\n// Components root command\nexport const typesCommand = program\n  .command(commands.TYPES)\n  .alias('ts')\n  .description(`Generate types d.ts for your component schemas`);\n","import type { JSONSchema } from 'json-schema-to-typescript';\nimport type { StoryblokPropertyType } from '../types/storyblok';\n\nexport const getAssetJSONSchema = (title: string): JSONSchema => ({\n  $id: '#/asset',\n  title,\n  type: 'object',\n  required: ['id', 'fieldtype', 'filename', 'name', 'title', 'focus', 'alt'],\n  properties: {\n    alt: {\n      type: ['string', 'null'],\n    },\n    copyright: {\n      type: ['string', 'null'],\n    },\n    fieldtype: {\n      type: 'string',\n      enum: ['asset'],\n    },\n    id: {\n      type: 'number',\n    },\n    filename: {\n      type: ['string', 'null'],\n    },\n    name: {\n      type: 'string',\n    },\n    title: {\n      type: ['string', 'null'],\n    },\n    focus: {\n      type: ['string', 'null'],\n    },\n    meta_data: {\n      type: 'object',\n    },\n    source: {\n      type: ['string', 'null'],\n    },\n    is_external_url: {\n      type: 'boolean',\n    },\n    is_private: {\n      type: 'boolean',\n    },\n    src: {\n      type: 'string',\n    },\n    updated_at: {\n      type: 'string',\n    },\n    // Cloudinary integration keys\n    width: {\n      type: ['number', 'null'],\n    },\n    height: {\n      type: ['number', 'null'],\n    },\n    aspect_ratio: {\n      type: ['number', 'null'],\n    },\n    public_id: {\n      type: ['string', 'null'],\n    },\n    content_type: {\n      type: 'string',\n    },\n  },\n});\n\nexport const getMultiassetJSONSchema = (title: string): JSONSchema => ({\n  $id: '#/multiasset',\n  title,\n  type: 'array',\n  items: {\n    type: 'object',\n    required: ['id', 'fieldtype', 'filename', 'name', 'title', 'focus', 'alt'],\n    properties: {\n      alt: {\n        type: ['string', 'null'],\n      },\n      copyright: {\n        type: ['string', 'null'],\n      },\n      fieldtype: {\n        type: 'string',\n        enum: ['asset'],\n      },\n      id: {\n        type: 'number',\n      },\n      filename: {\n        type: ['string', 'null'],\n      },\n      name: {\n        type: 'string',\n      },\n      title: {\n        type: ['string', 'null'],\n      },\n      focus: {\n        type: ['string', 'null'],\n      },\n      meta_data: {\n        type: 'object',\n      },\n      source: {\n        type: ['string', 'null'],\n      },\n      is_external_url: {\n        type: 'boolean',\n      },\n      is_private: {\n        type: 'boolean',\n      },\n      src: {\n        type: 'string',\n      },\n      updated_at: {\n        type: 'string',\n      },\n      // Cloudinary integration keys\n      width: {\n        type: ['number', 'null'],\n      },\n      height: {\n        type: ['number', 'null'],\n      },\n      aspect_ratio: {\n        type: ['number', 'null'],\n      },\n      public_id: {\n        type: ['string', 'null'],\n      },\n      content_type: {\n        type: 'string',\n      },\n    },\n  },\n});\n\n// TODO: find a reliable way to share props among different Link Types to increase maintainability\n// Currently not possible because of JSONSchema4 complaining\nconst multilinkSharedRequiredProps = ['fieldtype', 'id', 'url', 'cached_url', 'linktype'];\n\nexport const getMultilinkJSONSchema = (title: string): JSONSchema => ({\n  $id: '#/multilink',\n  title,\n  oneOf: [\n    {\n      type: 'object',\n      required: multilinkSharedRequiredProps,\n      properties: {\n        // Shared props\n        fieldtype: {\n          type: 'string',\n          enum: ['multilink'],\n        },\n        id: { type: 'string' },\n        url: { type: 'string' },\n        cached_url: { type: 'string' },\n        target: { type: 'string', enum: ['_blank', '_self'] },\n        // Custom props\n        anchor: {\n          type: 'string',\n        },\n        rel: {\n          type: 'string',\n        },\n        title: {\n          type: 'string',\n        },\n        prep: {\n          type: 'string',\n        },\n        linktype: {\n          type: 'string',\n          enum: ['story'],\n        },\n        story: {\n          type: 'object',\n          required: ['name', 'id', 'uuid', 'slug', 'full_slug'],\n          properties: {\n            name: {\n              type: 'string',\n            },\n            created_at: {\n              type: 'string',\n              format: 'date-time',\n            },\n            published_at: {\n              type: 'string',\n              format: 'date-time',\n            },\n            id: {\n              type: 'integer',\n            },\n            uuid: {\n              type: 'string',\n              format: 'uuid',\n            },\n            content: {\n              type: 'object',\n            },\n            slug: {\n              type: 'string',\n            },\n            full_slug: {\n              type: 'string',\n            },\n            sort_by_date: {\n              type: ['null', 'string'],\n              format: 'date-time',\n            },\n            position: {\n              type: 'integer',\n            },\n            tag_list: {\n              type: 'array',\n              items: {\n                type: 'string',\n              },\n            },\n            is_startpage: {\n              type: 'boolean',\n            },\n            parent_id: {\n              type: ['null', 'integer'],\n            },\n            meta_data: {\n              type: ['null', 'object'],\n            },\n            group_id: {\n              type: 'string',\n              format: 'uuid',\n            },\n            first_published_at: {\n              type: 'string',\n              format: 'date-time',\n            },\n            release_id: {\n              type: ['null', 'integer'],\n            },\n            lang: {\n              type: 'string',\n            },\n            path: {\n              type: ['null', 'string'],\n            },\n            alternates: {\n              type: 'array',\n            },\n            default_full_slug: {\n              type: ['null', 'string'],\n            },\n            translated_slugs: {\n              type: ['null', 'array'],\n            },\n          },\n        },\n      },\n    },\n    {\n      type: 'object',\n      required: multilinkSharedRequiredProps,\n      properties: {\n        // Shared props\n        fieldtype: {\n          type: 'string',\n          enum: ['multilink'],\n        },\n        id: { type: 'string' },\n        url: { type: 'string' },\n        cached_url: { type: 'string' },\n        target: { type: 'string', enum: ['_blank', '_self'] },\n        // Custom props\n        linktype: {\n          type: 'string',\n          enum: ['url'],\n        },\n        rel: {\n          type: 'string',\n        },\n        title: {\n          type: 'string',\n        },\n      },\n    },\n    {\n      type: 'object',\n      required: multilinkSharedRequiredProps,\n      properties: {\n        // Shared props\n        fieldtype: {\n          type: 'string',\n          enum: ['multilink'],\n        },\n        id: { type: 'string' },\n        url: { type: 'string' },\n        cached_url: { type: 'string' },\n        target: { type: 'string', enum: ['_blank', '_self'] },\n        // Custom props\n        email: {\n          type: 'string',\n        },\n        linktype: {\n          type: 'string',\n          enum: ['email'],\n        },\n      },\n    },\n    {\n      type: 'object',\n      required: multilinkSharedRequiredProps,\n      properties: {\n        // Shared props\n        fieldtype: {\n          type: 'string',\n          enum: ['multilink'],\n        },\n        id: { type: 'string' },\n        url: { type: 'string' },\n        cached_url: { type: 'string' },\n        target: { type: 'string', enum: ['_blank', '_self'] },\n        // Custom props\n        linktype: {\n          type: 'string',\n          enum: ['asset'],\n        },\n      },\n    },\n  ],\n});\n\nexport const getRichtextJSONSchema = (title: string): JSONSchema => ({\n  $id: '#/richtext',\n  title,\n  type: 'object',\n  required: ['type'],\n  properties: {\n    type: {\n      type: 'string',\n    },\n    content: {\n      type: 'array',\n      items: {\n        $ref: '#',\n      },\n    },\n    marks: {\n      type: 'array',\n      items: {\n        $ref: '#',\n      },\n    },\n    attrs: {},\n    text: {\n      type: 'string',\n    },\n  },\n});\n\nexport const getTableJSONSchema = (title: string): JSONSchema => ({\n  $id: '#/table',\n  title,\n  type: 'object',\n  required: ['tbody', 'thead'],\n  properties: {\n    thead: {\n      type: 'array',\n      items: {\n        type: 'object',\n        required: ['_uid', 'component'],\n        properties: {\n          _uid: {\n            type: 'string',\n          },\n          value: {\n            type: 'string',\n          },\n          component: {\n            type: 'number',\n          },\n        },\n      },\n    },\n    tbody: {\n      type: 'array',\n      items: {\n        type: 'object',\n        required: ['_uid', 'component', 'body'],\n        properties: {\n          _uid: {\n            type: 'string',\n          },\n          body: {\n            type: 'array',\n            items: {\n              type: 'object',\n              properties: {\n                _uid: {\n                  type: 'string',\n                },\n                value: {\n                  type: 'string',\n                },\n                component: {\n                  type: 'number',\n                },\n              },\n            },\n          },\n          component: {\n            type: 'number',\n          },\n        },\n      },\n    },\n  },\n});\n\nexport const storyblokSchemas = new Map<StoryblokPropertyType, JSONSchema>([\n  ['asset', getAssetJSONSchema],\n  ['multiasset', getMultiassetJSONSchema],\n  ['multilink', getMultilinkJSONSchema],\n  ['table', getTableJSONSchema],\n  ['richtext', getRichtextJSONSchema],\n]);\n","import { toPascalCase } from '../../../utils';\n\n/**\n * Generates imports for Storyblok types (ISbStoryData, StoryblokAsset, etc.)\n * @param storyblokPropertyTypes - Set of Storyblok property types used\n * @param STORY_TYPE - The ISbStoryData constant\n * @returns Array of import strings\n */\nexport function generateStoryblokImports(\n  storyblokPropertyTypes: Set<string>,\n  STORY_TYPE: string,\n): string[] {\n  const imports: string[] = [];\n\n  // Check if ISbStoryData is needed\n  const needsISbStoryData = storyblokPropertyTypes.has(STORY_TYPE);\n  if (needsISbStoryData) {\n    imports.push(`import type { ${STORY_TYPE} } from '@storyblok/js';`);\n    storyblokPropertyTypes.delete(STORY_TYPE);\n  }\n\n  if (storyblokPropertyTypes.size > 0) {\n    const typeImports = Array.from(storyblokPropertyTypes).map((type) => {\n      const pascalType = toPascalCase(type);\n      return `Storyblok${pascalType}`;\n    });\n\n    imports.push(`import type { ${typeImports.join(', ')} } from '../storyblok.d.ts';`);\n  }\n\n  return imports;\n}\n\ninterface TypeResult {\n  title: string;\n  content: string;\n  isComponent: boolean;\n  isDatasource: boolean;\n}\n\nfunction escapeRegExp(value: string): string {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nfunction hasIdentifier(content: string, identifier: string): boolean {\n  const regex = new RegExp(`\\\\b${escapeRegExp(identifier)}\\\\b`, 'g');\n  return regex.test(content);\n}\n\n/**\n * Detects which Storyblok types are used in a component's content\n * @param content - The generated type definition content\n * @param storyblokPropertyTypes - Set of all Storyblok property types\n * @param STORY_TYPE - The ISbStoryData constant\n * @returns Array of used Storyblok type names\n */\nexport function detectUsedStoryblokTypes(\n  content: string,\n  storyblokPropertyTypes: Set<string>,\n  STORY_TYPE: string,\n): string[] {\n  const usedTypes: string[] = [];\n\n  // Check for ISbStoryData\n  if (content.includes(STORY_TYPE)) {\n    usedTypes.push(STORY_TYPE);\n  }\n\n  // Check for other Storyblok types\n  Array.from(storyblokPropertyTypes).forEach((type) => {\n    const pascalType = toPascalCase(type);\n    if (content.includes(`Storyblok${pascalType}`)) {\n      usedTypes.push(type);\n    }\n  });\n\n  return usedTypes;\n}\n\n/**\n * Detects which datasource types are used in a component's content\n * @param content - The generated type definition content\n * @param datasourceResults - Array of datasource type results\n * @returns Array of used datasource type titles\n */\nexport function detectUsedDatasourceTypes(\n  content: string,\n  datasourceResults: TypeResult[],\n): string[] {\n  return datasourceResults\n    .filter(ds => hasIdentifier(content, ds.title))\n    .map(ds => ds.title);\n}\n\n/**\n * Detects which component types are referenced in a component's content\n * @param content - The generated type definition content\n * @param currentTitle - The title of the current component (to exclude self-reference)\n * @param componentResults - Array of all component type results\n * @returns Array of referenced component type titles\n */\nexport function detectReferencedComponents(\n  content: string,\n  currentTitle: string,\n  componentResults: TypeResult[],\n): string[] {\n  return componentResults\n    .filter(c => c.title !== currentTitle && hasIdentifier(content, c.title))\n    .map(c => c.title);\n}\n\n/**\n * Generates import statements for a component based on its dependencies\n * @param componentContent - The generated component type definition\n * @param componentTitle - The title of the component\n * @param storyblokPropertyTypes - Set of all Storyblok property types\n * @param datasourceResults - Array of datasource type results\n * @param componentResults - Array of all component type results\n * @param STORY_TYPE - The ISbStoryData constant\n * @returns Array of import strings\n */\nexport function generateComponentImports(\n  componentContent: string,\n  componentTitle: string,\n  storyblokPropertyTypes: Set<string>,\n  datasourceResults: TypeResult[],\n  componentResults: TypeResult[],\n  STORY_TYPE: string,\n): string[] {\n  const imports: string[] = [];\n\n  // Check if this component uses ISbStoryData or other Storyblok types\n  const usedStoryblokTypes = detectUsedStoryblokTypes(\n    componentContent,\n    storyblokPropertyTypes,\n    STORY_TYPE,\n  );\n\n  if (usedStoryblokTypes.length > 0) {\n    const hasISbStoryData = usedStoryblokTypes.includes(STORY_TYPE);\n    const otherTypes = usedStoryblokTypes.filter(t => t !== STORY_TYPE);\n\n    if (hasISbStoryData) {\n      imports.push(`import type { ${STORY_TYPE} } from '@storyblok/js';`);\n    }\n\n    if (otherTypes.length > 0) {\n      const typeImports = otherTypes.map((type) => {\n        const pascalType = toPascalCase(type);\n        return `Storyblok${pascalType}`;\n      });\n      imports.push(`import type { ${typeImports.join(', ')} } from '../storyblok.d.ts';`);\n    }\n  }\n\n  // Check if this component uses any datasource types\n  const usedDatasourceTypes = detectUsedDatasourceTypes(componentContent, datasourceResults);\n  if (usedDatasourceTypes.length > 0) {\n    imports.push(`import type { ${usedDatasourceTypes.join(', ')} } from './datasource-types.d.ts';`);\n  }\n\n  // Check if this component references other components\n  const referencedComponents = detectReferencedComponents(\n    componentContent,\n    componentTitle,\n    componentResults,\n  );\n  if (referencedComponents.length > 0) {\n    const componentImportsStr = referencedComponents\n      .map(name => `import type { ${name} } from './${name}.d.ts';`)\n      .join('\\n');\n    imports.push(componentImportsStr);\n  }\n\n  return imports;\n}\n\n/**\n * Creates a file object for datasources\n * @param datasourceResults - Array of datasource type results\n * @param typeDefs - Header comments for the file\n * @returns File object or null if no datasources\n */\nexport function createDatasourcesFile(\n  datasourceResults: TypeResult[],\n  typeDefs: string[],\n): { name: string; content: string } | null {\n  if (datasourceResults.length === 0) {\n    return null;\n  }\n\n  const content = [\n    ...typeDefs,\n    ...datasourceResults.map(r => r.content),\n  ].join('\\n');\n\n  return { name: 'datasource-types', content };\n}\n\n/**\n * Creates a file object for content types\n * @param contentTypeBloks - Set of component type names that are content types\n * @param typeDefs - Header comments for the file\n * @returns File object or null if no content types\n */\nexport function createContentTypesFile(\n  contentTypeBloks: Set<string>,\n  typeDefs: string[],\n): { name: string; content: string } | null {\n  if (contentTypeBloks.size === 0) {\n    return null;\n  }\n\n  // Get the component type names from the set\n  const contentTypeNames = Array.from(contentTypeBloks);\n\n  // Generate imports for each content type component\n  const imports = contentTypeNames\n    .map(name => `import type { ${name} } from './${name}.d.ts';`)\n    .join('\\n');\n\n  // Generate the ContentType union\n  const typeUnion = contentTypeNames.length > 0\n    ? contentTypeNames.join('\\n  | ')\n    : 'never';\n\n  const typeDefinition = `export type ContentType =\\n  | ${typeUnion};`;\n\n  const content = [\n    ...typeDefs,\n    imports,\n    typeDefinition,\n  ].join('\\n');\n\n  return { name: 'content-types', content };\n}\n\n/**\n * Creates a file object for a single component with its imports\n * @param componentResult - The component type result\n * @param typeDefs - Header comments for the file\n * @param componentImports - Array of import statements for this component\n * @returns File object\n */\nexport function createComponentFile(\n  componentResult: TypeResult,\n  typeDefs: string[],\n  componentImports: string[],\n): { name: string; content: string } {\n  return {\n    name: componentResult.title,\n    content: [\n      ...typeDefs,\n      ...componentImports,\n      componentResult.content,\n    ].join('\\n'),\n  };\n}\n","import { compile, type JSONSchema } from 'json-schema-to-typescript';\nimport type { Component, SpaceComponentsData } from '../../../commands/components/constants';\nimport { __dirname, capitalize, handleError, handleFileSystemError, toCamelCase, toPascalCase } from '../../../utils';\nimport type { GenerateTypesOptions } from './constants';\nimport type { StoryblokPropertyType } from '../../../types/storyblok';\nimport { storyblokSchemas } from '../../../utils/storyblok-schemas';\nimport { join, resolve } from 'pathe';\nimport { pathToFileURL } from 'node:url';\nimport { resolvePath, saveToFile } from '../../../utils/filesystem';\nimport { readFileSync } from 'node:fs';\nimport type { ComponentPropertySchema } from '../../../types/schemas';\nimport {\n  createComponentFile,\n  createContentTypesFile,\n  createDatasourcesFile,\n  generateComponentImports,\n  generateStoryblokImports,\n} from './utils';\n\nexport interface ComponentGroupsAndNamesObject {\n  componentGroups: Map<string, Set<string>>;\n  componentNames: Set<string>;\n}\n\n// Constants\nconst STORY_TYPE = 'ISbStoryData';\nconst DEFAULT_COMPONENT_FILENAME = 'storyblok-components';\nconst DEFAULT_TYPEDEFS_HEADER = [\n  '// This file was generated by the storyblok CLI.',\n  '// DO NOT MODIFY THIS FILE BY HAND.',\n];\nconst getDatasourceTypeTitle = (slug: string) =>\n  `${toPascalCase(slug)}DataSource`;\n\nconst getPropertyTypeAnnotation = (property: ComponentPropertySchema, prefix?: string, suffix?: string) => {\n  // If a property type is one of the ones provided by Storyblok, return that type\n  if (Array.from(storyblokSchemas.keys()).includes(property.type as StoryblokPropertyType)) {\n    return { type: property.type };\n  }\n\n  let type: string | string[] = 'unknown';\n\n  const options = property.options && property.options.length > 0 ? property.options.map((item: { value: string }) => item.value) : [];\n\n  // Add empty option to options array\n  if (options.length > 0 && property.exclude_empty_option !== true) {\n    options.unshift('');\n  }\n\n  if (property.source === 'internal_stories') {\n    // Only if there is a filter_content_type, we can return a proper type\n    if (property.filter_content_type) {\n      return {\n        tsType: `(${property.filter_content_type\n          .map(type2 => getStoryType(type2, prefix, suffix))\n          // In this case property.type can be `option` or `options`. In case of `options` the type should be an array\n          .join(' | ')} | string )${property.type === 'options' ? '[]' : ''}`,\n      };\n    }\n  }\n\n  if (\n    // If there is no `source` and there are options, the data source is the component itself\n    // TODO: check if this is an old behaviour (shouldn't this be handled as an \"internal\" source?)\n    (options.length > 0 && !property.source)\n    || property.source === 'internal_languages'\n    || property.source === 'external'\n  ) {\n    type = 'string';\n  }\n\n  if (property.source === 'internal') {\n    type = ['number', 'string'];\n  }\n\n  if (property.type === 'option') {\n    if (options.length > 0) {\n      return {\n        type,\n        enum: options,\n      };\n    }\n\n    return {\n      type,\n    };\n  }\n\n  if (property.type === 'options') {\n    if (options.length > 0) {\n      return {\n        type: 'array',\n        items: {\n          enum: options,\n        },\n      };\n    }\n\n    return {\n      type: 'array',\n      items: { type },\n    };\n  }\n\n  switch (property.type) {\n    case 'bloks':\n      return { type: 'array' };\n    case 'boolean':\n      return { type: 'boolean' };\n    case 'datetime':\n    case 'image':\n    case 'markdown':\n    case 'number':\n    case 'text':\n    case 'textarea':\n      return { type: 'string' };\n    default:\n      return { type: 'any' };\n  }\n};\n\nexport function getStoryType(property: string, prefix?: string, suffix?: string) {\n  return `${STORY_TYPE}<${prefix ?? ''}${capitalize(toCamelCase(property))}${suffix ?? ''}>`;\n}\n\n/**\n * Generates a TypeScript type name for a component\n * @param componentName - The name of the component\n * @param options - Options for generating the type name\n * @returns The generated type name\n *\n * The type name can be customized with the following options:\n * - typePrefix: Prefix to be prepended to all generated component type names (can be set via --type-prefix flag)\n */\nexport const getComponentType = (\n  componentName: string,\n  options: GenerateTypesOptions,\n): string => {\n  const prefix = options.typePrefix ?? '';\n  const suffix = options.typeSuffix ?? '';\n\n  // Sanitize the component name to handle special characters and emojis\n  const sanitizedName = componentName\n    // Replace any character that's not a letter or number with an underscore\n    .replace(/[^a-z0-9]/gi, '_')\n    // Replace multiple consecutive underscores with a single underscore\n    .replace(/_+/g, '_')\n    // Trim underscores from the beginning and end\n    .replace(/^_+|_+$/g, '');\n\n  // Convert to PascalCase\n  const componentType = toPascalCase(`${prefix}_${sanitizedName}_${suffix}`);\n\n  // If the component type starts with a number, prefix it with an underscore\n  const isFirstCharacterNumber = !Number.isNaN(Number.parseInt(componentType.charAt(0)));\n  return isFirstCharacterNumber ? `_${componentType}` : componentType;\n};\n\nconst getComponentPropertiesTypeAnnotations = async (\n  component: Component,\n  options: GenerateTypesOptions,\n  spaceData: SpaceComponentsData,\n  customFieldsParser?: (key: string, value: Record<string, unknown>) => Record<string, unknown>,\n): Promise<JSONSchema['properties']> => {\n  // Handle null/undefined schema\n  if (!component.schema || typeof component.schema !== 'object') {\n    return {};\n  }\n  return Object.entries(component.schema).reduce(async (accPromise, [key, value]) => {\n    const acc = await accPromise;\n\n    // Skip tabbed properties\n    if (key.startsWith('tab-')) {\n      return acc;\n    }\n\n    // Type guard to ensure value is ComponentPropertySchema\n    if (!value || typeof value !== 'object' || !('type' in value)) {\n      return acc;\n    }\n\n    const schema = value as ComponentPropertySchema;\n    const propertyType = schema.type;\n    const propertyTypeAnnotation: JSONSchema = {\n      [key]: getPropertyTypeAnnotation(schema, options.typePrefix, options.typeSuffix),\n    };\n\n    if (propertyType === 'custom' && customFieldsParser) {\n      const customField = typeof customFieldsParser === 'function' ? customFieldsParser(key, schema as unknown as Record<string, unknown>) : {};\n      return {\n        ...acc,\n        ...customField,\n      };\n    }\n\n    if (Array.from(storyblokSchemas.keys()).includes(propertyType as StoryblokPropertyType)) {\n      // For Storyblok property types, don't apply the prefix\n      const componentType = toPascalCase(propertyType);\n      propertyTypeAnnotation[key].tsType = `Storyblok${componentType}`;\n    }\n    if (spaceData.datasources.length > 0 && schema.source === 'internal' && schema?.datasource_slug) {\n      // Check if the datasource actually exists in spaceData.datasources\n      const datasourceExists = spaceData.datasources.some(ds => ds.slug === schema.datasource_slug);\n      if (datasourceExists) {\n        const type = getDatasourceTypeTitle(schema.datasource_slug);\n        // Assign type based on whether it's single or multiple selection\n        propertyTypeAnnotation[key].tsType\n            = propertyType === 'options' ? `${type}[]` : type;\n      }\n      // If datasource doesn't exist, fall back to default number | string union type\n      // The type annotation already has the correct fallback from getPropertyTypeAnnotation\n    }\n    if (propertyType === 'multilink') {\n      const excludedLinktypes: string[] = [\n        ...(!schema.email_link_type ? ['{ linktype?: \"email\" }'] : []),\n        ...(!schema.asset_link_type ? ['{ linktype?: \"asset\" }'] : []),\n      ];\n      const componentType = `Storyblok${toPascalCase(propertyType)}`;\n      propertyTypeAnnotation[key].tsType\n        = excludedLinktypes.length > 0 ? `Exclude<${componentType}, ${excludedLinktypes.join(' | ')}>` : componentType;\n    }\n\n    if (propertyType === 'bloks') {\n      if (schema.restrict_components) {\n        // Components restricted by groups\n        if (schema.restrict_type === 'groups') {\n          if (\n            Array.isArray(schema.component_group_whitelist)\n            && schema.component_group_whitelist.length > 0\n          ) {\n            // Find components that belong to the whitelisted groups\n            const componentsInGroupWhitelist = schema.component_group_whitelist.reduce(\n              (components: string[], groupUUID: string) => {\n                // Find components that have this group UUID\n                const componentsInGroup = spaceData.components.filter(\n                  component => component.component_group_uuid === groupUUID,\n                );\n\n                return componentsInGroup.length > 0\n                  ? [\n                      ...components,\n                      ...componentsInGroup.map(component => getComponentType(component.name, options)),\n                    ]\n                  : components;\n              },\n              [],\n            );\n\n            propertyTypeAnnotation[key].tsType\n              = componentsInGroupWhitelist.length > 0 ? `(${componentsInGroupWhitelist.join(' | ')})[]` : `never[]`;\n          }\n        }\n        else if (schema.restrict_type === 'tags') {\n          // Components restricted by tags\n          if (Array.isArray(schema.component_tag_whitelist) && schema.component_tag_whitelist.length > 0) {\n            // Find components that have any of the whitelisted tag IDs\n            const componentsWithTags = spaceData.components.filter(\n              component =>\n                component.internal_tag_ids\n                && component.internal_tag_ids.some(tagId =>\n                  schema.component_tag_whitelist!.includes(Number(tagId)),\n                ),\n            );\n\n            propertyTypeAnnotation[key].tsType\n              = componentsWithTags.length > 0\n                ? `(${componentsWithTags.map(component => getComponentType(component.name, options)).join(' | ')})[]`\n                : `never[]`;\n          }\n        }\n        else {\n          // Components restricted by 1-by-1 list\n          if (Array.isArray(schema.component_whitelist) && schema.component_whitelist.length > 0) {\n            propertyTypeAnnotation[key].tsType = `(${schema.component_whitelist\n              .map((name: string) => getComponentType(name, options))\n              .join(' | ')})[]`;\n          }\n        }\n      }\n      else {\n        // All components can be slotted in this property (AKA no restrictions)\n        // Add null check to ensure spaceData.components is defined\n        if (spaceData && Array.isArray(spaceData.components)) {\n          propertyTypeAnnotation[key].tsType = `(${spaceData.components\n            .map(component => getComponentType(component.name, options))\n            .join(' | ')})[]`;\n        }\n        else {\n          // Fallback to never[] if components is undefined\n          propertyTypeAnnotation[key].tsType = `never[]`;\n        }\n      }\n    }\n\n    return { ...acc, ...propertyTypeAnnotation };\n  }, Promise.resolve({} as JSONSchema));\n};\n\nconst loadCustomFieldsParser = async (path: string): Promise<((key: string, value: Record<string, unknown>) => Record<string, unknown>) | undefined> => {\n  try {\n    const customFieldsParser = await import(pathToFileURL(resolve(path)).href);\n    return customFieldsParser.default;\n  }\n  catch (error) {\n    handleError(error as Error);\n    return undefined;\n  }\n};\n\nasync function loadCompilerOptions(path: string) {\n  if (path) {\n    const compilerOptions = await import(pathToFileURL(resolve(path)).href);\n    return compilerOptions.default;\n  }\n  return {};\n}\n\nexport const generateTypes = async (\n  spaceData: SpaceComponentsData,\n  options: GenerateTypesOptions = {\n    strict: false,\n  },\n): Promise<string | Array<{ name: string; content: string }> | undefined> => {\n  try {\n    const typeDefs = [...DEFAULT_TYPEDEFS_HEADER];\n    const storyblokPropertyTypes = new Set<string>();\n    const contentTypeBloks = new Set<string>();\n    let customFieldsParser: ((key: string, value: Record<string, unknown>) => Record<string, unknown>) | undefined;\n    let compilerOptions: Record<string, unknown> | undefined;\n    // Custom fields parser\n    if (options.customFieldsParser) {\n      customFieldsParser = await loadCustomFieldsParser(options.customFieldsParser);\n    }\n\n    // Compiler options\n    if (options.compilerOptions) {\n      compilerOptions = await loadCompilerOptions(options.compilerOptions);\n    }\n    const componentsSchema = spaceData.components.map(async (component) => {\n    // Get the component type name with proper handling of numbers at the start\n      const type = getComponentType(component.name, options);\n      // Add all the Content Type and Universial Blok to contentTypeBloks\n      if (component.is_root) {\n        contentTypeBloks.add(type);\n      }\n      const componentPropertiesTypeAnnotations = await getComponentPropertiesTypeAnnotations(component, options, spaceData, customFieldsParser);\n      const requiredFields = Object.entries(component?.schema || {}).reduce(\n        (acc: string[], [key, value]) => {\n          if (value && typeof value === 'object' && 'required' in value && value.required) {\n            return [...acc, key];\n          }\n          return acc;\n        },\n        ['component', '_uid'] as string[],\n      );\n\n      // Check if any property has a type that's in storyblokSchemas.keys()\n      if (componentPropertiesTypeAnnotations) {\n        Object.entries(componentPropertiesTypeAnnotations).forEach(([_, property]) => {\n          if (property.type && Array.from(storyblokSchemas.keys()).includes(property.type as StoryblokPropertyType)) {\n            storyblokPropertyTypes.add(property.type as StoryblokPropertyType);\n          }\n          // Check if the property uses ISbStoryData\n          if (property.tsType && property.tsType.includes(STORY_TYPE)) {\n            storyblokPropertyTypes.add(STORY_TYPE);\n          }\n        });\n      }\n\n      const componentSchema: JSONSchema = {\n        $id: `#/${component.name}`,\n        title: type, // This is the key - we're using the properly formatted type name\n        type: 'object',\n        required: requiredFields,\n        properties: {\n          ...componentPropertiesTypeAnnotations,\n          component: {\n            type: 'string',\n            enum: [component.name],\n          },\n          _uid: {\n            type: 'string',\n          },\n        },\n      };\n\n      return componentSchema;\n    });\n    const resolvedComponentsSchema = await Promise.all(componentsSchema);\n\n    const datasourcesSchema = spaceData.datasources.map(async (datasource) => {\n      const allComponentTypes = resolvedComponentsSchema.map(schema => schema.title);\n\n      const enumValues: string[] | undefined = datasource.entries\n        ?.filter(d => d.value)\n        .map(d => d.value!);\n\n      // Handle potential null/undefined slug\n      if (!datasource.slug) {\n        return null;\n      }\n\n      const type = getDatasourceTypeTitle(datasource.slug);\n      // Check for conflicts with existing component types\n      if (allComponentTypes.includes(type)) {\n        console.warn(`Warning: Datasource type \"${type}\" conflicts with existing component type`);\n      }\n      const datasourceSchema: JSONSchema = {\n        $id: `#/${datasource.slug}`,\n        title: type,\n        type: 'string',\n        enum: enumValues,\n      };\n      return datasourceSchema;\n    });\n    const resolvedDatasourcesSchemaWithNulls = await Promise.all(datasourcesSchema);\n    const resolvedDatasourcesSchema = resolvedDatasourcesSchemaWithNulls.filter((s): s is JSONSchema => s !== null);\n\n    // Track which schemas are components, datasources, or other types\n    const componentTitles = new Set(resolvedComponentsSchema.map(s => s.title).filter(Boolean));\n    const datasourceTitles = new Set(resolvedDatasourcesSchema.map(s => s.title).filter(Boolean));\n\n    const contentTypeSchema: JSONSchema = {\n      $id: `#/ContentType`,\n      title: 'ContentType',\n      type: 'string',\n      tsType: contentTypeBloks.size > 0 ? `${Array.from(contentTypeBloks).join(' | ')}` : 'never',\n    };\n    const schemas = [\n      ...resolvedComponentsSchema,\n      ...resolvedDatasourcesSchema,\n      contentTypeSchema,\n    ];\n\n    const result = await Promise.all(schemas.map(async (schema) => {\n    // Use the title as the interface name\n      const title = schema.title || schema.$id.replace('#/', '');\n      return {\n        title,\n        content: await compile(schema, title, {\n          additionalProperties: !options.strict,\n          bannerComment: '',\n          ...compilerOptions,\n        }),\n        isComponent: componentTitles.has(title),\n        isDatasource: datasourceTitles.has(title),\n      };\n    }));\n\n    // Add imports for Storyblok types if needed\n    const imports = generateStoryblokImports(storyblokPropertyTypes, STORY_TYPE);\n\n    // If separate files, return an array of individual type definitions\n    if (options.separateFiles) {\n      const files: Array<{ name: string; content: string }> = [];\n\n      // Get datasource and ContentType schemas\n      const datasourceResults = result.filter(r => r.isDatasource);\n      const componentResults = result.filter(r => r.isComponent);\n\n      // Create datasources file if there are any\n      const datasourcesFile = createDatasourcesFile(datasourceResults, typeDefs);\n      if (datasourcesFile) {\n        files.push(datasourcesFile);\n      }\n\n      // Create content-types file if ContentType exists\n      // Pass contentTypeBloks to properly generate the union type with imports\n      const contentTypesFile = createContentTypesFile(\n        contentTypeBloks,\n        typeDefs,\n      );\n      if (contentTypesFile) {\n        files.push(contentTypesFile);\n      }\n\n      // For each component, determine which imports it needs and create the file\n      for (const componentResult of componentResults) {\n        const componentImports = generateComponentImports(\n          componentResult.content,\n          componentResult.title,\n          storyblokPropertyTypes,\n          datasourceResults,\n          componentResults,\n          STORY_TYPE,\n        );\n        files.push(createComponentFile(componentResult, typeDefs, componentImports));\n      }\n      return files;\n    }\n\n    // Otherwise, return a single combined file\n    const finalTypeDef = [...typeDefs, ...imports, ...result.map(r => r.content)];\n\n    return [\n      ...finalTypeDef,\n    ].join('\\n');\n  }\n  catch (error) {\n    handleError(error as Error);\n  }\n};\n\nexport const saveTypesToComponentsFile = async (\n  space: string,\n  typedefData: string | Array<{ name: string; content: string }>,\n  options: Pick<GenerateTypesOptions, 'path' | 'filename' | 'separateFiles'>,\n) => {\n  const { filename = DEFAULT_COMPONENT_FILENAME, path, separateFiles } = options;\n  // Ensure we always include the components/space folder structure regardless of custom path\n  const resolvedPath = path\n    ? resolve(process.cwd(), path, 'types', space)\n    : resolvePath(path, `types/${space}`);\n\n  try {\n    if (separateFiles && Array.isArray(typedefData)) {\n      // Save each component type to a separate file\n      for (const { name, content } of typedefData) {\n        await saveToFile(join(resolvedPath, `${name}.d.ts`), content);\n      }\n    }\n    else if (typeof typedefData === 'string') {\n      // Save all types to a single file\n      await saveToFile(join(resolvedPath, `${filename}.d.ts`), typedefData);\n    }\n  }\n  catch (error) {\n    handleFileSystemError('write', error as Error);\n  }\n};\n\n/**\n * Generates a d.ts file with the Storyblok type definitions\n * @param options - Options for generating the types\n * @returns Promise that resolves when the file is saved\n */\nexport const generateStoryblokTypes = async (options: Pick<GenerateTypesOptions, 'path'> = {}) => {\n  const { path } = options;\n\n  try {\n    // Get the path to the storyblok.ts file\n\n    const storyblokTypesPath = resolve(__dirname, './index.d.ts');\n    // Read the content of the storyblok.ts file\n    const storyblokTypesContent = readFileSync(storyblokTypesPath, 'utf-8');\n\n    // Define the content of the d.ts file\n    const typeDefs = [\n      '// This file was generated by the Storyblok CLI.',\n      '// DO NOT MODIFY THIS FILE BY HAND.',\n      `import type { ${STORY_TYPE} } from '@storyblok/js';`,\n      storyblokTypesContent,\n    ].join('\\n');\n\n    // Determine the path to save the file\n    const resolvedPath = path\n      ? resolve(process.cwd(), path, 'types')\n      : resolvePath(path, 'types');\n\n    await saveToFile(join(resolvedPath, `storyblok.d.ts`), typeDefs);\n    return true;\n  }\n  catch (error) {\n    handleFileSystemError('read', error as Error);\n    return false;\n  }\n};\n","import { readdir } from 'node:fs/promises';\nimport { join } from 'pathe';\nimport chalk from 'chalk';\nimport type { DatasourceEntry, SpaceDatasource, SpaceDatasourcesData } from '../constants';\nimport type { DatasourceCreate, DatasourceUpdate } from '../../../types';\nimport type { ReadDatasourcesOptions } from './constants';\nimport { filterJsonBySuffix, readJsonFile, resolvePath } from '../../../utils/filesystem';\nimport { getMapiClient } from '../../../api';\nimport { handleAPIError } from '../../../utils/error/api-error';\nimport { FileSystemError, handleFileSystemError } from '../../../utils/error/filesystem-error';\n\nexport const pushDatasource = async (spaceId: string, datasource: DatasourceCreate): Promise<SpaceDatasource | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.datasources.create({\n      path: {\n        space_id: Number(spaceId),\n      },\n      body: { datasource },\n      throwOnError: true,\n    });\n\n    return data.datasource;\n  }\n  catch (error) {\n    handleAPIError('push_datasource', error as Error, `Failed to push datasource ${datasource.name}`);\n  }\n};\n\nexport const updateDatasource = async (spaceId: string, datasourceId: number, datasource: DatasourceUpdate): Promise<SpaceDatasource | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.datasources.update(datasourceId, {\n      path: {\n        space_id: Number(spaceId),\n      },\n      body: {\n        datasource,\n      },\n      throwOnError: true,\n    });\n\n    return data.datasource;\n  }\n  catch (error) {\n    handleAPIError('update_datasource', error as Error, `Failed to update datasource ${datasource.name}`);\n  }\n};\n\nexport const upsertDatasource = async (space: string, datasource: DatasourceCreate, existingId?: number): Promise<SpaceDatasource | undefined> => {\n  if (existingId) {\n    return await updateDatasource(space, existingId, datasource);\n  }\n  else {\n    return await pushDatasource(space, datasource);\n  }\n};\n\n/**\n * Creates a new datasource entry in the specified space.\n * @param spaceId - The space ID\n * @param datasourceId - The datasource ID to add the entry to\n * @param entry - The datasource entry to create\n * @param position - Optional position index to control ordering\n * @returns The created datasource entry\n */\nexport const pushDatasourceEntry = async (spaceId: string, datasourceId: number, entry: DatasourceEntry, position?: number): Promise<DatasourceEntry | undefined> => {\n  try {\n    const client = getMapiClient();\n\n    const { data } = await client.datasourceEntries.create({\n      path: {\n        space_id: Number(spaceId),\n      },\n      body: {\n        datasource_entry: {\n          ...entry,\n          value: entry.value ?? '',\n          datasource_id: datasourceId,\n          ...(position != null && { position }),\n        },\n      } as any,\n      throwOnError: true,\n    });\n\n    return data.datasource_entry;\n  }\n  catch (error) {\n    handleAPIError('push_datasource', error as Error, `Failed to push datasource entry ${entry.name}`);\n  }\n};\n\n/**\n * Updates an existing datasource entry in the specified space.\n * @param spaceId - The space ID\n * @param entryId - The ID of the entry to update\n * @param entry - The updated datasource entry data\n * @param position - Optional position index to control ordering\n */\nexport const updateDatasourceEntry = async (spaceId: string, entryId: number, entry: DatasourceEntry, position?: number): Promise<void> => {\n  try {\n    const client = getMapiClient();\n    await client.datasourceEntries.update(entryId, {\n      path: {\n        space_id: Number(spaceId),\n      },\n      body: {\n        datasource_entry: {\n          ...entry,\n          ...(position != null && { position }),\n        },\n      } as any,\n      throwOnError: true,\n    });\n  }\n  catch (error) {\n    handleAPIError('update_datasource', error as Error, `Failed to update datasource entry ${entry.name}`);\n  }\n};\n\n/**\n * Creates or updates a datasource entry based on whether it already exists.\n * @param space - The space ID\n * @param datasourceId - The datasource ID (only needed for creation)\n * @param entry - The datasource entry to upsert\n * @param existingId - The existing entry ID if updating\n * @param position - Optional position index to control ordering\n * @returns The created or updated datasource entry\n */\nexport const upsertDatasourceEntry = async (\n  space: string,\n  datasourceId: number,\n  entry: DatasourceEntry,\n  existingId?: number,\n  position?: number,\n): Promise<DatasourceEntry | undefined> => {\n  if (existingId) {\n    await updateDatasourceEntry(space, existingId, entry, position);\n    return undefined;\n  }\n  else {\n    return await pushDatasourceEntry(space, datasourceId, entry, position);\n  }\n};\n\n/**\n * Deletes a datasource entry from the specified space.\n * @param spaceId - The space ID\n * @param entryId - The ID of the entry to delete\n */\nexport const deleteDatasourceEntry = async (spaceId: string, entryId: number): Promise<void> => {\n  try {\n    const client = getMapiClient();\n    await client.datasourceEntries.delete(entryId, {\n      path: {\n        space_id: Number(spaceId),\n      },\n      throwOnError: true,\n    });\n  }\n  catch (error) {\n    handleAPIError('delete_datasource_entry', error as Error, `Failed to delete datasource entry ${entryId}`);\n  }\n};\n\nfunction isDatasource(item: unknown): item is SpaceDatasource {\n  return typeof item === 'object'\n    && item !== null\n    && 'slug' in item\n    && typeof item.slug === 'string';\n}\n\nexport const readDatasourcesFiles = async (options: ReadDatasourcesOptions): Promise<SpaceDatasourcesData> => {\n  const { from, path, suffix } = options;\n  const resolvedPath = resolvePath(path, `datasources/${from}`);\n\n  let files: string[];\n  try {\n    files = await readdir(resolvedPath);\n  }\n  catch (error) {\n    const message = `No local datasources found for space ${chalk.bold(from)}. To push datasources, you need to pull them first:\n\n1. Pull the datasources from your source space:\n   ${chalk.cyan(`storyblok datasources pull --space ${from}`)}\n\n2. Then try pushing again:\n   ${chalk.cyan(`storyblok datasources push --space <target_space> --from ${from}`)}`;\n\n    throw new FileSystemError(\n      'file_not_found',\n      'read',\n      error as Error,\n      message,\n    );\n  }\n\n  const datasourceMap = new Map<string, { datasource: SpaceDatasource; file: string }>();\n  const duplicates: string[] = [];\n\n  for (const file of filterJsonBySuffix(files, suffix)) {\n    const { data, error } = await readJsonFile<unknown>(join(resolvedPath, file));\n    if (error) {\n      handleFileSystemError('read', error);\n      continue;\n    }\n\n    for (const item of data) {\n      if (isDatasource(item)) {\n        const existing = datasourceMap.get(item.slug);\n        if (existing) {\n          duplicates.push(`Datasource \"${item.slug}\" found in both \"${existing.file}\" and \"${file}\"`);\n        }\n        datasourceMap.set(item.slug, { datasource: item, file });\n      }\n    }\n  }\n\n  if (duplicates.length) {\n    throw new FileSystemError(\n      'file_not_found',\n      'read',\n      new Error('Duplicate datasources detected'),\n      `Duplicate datasources found in ${resolvedPath}:\\n\\n${duplicates.join('\\n')}\\n\\nThis can happen when multiple environment snapshots (e.g. datasources.json and datasources.dev.json) or mixed formats coexist in the same directory.\\n\\nTo fix this, either:\\n  - Use --suffix <env> to target a specific environment (e.g. --suffix dev)\\n  - Clean up the directory and pull datasources again in the format you intend`,\n    );\n  }\n\n  const datasources = [...datasourceMap.values()].map(({ datasource }) => datasource);\n  if (!datasources.length) {\n    throw new FileSystemError(\n      'file_not_found',\n      'read',\n      new Error('No datasource data found'),\n      `No datasources found in ${resolvedPath}. Please make sure you have pulled the datasources first.`,\n    );\n  }\n\n  return { datasources };\n};\n","import type { Command } from 'commander';\nimport { colorPalette, commands } from '../../../constants';\nimport { FileSystemError, handleError, konsola } from '../../../utils';\nimport { Spinner } from '@topcli/spinner';\nimport { type ComponentsData, readComponentsFiles } from '../../components/push/actions';\nimport type { GenerateTypesOptions } from './constants';\nimport { typesCommand } from '../command';\nimport { generateStoryblokTypes, generateTypes, saveTypesToComponentsFile } from './actions';\nimport { readDatasourcesFiles } from '../../datasources/push/actions';\nimport type { SpaceDatasourcesData } from '../../../commands/datasources/constants';\n\nconst generateCmd = typesCommand\n  .command('generate')\n  .description('Generate types d.ts for your component schemas')\n  .option(\n    '--filename <name>',\n    'Base file name for all component types when generating a single declarations file (e.g. components.d.ts). Ignored when using --separate-files.',\n  )\n  .option('--sf, --separate-files', 'Generate one .d.ts file per component instead of a single combined file')\n  .option('--strict', 'strict mode, no loose typing')\n  .option('--type-prefix <prefix>', 'prefix to be prepended to all generated component type names')\n  .option('--type-suffix <suffix>', 'suffix to be appended to all generated component type names')\n  .option('--suffix <suffix>', 'Components suffix')\n  .option('--custom-fields-parser <path>', 'Path to the parser file for Custom Field Types')\n  .option('--compiler-options <options>', 'path to the compiler options from json-schema-to-typescript')\n  .option('-s, --space <space>', 'space ID');\n\ngenerateCmd\n  .action(async (options: GenerateTypesOptions, command: Command) => {\n    konsola.title(`${commands.TYPES}`, colorPalette.TYPES, 'Generating types...');\n\n    const { space, path, verbose, suffix, filename, separateFiles } = command.optsWithGlobals();\n\n    const spinner = new Spinner({\n      verbose,\n    });\n\n    try {\n      spinner.start(`Generating types...`);\n      // Input format is auto-detected based on files on disk\n      const componentsData = await readComponentsFiles({\n        from: space,\n        path,\n        suffix,\n        verbose,\n      });\n      // Try to read datasources, but make it optional\n      let dataSourceData: SpaceDatasourcesData;\n      try {\n        dataSourceData = await readDatasourcesFiles({\n          from: space,\n          path,\n          suffix,\n          verbose,\n        });\n      }\n      catch (error) {\n        // Only catch the specific case where datasources don't exist\n        if (error instanceof FileSystemError && error.errorId === 'file_not_found') {\n          dataSourceData = { datasources: [] };\n        }\n        else {\n          throw error;\n        }\n      }\n      await generateStoryblokTypes({\n        path,\n      });\n\n      // Add empty datasources array to match expected type for generateTypes\n      const spaceDataWithComponentsAndDatasources: ComponentsData & SpaceDatasourcesData = {\n        ...componentsData,\n        ...dataSourceData,\n      };\n\n      const typedefData = await generateTypes(spaceDataWithComponentsAndDatasources, {\n        ...options,\n      });\n\n      if (typedefData) {\n        await saveTypesToComponentsFile(space, typedefData, {\n          filename,\n          path,\n          separateFiles,\n        });\n      }\n\n      spinner.succeed();\n      if (separateFiles && filename) {\n        konsola.warn(`The --filename option is ignored when using --separate-files`);\n      }\n\n      konsola.ok(`Successfully generated types for space ${space}`, true);\n      konsola.br();\n    }\n    catch (error) {\n      spinner.failed(`Failed to generate types for space ${space}`);\n      konsola.br();\n      handleError(error as Error, verbose);\n    }\n  });\n","import { commands } from '../../constants';\nimport { getProgram } from '../../program';\n\nconst program = getProgram(); // Get the shared singleton instance\n\n// Components root command\nexport const datasourcesCommand = program\n  .command(commands.DATASOURCES)\n  .alias('ds')\n  .description(`Manage your space's datasources`);\n","import type { Datasource, DatasourceEntry } from '../../types';\n\nexport type { DatasourceEntry };\n\nexport const DEFAULT_DATASOURCES_FILENAME = 'datasources';\n\nexport type SpaceDatasource = Datasource & {\n  entries?: DatasourceEntry[];\n};\n\nexport interface SpaceDatasourcesData {\n  datasources: SpaceDatasource[];\n}\n\nexport interface SpaceDatasourcesDataState {\n  local: SpaceDatasourcesData;\n  target: {\n    datasources: Map<string, SpaceDatasource>;\n  };\n}\n","import { handleAPIError, handleFileSystemError } from '../../../utils';\nimport { getMapiClient } from '../../../api';\nimport { join, resolve } from 'pathe';\nimport { resolvePath, sanitizeFilename, saveToFile } from '../../../utils/filesystem';\nimport { fetchAllPages } from '../../../utils/pagination';\nimport type { DatasourceEntry, SpaceDatasource } from '../constants';\nimport { DEFAULT_DATASOURCES_FILENAME } from '../constants';\nimport type { SaveDatasourcesOptions } from './constants';\n\n/**\n * Fetches entries for a given datasource id in a space.\n * @param spaceId - The space ID\n * @param datasourceId - The datasource ID\n * @returns Array of datasource entries\n */\nexport const fetchDatasourceEntries = async (\n  spaceId: string,\n  datasourceId: number,\n): Promise<DatasourceEntry[] | undefined> => {\n  try {\n    const client = getMapiClient();\n    return await fetchAllPages(\n      (page: number) => client.datasourceEntries.list({\n        path: {\n          space_id: Number(spaceId),\n        },\n        query: {\n          datasource_id: datasourceId,\n          page,\n        },\n        throwOnError: true,\n      }),\n      data => data?.datasource_entries || [],\n    );\n  }\n  catch (error) {\n    // Use 'pull_datasources' as the closest valid action for datasource entries errors\n    handleAPIError('pull_datasources', error as Error);\n  }\n};\n\nexport const fetchDatasources = async (spaceId: string): Promise<SpaceDatasource[] | undefined> => {\n  try {\n    const client = getMapiClient();\n    const datasources = await fetchAllPages(\n      (page: number) => client.datasources.list({\n        path: {\n          space_id: Number(spaceId),\n        },\n        query: {\n          page,\n        },\n        throwOnError: true,\n      }),\n      data => data.datasources || [],\n    );\n    // Fetch entries for each datasource in parallel\n    const datasourcesWithEntries = await Promise.all(\n      datasources.map(async (ds: SpaceDatasource) => {\n        if (!ds.id) {\n          return { ...ds, entries: [] };\n        }\n        const entries = await fetchDatasourceEntries(spaceId, ds.id);\n        return { ...ds, entries };\n      }),\n    );\n    return datasourcesWithEntries;\n  }\n  catch (error) {\n    handleAPIError('pull_datasources', error as Error);\n  }\n};\n\nexport const fetchDatasource = async (spaceId: string, datasourceName: string): Promise<SpaceDatasource | undefined> => {\n  try {\n    const client = getMapiClient();\n    const matches = await fetchAllPages(\n      (page: number) => client.datasources.list({\n        path: {\n          space_id: Number(spaceId),\n        },\n        query: {\n          page,\n          search: datasourceName,\n        },\n        throwOnError: true,\n      }),\n      data => data.datasources || [],\n    );\n    const found = matches.find((d: SpaceDatasource) => d.name === datasourceName);\n    if (!found) { return undefined; }\n    // Fetch entries for the found datasource\n    const entries = await fetchDatasourceEntries(spaceId, found.id as number);\n    return { ...found, entries: entries || [] } as SpaceDatasource;\n  }\n  catch (error) {\n    handleAPIError('pull_datasources', error as Error, `Failed to fetch datasource ${datasourceName}`);\n  }\n};\n\n// Filesystem actions\n\nexport const saveDatasourcesToFiles = async (\n  space: string,\n  datasources: SpaceDatasource[],\n  options: SaveDatasourcesOptions,\n) => {\n  const { filename = DEFAULT_DATASOURCES_FILENAME, suffix, path, separateFiles } = options;\n  // Ensure we always include the datasources/space folder structure regardless of custom path\n  const resolvedPath = path\n    ? resolve(process.cwd(), path, 'datasources', space)\n    : resolvePath(path, `datasources/${space}`);\n\n  try {\n    if (separateFiles) {\n      // Save in separate files without nested structure\n      for (const datasource of datasources) {\n        const sanitizedName = sanitizeFilename(datasource.name || '');\n        const datasourceFilePath = join(resolvedPath, suffix ? `${sanitizedName}.${suffix}.json` : `${sanitizedName}.json`);\n        await saveToFile(datasourceFilePath, JSON.stringify(datasource, null, 2));\n      }\n      return;\n    }\n\n    // Default to saving consolidated files\n    const datasourcesFilePath = join(resolvedPath, suffix ? `${filename}.${suffix}.json` : `${filename}.json`);\n    await saveToFile(datasourcesFilePath, JSON.stringify(datasources, null, 2));\n  }\n  catch (error) {\n    handleFileSystemError('write', error as Error);\n  }\n};\n","import type { Command } from 'commander';\nimport { colorPalette, commands, directories } from '../../../constants';\nimport { session } from '../../../session';\n\nimport { datasourcesCommand } from '../command';\nimport type { PullDatasourcesOptions } from './constants';\nimport { CommandError, handleError, konsola, requireAuthentication } from '../../../utils';\nimport chalk from 'chalk';\nimport { fetchDatasource, fetchDatasources, saveDatasourcesToFiles } from './actions';\nimport { isAbsolute, join, relative } from 'pathe';\nimport { resolveCommandPath } from '../../../utils/filesystem';\nimport { DEFAULT_DATASOURCES_FILENAME } from '../constants';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\n\nconst pullCmd = datasourcesCommand\n  .command('pull [datasourceName]')\n  .option('-f, --filename <filename>', 'custom name to be used in file(s) name instead of space id')\n  .option('--sf, --separate-files', 'Argument to create a single file for each datasource')\n  .option('--su, --suffix <suffix>', 'suffix to add to the file name (e.g. datasources.<suffix>.json)')\n  .option('-s, --space <space>', 'space ID')\n  .description('Pull datasources from your space');\n\npullCmd\n  .action(async (datasourceName: string | undefined, options: PullDatasourcesOptions, command: Command) => {\n    konsola.title(`${commands.DATASOURCES}`, colorPalette.DATASOURCES, datasourceName ? `Pulling datasource ${datasourceName}...` : 'Pulling datasources...');\n\n    const { space, path, verbose } = command.optsWithGlobals();\n    const {\n      separateFiles = false,\n      suffix,\n      filename,\n    } = options;\n\n    // Use default filename when not provided\n    const actualFilename = filename ?? DEFAULT_DATASOURCES_FILENAME;\n    // Keep writing under .storyblok unless a command-level --path explicitly overrides it.\n    const datasourcesOutputDir = resolveCommandPath(directories.datasources, space, path);\n\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n    if (!space) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      return;\n    }\n\n    const ui = getUI();\n    const logger = getLogger();\n    logger.info('Pulling datasources started', { space, datasourceName });\n    const spinnerDatasources = ui.createSpinner(`Fetching ${chalk.hex(colorPalette.DATASOURCES)('datasources')}`);\n\n    try {\n      let datasources;\n      if (datasourceName) {\n        const datasource = await fetchDatasource(space, datasourceName);\n        if (!datasource) {\n          spinnerDatasources.failed(`No datasource found with name \"${datasourceName}\"`);\n          return;\n        }\n        datasources = [datasource];\n      }\n      else {\n        datasources = await fetchDatasources(space);\n        if (!datasources || datasources.length === 0) {\n          spinnerDatasources.failed(`No datasources found in the space ${space}`);\n          return;\n        }\n      }\n\n      spinnerDatasources.succeed(`${chalk.hex(colorPalette.DATASOURCES)('Datasources')} - Completed in ${spinnerDatasources.elapsedTime.toFixed(2)}ms`);\n\n      await saveDatasourcesToFiles(\n        space,\n        datasources,\n        { ...options, path, separateFiles: separateFiles || !!datasourceName },\n      );\n      konsola.br();\n      if (separateFiles) {\n        if (filename && filename !== DEFAULT_DATASOURCES_FILENAME) {\n          konsola.warn(`The --filename option is ignored when using --separate-files`);\n        }\n        const filePath = `${datasourcesOutputDir}/`;\n        // Only show relative path if the base path wasn't absolute\n        const displayPath = (path && isAbsolute(path)) ? filePath : `${relative(process.cwd(), datasourcesOutputDir)}/`;\n        konsola.ok(`Datasources downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);\n      }\n      else if (datasourceName) {\n        const fileName = suffix ? `${actualFilename}.${suffix}.json` : `${datasourceName}.json`;\n        const filePath = join(datasourcesOutputDir, fileName);\n        // Only show relative path if the base path wasn't absolute\n        const displayPath = (path && isAbsolute(path)) ? filePath : relative(process.cwd(), filePath);\n        konsola.ok(`Datasource ${chalk.hex(colorPalette.PRIMARY)(datasourceName)} downloaded successfully in ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);\n      }\n      else {\n        const fileName = suffix ? `${actualFilename}.${suffix}.json` : `${actualFilename}.json`;\n        const filePath = join(datasourcesOutputDir, fileName);\n        // Only show relative path if the base path wasn't absolute\n        const displayPath = (path && isAbsolute(path)) ? filePath : relative(process.cwd(), filePath);\n        konsola.ok(`Datasources downloaded successfully to ${chalk.hex(colorPalette.PRIMARY)(displayPath)}`);\n      }\n      konsola.br();\n    }\n    catch (error) {\n      spinnerDatasources.failed(`Fetching ${chalk.hex(colorPalette.DATASOURCES)('Datasources')} - Failed`);\n      konsola.br();\n      handleError(error as Error, verbose);\n    }\n    finally {\n      logger.info('Pulling datasources finished', { space, datasourceName });\n    }\n  });\n","import type { Command } from 'commander';\nimport { colorPalette, commands } from '../../../constants';\nimport { CommandError, handleError, konsola, requireAuthentication } from '../../../utils';\nimport { datasourcesCommand } from '../command';\nimport type { PushDatasourcesOptions } from './constants';\nimport { session } from '../../../session';\nimport chalk from 'chalk';\nimport type { SpaceDatasource, SpaceDatasourcesDataState } from '../constants';\nimport { deleteDatasourceEntry, readDatasourcesFiles, upsertDatasource, upsertDatasourceEntry } from './actions';\nimport { fetchDatasources } from '../pull/actions';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\n\nconst pushCmd = datasourcesCommand\n  .command('push [datasourceName]')\n  .description(`Push your space's datasources schema as json`)\n  .option('-f, --from <from>', 'source space id')\n  .option('--fi, --filter <filter>', 'glob filter to apply to the datasources before pushing')\n  .option('--sf, --separate-files', 'Read from separate files instead of consolidated files')\n  .option('--su, --suffix <suffix>', 'Load only files matching *.<suffix>.json (e.g. datasources.dev.json)')\n  .option('-s, --space <space>', 'space ID');\n\npushCmd\n  .action(async (datasourceName: string | undefined, options: PushDatasourcesOptions, command: Command) => {\n    konsola.title(`${commands.DATASOURCES}`, colorPalette.DATASOURCES, datasourceName ? `Pushing datasource ${datasourceName}...` : 'Pushing datasources...');\n\n    const { space, path, verbose } = command.optsWithGlobals();\n\n    const { filter } = options;\n    const fromSpace = options.from || space;\n\n    // Check if the user is logged in\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n\n    // Check if the space is provided\n    if (!space) {\n      handleError(new CommandError(`Please provide the target space as argument --space TARGET_SPACE_ID.`), verbose);\n      return;\n    }\n    const logger = getLogger();\n    logger.info('Pushing datasources started', { space, fromSpace, datasourceName, filter });\n\n    konsola.info(`Attempting to push datasources ${chalk.bold('from')} space ${chalk.hex(colorPalette.DATASOURCES)(fromSpace)} ${chalk.bold('to')} ${chalk.hex(colorPalette.DATASOURCES)(space)}`);\n    konsola.br();\n\n    try {\n      // Read datasources data from source space (from option or target space)\n      const spaceState: SpaceDatasourcesDataState = {\n        local: await readDatasourcesFiles({\n          ...options,\n          path,\n          from: fromSpace,\n        }),\n        target: {\n          datasources: new Map(),\n        },\n      };\n\n      const targetSpaceDatasources = await fetchDatasources(space);\n\n      if (targetSpaceDatasources) {\n        (targetSpaceDatasources as SpaceDatasource[]).forEach((datasource) => {\n          spaceState.target.datasources.set(datasource.name, datasource);\n        });\n      }\n\n      if (datasourceName) {\n        spaceState.local = {\n          datasources: [spaceState.local.datasources.find(datasource => datasource.name === datasourceName) || [] as unknown as SpaceDatasource],\n        };\n        if (!spaceState.local.datasources.length) {\n          handleError(new CommandError(`Datasource \"${datasourceName}\" not found.`), verbose);\n          return;\n        }\n      }\n      else if (filter) {\n        spaceState.local.datasources = spaceState.local.datasources.filter(datasource => datasource.name.includes(filter));\n        if (!spaceState.local.datasources.length) {\n          handleError(new CommandError(`No datasources found matching pattern \"${filter}\".`), verbose);\n          return;\n        }\n        konsola.info(`Filter applied: ${filter}`);\n      }\n\n      if (!spaceState.local.datasources.length) {\n        konsola.warn('No datasources found. Please make sure you have pulled the datasources first.');\n        return;\n      }\n\n      const results = {\n        successful: [] as string[],\n        failed: [] as Array<{ name: string; error: unknown }>,\n      };\n\n      const ui = getUI();\n\n      for (const datasource of spaceState.local.datasources) {\n        const spinner = ui.createSpinner(`Pushing ${chalk.hex(colorPalette.DATASOURCES)(datasource.name)}`);\n\n        // Check if datasource already exists in target space by name\n        const existingDatasource = spaceState.target.datasources.get(datasource.name);\n        const existingId = existingDatasource?.id;\n\n        // Extract entries to handle separately (entries are not part of datasource definition)\n        const { entries, ...datasourceDefinition } = datasource;\n\n        const result = await upsertDatasource(space, datasourceDefinition, existingId);\n        if (result) {\n          results.successful.push(datasource.name);\n\n          // Sync entries: upsert all local entries with position, then delete stale target entries\n          const localEntries = entries ?? [];\n          const existingEntries = existingDatasource?.entries ?? [];\n\n          // Index existing entries by name with their position for O(1) lookup\n          const existingEntryMap = new Map(existingEntries.map((e, idx) => [e.name, { entry: e, position: idx + 1 }]));\n\n          for (let i = 0; i < localEntries.length; i++) {\n            const entry = localEntries[i];\n            const existing = existingEntryMap.get(entry.name);\n            const existingEntryId = existing?.entry.id;\n            const targetPosition = i + 1;\n\n            // Skip update when all mutable fields and position are identical\n            if (existing\n              && existing.entry.value === entry.value\n              && existing.entry.dimension_value === entry.dimension_value\n              && existing.position === targetPosition) {\n              logger.info('Skipped datasource entry (unchanged)', { datasource: datasource.name, entry: entry.name, position: targetPosition });\n              continue;\n            }\n\n            try {\n              await upsertDatasourceEntry(space, result.id, entry, existingEntryId, i + 1);\n              logger.info(existingEntryId ? 'Updated datasource entry' : 'Created datasource entry', { datasource: datasource.name, entry: entry.name, position: i + 1 });\n            }\n            catch (entryError) {\n              results.failed.push({ name: datasource.name, error: entryError });\n              spinner.failed(`${chalk.hex(colorPalette.DATASOURCES)(datasource.name)} - Failed in ${spinner.elapsedTime.toFixed(2)}ms`);\n            }\n          }\n\n          // Delete target entries that are not present in the local source\n          const localEntryNames = new Set(localEntries.map(e => e.name));\n          const staleEntries = existingEntries.filter(e => !localEntryNames.has(e.name));\n          for (const stale of staleEntries) {\n            try {\n              await deleteDatasourceEntry(space, stale.id);\n              logger.info('Deleted datasource entry', { datasource: datasource.name, entry: stale.name, entryId: stale.id });\n            }\n            catch (entryError) {\n              results.failed.push({ name: datasource.name, error: entryError });\n              spinner.failed(`${chalk.hex(colorPalette.DATASOURCES)(datasource.name)} - Failed in ${spinner.elapsedTime.toFixed(2)}ms`);\n            }\n          }\n\n          spinner.succeed(`${chalk.hex(colorPalette.DATASOURCES)(datasource.name)} - Completed in ${spinner.elapsedTime.toFixed(2)}ms`);\n        }\n        else {\n          results.failed.push({ name: datasource.name, error: result });\n          spinner.failed(`${chalk.hex(colorPalette.DATASOURCES)(datasource.name)} - Failed in ${spinner.elapsedTime.toFixed(2)}ms`);\n        }\n      }\n\n      if (results.failed.length > 0) {\n        if (!verbose) {\n          konsola.br();\n          konsola.info('For more information about the error, run the command with the `--verbose` flag');\n        }\n        else {\n          results.failed.forEach((failed) => {\n            handleError(failed.error as Error, verbose);\n          });\n        }\n      }\n    }\n    catch (error) {\n      handleError(error as Error, verbose);\n    }\n    finally {\n      logger.info('Pushing datasources finished', { space, fromSpace });\n    }\n  });\n","import { getMapiClient } from '../../../api';\nimport { handleAPIError } from '../../../utils';\n\n/**\n * Deletes a datasource by id from a Storyblok space.\n * @param spaceId - The space ID\n * @param id - The datasource id\n */\nexport async function deleteDatasource(spaceId: string, id: string): Promise<void> {\n  try {\n    const client = getMapiClient();\n    // Call the Storyblok Management API to delete the datasource by id\n    await client.datasources.delete(Number(id), {\n      path: {\n        space_id: Number(spaceId),\n      },\n      throwOnError: true,\n    });\n  }\n  catch (error) {\n    handleAPIError('delete_datasource', error as Error, `Datasource with id '${id}' not found in space ${spaceId}.`);\n  }\n}\n","import type { Command } from 'commander';\nimport { datasourcesCommand } from '../command';\nimport { deleteDatasource } from './actions';\nimport { CommandError, handleError, konsola, requireAuthentication } from '../../../utils';\nimport { session } from '../../../session';\nimport { colorPalette, commands } from '../../../constants';\nimport chalk from 'chalk';\nimport type { DeleteDatasourceOptions } from './constants';\nimport { fetchDatasource } from '../pull/actions';\nimport { confirm } from '@inquirer/prompts';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\n// Register the delete command under datasources\n// Usage: storyblok datasources delete <name> --space <SPACE_ID> [--id <ID>]\nconst deleteCmd = datasourcesCommand\n  .command('delete [name]')\n  .description('Delete a datasource from your space by name or id')\n  .option('--id <id>', 'Delete by datasource id instead of name')\n  .option('--force', 'Skip confirmation prompt for deletion (useful for CI)')\n  .option('-s, --space <space>', 'space ID');\n\ndeleteCmd\n  .action(async (name: string, options: DeleteDatasourceOptions, command: Command) => {\n    konsola.title(\n      `${commands.DATASOURCES}`,\n      colorPalette.DATASOURCES,\n      options.id\n        ? `Deleting datasource with id ${options.id}...`\n        : `Deleting datasource with name ${name}...`,\n    );\n\n    // Warn if both name and id are provided\n    if (name && options.id) {\n      konsola.warn(\n        'Both a datasource name and an id were provided. Only one is required. The id will be used as the source of truth.',\n      );\n    }\n\n    // Get global options\n    const { space, verbose } = command.optsWithGlobals();\n\n    // Authenticate user\n    const { state } = session();\n    if (!requireAuthentication(state, verbose)) { return; }\n    if (!space) {\n      handleError(new CommandError('Please provide the space as argument --space YOUR_SPACE_ID.'), verbose);\n      return;\n    }\n\n    const ui = getUI();\n    const logger = getLogger();\n    logger.info('Deleting datasource started', { space, name, id: options.id });\n\n    try {\n      // Use id if provided, otherwise use name\n      if (options.id) {\n        // Delete by id\n        const spinner = ui.createSpinner(`Deleting datasource...`);\n        await deleteDatasource(space, options.id);\n        spinner.succeed(`Datasource deleted`);\n        konsola.ok(`Datasource ${chalk.hex(colorPalette.DATASOURCES)(options.id)} deleted successfully from space ${space}.`);\n      }\n      else {\n        // Delete by name\n        const datasource = await fetchDatasource(space, name);\n        if (!datasource) {\n          throw new CommandError(`Datasource with name '${name}' not found in space ${space}.`);\n        }\n        // If --force is not set, prompt for confirmation\n        if (!options.force) {\n          // Echo datasource details to the user for confirmation\n          konsola.info(`Datasource details:`);\n          console.log(`  Name: ${chalk.hex(colorPalette.DATASOURCES)(datasource.name)}`);\n          console.log(`  ID: ${chalk.hex(colorPalette.DATASOURCES)(datasource.id)}`);\n          console.log(`  Space: ${chalk.hex(colorPalette.DATASOURCES)(space)}`);\n          console.log(`  Slug: ${chalk.hex(colorPalette.DATASOURCES)(datasource.slug)}`);\n          console.log(`  Created at: ${chalk.hex(colorPalette.DATASOURCES)(datasource.created_at)}`);\n          console.log(`  Updated at: ${chalk.hex(colorPalette.DATASOURCES)(datasource.updated_at)}`);\n          konsola.br();\n          // Ask for confirmation\n          const confirmed = await confirm({\n            message: `⚠️ ${chalk.yellow(` Are you sure you want to delete the ${datasource.name} datasource from space ${space}? This action cannot be undone.`)} `,\n            default: false,\n          });\n          if (!confirmed) {\n            konsola.warn('Deletion aborted by user.');\n            return;\n          }\n        }\n        const spinner = ui.createSpinner(`Deleting datasource...`);\n        await deleteDatasource(space, datasource.id.toString());\n        spinner.succeed(`Datasource deleted`);\n        konsola.ok(`Datasource ${chalk.hex(colorPalette.DATASOURCES)(name)} deleted successfully from space ${space}.`);\n      }\n    }\n    catch (error) {\n      handleError(error as Error, verbose);\n    }\n    finally {\n      logger.info('Deleting datasource finished', { space, name, id: options.id });\n    }\n  });\n","import { Octokit } from 'octokit';\n\nlet octokit: Octokit;\nlet lastToken: string | undefined;\n\nexport const createOctokit = (token?: string) => {\n  if (!octokit || token !== lastToken) {\n    const options: {\n      auth?: string;\n      request: {\n        fetch: typeof fetch;\n      };\n    } = {\n      request: {\n        fetch,\n      },\n    };\n    if (token) {\n      options.auth = token;\n    }\n    octokit = new Octokit(options);\n  }\n  return octokit;\n};\n","import type { RegionCode } from '../../constants';\n\nexport interface CreateOptions {\n  template?: string;\n  blueprint?: string; // Deprecated, use template instead\n  skipSpace?: boolean;\n  token?: string; // Access token for Storyblok\n  region?: RegionCode;\n}\ntype TemplateTechnology = 'REACT' | 'VUE' | 'SVELTE' | 'ASTRO' | 'NUXT' | 'NEXTJS' | 'ELEVENTY' | 'ANGULAR';\n\nexport interface Template {\n  name: string;\n  value: string;\n  template: string;\n  location: string;\n  description?: string | null;\n  updated_at?: string;\n  stars?: number;\n}\nexport const templates: Record<TemplateTechnology, Template> = {\n  REACT: {\n    name: 'React',\n    value: 'react',\n    template: 'https://github.com/storyblok/blueprint-core-react',\n    location: 'https://localhost:5173/',\n  },\n  VUE: {\n    name: 'Vue',\n    value: 'vue',\n    template: 'https://github.com/storyblok/blueprint-core-vue',\n    location: 'https://localhost:5173/',\n  },\n  SVELTE: {\n    name: 'Svelte',\n    value: 'svelte',\n    template: 'https://github.com/storyblok/blueprint-core-svelte',\n    location: 'https://localhost:5173/',\n  },\n  ASTRO: {\n    name: 'Astro',\n    value: 'astro',\n    template: 'https://github.com/storyblok/blueprint-core-astro',\n    location: 'https://localhost:4321/',\n  },\n  NUXT: {\n    name: 'Nuxt',\n    value: 'nuxt',\n    template: 'https://github.com/storyblok/blueprint-core-nuxt',\n    location: 'https://localhost:3000/',\n  },\n  NEXTJS: {\n    name: 'Next.js',\n    value: 'nextjs',\n    template: 'https://github.com/storyblok/blueprint-core-nextjs',\n    location: 'https://localhost:3000/',\n  },\n  ELEVENTY: {\n    name: 'Eleventy',\n    value: 'eleventy',\n    template: 'https://github.com/storyblok/blueprint-core-eleventy',\n    location: 'https://localhost:8080/',\n  },\n  ANGULAR: {\n    name: 'Angular',\n    value: 'angular',\n    template: 'https://github.com/storyblok/blueprint-core-angular',\n    location: 'https://localhost:4200/',\n  },\n} as const;\n","import { spawn } from 'node:child_process';\nimport { join } from 'pathe';\nimport fs from 'node:fs/promises';\nimport { saveToFile } from '../../utils/filesystem';\nimport { appDomains, type RegionCode } from '../../constants';\nimport { FileSystemError, handleFileSystemError } from '../../utils/error/filesystem-error';\nimport open from 'open';\nimport { createOctokit } from '../../github';\nimport { type Template, templates } from './constants';\nimport { getUI } from '../../utils/ui';\n\nconst ui = getUI({ enabled: true });\n\n/** Repository item from GitHub search API response */\ntype SearchReposResponse = Awaited<ReturnType<ReturnType<typeof createOctokit>['rest']['search']['repos']>>;\ntype SearchRepoItem = SearchReposResponse['data']['items'][number];\n/**\n * Generates a new project from a Storyblok blueprint template\n * @param blueprint - The blueprint name (react, vue, svelte, etc.)\n * @param projectName - The name of the project directory to create\n * @param targetPath - The target directory path where the project should be created\n * @returns Promise<void>\n */\nexport const generateProject = async (\n  blueprint: string,\n  projectName: string,\n  targetPath: string = process.cwd(),\n): Promise<void> => {\n  try {\n    const projectPath = join(targetPath, projectName);\n    const templateRepo = `storyblok/blueprint-core-${blueprint}`;\n\n    // Check if directory already exists\n    try {\n      await fs.access(projectPath);\n      // If we reach this point, the directory already exists\n      // Create a mock ENOTEMPTY error to use with our filesystem error system\n      const existsError: NodeJS.ErrnoException = new Error(`Directory ${projectName} already exists`) as NodeJS.ErrnoException;\n      existsError.code = 'ENOTEMPTY';\n      existsError.path = projectPath;\n      throw new FileSystemError('directory_not_empty', 'mkdir', existsError, `Directory ${projectName} already exists`);\n    }\n    catch (error) {\n      const fsError = error as NodeJS.ErrnoException;\n\n      // Directory doesn't exist (ENOENT), which is what we want\n      if (fsError.code === 'ENOENT') {\n        // Continue with project creation\n      }\n      else {\n        // Handle other filesystem errors using the error handler\n        handleFileSystemError('read', fsError);\n      }\n    }\n\n    // Clone the template repository using degit\n    const degitProcess = spawn('npx', ['degit', templateRepo, projectPath], {\n      stdio: 'inherit',\n      shell: true,\n    });\n\n    return new Promise((resolve, reject) => {\n      degitProcess.on('close', (code) => {\n        if (code === 0) {\n          resolve();\n        }\n        else {\n          reject(new Error(`Failed to clone template. Process exited with code ${code}`));\n        }\n      });\n\n      degitProcess.on('error', (error) => {\n        reject(new Error(`Failed to spawn degit process: ${error.message}`));\n      });\n    });\n  }\n  catch (error) {\n    handleFileSystemError('read', error as NodeJS.ErrnoException);\n  }\n};\n\n/**\n * Creates a .env file in the project directory with Storyblok configuration\n * @param projectPath - The absolute path to the project directory\n * @param storyblokVars - The Storyblok environment variables to include in the .env file\n * @param additionalVars - Optional additional environment variables to include\n * @returns Promise<void>\n */\nexport const createEnvFile = async (\n  projectPath: string,\n  storyblokVars: Record<string, string>,\n  additionalVars?: Record<string, string>,\n): Promise<void> => {\n  try {\n    const envPath = join(projectPath, '.env');\n\n    // Build the .env content\n    let envContent = `# Storyblok Configuration\n${Object.entries(storyblokVars).map(([key, value]) => `${key}=${value}`).join('\\n')}\n`;\n\n    // Add any additional environment variables\n    if (additionalVars && Object.keys(additionalVars).length > 0) {\n      envContent += '\\n# Additional Configuration\\n';\n      for (const [key, value] of Object.entries(additionalVars)) {\n        envContent += `${key}=${value}\\n`;\n      }\n    }\n\n    // Use the filesystem utility to save the file\n    await saveToFile(envPath, envContent);\n  }\n  catch (error) {\n    throw new Error(`Failed to create .env file: ${(error as Error).message}`);\n  }\n};\n\n// Helper to create .env file and handle errors\nexport async function handleEnvFileCreation(resolvedPath: string, token?: string, region?: RegionCode): Promise<boolean> {\n  const envVars: Record<string, string> = {};\n  if (token) {\n    envVars.STORYBLOK_DELIVERY_API_TOKEN = token;\n  }\n  if (region) {\n    envVars.STORYBLOK_REGION = region;\n  }\n  if (Object.keys(envVars).length === 0) {\n    ui.info('No environment variables to write');\n    return true;\n  }\n  try {\n    await createEnvFile(resolvedPath, envVars);\n    const writtenKeys = Object.keys(envVars).join(', ');\n    ui.ok(`Created .env file with: ${writtenKeys}`, true);\n    return true;\n  }\n  catch (error) {\n    ui.warn(`Failed to create .env file: ${(error as Error).message}`);\n    if (token) {\n      ui.info(\n        `You can manually add STORYBLOK_DELIVERY_API_TOKEN to your .env file.`,\n      );\n    }\n    if (region) {\n      ui.info(\n        `You can manually add STORYBLOK_REGION to your .env file.`,\n      );\n    }\n    return false;\n  }\n}\n\n/**\n * Generates the Storyblok app URL for a specific space based on region\n * @param spaceId - The ID of the Storyblok space\n * @param region - The region code (eu, us, cn, ca, ap)\n * @returns The complete URL to the space dashboard\n */\nexport const generateSpaceUrl = (spaceId: number, region: RegionCode): string => {\n  const domain = appDomains[region];\n\n  const utmParams = new URLSearchParams({\n    utm_source: 'storyblok-cli',\n    utm_medium: 'cli',\n    utm_campaign: 'create',\n  });\n  return `https://${domain}/#/me/spaces/${spaceId}/dashboard?${utmParams.toString()}`;\n};\n\n/**\n * Opens the Storyblok space dashboard in the user's default browser\n * @param spaceId - The ID of the Storyblok space\n * @param region - The region code (eu, us, cn, ca, ap)\n * @returns Promise<void>\n */\nexport const openSpaceInBrowser = async (spaceId: number, region: RegionCode): Promise<void> => {\n  try {\n    const spaceUrl = generateSpaceUrl(spaceId, region);\n\n    await open(spaceUrl);\n  }\n  catch (error) {\n    throw new Error(`Failed to open space in browser: ${(error as Error).message}`);\n  }\n};\n\n/**\n * Extracts port from repository topics\n * @param topics - Array of repository topics\n * @returns Port number as string, defaults to '3000' if not found\n */\nexport const extractPortFromTopics = (topics: string[]): string => {\n  const portTopic = topics.find(topic => topic.startsWith('port-'));\n  if (portTopic) {\n    const port = portTopic.replace('port-', '');\n    // Validate that it's a valid port number\n    if (/^\\d+$/.test(port) && Number.parseInt(port) > 0 && Number.parseInt(port) <= 65535) {\n      return port;\n    }\n  }\n  return '3000'; // Default fallback port\n};\n\n/**\n * Converts a GitHub repository to the format expected by the CLI\n * Uses static template name and location as priority if available\n * @param repo - GitHub repository data from search API\n * @returns Formatted blueprint object\n */\nexport const repositoryToTemplate = (repo: SearchRepoItem): Template => {\n  const technology = repo.name.replace('blueprint-core-', '');\n  const port = extractPortFromTopics(repo.topics || []);\n  const staticTemplate = templates[technology.toUpperCase() as keyof typeof templates];\n\n  return {\n    // Prioritize static template name over derived name\n    name: staticTemplate?.name || technology.charAt(0).toUpperCase() + technology.slice(1),\n    value: technology,\n    template: repo.clone_url,\n    // Prioritize static template location over topic-derived port\n    location: staticTemplate?.location || (port ? `https://localhost:${port}/` : 'https://localhost:3000/'),\n    description: repo.description,\n    updated_at: repo.updated_at,\n    stars: repo.stargazers_count,\n  };\n};\n\nexport const fetchBlueprintRepositories = async (): Promise<Template[]> => {\n  try {\n    const octokit = createOctokit();\n\n    // Search for repositories matching the blueprint pattern\n    const { data } = await octokit.rest.search.repos({\n      q: 'org:storyblok blueprint-core-',\n      sort: 'updated',\n      order: 'desc',\n      per_page: 100,\n    });\n\n    // Filter and convert repositories to blueprints\n    const blueprints = data.items\n      .filter(repo => repo.name.startsWith('blueprint-core-'))\n      .map(repositoryToTemplate)\n      .sort((a, b) => (b.stars || 0) - (a.stars || 0));\n\n    return blueprints;\n  }\n  catch {\n    ui.warn('Failed to fetch blueprints from GitHub. Using offline template list.');\n    return Object.values(templates);\n  }\n};\n","import { CommandError, handleError, isRegion, isVitest, requireAuthentication, toHumanReadable } from '../../utils';\nimport { colorPalette, commands, type RegionCode, regions } from '../../constants';\nimport { performInteractiveLogin } from '../login/helpers';\nimport { getProgram } from '../../program';\nimport type { CreateOptions } from './constants';\nimport { session } from '../../session';\nimport { confirm, input, select } from '@inquirer/prompts';\nimport { fetchBlueprintRepositories, generateProject, generateSpaceUrl, handleEnvFileCreation, openSpaceInBrowser } from './actions';\nimport { basename, dirname, resolve } from 'pathe';\nimport chalk from 'chalk';\nimport { createSpace, type SpaceCreate } from '../spaces';\nimport { Spinner } from '@topcli/spinner';\nimport type { User } from '../user/actions';\nimport { getUser } from '../user/actions';\nimport { getUI } from '../../utils/ui';\n\nconst ui = getUI({ enabled: true });\n\n// Helper to show next steps and project ready message\nfunction showNextSteps(technologyTemplate: string, finalProjectPath: string) {\n  ui.br();\n  ui.ok(`Your ${chalk.hex(colorPalette.PRIMARY)(technologyTemplate)} project is ready 🎉 !`);\n  ui.br();\n  ui.info(`Next steps:\\n  cd ${finalProjectPath}\\n  npm install\\n  npm run dev\\n        `);\n  ui.info(`Or check the dedicated guide at: ${chalk.hex(colorPalette.PRIMARY)(`https://www.storyblok.com/docs/guides/${technologyTemplate}`)}`);\n}\n\n// Helper to handle interactive login prompt\nasync function promptForLogin(verbose: boolean): Promise<{ token: string; region: RegionCode } | null> {\n  try {\n    ui.br();\n    const shouldLogin = await confirm({\n      message: 'Would you like to login now?',\n      default: true,\n    });\n\n    if (!shouldLogin) {\n      ui.warn('Login cancelled. You can login later using the \"storyblok login\" command.');\n      return null;\n    }\n\n    return await performInteractiveLogin({ verbose, showWelcomeMessage: true });\n  }\n  catch (error) {\n    ui.br();\n    handleError(error as Error, verbose);\n    return null;\n  }\n}\n\nconst program = getProgram(); // Get the shared singleton instance\n\n// Create root command\nexport const createCommand = program\n  .command(`${commands.CREATE} [project-path]`)\n  .alias('c')\n  .description(`Scaffold a new project using Storyblok`)\n  .option('-t, --template <template>', 'technology starter template')\n  .option('-b, --blueprint <blueprint>', '[DEPRECATED] use --template instead')\n  .option('--skip-space', 'skip space creation')\n  .option('--token <token>', 'Storyblok access token (skip space creation and use this token)')\n  .option(\n    '-r, --region <region>',\n    `The region to apply to the generated project template (does not affect space creation).`,\n  )\n  .action(async (projectPath: string, options: CreateOptions) => {\n    ui.title(`${commands.CREATE}`, colorPalette.CREATE);\n    // Global options\n    const verbose = program.opts().verbose;\n    // Command options - handle backward compatibility\n    const { template, blueprint, token } = options;\n\n    if (options.region && !isRegion(options.region)) {\n      handleError(new CommandError(`The provided region: ${options.region} is not valid. Please use one of the following values: ${Object.values(regions).join(' | ')}`));\n      return;\n    }\n    // Handle deprecated blueprint option\n    let selectedTemplate = template;\n    if (blueprint && !template) {\n      ui.warn(`The --blueprint flag is deprecated. Please use --template instead.`);\n      selectedTemplate = blueprint;\n    }\n    else if (blueprint && template) {\n      ui.warn(`Both --blueprint and --template provided. Using --template and ignoring --blueprint.`);\n    }\n\n    const { state, initializeSession } = session();\n\n    // Declare these outside to be used throughout the function\n    let password: string | undefined;\n    let region: RegionCode | undefined;\n\n    // Get region from session for fallback (even when using --token)\n    if (state.region) {\n      region = state.region;\n    }\n\n    // If --token or --skip-space is provided, we don't need full authentication\n    // Otherwise, check if user is authenticated and offer to login if not\n    if (!token && !options.skipSpace) {\n      if (!requireAuthentication(state, verbose)) {\n        const loginResult = await promptForLogin(verbose);\n        if (!loginResult) {\n          return;\n        }\n        // Re-initialize session after login\n        await initializeSession();\n      }\n\n      // After authentication check, password and region are guaranteed to be defined\n      const authenticatedState = state as { isLoggedIn: true; password: string; region: RegionCode; login?: string; envLogin?: boolean };\n      password = authenticatedState.password;\n      region = authenticatedState.region;\n\n      // Validate that user-provided region matches their account region when creating a space\n      // This check happens early before any project scaffolding\n      if (options.region && options.region !== region) {\n        handleError(new CommandError(`Cannot create space in region \"${options.region}\". Your account is configured for region \"${region}\". Space creation must use your account's region.`));\n        return;\n      }\n    }\n    else if (state.isLoggedIn && state.password) {\n      // If using --token or --skip-space but user is logged in, still get their credentials for getMapiClient\n      password = state.password;\n      if (state.region) {\n        region = state.region;\n      }\n    }\n\n    const spinnerBlueprints = new Spinner({\n      verbose: !isVitest,\n    });\n\n    const spinnerSpace = new Spinner({\n      verbose: !isVitest,\n    });\n\n    try {\n      spinnerBlueprints.start('Fetching starter templates...');\n      const templates = await fetchBlueprintRepositories();\n      spinnerBlueprints.succeed('Starter templates fetched successfully');\n\n      if (templates.length === 0) {\n        spinnerBlueprints.failed();\n        ui.warn('No starter templates found. Please contact support@storyblok.com');\n        ui.br();\n        return;\n      }\n\n      // Validate template if provided via flag\n      let technologyTemplate = selectedTemplate;\n      if (selectedTemplate) {\n        const validTemplates = templates;\n        const isValidTemplate = validTemplates.find(bp => bp.value === selectedTemplate);\n        if (!isValidTemplate) {\n          const validOptions = validTemplates.map(bp => bp.value).join(', ');\n          ui.warn(`Invalid template \"${chalk.hex(colorPalette.CREATE)(selectedTemplate)}\". Valid options are: ${chalk.hex(colorPalette.CREATE)(validOptions)}`);\n          ui.br();\n          // Reset template to show interactive selection\n          technologyTemplate = undefined;\n        }\n      }\n\n      // Select technology template (either not provided or invalid)\n      if (!technologyTemplate) {\n        technologyTemplate = await select({\n          message: 'Please select the technology you would like to use:',\n          choices: templates.map(template => ({\n            name: template.name,\n            value: template.value,\n          })),\n        });\n      }\n\n      // Get project path and extract name\n      let finalProjectPath = projectPath;\n      if (!projectPath) {\n        finalProjectPath = await input({\n          message: 'What is the path for your project?',\n          default: `./my-${technologyTemplate}-project`,\n          validate: (value: string) => {\n            if (!value.trim()) {\n              return 'Project path is required';\n            }\n            // Basic validation for valid paths\n            const projectName = basename(value);\n            if (!/^[\\w-]+$/.test(projectName)) {\n              return 'Project name (last part of the path) can only contain letters, numbers, hyphens, and underscores';\n            }\n            return true;\n          },\n        });\n      }\n\n      // Parse the path to get directory and project name\n      const resolvedPath = resolve(finalProjectPath);\n      const targetDirectory = dirname(resolvedPath);\n      const projectName = basename(resolvedPath);\n\n      ui.br();\n      ui.info(`Scaffolding your project using the ${chalk.hex(colorPalette.CREATE)(technologyTemplate)} template...`);\n\n      // Generate the project from the template\n      await generateProject(technologyTemplate!, projectName, targetDirectory);\n      ui.ok(`Project ${chalk.hex(colorPalette.PRIMARY)(projectName)} created successfully in ${chalk.hex(colorPalette.PRIMARY)(finalProjectPath)}`, true);\n\n      // If token is provided, use it as the access token, skip space creation, and update env\n      let createdSpace;\n      let userData: User;\n      let whereToCreateSpace = 'personal';\n      if (token) {\n        await handleEnvFileCreation(resolvedPath, token, options.region || region);\n        showNextSteps(technologyTemplate!, finalProjectPath);\n        return;\n      }\n      if (options.skipSpace) {\n        // Only create .env file if region is available (useful for configuring SDK)\n        if (options.region || region) {\n          await handleEnvFileCreation(resolvedPath, undefined, options.region || region);\n        }\n        showNextSteps(technologyTemplate!, finalProjectPath);\n        return;\n      }\n      try {\n        try {\n          // At this point, password and region are guaranteed to be defined because:\n          // 1. We're not in the token branch (which returns early)\n          // 2. Authentication was required and completed\n          const user = await getUser(password!, region!);\n          if (!user) {\n            throw new Error('User data is undefined');\n          }\n          userData = user;\n        }\n        catch {\n          ui.error('Failed to fetch user info. Your session may have expired.');\n          const loginResult = await promptForLogin(verbose);\n          if (!loginResult) {\n            ui.br();\n            return;\n          }\n          // Re-initialize session and retry fetching user\n          await initializeSession();\n          const { password: newPassword, region: newRegion } = session().state;\n          try {\n            const user = await getUser(newPassword!, newRegion!);\n            if (!user) {\n              throw new Error('User data is undefined');\n            }\n            userData = user;\n          }\n          catch (retryError) {\n            ui.error('Failed to fetch user info after login.', retryError);\n            ui.br();\n            return;\n          }\n        }\n\n        // Prepare choices for space creation\n        const choices = [\n          { name: 'My personal account', value: 'personal' },\n        ];\n        if (userData.has_org) {\n          choices.push({ name: `Organization (${userData?.org?.name})`, value: 'org' });\n        }\n        if (userData.has_partner) {\n          choices.push({ name: 'Partner Portal', value: 'partner' });\n        }\n\n        if (region === regions.EU && (userData.has_partner || userData.has_org)) {\n          whereToCreateSpace = await select({\n            message: `Where would you like to create this space?`,\n            choices,\n          });\n        }\n        if (region !== regions.EU && userData.has_org) {\n          whereToCreateSpace = 'org';\n        }\n        if (region !== regions.EU && !userData.has_org) {\n          ui.warn(`Space creation in this region is limited to Enterprise accounts. If you're part of an organization, please ensure you have the required permissions. For more information about Enterprise access, contact our Sales Team.`);\n          ui.br();\n          return;\n        }\n\n        spinnerSpace.start(`Creating space \"${toHumanReadable(projectName)}\"`);\n\n        // Find the selected blueprint from the dynamic blueprints array\n        const selectedBlueprint = templates.find(bp => bp.value === technologyTemplate);\n        const blueprintDomain = selectedBlueprint?.location || 'https://localhost:3000/';\n        const spaceToCreate: SpaceCreate = {\n          name: toHumanReadable(projectName),\n          domain: blueprintDomain,\n        };\n        if (whereToCreateSpace === 'org') {\n          spaceToCreate.org = userData.org;\n          spaceToCreate.in_org = true;\n        }\n        else if (whereToCreateSpace === 'partner') {\n          spaceToCreate.assign_partner = true;\n        }\n        createdSpace = await createSpace(spaceToCreate);\n        spinnerSpace.succeed(`Space \"${chalk.hex(colorPalette.PRIMARY)(toHumanReadable(projectName))}\" created successfully`);\n\n        // Create .env file with the Storyblok token\n        if (createdSpace?.first_token) {\n          await handleEnvFileCreation(resolvedPath, createdSpace.first_token, region!);\n        }\n\n        // Open the space in the browser\n        if (createdSpace?.id) {\n          try {\n            await openSpaceInBrowser(createdSpace.id, region!);\n            ui.info(`Opened space in your browser`);\n          }\n          catch (error) {\n            ui.warn(`Failed to open browser: ${(error as Error).message}`);\n            const spaceUrl = generateSpaceUrl(createdSpace.id, region!);\n            ui.info(`You can manually open your space at: ${chalk.hex(colorPalette.PRIMARY)(spaceUrl)}`);\n          }\n        }\n\n        // Show next steps and space info\n        showNextSteps(technologyTemplate!, finalProjectPath);\n        if (createdSpace?.first_token) {\n          if (whereToCreateSpace === 'org') {\n            ui.ok(`Storyblok space created in organization ${chalk.hex(colorPalette.PRIMARY)(userData?.org?.name)}, preview url and .env configured automatically. You can now open your space in the browser at ${chalk.hex(colorPalette.PRIMARY)(generateSpaceUrl(createdSpace.id, region!))}`);\n          }\n          else if (whereToCreateSpace === 'partner') {\n            ui.ok(`Storyblok space created in partner portal, preview url and .env configured automatically. You can now open your space in the browser at ${chalk.hex(colorPalette.PRIMARY)(generateSpaceUrl(createdSpace.id, region!))}`);\n          }\n          else {\n            ui.ok(`Storyblok space created, preview url and .env configured automatically. You can now open your space in the browser at ${chalk.hex(colorPalette.PRIMARY)(generateSpaceUrl(createdSpace.id, region!))}`);\n          }\n        }\n      }\n      catch (error) {\n        spinnerSpace.failed();\n        ui.br();\n        handleError(error as Error, verbose);\n        return;\n      }\n\n      // showNextSteps is already called in each relevant branch above; do not call it again here.\n    }\n    catch (error) {\n      spinnerSpace.failed();\n      spinnerBlueprints.failed();\n      ui.br();\n      handleError(error as Error, verbose);\n    }\n    ui.br();\n  });\n","import { commands } from '../../constants';\nimport { getProgram } from '../../program';\n\nconst program = getProgram();\n\nexport const logsCommand = program\n  .command(commands.LOGS)\n  .alias('lg')\n  .description(`Inspect and manage logs.`);\n","import type { Command } from 'commander';\nimport { resolveCommandPath } from '../../../utils/filesystem';\nimport { getUI } from '../../../utils/ui';\nimport { logsCommand } from '../command';\nimport { FileTransport } from '../../../lib/logger/logger-transport-file';\nimport { directories } from '../../../constants';\n\nconst listCmd = logsCommand.command('list')\n  .description('List logs')\n  .option('-s, --space <space>', 'space ID');\n\nlistCmd\n  .action(async (_options: unknown, command: Command) => {\n    const { space, path } = command.optsWithGlobals();\n    const ui = getUI();\n    const logsPath = resolveCommandPath(directories.logs, space, path);\n    const logFiles = FileTransport.listLogFiles(logsPath);\n\n    if (logFiles.length === 0) {\n      ui.info(`No logs found for space \"${space}\".`);\n      return;\n    }\n\n    ui.info(`Found ${logFiles.length} log file${logFiles.length === 1 ? '' : 's'} for space \"${space}\":`);\n    ui.list(logFiles);\n  });\n","import type { Command } from 'commander';\nimport { resolveCommandPath } from '../../../utils/filesystem';\nimport { getUI } from '../../../utils/ui';\nimport { logsCommand } from '../command';\nimport { FileTransport } from '../../../lib/logger/logger-transport-file';\nimport { directories } from '../../../constants';\n\nconst pruneCmd = logsCommand.command('prune')\n  .description('Prune logs')\n  .option('--keep <number>', 'Max number of log files to keep (default `0`, meaning remove all)', Number.parseInt, 0)\n  .option('-s, --space <space>', 'space ID');\n\npruneCmd\n  .action(async (options: { keep: number }, command: Command) => {\n    const { space, path } = command.optsWithGlobals();\n    const ui = getUI();\n    const logsPath = resolveCommandPath(directories.logs, space, path);\n    const deletedFilesCount = FileTransport.pruneLogFiles(logsPath, options.keep);\n\n    ui.info(`Deleted ${deletedFilesCount} log file${deletedFilesCount === 1 ? '' : 's'}`);\n  });\n","import { commands } from '../../constants';\nimport { getProgram } from '../../program';\n\nconst program = getProgram();\n\nexport const reportsCommand = program\n  .command(commands.REPORTS)\n  .alias('rp')\n  .description('Inspect and manage reports.');\n","import type { Command } from 'commander';\nimport { directories } from '../../../constants';\nimport { resolveCommandPath } from '../../../utils/filesystem';\nimport { Reporter } from '../../../lib/reporter/reporter';\nimport { getUI } from '../../../utils/ui';\nimport { reportsCommand } from '../command';\n\nconst listCmd = reportsCommand.command('list')\n  .description('List reports')\n  .option('-s, --space <space>', 'space ID');\n\nlistCmd\n  .action(async (_options: unknown, command: Command) => {\n    const { space, path } = command.optsWithGlobals();\n    const ui = getUI();\n    const reportsPath = resolveCommandPath(directories.reports, space, path);\n    const reportFiles = Reporter.listReportFiles(reportsPath, '.jsonl');\n\n    if (reportFiles.length === 0) {\n      ui.info(`No reports found for space \"${space}\".`);\n      return;\n    }\n\n    ui.info(`Found ${reportFiles.length} report file${reportFiles.length === 1 ? '' : 's'} for space \"${space}\":`);\n    ui.list(reportFiles);\n  });\n","import type { Command } from 'commander';\nimport { resolveCommandPath } from '../../../utils/filesystem';\nimport { Reporter } from '../../../lib/reporter/reporter';\nimport { getUI } from '../../../utils/ui';\nimport { reportsCommand } from '../command';\nimport { directories } from '../../../constants';\n\nconst pruneCmd = reportsCommand.command('prune')\n  .description('Prune reports')\n  .option('--keep <number>', 'Max number of report files to keep (default `0`, meaning remove all)', Number.parseInt, 0)\n  .option('-s, --space <space>', 'space ID');\n\npruneCmd\n  .action(async (options: { keep: number }, command: Command) => {\n    const { space, path } = command.optsWithGlobals();\n    const ui = getUI();\n    const reportsPath = resolveCommandPath(directories.reports, space, path);\n    const deletedFilesCount = Reporter.pruneReportFiles(reportsPath, options.keep, '.jsonl');\n\n    ui.info(`Deleted ${deletedFilesCount} report file${deletedFilesCount === 1 ? '' : 's'}`);\n  });\n","import { commands } from '../../constants';\nimport { getProgram } from '../../program';\n\nconst program = getProgram();\n\nexport const assetsCommand = program\n  .command(commands.ASSETS)\n  .description(`Manage your space's assets`);\n","import Storyblok from 'storyblok-js-client';\nimport { getMapiClient } from '../../api';\nimport { handleAPIError } from '../../utils/error/api-error';\nimport { toError } from '../../utils/error/error';\nimport type { RegionCode } from '../../constants';\nimport type { Asset, AssetFolderCreate, AssetFolderUpdate, AssetListQuery, AssetUpdate, AssetUpload } from './types';\n\n/**\n * Fetches a single page of assets from Storyblok Management API.\n */\nexport const fetchAssets = async ({ spaceId, params }: {\n  spaceId: string;\n  params?: AssetListQuery;\n}) => {\n  try {\n    const client = getMapiClient();\n    const { data, response } = await client.assets.list({\n      path: {\n        space_id: Number(spaceId),\n      },\n      query: {\n        ...params,\n        per_page: params?.per_page || 100,\n        page: params?.page || 1,\n      },\n      throwOnError: true,\n    });\n    const assets = (data?.assets || [])\n      .filter((asset): asset is Asset => Boolean(asset?.id && asset?.filename));\n\n    return {\n      assets,\n      headers: response.headers,\n    };\n  }\n  catch (maybeError) {\n    handleAPIError('pull_assets', toError(maybeError));\n  }\n};\n\nexport const downloadFile = async (filename: string) => {\n  const response = await fetch(filename);\n  if (!response.ok) {\n    throw new Error(`Failed to download ${filename}`);\n  }\n  return response.arrayBuffer();\n};\n\n/**\n * Fetches a signed URL for a private asset from the Content Delivery API.\n */\nexport const getSignedAssetUrl = async (\n  filename: Asset['filename'],\n  assetToken: string,\n  region?: RegionCode,\n): Promise<string> => {\n  try {\n    const client = new Storyblok({\n      accessToken: assetToken,\n      region: region || 'eu',\n    });\n\n    const response = await client.get('cdn/assets/me', {\n      filename,\n    });\n\n    return response.data.asset.signed_url;\n  }\n  catch (maybeError) {\n    handleAPIError('pull_asset', toError(maybeError));\n  }\n};\n\nexport const fetchAssetFolders = async ({ spaceId }: {\n  spaceId: string;\n}) => {\n  try {\n    const client = getMapiClient();\n    const { data, response } = await client.assetFolders.list({\n      path: {\n        space_id: Number(spaceId),\n      },\n      throwOnError: true,\n    });\n\n    return {\n      asset_folders: data.asset_folders || [],\n      headers: response.headers,\n    };\n  }\n  catch (maybeError) {\n    handleAPIError('pull_asset_folders', toError(maybeError));\n  }\n};\n\nexport const createAssetFolder = async (folder: AssetFolderCreate, {\n  spaceId,\n}: {\n  spaceId: string;\n}) => {\n  try {\n    const client = getMapiClient();\n    const { data } = await client.assetFolders.create({\n      path: {\n        space_id: Number(spaceId),\n      },\n      body: { asset_folder: folder },\n      throwOnError: true,\n    });\n    const { asset_folder } = data;\n    if (!asset_folder) {\n      throw new Error('Failed to create asset folder');\n    }\n\n    return asset_folder;\n  }\n  catch (maybeError) {\n    handleAPIError('push_asset_folder', toError(maybeError));\n  }\n};\n\nexport const updateAssetFolder = async (id: number, folder: AssetFolderUpdate, {\n  spaceId,\n}: {\n  spaceId: string;\n}) => {\n  try {\n    const client = getMapiClient();\n    await client.assetFolders.update(id, {\n      path: {\n        space_id: Number(spaceId),\n      },\n      body: { asset_folder: folder },\n      throwOnError: true,\n    });\n\n    return folder;\n  }\n  catch (maybeError) {\n    handleAPIError('push_asset_folder', toError(maybeError));\n  }\n};\n\n/** Downloads a remote asset file. Handles both public and private assets. */\nexport const downloadAssetFile = async (\n  asset: { filename: string; is_private?: boolean },\n  options: { assetToken?: string; region?: RegionCode },\n): Promise<ArrayBuffer> => {\n  let url = asset.filename;\n\n  if (asset.is_private) {\n    if (!options.assetToken) {\n      throw new Error(`Asset ${asset.filename} is private but no asset token was provided. Use --asset-token to provide a token.`);\n    }\n    url = await getSignedAssetUrl(asset.filename, options.assetToken, options.region);\n  }\n\n  return downloadFile(url);\n};\n\n/**\n * Updates the metadata of an existing asset, and optionally replaces the file.\n *\n * When `fileBuffer` is provided, the mapi-client performs the full three-step\n * replace flow (sign → S3 upload → finalize) before updating metadata.\n * `short_filename` is required alongside `fileBuffer` for the sign request.\n *\n * When no `fileBuffer` is given, only the metadata PUT is issued.\n */\nexport const updateAsset = async (\n  id: number,\n  asset: AssetUpdate & { short_filename?: string },\n  { spaceId, fileBuffer }: { spaceId: string; fileBuffer?: ArrayBuffer },\n): Promise<void> => {\n  try {\n    const client = getMapiClient();\n    const { short_filename, ...metadata } = asset;\n\n    if (fileBuffer !== undefined) {\n      if (!short_filename) {\n        throw new Error('short_filename is required when replacing an asset file');\n      }\n      await client.assets.update(id, {\n        path: { space_id: Number(spaceId) },\n        body: { asset: metadata, short_filename },\n        file: fileBuffer,\n      });\n    }\n    else {\n      await client.assets.update(id, {\n        path: { space_id: Number(spaceId) },\n        body: { asset: metadata },\n      });\n    }\n  }\n  catch (maybeError) {\n    handleAPIError('push_asset_update', toError(maybeError));\n  }\n};\n\n/**\n * Creates a new asset by performing the full three-step upload flow, then\n * applying metadata fields. Delegates entirely to the mapi-client's\n * `create()` convenience method.\n */\nexport const createAsset = async (\n  asset: AssetUpload,\n  fileBuffer: ArrayBuffer,\n  { spaceId }: { spaceId: string },\n): Promise<Asset> => {\n  try {\n    const client = getMapiClient();\n    // Strip `id` — it identifies the local/manifest asset for mapping and must\n    // not flow into the metadata update inside mapi-client's create().\n    const { id: _id, ...assetBody } = asset;\n    return await client.assets.create({\n      body: assetBody,\n      file: fileBuffer,\n      path: { space_id: Number(spaceId) },\n    });\n  }\n  catch (maybeError) {\n    handleAPIError('push_asset_create', toError(maybeError));\n  }\n};\n","import { basename, dirname, extname, join } from 'pathe';\nimport { readFile } from 'node:fs/promises';\nimport { toError } from '../../utils/error/error';\nimport type { ManifestEntry } from '../../utils/filesystem';\nimport { loadManifest, sanitizeFilename } from '../../utils/filesystem';\nimport type { Asset, AssetFolder, AssetFolderMap, AssetMap, AssetMapped } from './types';\n\nexport const parseAssetData = (raw?: string) => {\n  if (!raw) {\n    return {} as Partial<Asset>;\n  }\n\n  try {\n    const parsed = JSON.parse(raw) as Record<string, unknown>;\n    if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n      throw new Error('Asset data must be a JSON object.');\n    }\n    return parsed as Partial<Asset>;\n  }\n  catch (maybeError) {\n    throw new Error(`Invalid --data JSON: ${(toError(maybeError)).message}`);\n  }\n};\n\nexport const getSidecarFilename = (assetBinaryPath: string) => {\n  return join(dirname(assetBinaryPath), `${basename(assetBinaryPath, extname(assetBinaryPath))}.json`);\n};\n\nexport const loadSidecarAssetData = async (assetBinaryPath: string) => {\n  const sidecarPath = getSidecarFilename(assetBinaryPath);\n  try {\n    const sidecarRaw = await readFile(sidecarPath, 'utf8');\n    try {\n      return parseAssetData(sidecarRaw);\n    }\n    catch (maybeError) {\n      throw new Error(`Invalid sidecar JSON: ${toError(maybeError).message}`);\n    }\n  }\n  catch (maybeError) {\n    const error = toError(maybeError) as NodeJS.ErrnoException;\n    if (error.code === 'ENOENT') {\n      return {};\n    }\n    throw new Error(`Failed to read sidecar asset data: ${error.message}`);\n  }\n};\n\nexport const isRemoteSource = (assetBinaryPath: string) => {\n  try {\n    const url = new URL(assetBinaryPath);\n    return url.protocol === 'http:' || url.protocol === 'https:';\n  }\n  catch {\n    return false;\n  }\n};\n\nconst isValidManifestEntry = (entry: ManifestEntry) =>\n  Boolean(typeof entry.old_id === 'number'\n    && typeof entry.new_id === 'number'\n    && entry.old_filename\n    && entry.new_filename);\n\nexport const loadAssetMap = async (manifestFile: string): Promise<AssetMap> => {\n  const manifest = await loadManifest(manifestFile);\n  const entries: [number, { old: AssetMapped; new: AssetMapped }][] = manifest\n    .filter(isValidManifestEntry)\n    .map(e => [\n      Number(e.old_id),\n      {\n        old: { id: Number(e.old_id), filename: e.old_filename || '' },\n        new: { id: Number(e.new_id), filename: e.new_filename || '' },\n      },\n    ]);\n  return new Map(entries);\n};\n\nexport const loadAssetFolderMap = async (manifestFile: string) => {\n  const manifest = await loadManifest(manifestFile);\n  return new Map(manifest.map(e => [Number(e.old_id), Number(e.new_id)])) satisfies AssetFolderMap;\n};\n\n/**\n * Extracts the sanitized name and extension from an asset.\n * Uses short_filename if available, otherwise falls back to the filename basename.\n */\nexport const getAssetNameAndExt = (asset: Partial<Asset> & Required<Pick<Asset, 'id'>>) => {\n  const filename = asset.short_filename || (asset.filename ? basename(asset.filename) : undefined);\n  if (!filename) {\n    throw new Error(`Filename for asset with id ${asset.id} could not be determined!`);\n  }\n\n  const ext = extname(filename);\n  const name = sanitizeFilename(filename.replace(ext, ''));\n  return { name, ext };\n};\n\n/**\n * Generates the asset filename in the format: `${name}_${id}.json`\n */\nexport const getAssetFilename = (asset: Partial<Asset> & Required<Pick<Asset, 'id'>>) => {\n  const { name } = getAssetNameAndExt(asset);\n  return `${name}_${asset.id}.json`;\n};\n\n/**\n * Generates the asset binary filename in the format: `${name}_${id}${ext}`\n */\nexport const getAssetBinaryFilename = (asset: Partial<Asset> & Required<Pick<Asset, 'id'>>) => {\n  const { name, ext } = getAssetNameAndExt(asset);\n  return `${name}_${asset.id}${ext}`;\n};\n\n/**\n * Generates the folder filename in the format: `${sanitizedName}_${uuid}.json`\n * Falls back to uuid if the sanitized name is empty.\n */\nexport const getFolderFilename = (folder: Pick<AssetFolder, 'name' | 'uuid'>) => {\n  const sanitizedName = sanitizeFilename(folder.name || '');\n  const baseName = sanitizedName || folder.uuid;\n  return `${baseName}_${folder.uuid}.json`;\n};\n","import { Buffer } from 'node:buffer';\nimport { basename, extname, join } from 'pathe';\nimport { Readable, Transform, Writable } from 'node:stream';\nimport { Sema } from 'async-sema';\nimport { readdir, readFile, unlink } from 'node:fs/promises';\nimport { appendToFile, fileExists, saveToFile } from '../../utils/filesystem';\nimport { toError } from '../../utils/error/error';\nimport type { RegionCode } from '../../constants';\nimport { SUPPORTED_ASSET_EXTENSIONS } from '../../constants';\nimport { createAsset, createAssetFolder, downloadAssetFile, downloadFile, fetchAssetFolders, fetchAssets, updateAsset, updateAssetFolder } from './actions';\nimport type { Asset, AssetFolder, AssetFolderCreate, AssetFolderMap, AssetFolderUpdate, AssetListQuery, AssetMap, AssetUpdate, AssetUpload } from './types';\nimport { getMapiClient } from '../../api';\nimport { handleAPIError } from '../../utils/error/api-error';\nimport { FetchError } from '../../utils/fetch';\nimport { getAssetBinaryFilename, getAssetFilename, getFolderFilename, getSidecarFilename, isRemoteSource, loadSidecarAssetData } from './utils';\n\nconst apiConcurrencyLock = new Sema(12);\n\nexport const fetchAssetsStream = ({\n  spaceId,\n  params = {},\n  setTotalAssets,\n  setTotalPages,\n  onIncrement,\n  onPageSuccess,\n  onPageError,\n}: {\n  spaceId: string;\n  params?: AssetListQuery;\n  setTotalAssets?: (total: number) => void;\n  setTotalPages?: (totalPages: number) => void;\n  onIncrement?: () => void;\n  onPageSuccess?: (page: number, total: number) => void;\n  onPageError?: (error: Error, page: number, total: number) => void;\n}) => {\n  const listGenerator = async function* assetListIterator() {\n    let perPage = 100;\n    let page = 1;\n    let totalPages = 1;\n    setTotalPages?.(totalPages);\n\n    while (page <= totalPages) {\n      try {\n        const result = await fetchAssets({\n          spaceId,\n          params: {\n            ...params,\n            per_page: perPage,\n            page,\n          },\n        });\n\n        const { headers, assets } = result;\n        const total = Number(headers.get('Total'));\n        perPage = Number(headers.get('Per-Page')) || perPage;\n        totalPages = Math.max(1, Math.ceil(total / perPage));\n        setTotalAssets?.(total);\n        setTotalPages?.(totalPages);\n        onPageSuccess?.(page, totalPages);\n\n        for (const asset of assets) {\n          yield asset;\n        }\n\n        page += 1;\n      }\n      catch (maybeError) {\n        onPageError?.(toError(maybeError), page, totalPages);\n        break;\n      }\n      finally {\n        onIncrement?.();\n      }\n    }\n  };\n\n  return Readable.from(listGenerator());\n};\n\nexport const downloadAssetStream = ({\n  assetToken,\n  region,\n  onIncrement,\n  onAssetSuccess,\n  onAssetError,\n}: {\n  assetToken?: string;\n  region?: RegionCode;\n  onIncrement?: () => void;\n  onAssetSuccess?: (asset: Asset) => void;\n  onAssetError?: (error: Error, asset: Asset) => void;\n}) => {\n  const processing = new Set<Promise<unknown>>();\n\n  return new Transform({\n    objectMode: true,\n    async transform(asset: Asset, _encoding, callback) {\n      await apiConcurrencyLock.acquire();\n\n      const task = downloadAssetFile(asset, { assetToken, region })\n        .then((fileBuffer) => {\n          if (!fileBuffer) {\n            throw new Error('Invalid asset file!');\n          }\n          onAssetSuccess?.(asset);\n          this.push({ asset, fileBuffer });\n        })\n        .catch((maybeError) => {\n          onAssetError?.(toError(maybeError), asset);\n        })\n        .finally(() => {\n          onIncrement?.();\n          apiConcurrencyLock.release();\n          processing.delete(task);\n        });\n      processing.add(task);\n\n      callback();\n    },\n    flush(callback) {\n      Promise.allSettled(processing).finally(() => callback());\n    },\n  });\n};\n\nexport type WriteAssetTransport = (asset: Asset, fileBuffer: ArrayBuffer) => Promise<Asset>;\n\nexport const makeWriteAssetFSTransport = ({ directoryPath }: {\n  directoryPath: string;\n}): WriteAssetTransport => async (asset, fileBuffer) => {\n  const assetBinaryPath = join(directoryPath, getAssetBinaryFilename(asset));\n  const assetPath = join(directoryPath, getAssetFilename(asset));\n  await saveToFile(assetBinaryPath, Buffer.from(fileBuffer));\n  await saveToFile(assetPath, JSON.stringify(asset, null, 2));\n  return asset;\n};\n\nexport const writeAssetStream = ({\n  writeAsset,\n  onIncrement,\n  onAssetSuccess,\n  onAssetError,\n}: {\n  writeAsset: WriteAssetTransport;\n  onIncrement?: () => void;\n  onAssetSuccess?: (asset: Asset) => void;\n  onAssetError?: (error: Error, asset: Asset) => void;\n}) => {\n  const processing = new Set<Promise<void>>();\n\n  return new Writable({\n    objectMode: true,\n    async write(payload: { asset: Asset; fileBuffer: ArrayBuffer }, _encoding, callback) {\n      await apiConcurrencyLock.acquire();\n\n      const task = (async () => {\n        try {\n          await writeAsset(payload.asset, payload.fileBuffer);\n          onAssetSuccess?.(payload.asset);\n        }\n        catch (maybeError) {\n          onAssetError?.(toError(maybeError), payload.asset);\n        }\n      })();\n\n      processing.add(task);\n      task.finally(() => {\n        onIncrement?.();\n        apiConcurrencyLock.release();\n        processing.delete(task);\n      });\n\n      callback();\n    },\n    final(callback) {\n      Promise.all(processing).finally(() => callback());\n    },\n  });\n};\n\nexport const fetchAssetFoldersStream = ({\n  spaceId,\n  setTotalFolders,\n  onSuccess,\n  onError,\n}: {\n  spaceId: string;\n  setTotalFolders?: (total: number) => void;\n  onSuccess?: (folders: AssetFolder[]) => void;\n  onError?: (error: Error) => void;\n}) => {\n  const listGenerator = async function* folderListIterator() {\n    try {\n      const result = await fetchAssetFolders({ spaceId });\n      const { asset_folders } = result;\n      const total = asset_folders.length;\n      setTotalFolders?.(total);\n      onSuccess?.(asset_folders);\n\n      for (const folder of asset_folders) {\n        yield folder;\n      }\n    }\n    catch (maybeError) {\n      onError?.(toError(maybeError));\n    }\n  };\n\n  return Readable.from(listGenerator());\n};\n\nexport type WriteAssetFolderTransport = (folder: AssetFolder) => Promise<AssetFolder>;\n\nexport const makeWriteAssetFolderFSTransport = ({ directoryPath }: {\n  directoryPath: string;\n}): WriteAssetFolderTransport => async (folder) => {\n  const filename = getFolderFilename(folder);\n  await saveToFile(join(directoryPath, 'folders', filename), JSON.stringify(folder, null, 2));\n  return folder;\n};\n\nexport const writeAssetFolderStream = ({\n  writeAssetFolder,\n  onIncrement,\n  onFolderSuccess,\n  onFolderError,\n}: {\n  writeAssetFolder: WriteAssetFolderTransport;\n  onIncrement?: () => void;\n  onFolderSuccess?: (folder: AssetFolder) => void;\n  onFolderError?: (error: Error, folder: AssetFolder) => void;\n}) => {\n  const processing = new Set<Promise<void>>();\n\n  return new Writable({\n    objectMode: true,\n    async write(folder: AssetFolder, _encoding, callback) {\n      await apiConcurrencyLock.acquire();\n\n      const task = (async () => {\n        try {\n          await writeAssetFolder(folder);\n          onFolderSuccess?.(folder);\n        }\n        catch (maybeError) {\n          onFolderError?.(toError(maybeError), folder);\n        }\n      })();\n\n      processing.add(task);\n      task.finally(() => {\n        onIncrement?.();\n        apiConcurrencyLock.release();\n        processing.delete(task);\n      });\n\n      callback();\n    },\n    final(callback) {\n      Promise.all(processing).finally(() => callback());\n    },\n  });\n};\n\nexport interface ReadLocalAssetFolderOptions {\n  directoryPath: string;\n  setTotalFolders?: (total: number) => void;\n  onFolderError?: (error: Error) => void;\n}\n\nexport interface LocalAssetFolderPayload {\n  folder: AssetFolder;\n  context: {\n    localFilePath: string;\n  };\n}\n\nexport const readLocalAssetFoldersStream = ({\n  directoryPath,\n  setTotalFolders,\n  onFolderError,\n}: ReadLocalAssetFolderOptions) => {\n  const iterator = async function* readFolders() {\n    try {\n      const files = await readdir(directoryPath);\n      const jsonFiles = new Set(files.filter(file => file.endsWith('.json')));\n      setTotalFolders?.(jsonFiles.size);\n\n      const processed = new Set<number>();\n      let maxIterations = jsonFiles.size * jsonFiles.size;\n      while (jsonFiles.size > 0 && maxIterations-- > 0) {\n        for (const file of jsonFiles) {\n          try {\n            const filePath = join(directoryPath, file);\n            const content = await readFile(filePath, 'utf8');\n            const folder = JSON.parse(content) as AssetFolder;\n            jsonFiles.delete(file);\n            // We must ensure the parent folder was already processed before\n            // we can pass it to the next step in the pipeline. Otherwise,\n            // mapping from local to remote parent ID does not work correctly.\n            if (!folder.parent_id || processed.has(folder.parent_id)) {\n              processed.add(folder.id);\n              yield {\n                folder,\n                context: {\n                  localFilePath: filePath,\n                },\n              } satisfies LocalAssetFolderPayload;\n            }\n            // If the parent folder has not been processed yet, we postpone\n            // handling of the current folder by moving it to the end of the\n            // queue.\n            else {\n              jsonFiles.add(file);\n            }\n          }\n          catch (maybeError) {\n            onFolderError?.(toError(maybeError));\n          }\n        }\n      }\n      if (jsonFiles.size > 0) {\n        onFolderError?.(new Error(`Unable to resolve folder dependencies for: ${[...jsonFiles].join(', ')}`));\n      }\n    }\n    catch (maybeError) {\n      const error = toError(maybeError);\n      if ('code' in error && error.code === 'ENOENT') {\n        return;\n      }\n      onFolderError?.(error);\n    }\n  };\n  return Readable.from(iterator());\n};\n\nexport type CreateAssetFolderTransport = (folder: AssetFolderCreate) => Promise<AssetFolder>;\n\nexport const makeCreateAssetFolderAPITransport = ({ spaceId }: {\n  spaceId: string;\n}): CreateAssetFolderTransport => folder => createAssetFolder({\n  name: folder.name,\n  parent_id: folder.parent_id ?? undefined,\n}, {\n  spaceId,\n});\n\nexport type UpdateAssetFolderTransport = (id: number, folder: AssetFolderUpdate) => Promise<AssetFolderUpdate>;\n\nexport const makeUpdateAssetFolderAPITransport = ({ spaceId }: {\n  spaceId: string;\n}): UpdateAssetFolderTransport => (id, folder) => updateAssetFolder(id, folder, { spaceId });\n\nexport type GetAssetFolderTransport = (folderId: number) => Promise<AssetFolder | undefined>;\n\nexport const makeGetAssetFolderAPITransport = ({ spaceId }: {\n  spaceId: string;\n}): GetAssetFolderTransport => async (folderId) => {\n  const { data, response } = await getMapiClient().assetFolders.get(folderId, {\n    path: {\n      space_id: Number(spaceId),\n    },\n  });\n\n  if (!response.ok && response.status !== 404) {\n    handleAPIError('pull_asset_folder', new FetchError(response.statusText, response));\n  }\n\n  return data?.asset_folder;\n};\n\nexport type CleanupAssetFolderTransport = (context: { localFilePath: string }) => Promise<void>;\n\nexport const makeCleanupAssetFolderFSTransport = (): CleanupAssetFolderTransport =>\n  async ({ localFilePath }) => await unlink(localFilePath);\n\nexport const upsertAssetFolderStream = ({\n  transports,\n  maps,\n  onIncrement,\n  onFolderSuccess,\n  onFolderError,\n}: {\n  transports: {\n    getAssetFolder: GetAssetFolderTransport;\n    createAssetFolder: CreateAssetFolderTransport;\n    updateAssetFolder: UpdateAssetFolderTransport;\n    appendAssetFolderManifest: AppendAssetFolderManifestTransport;\n    cleanupAssetFolder?: CleanupAssetFolderTransport;\n  };\n  maps: { assetFolders: AssetFolderMap };\n  onIncrement?: () => void;\n  onFolderSuccess?: (localFolder: AssetFolder, remoteFolder: AssetFolder | (AssetFolderUpdate & { id: number })) => void;\n  onFolderError?: (error: Error, folder: AssetFolder) => void;\n}) => {\n  return new Writable({\n    objectMode: true,\n    async write({ folder, context }: LocalAssetFolderPayload, _encoding, callback) {\n      try {\n        const remoteParentId = folder.parent_id && (maps.assetFolders.get(folder.parent_id) || folder.parent_id);\n        const remoteFolderId = maps.assetFolders.get(folder.id) || folder.id;\n        const upsertFolder = {\n          ...folder,\n          id: remoteFolderId,\n          parent_id: remoteParentId,\n        };\n        // If a remote folder already exists, we must not create a new folder.\n        // This can happen when the user resumes a failed push or runs push multiple times.\n        const existingRemoteFolder = await transports.getAssetFolder(remoteFolderId);\n        const newRemoteFolder = existingRemoteFolder\n          ? { id: remoteFolderId, ...await transports.updateAssetFolder(remoteFolderId, { ...upsertFolder, parent_id: remoteParentId !== null ? remoteParentId : undefined }) }\n          : await transports.createAssetFolder(upsertFolder);\n\n        // If folder is already mapped it must also be in the manifest already.\n        if (!maps.assetFolders.get(folder.id)) {\n          await transports.appendAssetFolderManifest(folder, newRemoteFolder);\n        }\n\n        await transports.cleanupAssetFolder?.({ localFilePath: context.localFilePath });\n\n        onFolderSuccess?.(folder, newRemoteFolder);\n      }\n      catch (maybeError) {\n        onFolderError?.(toError(maybeError), folder);\n      }\n      finally {\n        onIncrement?.();\n        callback();\n      }\n    },\n  });\n};\n\nexport interface LocalAssetPayload {\n  asset: Asset | AssetUpload;\n  context: {\n    fileBuffer: ArrayBuffer;\n    assetBinaryPath: string;\n    assetPath?: string;\n  };\n}\n\nexport const readLocalAssetsStream = ({\n  directoryPath,\n  setTotalAssets,\n  onAssetError,\n}: {\n  directoryPath: string;\n  setTotalAssets?: (total: number) => void;\n  onAssetError?: (error: Error) => void;\n}) => {\n  const iterator = async function* readAssets() {\n    try {\n      const files = await readdir(directoryPath);\n      const binaryFiles = files.filter(f => SUPPORTED_ASSET_EXTENSIONS.has(extname(f).toLowerCase()));\n      setTotalAssets?.(binaryFiles.length);\n      for (const file of binaryFiles) {\n        const binaryFilePath = join(directoryPath, file);\n        try {\n          const sidecar = await loadSidecarAssetData(binaryFilePath);\n          const shortFilename: string = sidecar.short_filename\n            || (sidecar.filename ? basename(sidecar.filename) : undefined)\n            || file;\n          const asset = {\n            ...sidecar,\n            short_filename: shortFilename,\n          } satisfies AssetUpload;\n          const fileBuffer = await readFile(binaryFilePath) as unknown as ArrayBuffer;\n          const sidecarPath = getSidecarFilename(binaryFilePath);\n          yield {\n            asset,\n            context: {\n              fileBuffer,\n              assetBinaryPath: binaryFilePath,\n              assetPath: sidecarPath,\n            },\n          } satisfies LocalAssetPayload;\n        }\n        catch (maybeError) {\n          onAssetError?.(toError(maybeError));\n        }\n      }\n    }\n    catch (maybeError) {\n      onAssetError?.(toError(maybeError));\n    }\n  };\n  return Readable.from(iterator());\n};\n\nexport const readSingleAssetStream = ({\n  asset,\n  assetBinaryPath,\n  onAssetError,\n}: {\n  asset: AssetUpload;\n  assetBinaryPath: string;\n  onAssetError?: (error: Error) => void;\n}) => {\n  const iterator = async function* readSingleAsset() {\n    try {\n      if (!isRemoteSource(assetBinaryPath) && !await fileExists(assetBinaryPath)) {\n        throw new Error('Asset path must point to a file.');\n      }\n      const fileBuffer = (isRemoteSource(assetBinaryPath)\n        ? await downloadFile(assetBinaryPath)\n        : await readFile(assetBinaryPath)) as ArrayBuffer;\n\n      yield {\n        asset,\n        context: {\n          fileBuffer,\n          assetBinaryPath,\n        },\n      } satisfies LocalAssetPayload;\n    }\n    catch (maybeError) {\n      onAssetError?.(toError(maybeError));\n    }\n  };\n  return Readable.from(iterator());\n};\n\nexport type CreateAssetTransport = (asset: AssetUpload, fileBuffer: ArrayBuffer) => Promise<Asset>;\n\nexport const makeCreateAssetAPITransport = ({ spaceId }: { spaceId: string }): CreateAssetTransport =>\n  (asset, fileBuffer) => createAsset(asset, fileBuffer, { spaceId });\n\nexport type UpdateAssetTransport = (id: number, asset: AssetUpdate & { short_filename?: string }, fileBuffer?: ArrayBuffer) => Promise<void>;\n\nexport const makeUpdateAssetAPITransport = ({\n  spaceId,\n}: {\n  spaceId: string;\n}): UpdateAssetTransport =>\n  (id, asset, fileBuffer) => updateAsset(id, asset, { spaceId, fileBuffer });\n\nexport type AppendAssetManifestTransport = (\n  localAsset: { id: Asset['id']; filename?: string },\n  remoteAsset: { id: Asset['id']; filename?: string },\n) => Promise<void>;\n\nexport const makeAppendAssetManifestFSTransport = ({ manifestFile }: { manifestFile: string }): AppendAssetManifestTransport =>\n  async (localAsset, remoteAsset) => {\n    const createdAt = new Date().toISOString();\n    await appendToFile(manifestFile, JSON.stringify({\n      old_id: localAsset.id,\n      new_id: remoteAsset.id,\n      old_filename: localAsset.filename,\n      new_filename: remoteAsset.filename,\n      created_at: createdAt,\n    }));\n  };\n\nexport type AppendAssetFolderManifestTransport = (\n  localFolder: { id: AssetFolder['id'] },\n  remoteFolder: { id: AssetFolder['id'] },\n) => Promise<void>;\n\nexport const makeAppendAssetFolderManifestFSTransport = ({ manifestFile }: { manifestFile: string }): AppendAssetFolderManifestTransport =>\n  async (localFolder, remoteFolder) => {\n    const createdAt = new Date().toISOString();\n    await appendToFile(manifestFile, JSON.stringify({\n      old_id: localFolder.id,\n      new_id: remoteFolder.id,\n      created_at: createdAt,\n    }));\n  };\n\nexport type GetAssetTransport = (assetId: number) => Promise<Asset | undefined>;\n\nexport const makeGetAssetAPITransport = ({ spaceId }: { spaceId: string }): GetAssetTransport =>\n  async (assetId: number) => {\n    const { data, response } = await getMapiClient().assets.get(assetId, {\n      path: {\n        space_id: Number(spaceId),\n      },\n    });\n\n    if (!response.ok && response.status !== 404) {\n      handleAPIError('pull_asset', new FetchError(response.statusText, response));\n    }\n\n    if (data?.deleted_at) {\n      return undefined;\n    }\n\n    return data;\n  };\n\nexport type CleanupAssetTransport = (context: { assetBinaryPath: string; assetPath?: string }) => Promise<void>;\n\nconst saveDelete = async (filePath: string) => {\n  if (await fileExists(filePath)) {\n    await unlink(filePath);\n  }\n};\nexport const makeCleanupAssetFSTransport = (): CleanupAssetTransport =>\n  async ({ assetBinaryPath, assetPath }) => {\n    const assetOrSidecarPath = assetPath || getSidecarFilename(assetBinaryPath);\n    await Promise.all([\n      assetBinaryPath && saveDelete(assetBinaryPath),\n      assetOrSidecarPath && saveDelete(assetOrSidecarPath),\n    ]);\n  };\n\nconst hasId = (a: unknown): a is { id: number } => {\n  return !!a && typeof a === 'object' && 'id' in a && typeof (a as any).id === 'number';\n};\nconst hasShortFilename = (a: unknown): a is { short_filename: string } => {\n  return !!a && typeof a === 'object' && 'short_filename' in a && typeof (a as any).short_filename === 'string';\n};\n\nconst processAsset = async ({\n  localAsset,\n  fileBuffer,\n  assetBinaryPath,\n  assetPath,\n  transports,\n  maps,\n}: {\n  localAsset: Asset | AssetUpload;\n  fileBuffer: ArrayBuffer;\n  assetBinaryPath: string;\n  assetPath?: string;\n  transports: {\n    getAsset: GetAssetTransport;\n    createAsset: CreateAssetTransport;\n    updateAsset: UpdateAssetTransport;\n    appendAssetManifest: AppendAssetManifestTransport;\n    cleanupAsset?: CleanupAssetTransport;\n  };\n  maps: { assets: AssetMap; assetFolders: AssetFolderMap };\n}): Promise<{ status: 'created' | 'updated'; remoteAsset: Asset }> => {\n  const remoteFolderId = localAsset.asset_folder_id\n    && (maps.assetFolders.get(localAsset.asset_folder_id) || localAsset.asset_folder_id);\n  const remoteAssetId = hasId(localAsset)\n    ? maps.assets.get(localAsset.id)?.new.id || localAsset.id\n    : undefined;\n  const remoteAsset = remoteAssetId ? await transports.getAsset(remoteAssetId) : null;\n\n  let newRemoteAsset: Asset;\n  let status: 'created' | 'updated';\n  if (remoteAsset) {\n    // Build only the writable metadata fields for the API update.\n    // Read-only fields (filename, short_filename, etc.) are intentionally excluded.\n    const updatePayload: AssetUpdate = {\n      asset_folder_id: remoteFolderId,\n      alt: 'alt' in localAsset ? localAsset.alt : remoteAsset.alt,\n      title: 'title' in localAsset ? localAsset.title : remoteAsset.title,\n      copyright: 'copyright' in localAsset ? localAsset.copyright : remoteAsset.copyright,\n      source: 'source' in localAsset ? localAsset.source : remoteAsset.source,\n      is_private: 'is_private' in localAsset ? localAsset.is_private : remoteAsset.is_private,\n      focus: 'focus' in localAsset ? localAsset.focus : remoteAsset.focus,\n      expire_at: 'expire_at' in localAsset ? localAsset.expire_at : remoteAsset.expire_at,\n      publish_at: 'publish_at' in localAsset ? localAsset.publish_at : remoteAsset.publish_at,\n      internal_tag_ids: 'internal_tag_ids' in localAsset ? localAsset.internal_tag_ids : remoteAsset.internal_tag_ids,\n      meta_data: 'meta_data' in localAsset ? localAsset.meta_data : remoteAsset.meta_data,\n    };\n\n    // Always perform the full replace flow (sign → S3 upload → finalize)\n    // and update metadata. No change detection — see ADR-0003.\n    await transports.updateAsset(\n      remoteAsset.id,\n      { ...updatePayload, short_filename: remoteAsset.short_filename },\n      fileBuffer,\n    );\n    // updateAsset returns void; the remote asset's readonly fields are unchanged.\n    newRemoteAsset = { ...remoteAsset, ...updatePayload };\n    status = 'updated';\n  }\n  else if (hasShortFilename(localAsset)) {\n    const createPayload = {\n      ...localAsset,\n      asset_folder_id: remoteFolderId,\n    } satisfies AssetUpload;\n    newRemoteAsset = await transports.createAsset(createPayload, fileBuffer);\n    status = 'created';\n  }\n  else {\n    throw new Error('Could neither create nor update the asset: Missing ID and Filename');\n  }\n\n  // This leads to (temporary) duplicate entries of mappings with the same IDs.\n  // We can't check the map for existing entries and skip if we find one,\n  // because the asset might have a new filename which must be reflected in the\n  // map.\n  if (hasId(localAsset)) {\n    await transports.appendAssetManifest(localAsset, newRemoteAsset);\n  }\n  await transports.cleanupAsset?.({ assetBinaryPath, assetPath });\n\n  return { status, remoteAsset: newRemoteAsset };\n};\n\nexport const upsertAssetStream = ({\n  transports,\n  maps,\n  onIncrement,\n  onAssetSuccess,\n  onAssetError,\n}: {\n  transports: {\n    getAsset: GetAssetTransport;\n    createAsset: CreateAssetTransport;\n    updateAsset: UpdateAssetTransport;\n    appendAssetManifest: AppendAssetManifestTransport;\n    cleanupAsset?: CleanupAssetTransport;\n  };\n  maps: { assets: AssetMap; assetFolders: AssetFolderMap };\n  onIncrement?: () => void;\n  onAssetSuccess?: (localAsset: Asset | AssetUpload, remoteAsset: Asset) => void;\n  onAssetError?: (error: Error, asset: Asset | AssetUpload) => void;\n}) => {\n  const processing = new Set<Promise<void>>();\n\n  return new Writable({\n    objectMode: true,\n    async write({ asset: localAsset, context }: LocalAssetPayload, _encoding, callback) {\n      await apiConcurrencyLock.acquire();\n      const task = (async () => {\n        try {\n          const { remoteAsset } = await processAsset({\n            localAsset,\n            fileBuffer: context.fileBuffer,\n            assetBinaryPath: context.assetBinaryPath,\n            assetPath: context.assetPath,\n            transports,\n            maps,\n          });\n\n          onAssetSuccess?.(localAsset, remoteAsset);\n        }\n        catch (maybeError) {\n          onAssetError?.(toError(maybeError), localAsset);\n        }\n      })();\n\n      processing.add(task);\n      task.finally(() => {\n        onIncrement?.();\n        apiConcurrencyLock.release();\n        processing.delete(task);\n      });\n\n      callback();\n    },\n    final(callback) {\n      Promise.all(processing).finally(() => callback());\n    },\n  });\n};\n","import { pipeline } from 'node:stream/promises';\nimport { colorPalette, commands, directories } from '../../../constants';\nimport { assetsCommand } from '../command';\nimport { getUI } from '../../../utils/ui';\nimport { session } from '../../../session';\nimport { resolveCommandPath } from '../../../utils/filesystem';\nimport { getLogger } from '../../../lib/logger/logger';\nimport { getReporter } from '../../../lib/reporter/reporter';\nimport { requireAuthentication } from '../../../utils/auth';\nimport { CommandError } from '../../../utils/error/command-error';\nimport { handleError, logOnlyError, toError } from '../../../utils/error/error';\nimport {\n  downloadAssetStream,\n  fetchAssetFoldersStream,\n  fetchAssetsStream,\n  makeWriteAssetFolderFSTransport,\n  makeWriteAssetFSTransport,\n  writeAssetFolderStream,\n  writeAssetStream,\n} from '../streams';\n\nconst pullCmd = assetsCommand\n  .command('pull')\n  .option('-s, --space <space>', 'space ID')\n  .option('-d, --dry-run', 'Preview changes without applying them to Storyblok')\n  .option('-q, --query <query>', 'Filter assets using Storyblok filter query syntax. Example: --query=\"search=my-file.jpg&with_tags=tag1,tag2\"')\n  .option('--asset-token <token>', 'Asset token for accessing private assets')\n  .description(`Download your space's assets as local files.`);\n\npullCmd\n  .action(async (options, command) => {\n    const ui = getUI();\n    const logger = getLogger();\n\n    ui.title(`${commands.ASSETS}`, colorPalette.ASSETS, 'Pulling assets...');\n    logger.info('Pulling assets started');\n\n    if (options.dryRun) {\n      ui.warn(`DRY RUN MODE ENABLED: No changes will be made.\\n`);\n      logger.warn('Dry run mode enabled');\n    }\n\n    const { space, path: basePath, verbose } = command.optsWithGlobals();\n    const assetToken = options.assetToken as string | undefined;\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      process.exitCode = 2;\n      return;\n    }\n    if (!space) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      process.exitCode = 2;\n      return;\n    }\n\n    const { region } = state;\n\n    const summary = {\n      folderResults: { total: 0, succeeded: 0, failed: 0 },\n      fetchAssetPages: { total: 0, succeeded: 0, failed: 0 },\n      fetchAssets: { total: 0, succeeded: 0, failed: 0 },\n      save: { total: 0, succeeded: 0, failed: 0 },\n    };\n\n    let fatalError = false;\n\n    try {\n      const folderProgress = ui.createProgressBar({ title: 'Folders...'.padEnd(25) });\n      const fetchAssetPagesProgress = ui.createProgressBar({ title: 'Fetching Asset Pages...'.padEnd(24) });\n      const fetchAssetsProgress = ui.createProgressBar({ title: 'Fetching Assets...'.padEnd(24) });\n      const saveProgress = ui.createProgressBar({ title: 'Saving Assets...'.padEnd(24) });\n      await pipeline(\n        fetchAssetFoldersStream({\n          spaceId: space,\n          setTotalFolders: (total) => {\n            summary.folderResults.total = total;\n            folderProgress.setTotal(total);\n          },\n          onSuccess: () => {\n            logger.info('Fetched asset folders');\n          },\n          onError: (error) => {\n            summary.folderResults.failed += 1;\n            summary.folderResults.total = summary.folderResults.total || 1;\n            folderProgress.setTotal(summary.folderResults.total);\n            logOnlyError(error);\n          },\n        }),\n        writeAssetFolderStream({\n          writeAssetFolder: options.dryRun\n            ? async folder => folder\n            : makeWriteAssetFolderFSTransport({\n                directoryPath: resolveCommandPath(directories.assets, space, basePath),\n              }),\n          onIncrement: () => {\n            folderProgress.increment();\n          },\n          onFolderSuccess: (folder) => {\n            logger.info('Saved folder', { folderId: folder.id });\n            summary.folderResults.succeeded += 1;\n          },\n          onFolderError: (error, folder) => {\n            summary.folderResults.failed += 1;\n            summary.folderResults.total = Math.max(summary.folderResults.total, summary.folderResults.succeeded + summary.folderResults.failed);\n            logOnlyError(error, { folderId: folder.id });\n          },\n        }),\n      );\n      await pipeline(\n        fetchAssetsStream({\n          spaceId: space,\n          params: options.query ? Object.fromEntries(new URLSearchParams(options.query)) : {},\n          setTotalAssets: (total) => {\n            summary.fetchAssets.total = total;\n            summary.save.total = total;\n            fetchAssetsProgress.setTotal(total);\n            saveProgress.setTotal(total);\n          },\n          setTotalPages: (totalPages) => {\n            summary.fetchAssetPages.total = totalPages;\n            fetchAssetPagesProgress.setTotal(totalPages);\n          },\n          onIncrement: () => {\n            fetchAssetPagesProgress.increment();\n          },\n          onPageSuccess: (page, totalPages) => {\n            logger.info(`Fetched assets page ${page} of ${totalPages}`);\n            summary.fetchAssetPages.succeeded += 1;\n          },\n          onPageError: (error, page, totalPages) => {\n            summary.fetchAssetPages.failed += 1;\n            logOnlyError(error, { page, totalPages });\n          },\n        }),\n        downloadAssetStream({\n          assetToken,\n          region,\n          onIncrement: () => {\n            fetchAssetsProgress.increment();\n          },\n          onAssetSuccess: (asset) => {\n            logger.info('Fetched asset', { assetId: asset.id });\n            summary.fetchAssets.succeeded += 1;\n          },\n          onAssetError: (error, asset) => {\n            summary.fetchAssets.failed += 1;\n            summary.save.total -= 1;\n            saveProgress.setTotal(summary.save.total);\n            logOnlyError(error, { assetId: asset.id });\n          },\n        }),\n        writeAssetStream({\n          writeAsset: options.dryRun\n            ? async asset => asset\n            : makeWriteAssetFSTransport({\n                directoryPath: resolveCommandPath(directories.assets, space, basePath),\n              }),\n          onIncrement: () => {\n            saveProgress.increment();\n          },\n          onAssetSuccess: (asset) => {\n            logger.info('Saved asset', { assetId: asset.id });\n            summary.save.succeeded += 1;\n          },\n          onAssetError: (error, asset) => {\n            summary.save.failed += 1;\n            logOnlyError(error, { assetId: asset.id });\n          },\n        }),\n      );\n    }\n    catch (maybeError) {\n      fatalError = true;\n      handleError(toError(maybeError));\n    }\n    finally {\n      logger.info('Pulling assets finished', summary);\n      ui.stopAllProgressBars();\n      const failedAssets = Math.max(summary.fetchAssets.failed, summary.save.failed);\n      const folderSummary = {\n        total: summary.folderResults.total,\n        succeeded: summary.folderResults.succeeded,\n        failed: summary.folderResults.failed,\n      };\n      ui.info(`Pull results: ${summary.save.total} assets pulled, ${failedAssets} assets failed`);\n      ui.list([\n        `Folders: ${folderSummary.succeeded}/${folderSummary.total} succeeded, ${folderSummary.failed} failed.`,\n        `Fetching pages: ${summary.fetchAssetPages.succeeded}/${summary.fetchAssetPages.total} succeeded, ${summary.fetchAssetPages.failed} failed.`,\n        `Fetching assets: ${summary.fetchAssets.succeeded}/${summary.fetchAssets.total} succeeded, ${summary.fetchAssets.failed} failed.`,\n        `Saving assets: ${summary.save.succeeded}/${summary.save.total} succeeded, ${summary.save.failed} failed.`,\n      ]);\n\n      const reporter = getReporter();\n      reporter.addSummary('folderResults', folderSummary);\n      reporter.addSummary('fetchAssetPagesResults', summary.fetchAssetPages);\n      reporter.addSummary('fetchAssetsResults', summary.fetchAssets);\n      reporter.addSummary('saveResults', summary.save);\n      reporter.finalize();\n\n      const failedTotal = summary.folderResults.failed\n        + summary.fetchAssetPages.failed\n        + summary.fetchAssets.failed\n        + summary.save.failed;\n      process.exitCode = fatalError ? 2 : failedTotal > 0 ? 1 : 0;\n    }\n  });\n","import type { Component } from '../components/constants';\nimport type { Story } from './constants';\nimport type { AssetMap } from '../assets/types';\nimport { normalizeAssetUrl } from '@storyblok/management-api-client';\n\nexport interface RefMaps {\n  assets?: AssetMap;\n  stories?: Map<unknown, string | number>;\n}\n\nexport type ComponentSchemas = Record<Component['name'], Component['schema']>;\n\ntype RefMapper = <const T extends Record<string, unknown>>(data: T, options: {\n  schema: Component['schema'];\n  schemas: ComponentSchemas;\n  maps: RefMaps;\n  fieldRefMappers: FieldRefMappers;\n}) => T;\n\ntype FieldRefMappers = Record<string, RefMapper>;\n\nconst traverseAndMapBySchema = (\n  data: any,\n  {\n    schemas,\n    maps,\n    fieldRefMappers,\n  }: {\n    schemas: ComponentSchemas;\n    maps: RefMaps;\n    fieldRefMappers: FieldRefMappers;\n  },\n): any => {\n  if (!data?.component) {\n    return data ?? {};\n  }\n  const schema = schemas[data.component];\n  if (!schema) {\n    return data;\n  }\n  const dataNew = { ...data };\n\n  for (const [fieldName, fieldValue] of Object.entries(data)) {\n    const fieldSchema = schema[fieldName.replace(/__i18n__.*/, '')] as Component['schema'];\n    const fieldType = fieldSchema && typeof fieldSchema === 'object' && 'type' in fieldSchema && fieldSchema.type;\n    const fieldRefMapper = typeof fieldType === 'string' && fieldRefMappers[fieldType];\n\n    if (fieldRefMapper) {\n      dataNew[fieldName] = fieldRefMapper(fieldValue as any, {\n        schema: fieldSchema,\n        schemas,\n        maps,\n        fieldRefMappers,\n      });\n    }\n  }\n\n  return dataNew;\n};\n\nconst traverseAndMapRichtextDoc = (\n  data: any,\n  {\n    schemas,\n    maps,\n    fieldRefMappers,\n  }: {\n    schemas: ComponentSchemas;\n    maps: RefMaps;\n    fieldRefMappers: FieldRefMappers;\n  },\n): any => {\n  if (Array.isArray(data)) {\n    return data.map(item => traverseAndMapRichtextDoc(item, {\n      schemas,\n      maps,\n      fieldRefMappers,\n    }));\n  }\n\n  if (data && typeof data === 'object') {\n    if (data.type === 'link' && data.attrs?.linktype === 'story') {\n      return {\n        ...data,\n        attrs: {\n          ...data.attrs,\n          uuid: maps.stories?.get(data.attrs.uuid) || data.attrs.uuid,\n        },\n      };\n    }\n    if (data.type === 'blok') {\n      return {\n        ...data,\n        attrs: {\n          ...data.attrs,\n          body: (data.attrs?.body ?? []).map((d: any) => traverseAndMapBySchema(d, {\n            schemas,\n            maps,\n            fieldRefMappers,\n          })),\n        },\n      };\n    }\n\n    const newData: any = {};\n    for (const [k, value] of Object.entries(data)) {\n      newData[k] = traverseAndMapRichtextDoc(value, {\n        schemas,\n        maps,\n        fieldRefMappers,\n      });\n    }\n    return newData;\n  }\n\n  return data;\n};\n\n/**\n * Richtext field reference mapper.\n */\nconst richtextFieldRefMapper: RefMapper = (data, { schemas, maps, fieldRefMappers }) => traverseAndMapRichtextDoc(data, {\n  schemas,\n  maps,\n  fieldRefMappers,\n});\n\n/**\n * Multilink field reference mapper.\n */\nconst multilinkFieldRefMapper: RefMapper = (data, { maps }) => {\n  if (data.linktype !== 'story') {\n    return data;\n  }\n\n  return {\n    ...data,\n    id: maps.stories?.get(data.id) || data.id,\n  };\n};\n\n/**\n * Bloks field reference mapper.\n */\nconst bloksFieldRefMapper: RefMapper = (data, { schemas, maps, fieldRefMappers }) => {\n  if (!Array.isArray(data)) {\n    throw new TypeError(`Invalid bloks field: expected an array, but received ${JSON.stringify(data)}. Please make sure your bloks field value is an array of components (e.g. [{ component: \"my_blok\", ... }]).`);\n  }\n\n  return data.map((d: any) => traverseAndMapBySchema(d, {\n    schemas,\n    maps,\n    fieldRefMappers,\n  })) as any;\n};\n\n/**\n * Asset field reference mapper.\n *\n * Normalizes asset filenames from S3 origin URLs to CDN URLs. The MAPI returns\n * asset filenames as S3 URLs (https://s3.amazonaws.com/a.storyblok.com/f/...)\n * but story content must reference the CDN URL (https://a.storyblok.com/f/...)\n * so that the Storyblok Image Service (/m/...) works correctly.\n */\nconst assetFieldRefMapper: RefMapper = (data, { maps }) => {\n  const mappedAsset = typeof data.id === 'number' ? maps.assets?.get(data.id) : undefined;\n\n  if (!mappedAsset) {\n    return data;\n  }\n\n  return {\n    ...data,\n    ...mappedAsset.new,\n    filename: normalizeAssetUrl(mappedAsset.new.filename),\n  };\n};\n\n/**\n * Multi asset field reference mapper.\n */\nconst multiassetFieldRefMapper: RefMapper = (data, options) => {\n  if (!Array.isArray(data)) {\n    throw new TypeError(`Invalid multiasset field: expected an array, but received ${JSON.stringify(data)}. Please make sure your multiasset field value is an array of asset objects (e.g. [{ filename: \"...\", id: 123 }]).`);\n  }\n\n  return data.map((d: any) => assetFieldRefMapper(d, options)) as any;\n};\n\n/**\n * Options field reference mapper.\n */\nconst optionsFieldRefMapper: RefMapper = (data, { schema, maps }) => {\n  if (schema.source !== 'internal_stories' || !Array.isArray(data)) {\n    return data;\n  }\n\n  return data.map((d: any) => maps.stories?.get(d) || d) as any;\n};\n\nconst fieldRefMappers = {\n  asset: assetFieldRefMapper,\n  bloks: bloksFieldRefMapper,\n  multiasset: multiassetFieldRefMapper,\n  multilink: multilinkFieldRefMapper,\n  options: optionsFieldRefMapper,\n  richtext: richtextFieldRefMapper,\n} as const;\n\n/**\n * Story field reference mapper.\n */\nexport const storyRefMapper = (story: Story, { schemas, maps }: {\n  schemas: ComponentSchemas;\n  maps: RefMaps;\n}) => {\n  const alternates = story.alternates\n    ? (story.alternates as Required<Story>['alternates']).map((a: any) => ({\n        ...a,\n        id: maps.stories?.get(a.id) ?? a.id,\n        parent_id: maps.stories?.get(a.parent_id) ?? a.parent_id,\n      }))\n    : story.alternates;\n\n  const parentId = maps.stories?.get(story.parent_id) ?? story.parent_id;\n  return {\n    ...story,\n    content: story.content?.component\n      ? traverseAndMapBySchema(story.content, {\n          schemas,\n          maps,\n          fieldRefMappers,\n        })\n      : story.content,\n    id: Number(maps.stories?.get(story.id) ?? story.id),\n    uuid: String(maps.stories?.get(story.uuid) ?? story.uuid),\n    parent_id: parentId != null ? Number(parentId) : 0,\n    alternates,\n  } satisfies Story;\n};\n","import { readFile, unlink } from 'node:fs/promises';\nimport { extname, join, resolve } from 'pathe';\nimport { Readable, Transform, Writable } from 'node:stream';\nimport { Sema } from 'async-sema';\nimport { createStory, fetchStories, fetchStory, updateStory } from './actions';\nimport type { ExistingTargetStories, StoriesQueryParams, Story, StoryIndexEntry, TargetStoryRef } from './constants';\nimport { normalizeFullSlug } from './constants';\nimport { appendToFile, readDirectory, saveToFile } from '../../utils/filesystem';\nimport { toError } from '../../utils/error/error';\nimport { type ComponentSchemas, type RefMaps, storyRefMapper } from './ref-mapper';\nimport { getStoryFilename, isStoryPublishedWithoutChanges } from './utils';\n\nconst apiConcurrencyLock = new Sema(12);\n\nexport const fetchStoriesStream = ({\n  spaceId,\n  params = {},\n  setTotalStories,\n  setTotalPages,\n  onIncrement,\n  onPageSuccess,\n  onPageError,\n}: {\n  spaceId: string;\n  params?: StoriesQueryParams;\n  setTotalStories?: (total: number) => void;\n  setTotalPages?: (totalPages: number) => void;\n  onIncrement?: () => void;\n  onPageSuccess?: (page: number, total: number) => void;\n  onPageError?: (error: Error, page: number, total: number) => void;\n}) => {\n  const listGenerator = async function* storyListIterator() {\n    let perPage = 100;\n    let page = 1;\n    let totalPages = 1;\n    // Set a default for total pages in case the first request fails.\n    setTotalPages?.(totalPages);\n\n    while (page <= totalPages) {\n      try {\n        const result = await fetchStories(spaceId, {\n          ...params,\n          per_page: perPage,\n          page,\n        });\n\n        if (!result) {\n          break;\n        }\n\n        const { headers } = result;\n        const total = Number(headers.get('Total'));\n        perPage = Number(headers.get('Per-Page'));\n        totalPages = Math.ceil(total / perPage);\n        setTotalStories?.(total);\n        setTotalPages?.(totalPages);\n        onPageSuccess?.(page, totalPages);\n\n        for (const story of result.stories) {\n          yield story;\n        }\n\n        page += 1;\n      }\n      catch (maybeError) {\n        onPageError?.(toError(maybeError), page, totalPages);\n        break;\n      }\n      finally {\n        onIncrement?.();\n      }\n    }\n  };\n\n  return Readable.from(listGenerator());\n};\n\nexport const fetchStoryStream = ({\n  spaceId,\n  onIncrement,\n  onStorySuccess,\n  onStoryError,\n}: {\n  spaceId: string;\n  onIncrement?: () => void;\n  onStorySuccess?: (story: Story) => void;\n  onStoryError?: (error: Error, story: Story) => void;\n}) => {\n  const processing = new Set<Promise<void>>();\n\n  return new Transform({\n    objectMode: true,\n    async transform(listStory: Story, _encoding, callback) {\n      // Wait for a slot\n      await apiConcurrencyLock.acquire();\n\n      const task = fetchStory(spaceId, listStory.id.toString())\n        .then((story) => {\n          if (typeof story === 'undefined') {\n            throw new TypeError('Invalid story!');\n          }\n          onStorySuccess?.(story);\n          this.push(story);\n        })\n        .catch((maybeError) => {\n          onStoryError?.(toError(maybeError), listStory);\n        })\n        .finally(() => {\n          onIncrement?.();\n          apiConcurrencyLock.release();\n          processing.delete(task);\n        });\n      processing.add(task);\n\n      // Call callback immediately to allow the stream to process the next chunk\n      // (The `readLock` prevents us from reading too fast)\n      callback();\n    },\n    // Ensure all pending requests finish before closing the stream\n    flush(callback) {\n      Promise.all(processing).finally(() => callback());\n    },\n  });\n};\n\nexport const readLocalStoriesStream = ({\n  directoryPath,\n  fileFilter = () => true,\n  setTotalStories,\n  onIncrement,\n  onStorySuccess,\n  onStoryError,\n}: {\n  directoryPath: string;\n  /**\n   * Decides whether a local story file should flow into the pipeline.\n   * Receives the `filename` only — callers that need to resolve to a uuid\n   * should rely on an external index (e.g. the scan index from pass 1),\n   * because filenames `${slug}_${uuid}.json` can't be parsed reliably when\n   * either segment contains underscores.\n   */\n  fileFilter?: (options: { filename: string }) => boolean;\n  setTotalStories?: (total: number) => void;\n  onIncrement?: () => void;\n  onStorySuccess?: (story: Story) => void;\n  onStoryError?: (error: Error, filename: string) => void;\n}) => {\n  const listGenerator = async function* localStoryIterator() {\n    const files = (await readDirectory(directoryPath))\n      .filter(f => extname(f) === '.json' && fileFilter({ filename: f }));\n    setTotalStories?.(files.length);\n\n    for (const file of files) {\n      try {\n        const filePath = join(directoryPath, file);\n        const fileContent = await readFile(filePath, 'utf-8');\n        const story = JSON.parse(fileContent) as Story;\n        onStorySuccess?.(story);\n        yield story;\n      }\n      catch (maybeError) {\n        onStoryError?.(toError(maybeError), file);\n      }\n      finally {\n        onIncrement?.();\n      }\n    }\n  };\n\n  return Readable.from(listGenerator());\n};\n\nexport const mapReferencesStream = ({\n  schemas,\n  maps,\n  onIncrement,\n  onStorySuccess,\n  onStoryError,\n}: {\n  schemas: ComponentSchemas;\n  maps: RefMaps;\n  onIncrement?: () => void;\n  onStorySuccess?: (localStory: Story) => void;\n  onStoryError?: (error: Error, story: Story) => void;\n}) => {\n  return new Transform({\n    objectMode: true,\n    transform(localStory: Story, _encoding, callback) {\n      try {\n        const mappedStory = storyRefMapper(localStory, { schemas, maps });\n        onStorySuccess?.(mappedStory);\n        this.push(mappedStory);\n      }\n      catch (maybeError) {\n        onStoryError?.(toError(maybeError), localStory);\n      }\n      finally {\n        onIncrement?.();\n        callback();\n      }\n    },\n  });\n};\n\nexport type AppendToManifestTransport = (entry: StoryIndexEntry, remoteStory: TargetStoryRef) => Promise<void>;\n\nexport const makeAppendToManifestFSTransport = ({ manifestFile }: {\n  manifestFile: string;\n}): AppendToManifestTransport => async (entry, remoteStory) => {\n  const createdAt = new Date().toISOString();\n  await appendToFile(manifestFile, JSON.stringify({\n    old_id: entry.uuid,\n    new_id: remoteStory.uuid,\n    created_at: createdAt,\n  }));\n  await appendToFile(manifestFile, JSON.stringify({\n    old_id: entry.id,\n    new_id: remoteStory.id,\n    created_at: createdAt,\n  }));\n};\n\n/**\n * Scans all local `.json` story files and returns a lightweight index\n * (metadata only, no full content) used for level-by-level creation ordering.\n */\nexport const scanLocalStoryIndex = async ({\n  directoryPath,\n  setTotalStories,\n  onIncrement,\n  onError,\n}: {\n  directoryPath: string;\n  setTotalStories?: (total: number) => void;\n  onIncrement?: () => void;\n  onError?: (error: Error, filename: string) => void;\n}): Promise<StoryIndexEntry[]> => {\n  const files = (await readDirectory(directoryPath)).filter(f => extname(f) === '.json');\n  setTotalStories?.(files.length);\n  const entries: StoryIndexEntry[] = [];\n\n  for (const file of files) {\n    try {\n      const filePath = join(directoryPath, file);\n      const fileContent = await readFile(filePath, 'utf-8');\n      const story = JSON.parse(fileContent) as Story;\n      if (!story.uuid) {\n        // A missing uuid would otherwise collapse multiple stories onto the\n        // same empty-string key in downstream maps and silently lose content.\n        throw new Error(`Story \"${file}\" is missing a uuid and cannot be pushed.`);\n      }\n      entries.push({\n        filename: file,\n        id: story.id,\n        uuid: story.uuid,\n        slug: story.slug ?? '',\n        name: story.name ?? '',\n        full_slug: story.full_slug ?? '',\n        is_folder: story.is_folder ?? false,\n        is_startpage: (story as Record<string, unknown>).is_startpage === true,\n        parent_id: story.parent_id ?? null,\n        component: story.content?.component,\n      });\n    }\n    catch (maybeError) {\n      onError?.(toError(maybeError), file);\n    }\n    finally {\n      onIncrement?.();\n    }\n  }\n\n  return entries;\n};\n\nexport const groupStoriesByDepth = (entries: StoryIndexEntry[]): StoryIndexEntry[][] => {\n  const depthMap = new Map<number, StoryIndexEntry[]>();\n\n  for (const entry of entries) {\n    const slug = normalizeFullSlug(entry.full_slug || '');\n    const depth = slug === '' ? 0 : slug.split('/').length - 1;\n    if (!depthMap.has(depth)) {\n      depthMap.set(depth, []);\n    }\n    depthMap.get(depth)!.push(entry);\n  }\n\n  const maxDepth = depthMap.size > 0 ? Math.max(...depthMap.keys()) : 0;\n  const levels: StoryIndexEntry[][] = [];\n\n  for (let d = 0; d <= maxDepth; d++) {\n    const level = depthMap.get(d);\n    if (!level || level.length === 0) {\n      continue;\n    }\n    // Folders first so that concurrent task ordering is deterministic\n    // (parent-child correctness is guaranteed by the level-by-level iteration,\n    // since a folder is always at a shallower depth than its children).\n    level.sort((a, b) => {\n      if (a.is_folder && !b.is_folder) {\n        return -1;\n      }\n      if (!a.is_folder && b.is_folder) {\n        return 1;\n      }\n      return 0;\n    });\n    levels.push(level);\n  }\n\n  return levels;\n};\n\nconst findSlugMatch = ({\n  entry,\n  existingTargetStories,\n  claimedRemoteIds,\n}: {\n  entry: StoryIndexEntry;\n  existingTargetStories: ExistingTargetStories;\n  claimedRemoteIds: Set<number>;\n}): TargetStoryRef | undefined => {\n  const normalizedSlug = entry.full_slug ? normalizeFullSlug(entry.full_slug) : undefined;\n  const slugCandidates = normalizedSlug\n    ? existingTargetStories.bySlug.get(normalizedSlug)\n    : undefined;\n  if (!slugCandidates) {\n    return undefined;\n  }\n  const unclaimed = slugCandidates.filter(ref => !claimedRemoteIds.has(ref.id));\n  return unclaimed.find(ref => ref.is_folder === entry.is_folder) ?? unclaimed[0];\n};\n\nexport const createStoriesForLevel = async ({\n  level,\n  spaceId,\n  maps,\n  existingTargetStories,\n  claimedRemoteIds,\n  isCrossSpace,\n  dryRun,\n  appendToManifest,\n  onStorySuccess,\n  onStorySkipped,\n  onStoryError,\n}: {\n  level: StoryIndexEntry[];\n  spaceId: string;\n  maps: RefMaps;\n  existingTargetStories: ExistingTargetStories;\n  claimedRemoteIds: Set<number>;\n  isCrossSpace: boolean;\n  dryRun: boolean;\n  appendToManifest: AppendToManifestTransport;\n  onStorySuccess?: (entry: StoryIndexEntry, remoteStory: Story) => void;\n  onStorySkipped?: (entry: StoryIndexEntry, remoteStory: TargetStoryRef, reason: string) => void;\n  onStoryError?: (error: Error, entry: StoryIndexEntry) => void;\n}): Promise<void> => {\n  const processEntry = async (entry: StoryIndexEntry) => {\n    await apiConcurrencyLock.acquire();\n    try {\n      // Primary: check manifest mapping (from a previous push).\n      const mappedStoryId = maps.stories?.get(entry.id);\n      const mappedRemoteStory = mappedStoryId\n        ? existingTargetStories.byId.get(Number(mappedStoryId))\n        : undefined;\n      if (mappedRemoteStory) {\n        claimedRemoteIds.add(mappedRemoteStory.id);\n        onStorySkipped?.(entry, mappedRemoteStory, 'matched by manifest mapping from a previous push');\n        return;\n      }\n\n      // Fallback: match by full_slug when no manifest entry exists (first push).\n      // Only match if the remote story hasn't already been claimed by another\n      // local entry (prevents mis-matching after slug swaps or renames).\n      // A folder and its startpage share the same full_slug, so bySlug stores\n      // an array of candidates. We prefer matching by is_folder to avoid\n      // cross-mapping folders to startpages (which would break parent_id\n      // resolution for children).\n      const match = findSlugMatch({ entry, existingTargetStories, claimedRemoteIds });\n      if (match) {\n        const isMatchConfirmed = isCrossSpace || match.uuid === entry.uuid;\n        if (isMatchConfirmed) {\n          claimedRemoteIds.add(match.id);\n          await appendToManifest(entry, match);\n          onStorySkipped?.(entry, match, 'matched by slug in target space');\n          return;\n        }\n      }\n\n      if (!entry.is_folder && !entry.component) {\n        throw new Error(`Story \"${entry.slug}\" (${entry.filename}) is missing a content type (content.component). Every story must define a content field with a valid component.`);\n      }\n\n      // Resolve parent_id from the maps (parent was created in a previous level).\n      const resolvedParentId = entry.parent_id != null\n        ? maps.stories?.get(entry.parent_id)\n        : undefined;\n\n      if (dryRun) {\n        const fakeRemote = { id: entry.id, uuid: entry.uuid } as Story;\n        onStorySuccess?.(entry, fakeRemote);\n        return;\n      }\n\n      const remoteStory = await createStory(spaceId, {\n        story: {\n          slug: entry.slug,\n          name: entry.name,\n          is_folder: entry.is_folder,\n          ...(resolvedParentId != null ? { parent_id: Number(resolvedParentId) } : {}),\n          ...(entry.is_startpage && resolvedParentId != null ? { is_startpage: true } : {}),\n          ...(entry.component\n            ? { content: { _uid: '', component: entry.component } }\n            : {}),\n        },\n        publish: 0,\n      });\n      if (!remoteStory) {\n        throw new Error('No response!');\n      }\n\n      await appendToManifest(entry, remoteStory);\n      onStorySuccess?.(entry, remoteStory);\n    }\n    catch (maybeError) {\n      onStoryError?.(toError(maybeError), entry);\n    }\n    finally {\n      apiConcurrencyLock.release();\n    }\n  };\n\n  // Process folders first and await them before non-folders.\n  // A startpage shares the same full_slug (and depth) as its parent folder,\n  // so both land in the same level. Without this split the folder's ID might\n  // not be mapped yet when the startpage tries to resolve its parent_id.\n  const folders = level.filter(e => e.is_folder);\n  const nonFolders = level.filter(e => !e.is_folder);\n\n  const folderTasks: Promise<void>[] = [];\n  for (const entry of folders) {\n    folderTasks.push(processEntry(entry));\n  }\n  await Promise.all(folderTasks);\n\n  const storyTasks: Promise<void>[] = [];\n  for (const entry of nonFolders) {\n    storyTasks.push(processEntry(entry));\n  }\n  await Promise.all(storyTasks);\n};\n\nexport type WriteStoryTransport = (story: Story) => Promise<Story>;\n\nexport const makeWriteStoryFSTransport = ({ directoryPath }: {\n  directoryPath: string;\n}): WriteStoryTransport => async (story) => {\n  await saveToFile(resolve(directoryPath, getStoryFilename(story)), JSON.stringify(story, null, 2));\n  return story;\n};\n\nexport const makeWriteStoryAPITransport = ({ spaceId, publish }: {\n  spaceId: string;\n  publish?: number;\n}): WriteStoryTransport => mappedLocalStory => updateStory(spaceId, mappedLocalStory.id, {\n  story: {\n    ...mappedLocalStory,\n    parent_id: mappedLocalStory.parent_id ?? undefined,\n  },\n  publish: publish ?? (isStoryPublishedWithoutChanges(mappedLocalStory) ? 1 : 0),\n});\n\nexport type CleanupStoryTransport = (mappedStory: Story) => Promise<void>;\n\nexport const makeCleanupStoryFSTransport = ({ directoryPath, maps }: {\n  directoryPath: string;\n  maps: RefMaps;\n}): CleanupStoryTransport => {\n  // Pre-build reverse lookup (remoteUuid → localUuid) so each cleanup call\n  // is O(1) instead of scanning the full map.\n  const reverseUuidMap = new Map<string | number, string>();\n  if (maps.stories) {\n    for (const [key, value] of maps.stories.entries()) {\n      if (typeof key === 'string') {\n        reverseUuidMap.set(value, key);\n      }\n    }\n  }\n\n  return async (mappedStory: Story) => {\n    const uuid = mappedStory.uuid ?? '';\n    const originalUuid = reverseUuidMap.get(uuid) ?? uuid;\n    const storyFilename = getStoryFilename({\n      slug: mappedStory.slug,\n      uuid: originalUuid,\n    });\n    const storyFilePath = resolve(directoryPath, storyFilename);\n    await unlink(storyFilePath);\n  };\n};\n\nexport const writeStoryStream = ({\n  transports,\n  onIncrement,\n  onStorySuccess,\n  onStoryError,\n}: {\n  transports: {\n    writeStory: WriteStoryTransport;\n    cleanupStory?: CleanupStoryTransport;\n  };\n  onIncrement?: () => void;\n  onStorySuccess?: (mappedLocalStory: Story, remoteStory: Story) => void;\n  onStoryError?: (error: Error, story: Story) => void;\n}) => {\n  const processing = new Set<Promise<void>>();\n\n  return new Writable({\n    objectMode: true,\n    async write(mappedLocalStory: Story, _encoding, callback) {\n      await apiConcurrencyLock.acquire();\n\n      const task = (async () => {\n        try {\n          const remoteStory = await transports.writeStory(mappedLocalStory);\n          await transports.cleanupStory?.(remoteStory);\n\n          onStorySuccess?.(mappedLocalStory, remoteStory);\n        }\n        catch (maybeError) {\n          onStoryError?.(toError(maybeError), mappedLocalStory);\n        }\n      })();\n\n      processing.add(task);\n      task.finally(() => {\n        onIncrement?.();\n        apiConcurrencyLock.release();\n        processing.delete(task);\n      });\n\n      callback();\n    },\n    final(callback) {\n      Promise.all(processing).finally(() => callback());\n    },\n  });\n};\n","/**\n * Walks a richtext AST and invokes `onBlok` for every content node embedded in\n * a `type: 'blok'` attrs.body array. Read-only: does not reconstruct the tree.\n *\n * Ref-mapper has its own richtext traversal because it also remaps `type: 'link'`\n * story uuids and must return a new tree with mapped references. Extract a\n * shared map-with-rebuild helper only once that walker grows a second consumer.\n */\nexport const walkRichtextBloks = (node: unknown, onBlok: (blok: unknown) => void): void => {\n  if (Array.isArray(node)) {\n    for (const item of node) { walkRichtextBloks(item, onBlok); }\n    return;\n  }\n  if (!node || typeof node !== 'object') { return; }\n\n  const obj = node as Record<string, unknown>;\n  if (obj.type === 'blok' && obj.attrs && typeof obj.attrs === 'object') {\n    const body = (obj.attrs as Record<string, unknown>).body;\n    if (Array.isArray(body)) {\n      for (const blok of body) { onBlok(blok); }\n    }\n  }\n  for (const value of Object.values(obj)) { walkRichtextBloks(value, onBlok); }\n};\n","import { pipeline } from 'node:stream/promises';\nimport { Writable } from 'node:stream';\nimport type { Component } from '../components/constants';\nimport type { Story } from './constants';\nimport type { ComponentSchemas } from './ref-mapper';\nimport { walkRichtextBloks } from './richtext';\nimport { readLocalStoriesStream } from './streams';\n\nexport interface SchemaIssues {\n  driftByComponent: Map<Component['name'], Set<string>>;\n  missingSchemas: Set<Component['name']>;\n}\n\n/**\n * Aggregated schema-validation result across every local story in a directory.\n * Every drift field and missing component is paired with the set of affected\n * story `full_slug`s so the error message can point users at the files to fix.\n */\nexport interface AggregatedSchemaIssues {\n  driftByComponent: Map<Component['name'], Map<string, Set<string>>>;\n  missingSchemas: Map<Component['name'], Set<string>>;\n  total: number;\n}\n\nconst RESERVED_KEYS = new Set(['component']);\nconst isReservedKey = (key: string) => RESERVED_KEYS.has(key) || key.startsWith('_');\n\nconst MAX_STORIES_PER_ENTRY = 5;\n\nconst addDrift = (\n  driftByComponent: Map<string, Set<string>>,\n  component: string,\n  field: string,\n): void => {\n  const existing = driftByComponent.get(component) ?? new Set<string>();\n  existing.add(field);\n  driftByComponent.set(component, existing);\n};\n\n/**\n * Validates a story's content against local component schemas without mutating\n * either input. Records two kinds of issues:\n *\n * - `missingSchemas`: the content references a component whose schema is not\n *   available locally. Descent into that subtree stops.\n * - `driftByComponent`: for each known component, the set of content fields\n *   the component's schema does not declare (schema drift).\n *\n * Descends into fields declared as `bloks` (array of bloks) and `richtext`\n * (traverses the AST, recursing into `type: 'blok'` nodes).\n */\nexport const validateStoryAgainstSchemas = (\n  story: Story,\n  schemas: ComponentSchemas,\n): SchemaIssues => {\n  const driftByComponent = new Map<string, Set<string>>();\n  const missingSchemas = new Set<Component['name']>();\n\n  const visit = (data: unknown): void => {\n    if (!data || typeof data !== 'object' || Array.isArray(data)) { return; }\n    const node = data as Record<string, unknown>;\n    const componentName = node.component;\n    if (typeof componentName !== 'string' || componentName.length === 0) { return; }\n\n    const schema = schemas[componentName];\n    if (!schema) {\n      missingSchemas.add(componentName);\n      return;\n    }\n\n    for (const [fieldName, fieldValue] of Object.entries(node)) {\n      if (isReservedKey(fieldName)) { continue; }\n\n      const normalized = fieldName.replace(/__i18n__.*/, '');\n      const fieldSchema = (schema as Record<string, unknown>)[normalized] as\n        | Record<string, unknown>\n        | undefined;\n\n      if (!fieldSchema) {\n        addDrift(driftByComponent, componentName, normalized);\n        continue;\n      }\n\n      const fieldType = typeof fieldSchema.type === 'string' ? fieldSchema.type : undefined;\n\n      if (fieldType === 'bloks' && Array.isArray(fieldValue)) {\n        for (const item of fieldValue) { visit(item); }\n      }\n      else if (fieldType === 'richtext' && fieldValue && typeof fieldValue === 'object') {\n        walkRichtextBloks(fieldValue, blok => visit(blok));\n      }\n    }\n  };\n\n  visit(story.content);\n\n  return { driftByComponent, missingSchemas };\n};\n\nconst addStoryToSet = (bag: Map<string, Set<string>>, key: string, storySlug: string): void => {\n  const existing = bag.get(key) ?? new Set<string>();\n  existing.add(storySlug);\n  bag.set(key, existing);\n};\n\n/**\n * Streams every local story from `directoryPath` through\n * `validateStoryAgainstSchemas`, aggregating drift fields and missing component\n * schemas across the whole push and recording which stories are affected.\n * Resolves with an empty result when the directory does not exist — the\n * downstream pipeline reports that separately.\n */\nexport const collectSchemaIssues = async ({\n  directoryPath,\n  schemas,\n}: {\n  directoryPath: string;\n  schemas: ComponentSchemas;\n}): Promise<AggregatedSchemaIssues> => {\n  const issues: AggregatedSchemaIssues = {\n    driftByComponent: new Map(),\n    missingSchemas: new Map(),\n    total: 0,\n  };\n\n  try {\n    await pipeline(\n      readLocalStoriesStream({ directoryPath }),\n      new Writable({\n        objectMode: true,\n        write(story: Story, _encoding, callback) {\n          issues.total += 1;\n          const storyIdentifier = story.full_slug || story.slug;\n          const { driftByComponent, missingSchemas } = validateStoryAgainstSchemas(story, schemas);\n\n          for (const component of missingSchemas) {\n            addStoryToSet(issues.missingSchemas, component, storyIdentifier);\n          }\n          for (const [component, fields] of driftByComponent) {\n            const fieldMap = issues.driftByComponent.get(component) ?? new Map<string, Set<string>>();\n            for (const field of fields) { addStoryToSet(fieldMap, field, storyIdentifier); }\n            issues.driftByComponent.set(component, fieldMap);\n          }\n          callback();\n        },\n      }),\n    );\n  }\n  catch (error) {\n    // Missing directory is surfaced by the downstream read stream during Pass 1;\n    // pre-flight has nothing to add. Other errors propagate to the caller.\n    if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') { throw error; }\n  }\n\n  return issues;\n};\n\nconst formatStoryList = (stories: Set<string>): string => {\n  const sorted = [...stories].sort();\n  if (sorted.length <= MAX_STORIES_PER_ENTRY) { return sorted.join(', '); }\n  const shown = sorted.slice(0, MAX_STORIES_PER_ENTRY).join(', ');\n  return `${shown}, and ${sorted.length - MAX_STORIES_PER_ENTRY} more`;\n};\n\n/**\n * Builds the multi-line error message shown to the user when\n * `collectSchemaIssues` finds at least one problem. Splits the two kinds of\n * issues into separate sections with tailored remedies: the fix for a missing\n * component schema is different from the fix for an undeclared field, and\n * running `storyblok components pull` is not always the right answer.\n */\nexport const formatSchemaIssues = (issues: AggregatedSchemaIssues): string => {\n  const lines: string[] = ['Schema validation failed. Push aborted.'];\n\n  if (issues.missingSchemas.size > 0) {\n    lines.push('');\n    lines.push('Missing component schemas:');\n    const sortedMissing = [...issues.missingSchemas.entries()]\n      .sort(([a], [b]) => a.localeCompare(b));\n    for (const [component, stories] of sortedMissing) {\n      lines.push(`  - ${component} (in stories: ${formatStoryList(stories)})`);\n    }\n    lines.push('');\n    lines.push('If these components exist in Storyblok, run `storyblok components pull` to sync them locally.');\n    lines.push('Otherwise, create them in Storyblok first, or remove the references from the affected stories.');\n  }\n\n  if (issues.driftByComponent.size > 0) {\n    lines.push('');\n    lines.push('Fields not declared in local schemas:');\n    const sortedComponents = [...issues.driftByComponent.entries()]\n      .sort(([a], [b]) => a.localeCompare(b));\n    for (const [component, fieldMap] of sortedComponents) {\n      const sortedFields = [...fieldMap.entries()].sort(([a], [b]) => a.localeCompare(b));\n      for (const [field, stories] of sortedFields) {\n        lines.push(`  - ${component}.${field} (in stories: ${formatStoryList(stories)})`);\n      }\n    }\n    lines.push('');\n    lines.push('These fields will be lost when the stories are pushed. To fix, either:');\n    lines.push('  - Add the field to the component in Storyblok, then run `storyblok components pull`');\n    lines.push('  - Or remove the field from the affected story JSON files');\n  }\n\n  return lines.join('\\n');\n};\n\nexport const hasSchemaIssues = (issues: AggregatedSchemaIssues): boolean =>\n  issues.missingSchemas.size > 0 || issues.driftByComponent.size > 0;\n","import { pipeline } from 'node:stream/promises';\nimport type { Component } from '../components/constants';\nimport type { Story } from '../stories/constants';\nimport type { UI } from '../../utils/ui';\nimport type { WriteStoryTransport } from '../stories/streams';\nimport { fetchStoriesStream, fetchStoryStream, mapReferencesStream, writeStoryStream } from '../stories/streams';\nimport { validateStoryAgainstSchemas } from '../stories/validate-story';\nimport type { Logger } from '../../lib/logger/logger';\nimport type { Report } from '../../lib/reporter/reporter';\nimport { logOnlyError } from '../../utils/error/error';\nimport type {\n  AppendAssetFolderManifestTransport,\n  AppendAssetManifestTransport,\n  CleanupAssetFolderTransport,\n  CleanupAssetTransport,\n  CreateAssetFolderTransport,\n  CreateAssetTransport,\n  GetAssetFolderTransport,\n  GetAssetTransport,\n  UpdateAssetFolderTransport,\n  UpdateAssetTransport,\n} from './streams';\nimport { readLocalAssetFoldersStream, readLocalAssetsStream, readSingleAssetStream, upsertAssetFolderStream, upsertAssetStream } from './streams';\nimport type { AssetFolderMap, AssetMap, AssetUpload } from './types';\n\nconst PROGRESS_BAR_PADDING = 23;\n\ntype Summaries = [string, Report['summary'][string]][];\n\nexport const upsertAssetFoldersPipeline = async ({\n  directoryPath,\n  logger,\n  maps,\n  transports,\n  ui,\n}: {\n  directoryPath: string;\n  logger: Logger;\n  maps: { assetFolders: AssetFolderMap };\n  transports: {\n    getAssetFolder: GetAssetFolderTransport;\n    createAssetFolder: CreateAssetFolderTransport;\n    updateAssetFolder: UpdateAssetFolderTransport;\n    appendAssetFolderManifest: AppendAssetFolderManifestTransport;\n    cleanupAssetFolder?: CleanupAssetFolderTransport;\n  };\n  ui: UI;\n}): Promise<Summaries> => {\n  const folderProgress = ui.createProgressBar({ title: 'Folders...'.padEnd(PROGRESS_BAR_PADDING) });\n  const summary = { total: 0, succeeded: 0, failed: 0 };\n\n  await pipeline(\n    readLocalAssetFoldersStream({\n      directoryPath,\n      setTotalFolders: (total) => {\n        summary.total = total;\n        folderProgress.setTotal(total);\n      },\n      onFolderError: (error) => {\n        summary.failed += 1;\n        logOnlyError(error);\n      },\n    }),\n    upsertAssetFolderStream({\n      transports,\n      maps,\n      onIncrement: () => folderProgress.increment(),\n      onFolderSuccess: (localFolder, remoteFolder) => {\n        summary.succeeded += 1;\n        maps.assetFolders.set(localFolder.id, remoteFolder.id);\n        logger.info('Created asset folder', { folderId: remoteFolder.id });\n      },\n      onFolderError: (error, folder) => {\n        summary.failed += 1;\n        logOnlyError(error, { folderId: folder.id });\n      },\n    }),\n  );\n\n  return [['assetFolderResults', summary]];\n};\n\nexport const upsertAssetsPipeline = async ({\n  assetBinaryPath,\n  assetData,\n  directoryPath,\n  logger,\n  maps,\n  transports,\n  ui,\n}: {\n  assetBinaryPath?: string;\n  assetData?: AssetUpload;\n  directoryPath: string;\n  logger: Logger;\n  maps: { assets: AssetMap; assetFolders: AssetFolderMap };\n  transports: {\n    getAsset: GetAssetTransport;\n    createAsset: CreateAssetTransport;\n    updateAsset: UpdateAssetTransport;\n    appendAssetManifest: AppendAssetManifestTransport;\n    cleanupAsset: CleanupAssetTransport;\n  };\n  ui: UI;\n}): Promise<Summaries> => {\n  const assetProgress = ui.createProgressBar({ title: 'Assets...'.padEnd(PROGRESS_BAR_PADDING) });\n  const summary = { total: 0, succeeded: 0, failed: 0 };\n\n  const steps = [];\n  // Use the asset provided via the CLI.\n  if (assetBinaryPath && assetData) {\n    summary.total = 1;\n    assetProgress.setTotal(1);\n\n    steps.push(readSingleAssetStream({\n      asset: assetData,\n      assetBinaryPath,\n      onAssetError: (error) => {\n        summary.failed += 1;\n        assetProgress.increment();\n        logOnlyError(error);\n      },\n    }));\n  }\n  // Read assets from the local file system.\n  else {\n    steps.push(readLocalAssetsStream({\n      directoryPath,\n      setTotalAssets: (total) => {\n        summary.total = total;\n        assetProgress.setTotal(total);\n      },\n      onAssetError: (error) => {\n        summary.failed += 1;\n        assetProgress.increment();\n        logOnlyError(error);\n      },\n    }));\n  }\n\n  steps.push(upsertAssetStream({\n    transports,\n    maps,\n    onIncrement: () => assetProgress.increment(),\n    onAssetSuccess: (localAssetResult, remoteAsset) => {\n      if ('id' in localAssetResult && localAssetResult.id) {\n        maps.assets.set(localAssetResult.id, {\n          old: localAssetResult,\n          new: {\n            id: remoteAsset.id,\n            filename: remoteAsset.filename,\n            meta_data: remoteAsset.meta_data,\n          },\n        });\n      }\n\n      summary.succeeded += 1;\n      logger.info('Uploaded asset', { assetId: remoteAsset.id });\n    },\n    onAssetError: (error, asset) => {\n      summary.failed += 1;\n      logOnlyError(error, { assetId: asset.id });\n    },\n  }));\n  await pipeline(steps);\n\n  return [['assetResults', summary]];\n};\n\nexport const mapAssetReferencesInStoriesPipeline = async ({\n  logger,\n  maps,\n  schemas,\n  space,\n  transports,\n  ui,\n}: {\n  logger: Logger;\n  maps: { assets: AssetMap };\n  schemas: Record<Component['name'], Component['schema']>;\n  space: string;\n  transports: {\n    writeStory: WriteStoryTransport;\n  };\n  ui: UI;\n}): Promise<Summaries> => {\n  if (Object.keys(schemas).length === 0) {\n    const message = 'No components found. Please run `storyblok components pull` to fetch the latest components.';\n    ui.error(message);\n    logger.error(message);\n    return [];\n  }\n\n  const fetchStoryPagesProgress = ui.createProgressBar({ title: 'Fetching Story Pages...'.padEnd(PROGRESS_BAR_PADDING) });\n  const fetchStoriesProgress = ui.createProgressBar({ title: 'Fetching Stories...'.padEnd(PROGRESS_BAR_PADDING) });\n  const processProgress = ui.createProgressBar({ title: 'Processing Stories...'.padEnd(PROGRESS_BAR_PADDING) });\n  const updateProgress = ui.createProgressBar({ title: 'Updating Stories...'.padEnd(PROGRESS_BAR_PADDING) });\n\n  const summaries = {\n    fetchStoryPages: { total: 0, succeeded: 0, failed: 0 },\n    fetchStories: { total: 0, succeeded: 0, failed: 0 },\n    storyProcessResults: { total: 0, succeeded: 0, failed: 0 },\n    storyUpdateResults: { total: 0, succeeded: 0, failed: 0 },\n  };\n\n  const warnAboutMissingSchemas = (missingSchemas: Set<Component['name']>, story: Story) => {\n    const missingSchemaWarnings = new Set<string>();\n    for (const schemaName of missingSchemas) {\n      if (missingSchemaWarnings.has(schemaName)) {\n        continue;\n      }\n      const message = `The component \"${schemaName}\" was not found. Please run \\`storyblok components pull\\` to fetch the latest components.`;\n      logger.warn(message, { storyId: story.uuid });\n      missingSchemaWarnings.add(schemaName);\n    }\n  };\n\n  // If we only have one asset map entry, we can filter for stories referencing this asset.\n  const assetMapValues = [...maps.assets.values()];\n  const reference_search = assetMapValues.length === 1 ? assetMapValues[0].new.filename : undefined;\n\n  await pipeline(\n    fetchStoriesStream({\n      spaceId: space,\n      params: {\n        reference_search,\n      },\n      setTotalPages: (totalPages) => {\n        summaries.fetchStoryPages.total = totalPages;\n        fetchStoryPagesProgress.setTotal(totalPages);\n      },\n      setTotalStories: (total) => {\n        summaries.fetchStories.total = total;\n        summaries.storyProcessResults.total = total;\n        summaries.storyUpdateResults.total = total;\n        fetchStoriesProgress.setTotal(total);\n        processProgress.setTotal(total);\n        updateProgress.setTotal(total);\n      },\n      onIncrement: () => fetchStoryPagesProgress.increment(),\n      onPageSuccess: (page, total) => {\n        logger.info(`Fetched stories page ${page} of ${total}`);\n        summaries.fetchStoryPages.succeeded += 1;\n      },\n      onPageError: (error, page, total) => {\n        summaries.fetchStoryPages.failed += 1;\n        logOnlyError(error, { page, total });\n      },\n    }),\n    fetchStoryStream({\n      spaceId: space,\n      onIncrement: () => {\n        fetchStoriesProgress.increment();\n      },\n      onStorySuccess: (story) => {\n        logger.info('Fetched story', { storyId: story.id });\n        summaries.fetchStories.succeeded += 1;\n      },\n      onStoryError: (error, story) => {\n        summaries.fetchStories.failed += 1;\n        summaries.storyProcessResults.total -= 1;\n        summaries.storyUpdateResults.total -= 1;\n        processProgress.setTotal(summaries.storyProcessResults.total);\n        updateProgress.setTotal(summaries.storyProcessResults.total);\n        logOnlyError(error, { storyId: story.id });\n      },\n    }),\n    // Map all references to numeric ids and uuids.\n    mapReferencesStream({\n      schemas,\n      maps: { stories: new Map(), ...maps },\n      onIncrement() {\n        processProgress.increment();\n      },\n      onStorySuccess(localStory) {\n        const { missingSchemas } = validateStoryAgainstSchemas(localStory, schemas);\n        warnAboutMissingSchemas(missingSchemas, localStory);\n        logger.info('Processed story', { storyId: localStory.uuid });\n        summaries.storyProcessResults.succeeded += 1;\n      },\n      onStoryError(error, localStory) {\n        summaries.storyProcessResults.failed += 1;\n        summaries.storyUpdateResults.total -= 1;\n        updateProgress.setTotal(summaries.storyUpdateResults.total);\n        logOnlyError(error, { storyId: localStory.id });\n      },\n    }),\n    // Update remote stories with correct references.\n    writeStoryStream({\n      transports: {\n        writeStory: transports.writeStory,\n      },\n      onIncrement() {\n        updateProgress.increment();\n      },\n      onStorySuccess(localStory) {\n        logger.info('Updated story', { storyId: localStory.uuid });\n        summaries.storyUpdateResults.succeeded += 1;\n      },\n      onStoryError(error, localStory) {\n        summaries.storyUpdateResults.failed += 1;\n        logOnlyError(error, { storyId: localStory.id });\n      },\n    }),\n  );\n\n  return Object.entries(summaries);\n};\n","import { basename, join } from 'pathe';\nimport { colorPalette, commands, directories } from '../../../constants';\nimport { assetsCommand } from '../command';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\nimport { getReporter, type Report } from '../../../lib/reporter/reporter';\nimport { session } from '../../../session';\nimport { requireAuthentication } from '../../../utils/auth';\nimport { CommandError } from '../../../utils/error/command-error';\nimport { handleError, toError } from '../../../utils/error/error';\nimport { deduplicateManifest, resolveCommandPath } from '../../../utils/filesystem';\nimport {\n  makeAppendAssetFolderManifestFSTransport,\n  makeAppendAssetManifestFSTransport,\n  makeCleanupAssetFolderFSTransport,\n  makeCleanupAssetFSTransport,\n  makeCreateAssetAPITransport,\n  makeCreateAssetFolderAPITransport,\n  makeGetAssetAPITransport,\n  makeGetAssetFolderAPITransport,\n  makeUpdateAssetAPITransport,\n  makeUpdateAssetFolderAPITransport,\n} from '../streams';\nimport type { Asset, AssetFolder, AssetFolderCreate, AssetFolderUpdate, AssetMapped, AssetUpload } from '../types';\nimport { isRemoteSource, loadAssetFolderMap, loadAssetMap, loadSidecarAssetData, parseAssetData } from '../utils';\nimport { findComponentSchemas } from '../../stories/utils';\nimport { mapAssetReferencesInStoriesPipeline, upsertAssetFoldersPipeline, upsertAssetsPipeline } from '../pipelines';\nimport type { Story } from '../../stories/constants';\nimport { makeWriteStoryAPITransport } from '../../stories/streams';\n\nconst pushCmd = assetsCommand\n  .command('push')\n  .argument('[asset]', 'path or URL of a single asset to push')\n  .option('-s, --space <space>', 'space ID')\n  .option('-f, --from <from>', 'source space id')\n  .option('--data <data>', 'inline asset data as JSON')\n  .option('--short-filename <short-filename>', 'override the asset filename')\n  .option('--folder <folderId>', 'destination asset folder ID')\n  .option('--cleanup', 'delete local assets and metadata after a successful push (note: does not cleanup manifests)')\n  .option('--update-stories', 'update file references in stories if necessary', false)\n  .option('-d, --dry-run', 'Preview changes without applying them to Storyblok')\n  .description(`Push local assets to a Storyblok space.`);\n\npushCmd\n  .action(async (assetInput, options, command) => {\n    const ui = getUI();\n    const logger = getLogger();\n    const reporter = getReporter();\n\n    ui.title(`${commands.ASSETS}`, colorPalette.ASSETS, 'Pushing assets...');\n    logger.info('Pushing assets started');\n\n    if (options.dryRun) {\n      ui.warn(`DRY RUN MODE ENABLED: No changes will be made.\\n`);\n      logger.warn('Dry run mode enabled');\n    }\n\n    const { space: targetSpace, path: basePath, verbose } = command.optsWithGlobals();\n    const fromSpace = (options.from as string | undefined) || targetSpace;\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      process.exitCode = 2;\n      return;\n    }\n    if (!targetSpace) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      process.exitCode = 2;\n      return;\n    }\n\n    const summaries: [string, Report['summary'][string]][] = [];\n    let fatalError = false;\n\n    const manifestFile = join(resolveCommandPath(directories.assets, fromSpace, basePath), 'manifest.jsonl');\n    const folderManifestFile = join(resolveCommandPath(directories.assets, fromSpace, basePath), 'folders', 'manifest.jsonl');\n\n    try {\n      const [assetMap, assetFolderMap] = await Promise.all([\n        loadAssetMap(manifestFile),\n        loadAssetFolderMap(folderManifestFile),\n      ]);\n      const maps = { assets: assetMap, assetFolders: assetFolderMap };\n      const assetsDirectoryPath = resolveCommandPath(directories.assets, fromSpace, basePath);\n\n      /**\n       * Upsert Asset Folders\n       */\n      const assetFolderGetTransport = makeGetAssetFolderAPITransport({ spaceId: targetSpace });\n      const assetFolderCreateTransport = options.dryRun\n        ? async (folder: AssetFolderCreate) => folder as AssetFolder\n        : makeCreateAssetFolderAPITransport({ spaceId: targetSpace });\n      const assetFolderUpdateTransport = options.dryRun\n        ? async (_id: number, folder: AssetFolderUpdate) => folder\n        : makeUpdateAssetFolderAPITransport({ spaceId: targetSpace });\n      const assetFolderManifestTransport = options.dryRun\n        ? () => Promise.resolve()\n        : makeAppendAssetFolderManifestFSTransport({ manifestFile: folderManifestFile });\n      const cleanupAssetFolderTransport = options.cleanup && !options.dryRun\n        ? makeCleanupAssetFolderFSTransport()\n        : () => Promise.resolve();\n\n      summaries.push(...await upsertAssetFoldersPipeline({\n        directoryPath: join(assetsDirectoryPath, 'folders'),\n        logger,\n        maps,\n        transports: {\n          getAssetFolder: assetFolderGetTransport,\n          createAssetFolder: assetFolderCreateTransport,\n          updateAssetFolder: assetFolderUpdateTransport,\n          appendAssetFolderManifest: assetFolderManifestTransport,\n          cleanupAssetFolder: cleanupAssetFolderTransport,\n        },\n        ui,\n      }));\n\n      /**\n       * Upsert Assets\n       */\n      const assetBinaryPath = typeof assetInput === 'string' && assetInput.trim().length > 0\n        ? assetInput\n        : undefined;\n      let assetData: AssetUpload | undefined;\n      if (assetBinaryPath) {\n        const assetDataPartial = options.data\n          ? parseAssetData(options.data)\n          : !isRemoteSource(assetBinaryPath)\n              ? await loadSidecarAssetData(assetBinaryPath)\n              : {};\n        const sourceBasename = isRemoteSource(assetBinaryPath)\n          ? basename(new URL(assetBinaryPath).pathname)\n          : basename(assetBinaryPath);\n        const shortFilename = options.shortFilename || assetDataPartial.short_filename || sourceBasename;\n        const folderId = options.folder ? Number(options.folder) : undefined;\n        assetData = {\n          ...assetDataPartial,\n          short_filename: shortFilename,\n          asset_folder_id: folderId,\n        } satisfies AssetUpload;\n      }\n\n      const getAssetTransport = makeGetAssetAPITransport({ spaceId: targetSpace });\n      const createAssetTransport = options.dryRun\n        ? async (asset: AssetUpload) => asset as Asset\n        : makeCreateAssetAPITransport({ spaceId: targetSpace });\n      const updateAssetTransport = options.dryRun\n        ? async () => {}\n        : makeUpdateAssetAPITransport({ spaceId: targetSpace });\n      const assetManifestTransport = options.dryRun\n        ? () => Promise.resolve()\n        : makeAppendAssetManifestFSTransport({ manifestFile });\n      const cleanupAssetTransport = options.cleanup && !options.dryRun\n        ? makeCleanupAssetFSTransport()\n        : () => Promise.resolve();\n\n      summaries.push(...await upsertAssetsPipeline({\n        assetBinaryPath,\n        assetData,\n        directoryPath: assetsDirectoryPath,\n        logger,\n        maps,\n        transports: {\n          getAsset: getAssetTransport,\n          createAsset: createAssetTransport,\n          updateAsset: updateAssetTransport,\n          appendAssetManifest: assetManifestTransport,\n          cleanupAsset: cleanupAssetTransport,\n        },\n        ui,\n      }));\n\n      /**\n       * Map Asset References in Stories\n       */\n      const hasUpdatedFilename = (entry: { old: Asset | AssetMapped | AssetUpload; new: AssetMapped }) =>\n        'filename' in entry.old && entry.old.filename !== entry.new.filename;\n      const hasMetadata = (entry: { old: Asset | AssetMapped | AssetUpload; new: AssetMapped }) =>\n        'meta_data' in entry.new && entry.new.meta_data;\n      const hasUpdatedAssets = maps.assets.values().some(v => hasUpdatedFilename(v) || hasMetadata(v));\n      if (hasUpdatedAssets && options.updateStories) {\n        const schemas = await findComponentSchemas(resolveCommandPath(directories.components, fromSpace, basePath));\n        const writeStoryTransport = options.dryRun\n          ? async (story: Story) => story\n          : makeWriteStoryAPITransport({ spaceId: targetSpace });\n\n        summaries.push(...await mapAssetReferencesInStoriesPipeline({\n          logger,\n          maps,\n          schemas,\n          space: targetSpace,\n          transports: {\n            writeStory: writeStoryTransport,\n          },\n          ui,\n        }));\n      }\n\n      if (!options.dryRun) {\n        await deduplicateManifest(manifestFile);\n      }\n    }\n    catch (maybeError) {\n      fatalError = true;\n      handleError(toError(maybeError), verbose);\n    }\n    finally {\n      ui.stopAllProgressBars();\n\n      const summary = Object.fromEntries(summaries);\n      logger.info('Pushing assets finished', { summary });\n      const assetsTotal = summary.assetResults?.total ?? 0;\n      const assetsSucceeded = summary.assetResults?.succeeded ?? 0;\n      const assetsFailed = summary.assetResults?.failed ?? 0;\n\n      ui.info(`Push results: ${assetsTotal} processed, ${assetsFailed} assets failed`);\n      ui.list([\n        `Folders: ${summary.assetFolderResults?.succeeded ?? 0}/${summary.assetFolderResults?.total ?? 0} succeeded, ${summary.assetFolderResults?.failed ?? 0} failed.`,\n        `Assets: ${assetsSucceeded}/${assetsTotal} succeeded, ${assetsFailed} failed.`,\n      ]);\n      for (const [name, reportSummary] of summaries) {\n        reporter.addSummary(name, reportSummary);\n      }\n      reporter.finalize();\n\n      const failedTotal = Object.values(summary).reduce((total, entry) => {\n        if (!entry || typeof entry.failed !== 'number') {\n          return total;\n        }\n        return total + entry.failed;\n      }, 0);\n      process.exitCode = fatalError ? 2 : failedTotal > 0 ? 1 : 0;\n    }\n  });\n","import { commands } from '../../constants';\nimport { getProgram } from '../../program';\n\nconst program = getProgram();\n\nexport const storiesCommand = program\n  .command(commands.STORIES)\n  .description(`Manage your space's stories`);\n","import { pipeline } from 'node:stream/promises';\nimport type { Story } from '../constants';\nimport { colorPalette, commands, directories } from '../../../constants';\nimport { session } from '../../../session';\nimport { storiesCommand } from '../command';\nimport { resolveCommandPath } from '../../../utils/filesystem';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\nimport { getReporter } from '../../../lib/reporter/reporter';\nimport { fetchStoriesStream, fetchStoryStream, makeWriteStoryFSTransport, writeStoryStream } from '../streams';\nimport { requireAuthentication } from '../../../utils/auth';\nimport { handleError, toError } from '../../../utils/error/error';\nimport { CommandError } from '../../../utils/error/command-error';\n\nconst pullCmd = storiesCommand\n  .command('pull')\n  .option('-s, --space <space>', 'space ID')\n  .option('-d, --dry-run', 'Preview changes without applying them to Storyblok')\n  .option('-q, --query <query>', 'Filter stories by content attributes using Storyblok filter query syntax. Example: --query=\"[highlighted][in]=true\"')\n  .option('--starts-with <path>', 'Filter stories by path. Example: --starts-with=\"/en/blog/\"')\n  .description(`Download your space's stories as separate json files.`);\n\npullCmd\n  .action(async (options, command) => {\n    const ui = getUI();\n    const logger = getLogger();\n    const reporter = getReporter();\n\n    ui.title(`${commands.STORIES}`, colorPalette.STORIES, 'Pulling stories...');\n    logger.info('Pulling stories started');\n\n    if (options.dryRun) {\n      ui.warn(`DRY RUN MODE ENABLED: No changes will be made.\\n`);\n      logger.warn('Dry run mode enabled');\n    }\n\n    const { space, path: basePath, verbose } = command.optsWithGlobals();\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n    if (!space) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      return;\n    }\n\n    const summary = {\n      fetchStoryPages: { total: 0, succeeded: 0, failed: 0 },\n      fetchStories: { total: 0, succeeded: 0, failed: 0 },\n      save: { total: 0, succeeded: 0, failed: 0 },\n    };\n    try {\n      const fetchStoryPagesProgress = ui.createProgressBar({ title: 'Fetching Story Pages...'.padEnd(23) });\n      const fetchStoriesProgress = ui.createProgressBar({ title: 'Fetching Stories...'.padEnd(23) });\n      const saveProgress = ui.createProgressBar({ title: 'Saving Stories...'.padEnd(23) });\n      await pipeline(\n        fetchStoriesStream({\n          spaceId: space,\n          params: {\n            filter_query: options.query,\n            starts_with: options.startsWith,\n          },\n          setTotalPages: (totalPages) => {\n            summary.fetchStoryPages.total = totalPages;\n            fetchStoryPagesProgress.setTotal(totalPages);\n          },\n          setTotalStories: (total) => {\n            summary.fetchStories.total = total;\n            summary.save.total = total;\n            fetchStoriesProgress.setTotal(total);\n            saveProgress.setTotal(total);\n          },\n          onIncrement: () => {\n            fetchStoryPagesProgress.increment();\n          },\n          onPageSuccess: (page, total) => {\n            logger.info(`Fetched stories page ${page} of ${total}`);\n            summary.fetchStoryPages.succeeded += 1;\n          },\n          onPageError: (error, page, total) => {\n            summary.fetchStoryPages.failed += 1;\n            handleError(error, verbose, { page, total });\n          },\n        }),\n        fetchStoryStream({\n          spaceId: space,\n          onIncrement: () => {\n            fetchStoriesProgress.increment();\n          },\n          onStorySuccess: (story) => {\n            logger.info('Fetched story', { storyId: story.id });\n            summary.fetchStories.succeeded += 1;\n          },\n          onStoryError: (error, story) => {\n            summary.fetchStories.failed += 1;\n            summary.save.total -= 1;\n            saveProgress.setTotal(summary.save.total);\n            handleError(error, verbose, { storyId: story.id });\n          },\n        }),\n        writeStoryStream({\n          transports: {\n            writeStory: options.dryRun\n              ? async (story: Story) => story\n              : makeWriteStoryFSTransport({ directoryPath: resolveCommandPath(directories.stories, space, basePath) }),\n          },\n          onIncrement: () => {\n            saveProgress.increment();\n          },\n          onStorySuccess: (story) => {\n            logger.info('Saved story', { storyId: story.id });\n            summary.save.succeeded += 1;\n          },\n          onStoryError: (error, story) => {\n            summary.save.failed += 1;\n            handleError(error, verbose, { storyId: story.id });\n          },\n        }),\n      );\n    }\n    catch (maybeError) {\n      handleError(toError(maybeError));\n    }\n    finally {\n      logger.info('Pulling stories finished', summary);\n      ui.stopAllProgressBars();\n      ui.info(`Pull results: ${summary.save.total} stories pulled, ${Math.max(summary.fetchStories.failed, summary.save.failed)} stories failed`);\n      ui.list([\n        `Fetching pages: ${summary.fetchStoryPages.succeeded}/${summary.fetchStoryPages.total} succeeded, ${summary.fetchStoryPages.failed} failed.`,\n        `Fetching stories: ${summary.fetchStories.succeeded}/${summary.fetchStories.total} succeeded, ${summary.fetchStories.failed} failed.`,\n        `Saving stories: ${summary.save.succeeded}/${summary.save.total} succeeded, ${summary.save.failed} failed.`,\n      ]);\n\n      reporter.addSummary('fetchStoryPagesResults', summary.fetchStoryPages);\n      reporter.addSummary('fetchStoriesResults', summary.fetchStories);\n      reporter.addSummary('saveResults', summary.save);\n      reporter.finalize();\n    }\n  });\n","import { APIError } from '../../../utils';\nimport type { UI } from '../../../utils/ui';\n\ninterface FailedStoryRecord {\n  filename?: string;\n  full_slug?: string;\n  slug?: string;\n  uuid?: string;\n  id?: number | string;\n  error: Error;\n}\n\n/**\n * Anything that carries a story's identity. Structural — accepts\n * `StoryIndexEntry`, MAPI `Story`, or an ad-hoc `{ filename }`.\n */\nexport interface StoryIdentity {\n  filename?: string;\n  full_slug?: string;\n  slug?: string;\n  uuid?: string;\n  id?: number | string;\n}\n\nfunction formatStoryIdentifier(record: FailedStoryRecord): string {\n  const title = record.full_slug ?? record.slug ?? record.uuid ?? record.id?.toString() ?? record.filename ?? 'unknown story';\n  const extras: string[] = [];\n  if (record.uuid && record.uuid !== title) { extras.push(`uuid: ${record.uuid}`); }\n  if (record.filename && record.filename !== title) { extras.push(`file: ${record.filename}`); }\n  return extras.length > 0 ? `${title} (${extras.join(', ')})` : title;\n}\n\nconst ENRICHABLE_FIELDS = ['full_slug', 'slug', 'uuid', 'id', 'filename'] as const satisfies readonly (keyof FailedStoryRecord)[];\n\n/**\n * Splice the record's value into field-level API error lines so users can see\n * which* value the server objected to. Example: `slug: is invalid` with\n * `record.slug === 'about#'` becomes `slug (about#): is invalid`.\n */\nfunction enrichFieldMessage(detail: string, record: FailedStoryRecord): string {\n  const match = detail.match(/^(\\w+):/);\n  if (!match) { return detail; }\n  const field = match[1];\n  if (!ENRICHABLE_FIELDS.includes(field as typeof ENRICHABLE_FIELDS[number])) { return detail; }\n  const value = record[field as keyof FailedStoryRecord];\n  if (value == null || value === '' || value instanceof Error) { return detail; }\n  return `${field} (${String(value)})${detail.slice(field.length)}`;\n}\n\nfunction renderFailureReport(ui: UI, records: FailedStoryRecord[], verbose: boolean): void {\n  if (records.length === 0) { return; }\n\n  ui.error(`Failed stories (${records.length}):`, undefined, { header: false, margin: false });\n\n  const lines: string[] = [];\n  for (const record of records) {\n    lines.push(formatStoryIdentifier(record));\n    const messages = record.error instanceof APIError ? record.error.messageStack : [record.error.message];\n    const [primary, ...rest] = messages;\n    lines.push(`  • ${enrichFieldMessage(primary ?? 'Unknown error', record)}`);\n    for (const detail of rest) {\n      lines.push(`      └─ ${enrichFieldMessage(detail, record)}`);\n    }\n    if (verbose && record.error.stack) {\n      for (const frame of record.error.stack.split('\\n')) {\n        lines.push(`      ${frame}`);\n      }\n    }\n  }\n  ui.list(lines);\n  ui.br();\n  if (!verbose) {\n    ui.info('Re-run with the `--verbose` flag for full stack traces.', { margin: false });\n  }\n}\n\n/**\n * Collects per-story failures across the push phases, dedups by identity on\n * insertion, and renders a grouped summary. The collector is phase-agnostic:\n * callers just ask `record()` \"is this a new failure?\" and decide their own\n * counter bookkeeping based on the answer.\n *\n * Identity key priority: `full_slug` → `uuid` → `filename` → synthetic.\n * `full_slug` is the only cross-phase-stable, in-space-unique identifier\n * (`uuid`/`id` are remapped by `storyRefMapper`, `slug` alone is not unique\n * because two stories can share a leaf slug under different parents).\n */\nexport class FailureCollector {\n  private records = new Map<string, FailedStoryRecord>();\n\n  private keyFor(story: StoryIdentity): string {\n    return story.full_slug ?? story.uuid ?? story.filename ?? `__unknown_${this.records.size}`;\n  }\n\n  /**\n   * Record a failure. Returns `true` if this is the first failure seen for\n   * this story's identity, `false` if one was already recorded (in which case\n   * the caller should skip counter updates to avoid double-billing).\n   */\n  record(story: StoryIdentity, error: Error): boolean {\n    const key = this.keyFor(story);\n    if (this.records.has(key)) { return false; }\n    this.records.set(key, {\n      filename: story.filename,\n      full_slug: story.full_slug,\n      slug: story.slug,\n      uuid: story.uuid,\n      id: story.id,\n      error,\n    });\n    return true;\n  }\n\n  get isEmpty(): boolean {\n    return this.records.size === 0;\n  }\n\n  get size(): number {\n    return this.records.size;\n  }\n\n  render(ui: UI, verbose: boolean = false): void {\n    renderFailureReport(ui, [...this.records.values()], verbose);\n  }\n\n  toReporterMeta(): Array<{\n    filename: string | undefined;\n    full_slug: string | undefined;\n    slug: string | undefined;\n    uuid: string | undefined;\n    id: number | string | undefined;\n    error: string;\n  }> {\n    return [...this.records.values()].map(r => ({\n      filename: r.filename,\n      full_slug: r.full_slug,\n      slug: r.slug,\n      uuid: r.uuid,\n      id: r.id,\n      error: r.error.message,\n    }));\n  }\n}\n","import { pipeline } from 'node:stream/promises';\nimport { join } from 'pathe';\nimport type { Story } from '../constants';\nimport { colorPalette, commands, directories } from '../../../constants';\nimport { CommandError, handleError, logOnlyError, requireAuthentication, toError } from '../../../utils';\nimport { session } from '../../../session';\nimport { storiesCommand } from '../command';\nimport { loadManifest, resolveCommandPath } from '../../../utils/filesystem';\nimport { getUI } from '../../../utils/ui';\nimport { getLogger } from '../../../lib/logger/logger';\nimport { getReporter } from '../../../lib/reporter/reporter';\nimport { createStoriesForLevel, groupStoriesByDepth, makeAppendToManifestFSTransport, makeCleanupStoryFSTransport, makeWriteStoryAPITransport, mapReferencesStream, readLocalStoriesStream, scanLocalStoryIndex, writeStoryStream } from '../streams';\nimport { findComponentSchemas } from '../utils';\nimport { loadAssetMap } from '../../assets/utils';\nimport { prefetchTargetStoriesByKeys } from '../actions';\nimport { collectSchemaIssues, formatSchemaIssues, hasSchemaIssues } from '../validate-story';\nimport { FailureCollector } from './failure-report';\n\nconst pushCmd = storiesCommand\n  .command('push')\n  .option('-s, --space <space>', 'space ID')\n  .option('-f, --from <from>', 'source space id')\n  .option('-d, --dry-run', 'Preview changes without applying them to Storyblok')\n  .option('--publish', 'Publish stories after pushing')\n  .option('--cleanup', 'delete local stories after a successful push (note: does not cleanup manifests)')\n  .description(`Push local stories to a Storyblok space.`);\n\npushCmd\n  .action(async (options, command) => {\n    const ui = getUI();\n    const logger = getLogger();\n    const reporter = getReporter();\n\n    ui.title(`${commands.STORIES}`, colorPalette.STORIES, 'Pushing stories...');\n    logger.info('Pushing stories started');\n\n    if (options.dryRun) {\n      ui.warn(`DRY RUN MODE ENABLED: No changes will be made.\\n`);\n      logger.warn('Dry run mode enabled');\n    }\n\n    const { space, path: basePath, verbose } = command.optsWithGlobals();\n    const fromSpace = options.from || space;\n    const { state } = session();\n\n    if (!requireAuthentication(state, verbose)) {\n      return;\n    }\n    if (!space) {\n      handleError(new CommandError(`Please provide the space as argument --space YOUR_SPACE_ID.`), verbose);\n      return;\n    }\n\n    const pendingWarnings: string[] = [];\n    const failures = new FailureCollector();\n\n    const summary = {\n      creationResults: { total: 0, succeeded: 0, skipped: 0, failed: 0 },\n      processResults: { total: 0, succeeded: 0, failed: 0 },\n      updateResults: { total: 0, succeeded: 0, failed: 0 },\n    };\n    try {\n      const manifestFile = join(resolveCommandPath(directories.stories, fromSpace, basePath), 'manifest.jsonl');\n      const manifest = await loadManifest(manifestFile);\n      const assetManifestFile = join(resolveCommandPath(directories.assets, fromSpace, basePath), 'manifest.jsonl');\n      const maps = {\n        assets: await loadAssetMap(assetManifestFile),\n        stories: new Map<unknown, string | number>(manifest.map(e => [e.old_id, e.new_id])),\n      };\n\n      const schemas = await findComponentSchemas(resolveCommandPath(directories.components, fromSpace, basePath));\n      if (Object.keys(schemas).length === 0) {\n        const message = 'No components found. Please run `storyblok components pull` to fetch the latest components.';\n        ui.error(message);\n        logger.error(message);\n        return;\n      }\n\n      const storiesDirectoryPath = resolveCommandPath(directories.stories, fromSpace, basePath);\n\n      // Pre-flight schema validation. Aborts before any API call if a story's\n      // content references a missing component, or has fields that the local\n      // schema does not declare (schema drift).\n      const schemaIssues = await collectSchemaIssues({ directoryPath: storiesDirectoryPath, schemas });\n      if (hasSchemaIssues(schemaIssues)) {\n        const message = formatSchemaIssues(schemaIssues);\n        ui.error(message);\n        logger.error(message);\n        // Surface the failure in the run summary so the report status is\n        // FAILURE rather than a trivial zero-counts SUCCESS.\n        const total = Math.max(schemaIssues.total, 1);\n        summary.creationResults.total = total;\n        summary.creationResults.failed = total;\n        return;\n      }\n\n      // Warn when story content includes custom plugin payloads. References\n      // embedded inside a plugin's opaque JSON can't be auto-remapped, so the\n      // user may need to update them manually. Emitted once per plugin name\n      // per story during Pass 2, after schema validation has confirmed the\n      // content shape is trustworthy.\n      const warnAboutCustomPlugins = (story: Story) => {\n        const warned = new Set<string>();\n        const visit = (node: unknown): void => {\n          if (Array.isArray(node)) {\n            for (const item of node) { visit(item); }\n            return;\n          }\n          if (!node || typeof node !== 'object') { return; }\n          const obj = node as Record<string, unknown>;\n          const plugin = obj.plugin;\n          if (typeof plugin === 'string' && !warned.has(plugin)) {\n            warned.add(plugin);\n            const message = `The custom plugin \"${plugin}\" may contain references that require manual updates.`;\n            pendingWarnings.push(message);\n            logger.warn(message, { storyId: story.uuid });\n          }\n          for (const value of Object.values(obj)) { visit(value); }\n        };\n        visit(story.content);\n      };\n\n      /**\n       * Pass 1: Scan local stories, group by depth, and create remote\n       * placeholders level-by-level so that parent folders exist before\n       * their children are created.\n       *\n       * Scan happens before the prefetch so we know which slugs and ids\n       * to look up — the prefetch only fetches what the push actually needs.\n       */\n      const scanProgress = ui.createProgressBar({ title: 'Scanning Stories...'.padEnd(21) });\n      const storyIndex = await scanLocalStoryIndex({\n        directoryPath: storiesDirectoryPath,\n        setTotalStories(total) {\n          scanProgress.setTotal(total);\n        },\n        onIncrement() {\n          scanProgress.increment();\n        },\n        onError(error, filename) {\n          if (failures.record({ filename }, error)) {\n            summary.creationResults.failed += 1;\n          }\n          logOnlyError(error, { storyFile: filename });\n        },\n      });\n      const levels = groupStoriesByDepth(storyIndex);\n      scanProgress.stop();\n\n      // Targeted prefetch: only the local stories' slugs + manifest-mapped ids.\n      // For a small push against a large target space, this is O(local) calls\n      // instead of O(target/100) — and they run concurrently through the MAPI throttle.\n      const localSlugs = storyIndex.map(entry => entry.full_slug).filter(Boolean);\n      const localIdSet = new Set(storyIndex.map(entry => entry.id));\n      const manifestIds: number[] = [];\n      for (const [key, value] of maps.stories.entries()) {\n        if (typeof key === 'number' && localIdSet.has(key) && typeof value === 'number') {\n          manifestIds.push(value);\n        }\n      }\n      const fetchProgress = ui.createProgressBar({ title: 'Matching Stories...'.padEnd(21) });\n      const existingTargetStories = await prefetchTargetStoriesByKeys(\n        space,\n        { slugs: localSlugs, ids: manifestIds },\n        {\n          onTotal: total => fetchProgress.setTotal(total),\n          onIncrement: count => fetchProgress.increment(count),\n        },\n      );\n      fetchProgress.stop();\n\n      const creationProgress = ui.createProgressBar({ title: 'Creating Stories...'.padEnd(21) });\n      const processProgress = ui.createProgressBar({ title: 'Processing Stories...'.padEnd(21) });\n      const updateProgress = ui.createProgressBar({ title: 'Updating Stories...'.padEnd(21) });\n      const totalStories = storyIndex.length + summary.creationResults.failed;\n      summary.creationResults.total = totalStories;\n      summary.processResults.total = totalStories;\n      summary.updateResults.total = totalStories;\n      creationProgress.setTotal(totalStories);\n      processProgress.setTotal(totalStories);\n      updateProgress.setTotal(totalStories);\n\n      const appendToManifest = options.dryRun\n        ? (() => Promise.resolve()) as ReturnType<typeof makeAppendToManifestFSTransport>\n        : makeAppendToManifestFSTransport({ manifestFile });\n\n      // Tracks which remote story IDs have been matched to a local entry,\n      // preventing two local stories from mapping to the same remote\n      // (e.g. after slug swaps or renames between pushes).\n      const claimedRemoteIds = new Set<number>();\n\n      for (const level of levels) {\n        await createStoriesForLevel({\n          level,\n          spaceId: space,\n          maps,\n          existingTargetStories,\n          claimedRemoteIds,\n          isCrossSpace: fromSpace !== space,\n          dryRun: options.dryRun ?? false,\n          appendToManifest,\n          onStorySuccess(entry, remoteStory) {\n            if (!entry.uuid) {\n              throw new Error(`Local story file \"${entry.filename}\" is missing a \"uuid\" field. Re-pull the story or add the uuid manually.`);\n            }\n            if (!remoteStory.uuid) {\n              throw new Error(`Storyblok API returned a story without a uuid for slug \"${entry.slug}\".`);\n            }\n            maps.stories.set(entry.id, remoteStory.id);\n            maps.stories.set(entry.uuid, remoteStory.uuid);\n            logger.info('Created story', { storyId: remoteStory.uuid });\n            summary.creationResults.succeeded += 1;\n            creationProgress.increment();\n          },\n          onStorySkipped(entry, remoteStory, reason) {\n            if (!entry.uuid) {\n              throw new Error(`Local story file \"${entry.filename}\" is missing a \"uuid\" field. Re-pull the story or add the uuid manually.`);\n            }\n            if (!remoteStory.uuid) {\n              throw new Error(`Storyblok API returned a story without a uuid for slug \"${entry.slug}\".`);\n            }\n            maps.stories.set(entry.id, remoteStory.id);\n            maps.stories.set(entry.uuid, remoteStory.uuid);\n            logger.info(`Skipped creating story: ${reason}`, { storyId: entry.uuid });\n            summary.creationResults.skipped += 1;\n            creationProgress.increment();\n          },\n          onStoryError(error, entry) {\n            if (failures.record(entry, error)) {\n              summary.creationResults.failed += 1;\n              summary.processResults.total -= 1;\n              summary.updateResults.total -= 1;\n              processProgress.setTotal(summary.processResults.total);\n              updateProgress.setTotal(summary.updateResults.total);\n            }\n            creationProgress.increment();\n            logOnlyError(error, { storyId: entry.uuid });\n          },\n        });\n      }\n\n      if (summary.creationResults.failed > 0) {\n        const message = `${summary.creationResults.failed} ${summary.creationResults.failed === 1 ? 'story' : 'stories'} failed to create. References to these stories will be left unmapped.`;\n        pendingWarnings.push(message);\n        logger.warn(message);\n      }\n\n      /**\n       * Pass 2: Update remote stories with corrected references.\n       *\n       * We need to run the second pass in a separate pipeline because we need a\n       * complete map of all stories.\n       */\n      const uuidByFilename = new Map(storyIndex.map(entry => [entry.filename, entry.uuid]));\n\n      await pipeline(\n        // Read local stories from `.json` files.\n        readLocalStoriesStream({\n          directoryPath: storiesDirectoryPath,\n          fileFilter({ filename }) {\n            // Only load files that were successfully created and mapped.\n            const uuid = uuidByFilename.get(filename);\n            return uuid != null && Boolean(maps.stories.get(uuid));\n          },\n          setTotalStories(total) {\n            summary.processResults.total = total;\n            summary.updateResults.total = total;\n            processProgress.setTotal(total);\n            updateProgress.setTotal(total);\n          },\n          onStoryError(error, filename) {\n            if (failures.record({ filename }, error)) {\n              summary.processResults.failed += 1;\n            }\n            else {\n              // Already counted as failed in an earlier phase; drop from this\n              // phase's total so `succeeded + failed === total` holds.\n              summary.processResults.total -= 1;\n              processProgress.setTotal(summary.processResults.total);\n            }\n            summary.updateResults.total -= 1;\n            updateProgress.setTotal(summary.updateResults.total);\n            logOnlyError(error, { storyFile: filename });\n          },\n        }),\n        // Map all references to numeric ids and uuids.\n        mapReferencesStream({\n          schemas,\n          maps,\n          onIncrement() {\n            processProgress.increment();\n          },\n          onStorySuccess(localStory) {\n            warnAboutCustomPlugins(localStory);\n            logger.info('Processed story', { storyId: localStory.uuid });\n            summary.processResults.succeeded += 1;\n          },\n          onStoryError(error, localStory) {\n            // Always keep the audit trail — even when we suppress the\n            // user-facing summary entry for stories that already failed\n            // creation, the file log should retain the full per-phase error.\n            logOnlyError(error, { storyId: localStory.uuid });\n            if (failures.record(localStory, error)) {\n              summary.processResults.failed += 1;\n            }\n            else {\n              summary.processResults.total -= 1;\n              processProgress.setTotal(summary.processResults.total);\n            }\n            summary.updateResults.total -= 1;\n            updateProgress.setTotal(summary.updateResults.total);\n          },\n        }),\n        // Update remote stories with correct references.\n        writeStoryStream({\n          transports: {\n            writeStory: options.dryRun\n              ? async (story: Story) => story\n              : makeWriteStoryAPITransport({\n                  spaceId: space,\n                  publish: options.publish ? 1 : undefined,\n                }),\n            cleanupStory: options.cleanup && !options.dryRun\n              ? makeCleanupStoryFSTransport({ directoryPath: storiesDirectoryPath, maps })\n              : undefined,\n          },\n          onIncrement() {\n            updateProgress.increment();\n          },\n          onStorySuccess(localStory) {\n            logger.info('Updated story', { storyId: localStory.uuid });\n            summary.updateResults.succeeded += 1;\n          },\n          onStoryError(error, localStory) {\n            logOnlyError(error, { storyId: localStory.uuid });\n            if (failures.record(localStory, error)) {\n              summary.updateResults.failed += 1;\n            }\n            else {\n              // Already counted as failed in an earlier phase; drop from this\n              // phase's total so `succeeded + failed === total` holds.\n              summary.updateResults.total -= 1;\n              updateProgress.setTotal(summary.updateResults.total);\n            }\n          },\n        }),\n      );\n    }\n    catch (maybeError) {\n      handleError(toError(maybeError), verbose);\n    }\n    finally {\n      logger.info('Pushing stories finished', summary);\n      ui.stopAllProgressBars();\n      ui.br();\n\n      const failedCount = failures.size;\n      ui.info(`Push results: ${summary.creationResults.total} ${summary.creationResults.total === 1 ? 'story' : 'stories'} pushed, ${failedCount} ${failedCount === 1 ? 'story' : 'stories'} failed`);\n      ui.list([\n        `Creating stories: ${summary.creationResults.succeeded + summary.creationResults.skipped}/${summary.creationResults.total} succeeded, ${summary.creationResults.failed} failed.`,\n        `Processing stories: ${summary.processResults.succeeded}/${summary.processResults.total} succeeded, ${summary.processResults.failed} failed.`,\n        `Updating stories: ${summary.updateResults.succeeded}/${summary.updateResults.total} succeeded, ${summary.updateResults.failed} failed.`,\n      ]);\n\n      if (pendingWarnings.length > 0 || !failures.isEmpty) {\n        ui.br();\n      }\n\n      for (const warning of pendingWarnings) {\n        ui.warn(warning);\n      }\n\n      if (pendingWarnings.length > 0 && !failures.isEmpty) {\n        ui.br();\n      }\n\n      failures.render(ui, verbose);\n\n      reporter.addSummary('creationResults', summary.creationResults);\n      reporter.addSummary('processResults', summary.processResults);\n      reporter.addSummary('updateResults', summary.updateResults);\n      if (!failures.isEmpty) {\n        reporter.addMeta('failedStories', failures.toReporterMeta());\n      }\n      reporter.finalize();\n    }\n  });\n","#!/usr/bin/env node\nimport 'dotenv/config';\n\nimport { handleError, konsola } from './utils';\nimport { getProgram } from './program';\nimport './commands/login';\nimport './commands/logout';\nimport './commands/signup';\nimport './commands/user';\nimport './commands/components';\nimport './commands/languages';\nimport './commands/migrations';\nimport './commands/types';\nimport './commands/datasources';\nimport './commands/create';\nimport './commands/logs';\nimport './commands/reports';\nimport './commands/assets';\nimport './commands/stories';\n\nimport { colorPalette } from './constants';\n\nexport * from './types/storyblok';\n\nconst program = getProgram();\n\nkonsola.br();\nkonsola.br();\nkonsola.title(` Storyblok CLI `, colorPalette.PRIMARY);\n\n// Handle invalid commands\nprogram.on('command:*', () => {\n  console.error(`Invalid command: ${program.args.join(' ')}`);\n  konsola.br();\n  program.outputHelp();\n  process.exit(1);\n});\n\ntry {\n  program.parse(process.argv);\n}\ncatch (error) {\n  handleError(error as Error);\n}\n"],"names":["c12LoadConfig","resolvePath","__filename","__dirname","packageJson","readFileImpl","program","region","pullCmd","componentName","pushCmd","generateCmd","result","readFile","component","ui","template","projectName","listCmd","pruneCmd","apiConcurrencyLock","pipeline","fieldRefMappers"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACO,MAAM,QAAA,GAAW;AAAA,EACtB,KAAA,EAAO,OAAA;AAAA,EACP,MAAA,EAAQ,QAAA;AAAA,EACR,MAAA,EAAQ,QAAA;AAAA,EACR,IAAA,EAAM,MAAA;AAAA,EACN,UAAA,EAAY,YAAA;AAAA,EACZ,SAAA,EAAW,WAAA;AAAA,EACX,UAAA,EAAY,YAAA;AAAA,EACZ,KAAA,EAAO,OAAA;AAAA,EACP,WAAA,EAAa,aAAA;AAAA,EACb,MAAA,EAAQ,QAAA;AAAA,EACR,IAAA,EAAM,MAAA;AAAA,EACN,OAAA,EAAS,SAAA;AAAA,EACT,MAAA,EAAQ,QAAA;AAAA,EACR,OAAA,EAAS;AACX,CAAA;AAEO,MAAM,YAAA,GAAe;AAAA,EAC1B,OAAA,EAAS,SAAA;AAAA,EACT,KAAA,EAAO,SAAA;AAAA,EACP,MAAA,EAAQ,SAAA;AAAA,EACR,MAAA,EAAQ,SAAA;AAAA,EACR,IAAA,EAAM,SAAA;AAAA,EACN,UAAA,EAAY,SAAA;AAAA,EACZ,SAAA,EAAW,SAAA;AAAA,EACX,UAAA,EAAY,SAAA;AAAA,EACZ,KAAA,EAAO,SAAA;AAAA,EACP,MAAA,EAAQ,SAAA;AAAA,EACR,MAAA,EAAQ,SAAA;AAAA,EACR,IAAA,EAAM,SAAA;AAAA,EACN,OAAA,EAAS,SAAA;AAAA,EACT,WAAA,EAAa,SAAA;AAAA,EACb,IAAA,EAAM,SAAA;AAAA,EACN,OAAA,EAAS,SAAA;AAAA,EACT,MAAA,EAAQ,SAAA;AAAA,EACR,OAAA,EA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