crosssync 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/dist/index.js +292 -30
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../node_modules/commander/lib/error.js","../../../node_modules/commander/lib/argument.js","../../../node_modules/commander/lib/help.js","../../../node_modules/commander/lib/option.js","../../../node_modules/commander/lib/suggestSimilar.js","../../../node_modules/commander/lib/command.js","../../../node_modules/commander/index.js","../../shared/src/constants.ts","../../shared/src/bookmark.ts","../../shared/src/history.ts","../../shared/src/config.ts","../../shared/src/utils.ts","../../shared/src/index.ts","../../core/src/constants.ts","../../core/src/logger.ts","../../core/src/browser-status.ts","../../core/src/readers/chromium.ts","../../core/src/readers/index.ts","../../core/src/merger.ts","../../core/src/backup.ts","../../core/src/sync.ts","../../core/src/index.ts","../src/index.ts","../../../node_modules/commander/esm.mjs","../src/constants.ts","../src/context.ts","../src/commands/backup.ts","../src/commands/read.ts","../src/commands/config.ts","../src/commands/cron.ts","../src/cron/index.ts","../src/cron/linux.ts","../src/cron/invocation.ts","../src/cron/runner.ts","../src/cron/schedule.ts","../src/cron/macos.ts","../src/cron/windows.ts","../src/commands/export.ts","../src/export-files.ts","../src/commands/sync.ts","../src/commands/logs.ts","../src/commands/status.ts"],"sourcesContent":["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.length > 3 && this._name.slice(-3) === '...') {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n","const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(max, helper.subcommandTerm(command).length);\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(max, helper.argumentTerm(argument).length);\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n return `${option.description} (${extraInfo.join(', ')})`;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescripton = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescripton}`;\n }\n return extraDescripton;\n }\n return argument.description;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth || 80;\n const itemIndentWidth = 2;\n const itemSeparatorWidth = 2; // between term and description\n function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(\n fullText,\n helpWidth - itemIndentWidth,\n termWidth + itemSeparatorWidth,\n );\n }\n return term;\n }\n function formatList(textArray) {\n return textArray.join('\\n').replace(/^/gm, ' '.repeat(itemIndentWidth));\n }\n\n // Usage\n let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.wrap(commandDescription, helpWidth, 0),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return formatItem(\n helper.argumentTerm(argument),\n helper.argumentDescription(argument),\n );\n });\n if (argumentList.length > 0) {\n output = output.concat(['Arguments:', formatList(argumentList), '']);\n }\n\n // Options\n const optionList = helper.visibleOptions(cmd).map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (optionList.length > 0) {\n output = output.concat(['Options:', formatList(optionList), '']);\n }\n\n if (this.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (globalOptionList.length > 0) {\n output = output.concat([\n 'Global Options:',\n formatList(globalOptionList),\n '',\n ]);\n }\n }\n\n // Commands\n const commandList = helper.visibleCommands(cmd).map((cmd) => {\n return formatItem(\n helper.subcommandTerm(cmd),\n helper.subcommandDescription(cmd),\n );\n });\n if (commandList.length > 0) {\n output = output.concat(['Commands:', formatList(commandList), '']);\n }\n\n return output.join('\\n');\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Wrap the given string to width characters per line, with lines after the first indented.\n * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.\n *\n * @param {string} str\n * @param {number} width\n * @param {number} indent\n * @param {number} [minColumnWidth=40]\n * @return {string}\n *\n */\n\n wrap(str, width, indent, minColumnWidth = 40) {\n // Full \\s characters, minus the linefeeds.\n const indents =\n ' \\\\f\\\\t\\\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff';\n // Detect manually wrapped and indented strings by searching for line break followed by spaces.\n const manualIndent = new RegExp(`[\\\\n][${indents}]+`);\n if (str.match(manualIndent)) return str;\n // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).\n const columnWidth = width - indent;\n if (columnWidth < minColumnWidth) return str;\n\n const leadingStr = str.slice(0, indent);\n const columnText = str.slice(indent).replace('\\r\\n', '\\n');\n const indentString = ' '.repeat(indent);\n const zeroWidthSpace = '\\u200B';\n const breaks = `\\\\s${zeroWidthSpace}`;\n // Match line end (so empty lines don't collapse),\n // or as much text as will fit in column, or excess text up to first break.\n const regex = new RegExp(\n `\\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,\n 'g',\n );\n const lines = columnText.match(regex) || [];\n return (\n leadingStr +\n lines\n .map((line, i) => {\n if (line === '\\n') return ''; // preserve empty lines\n return (i > 0 ? indentString : '') + line.trimEnd();\n })\n .join('\\n')\n );\n }\n}\n\nexports.Help = Help;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag;\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as a object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // Use original very loose parsing to maintain backwards compatibility for now,\n // which allowed for example unintended `-sw, --short-word` [sic].\n const flagParts = flags.split(/[ |,]+/);\n if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))\n shortFlag = flagParts.shift();\n longFlag = flagParts.shift();\n // Add support for lone short flag without significantly changing parsing!\n if (!shortFlag && /^-[^-]$/.test(longFlag)) {\n shortFlag = longFlag;\n longFlag = undefined;\n }\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n","const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n","const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = true;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n\n // see .configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n outputError: (str, write) => write(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // functions to change where being written, stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // matching functions to specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // functions based on what is being written out\n * outputError(str, write) // used for displaying errors, and not used for displaying help\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n Object.assign(this._outputConfiguration, configuration);\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [fn] - custom argument processing function\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, fn, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof fn === 'function') {\n argument.default(defaultValue).argParser(fn);\n } else {\n argument.default(fn);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument && previousArgument.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n return this;\n }\n\n enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._concatValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch (err) {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise && promise.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent && this.parent.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} argv\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(argv) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n const args = argv.slice();\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n // parse options\n let activeVariadicOption = null;\n while (args.length) {\n const arg = args.shift();\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args);\n break;\n }\n\n if (activeVariadicOption && !maybeOption(arg)) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args.shift();\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (args.length > 0 && !maybeOption(args[0])) {\n value = args.shift();\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option, emit and put back remainder of arg for further processing\n this.emit(`option:${option.name()}`);\n args.unshift(`-${arg.slice(2)}`);\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n if (maybeOption(arg)) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg);\n if (args.length > 0) operands.push(...args);\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg);\n if (args.length > 0) dest.push(...args);\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n if (helper.helpWidth === undefined) {\n helper.helpWidth =\n contextOptions && contextOptions.error\n ? this._outputConfiguration.getErrHelpWidth()\n : this._outputConfiguration.getOutHelpWidth();\n }\n return helper.formatHelp(this, helper);\n }\n\n /**\n * @private\n */\n\n _getHelpContext(contextOptions) {\n contextOptions = contextOptions || {};\n const context = { error: !!contextOptions.error };\n let write;\n if (context.error) {\n write = (arg) => this._outputConfiguration.writeErr(arg);\n } else {\n write = (arg) => this._outputConfiguration.writeOut(arg);\n }\n context.write = contextOptions.write || write;\n context.command = this;\n return context;\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n const context = this._getHelpContext(contextOptions);\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', context));\n this.emit('beforeHelp', context);\n\n let helpInformation = this.helpInformation(context);\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n context.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', context);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', context),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n this._helpOption = this._helpOption ?? undefined; // preserve existing option\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n flags = flags ?? '-h, --help';\n description = description ?? 'display help for command';\n this._helpOption = this.createOption(flags, description);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = process.exitCode || 0;\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\nexports.Command = Command;\n","const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n","export const SHARED_PACKAGE = '@crosssync/shared';\nexport const SHARED_VERSION = '0.1.0';\n\n/** Log levels, ordered from most to least verbose. */\nexport const LOG_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type LogLevel = (typeof LOG_LEVELS)[number];\n\n/** Supported Chromium-based browsers. */\nexport const BROWSERS = ['chrome', 'edge'] as const;\nexport type BrowserName = (typeof BROWSERS)[number];\n\n/**\n * Chromium timestamps are microseconds since 1601-01-01T00:00:00Z.\n * This is the offset between that epoch and the Unix epoch, in milliseconds.\n */\nexport const CHROMIUM_EPOCH_OFFSET_MS = 11644473600000;\n\n/** Directory name (created under the user home) holding all CrossSync runtime data. */\nexport const CROSSSYNC_DIR_NAME = '.crosssync';\nexport const BACKUP_DIR_NAME = 'backups';\nexport const EXPORT_DIR_NAME = 'export';\nexport const LOG_DIR_NAME = 'logs';\nexport const CONFIG_FILE_NAME = 'config.json';\nexport const LOG_FILE_NAME = 'crosssync.log';\n\n/** File names inside a Chromium profile directory. */\nexport const BOOKMARKS_FILE_NAME = 'Bookmarks';\nexport const HISTORY_FILE_NAME = 'History';\n\n/** Chromium profile directory names that actually hold user data. */\nexport const PROFILE_NAME_PATTERN = /^(Default|Profile \\d+)$/;\n\nexport const DEFAULT_PROFILE = 'Default';\nexport const DEFAULT_LOG_LEVEL: LogLevel = 'info';\nexport const CONFIG_VERSION = 1;\n\n/** How many of the most recent export files are kept after a successful run. */\nexport const DEFAULT_EXPORT_RETENTION = 10;\n\n/** Cron expression installed by default: every day at 09:00 local time. */\nexport const DEFAULT_CRON_SCHEDULE = '0 9 * * *';\n","/**\n * Types mirroring the Chromium `Bookmarks` JSON file, shared by Chrome and Edge.\n *\n * Chromium writes snake_case keys (`date_added`, `date_modified`, ...) and encodes\n * timestamps as microsecond strings since the Windows epoch (1601-01-01).\n */\n\nexport const BOOKMARK_NODE_TYPES = ['folder', 'url'] as const;\nexport type BookmarkNodeType = (typeof BOOKMARK_NODE_TYPES)[number];\n\nexport interface BookmarkNode {\n /** Chromium-managed numeric id, string encoded. */\n id: string;\n /** Display name. Root folders use localized names. */\n name: string;\n type: BookmarkNodeType;\n /** Present on `folder` nodes only. */\n children?: BookmarkNode[];\n /** Present on `url` nodes only. */\n url?: string;\n /** Chromium GUID; regenerated when absent. */\n guid?: string;\n /** Microseconds since the Windows epoch, string encoded. */\n date_added?: string;\n date_modified?: string;\n date_last_used?: string;\n meta_info?: Record<string, unknown>;\n}\n\n/** Fixed top-level folders of a Chromium bookmark file. */\nexport const BOOKMARK_ROOT_KEYS = ['bookmark_bar', 'other', 'synced'] as const;\nexport type BookmarkRootKey = (typeof BOOKMARK_ROOT_KEYS)[number];\n\nexport interface BookmarkRoots {\n bookmark_bar: BookmarkNode;\n other: BookmarkNode;\n synced?: BookmarkNode;\n}\n\nexport interface BookmarkFile {\n /** Chrome validates this MD5 field; CrossSync drops it on write-back. */\n checksum?: string;\n roots: BookmarkRoots;\n version?: number;\n}\n\n/** A bookmark node together with the folder path leading to it. */\nexport interface FlatBookmark {\n node: BookmarkNode;\n /** Folder names from the root down to (excluding) the node itself. */\n folderPath: string[];\n}\n\nexport function isBookmarkFolder(node: BookmarkNode): boolean {\n return node.type === 'folder';\n}\n\nexport function isBookmarkUrl(node: BookmarkNode): boolean {\n return node.type === 'url';\n}\n\n/** Depth-first traversal of a bookmark tree. */\nexport function walkBookmarkTree(node: BookmarkNode, visit: (node: BookmarkNode) => void): void {\n visit(node);\n for (const child of node.children ?? []) {\n walkBookmarkTree(child, visit);\n }\n}\n\n/** Flattens a bookmark tree into a list of nodes while keeping their folder path. */\nexport function flattenBookmarks(root: BookmarkNode, folderPath: string[] = []): FlatBookmark[] {\n const result: FlatBookmark[] = [{ node: root, folderPath }];\n const nextPath = root.type === 'folder' ? [...folderPath, root.name] : folderPath;\n for (const child of root.children ?? []) {\n result.push(...flattenBookmarks(child, nextPath));\n }\n return result;\n}\n\n/** Counts nodes in a bookmark tree, optionally filtered by node type. */\nexport function countBookmarks(root: BookmarkNode, type?: BookmarkNodeType): number {\n let total = 0;\n walkBookmarkTree(root, (node) => {\n if (!type || node.type === type) {\n total += 1;\n }\n });\n return total;\n}\n","/**\n * Types mirroring the Chromium `History` SQLite database (`urls` table).\n *\n * Chromium stores `last_visit_time` as microseconds since the Windows epoch and\n * `visit_count` / `typed_count` as integers. CrossSync normalises the timestamp\n * to Unix milliseconds so downstream code never deals with the Chromium epoch.\n */\n\nexport interface HistoryEntry {\n /** Chromium `urls.id`; absent for entries built in memory. */\n id?: number;\n url: string;\n title: string;\n visitCount: number;\n typedCount: number;\n /** Unix epoch milliseconds. */\n lastVisitTime: number;\n}\n\n/** A `History` file together with the profile it was read from. */\nexport interface HistoryFile {\n browser: string;\n profile: string;\n entries: HistoryEntry[];\n}\n\nexport const HISTORY_QUERY = [\n 'SELECT id, url, title, visit_count, typed_count, last_visit_time',\n 'FROM urls',\n \"WHERE url IS NOT NULL AND url != ''\",\n 'ORDER BY last_visit_time DESC',\n].join(' ');\n","import type { BrowserName, LogLevel } from './constants';\nimport {\n CONFIG_VERSION,\n DEFAULT_CRON_SCHEDULE,\n DEFAULT_EXPORT_RETENTION,\n DEFAULT_LOG_LEVEL,\n DEFAULT_PROFILE,\n} from './constants';\n\n/** Whether a run may write merged bookmarks back into the browser files. */\nexport const SYNC_STRATEGIES = ['merge', 'export'] as const;\nexport type SyncStrategy = (typeof SYNC_STRATEGIES)[number];\n\nexport interface BrowserConfig {\n enabled: boolean;\n /** Override for the auto-detected browser \"User Data\" directory. */\n dataDir?: string;\n}\n\nexport interface SyncConfig {\n bookmarks: boolean;\n history: boolean;\n /** `merge` = merge then write back; `export` = read-only, write merged output only. */\n strategy: SyncStrategy;\n}\n\nexport interface ScheduleConfig {\n /** True when a scheduled task/timer has been installed. */\n installed: boolean;\n /** Cron expression used by the installed schedule. */\n expression: string;\n}\n\nexport interface ExportsConfig {\n /** How many of the most recent export files to keep; `0` disables cleanup. */\n keep: number;\n}\n\nexport interface CliConfig {\n version: number;\n /** Absolute path of the CrossSync data directory (`~/.crosssync`). */\n dataDir: string;\n backupDir: string;\n exportDir: string;\n logDir: string;\n logLevel: LogLevel;\n /** Chromium profile to sync: `Default`, `Profile 1`, ... or `all`. */\n profile: string;\n browsers: Record<BrowserName, BrowserConfig>;\n sync: SyncConfig;\n schedule: ScheduleConfig;\n /** Optional so configs written by older versions keep loading. */\n exports?: ExportsConfig;\n}\n\n/** Reads `exports.keep`, falling back to the default for older config files. */\nexport function resolveExportRetention(config: Pick<CliConfig, 'exports'>): number {\n return config.exports?.keep ?? DEFAULT_EXPORT_RETENTION;\n}\n\nexport interface CreateDefaultConfigOptions {\n dataDir: string;\n backupDir: string;\n exportDir: string;\n logDir: string;\n profile?: string;\n logLevel?: LogLevel;\n}\n\nexport function createDefaultConfig(options: CreateDefaultConfigOptions): CliConfig {\n return {\n version: CONFIG_VERSION,\n dataDir: options.dataDir,\n backupDir: options.backupDir,\n exportDir: options.exportDir,\n logDir: options.logDir,\n logLevel: options.logLevel ?? DEFAULT_LOG_LEVEL,\n profile: options.profile ?? DEFAULT_PROFILE,\n browsers: {\n chrome: { enabled: true },\n edge: { enabled: true },\n },\n sync: {\n bookmarks: true,\n history: true,\n strategy: 'merge',\n },\n schedule: {\n installed: false,\n expression: DEFAULT_CRON_SCHEDULE,\n },\n exports: {\n keep: DEFAULT_EXPORT_RETENTION,\n },\n };\n}\n","import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport { createRequire } from 'module';\n\nimport type { BookmarkFile, BookmarkNode } from './bookmark';\nimport { SYNC_STRATEGIES, type CliConfig } from './config';\nimport type { BrowserName, LogLevel } from './constants';\nimport {\n BACKUP_DIR_NAME,\n BROWSERS,\n CHROMIUM_EPOCH_OFFSET_MS,\n CONFIG_FILE_NAME,\n CROSSSYNC_DIR_NAME,\n EXPORT_DIR_NAME,\n LOG_DIR_NAME,\n LOG_FILE_NAME,\n LOG_LEVELS,\n PROFILE_NAME_PATTERN,\n} from './constants';\nimport type { HistoryEntry } from './history';\n\n/* -------------------------------------------------------------------------- */\n/* JSON helpers */\n/* -------------------------------------------------------------------------- */\n\nexport function safeJsonParse<T>(input: string): T | null {\n try {\n return JSON.parse(input) as T;\n } catch {\n return null;\n }\n}\n\nexport function readJsonFile<T>(filePath: string): T | null {\n try {\n return safeJsonParse<T>(fs.readFileSync(filePath, 'utf8'));\n } catch {\n return null;\n }\n}\n\n/**\n * Writes JSON via a temporary file in the same directory followed by a rename,\n * so a partial write can never corrupt an existing file.\n */\nexport function writeJsonFileSafe(filePath: string, data: unknown): void {\n const dir = path.dirname(filePath);\n ensureDir(dir);\n const tempFile = path.join(dir, `${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`);\n try {\n fs.writeFileSync(tempFile, `${JSON.stringify(data, null, 2)}\\n`, 'utf8');\n fs.renameSync(tempFile, filePath);\n } catch (error) {\n safeUnlink(tempFile);\n throw error;\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Filesystem helpers */\n/* -------------------------------------------------------------------------- */\n\nexport function pathExists(target: string): boolean {\n try {\n fs.accessSync(target);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function ensureDir(dir: string): string {\n fs.mkdirSync(dir, { recursive: true });\n return dir;\n}\n\nexport function safeUnlink(target: string): void {\n try {\n fs.unlinkSync(target);\n } catch {\n /* ignore: the file may already be gone */\n }\n}\n\nexport function removeDirSafe(dir: string): void {\n try {\n fs.rmSync(dir, { recursive: true, force: true });\n } catch {\n /* ignore: best effort cleanup */\n }\n}\n\n/** Copies a (possibly locked) file to a new location, then renames it into place. */\nexport function copyFileSafe(source: string, destination: string): void {\n ensureDir(path.dirname(destination));\n const tempFile = `${destination}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.copyFileSync(source, tempFile);\n fs.renameSync(tempFile, destination);\n } catch (error) {\n safeUnlink(tempFile);\n throw error;\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Chromium time conversion */\n/* -------------------------------------------------------------------------- */\n\n/** Converts a Chromium microsecond timestamp into Unix epoch milliseconds. */\nexport function parseChromiumTime(value: string | number | null | undefined): number {\n if (value === null || value === undefined || value === '') {\n return 0;\n }\n const micros = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(micros)) {\n return 0;\n }\n return Math.round(micros / 1000) - CHROMIUM_EPOCH_OFFSET_MS;\n}\n\n/** Converts Unix epoch milliseconds into a Chromium microsecond timestamp string. */\nexport function toChromiumTime(unixMs: number): string {\n return String((unixMs + CHROMIUM_EPOCH_OFFSET_MS) * 1000);\n}\n\n/* -------------------------------------------------------------------------- */\n/* Cross-platform path resolution */\n/* -------------------------------------------------------------------------- */\n\nexport function resolveHomeDir(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n): string {\n if (platform === 'win32' && env.USERPROFILE) {\n return env.USERPROFILE;\n }\n if (env.HOME) {\n return env.HOME;\n }\n try {\n return os.homedir();\n } catch {\n return process.cwd();\n }\n}\n\ntype BrowserPathSegments = Record<'win32' | 'darwin' | 'linux', string[]>;\n\nconst BROWSER_PATH_SEGMENTS: Record<BrowserName, BrowserPathSegments> = {\n chrome: {\n win32: ['Google', 'Chrome', 'User Data'],\n darwin: ['Library', 'Application Support', 'Google', 'Chrome'],\n linux: ['.config', 'google-chrome'],\n },\n edge: {\n win32: ['Microsoft', 'Edge', 'User Data'],\n darwin: ['Library', 'Application Support', 'Microsoft Edge'],\n linux: ['.config', 'microsoft-edge'],\n },\n};\n\nexport interface ResolveBrowserDataDirOptions {\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n homeDir?: string;\n}\n\n/** Resolves the \"User Data\" directory of a Chromium browser for the current OS. */\nexport function resolveBrowserDataDir(\n browser: BrowserName,\n options: ResolveBrowserDataDirOptions = {},\n): string {\n const platform = options.platform ?? process.platform;\n const env = options.env ?? process.env;\n const home = options.homeDir ?? resolveHomeDir(env, platform);\n const segments = BROWSER_PATH_SEGMENTS[browser];\n\n if (platform === 'win32') {\n const localAppData = env.LOCALAPPDATA ?? path.join(home, 'AppData', 'Local');\n return path.join(localAppData, ...segments.win32);\n }\n const key = platform === 'darwin' ? 'darwin' : 'linux';\n return path.join(home, ...segments[key]);\n}\n\n/** Lists the Chromium profile directory names found inside a \"User Data\" directory. */\nexport function listProfiles(dataDir: string): string[] {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dataDir, { withFileTypes: true });\n } catch {\n return [];\n }\n return entries\n .filter((entry) => entry.isDirectory() && PROFILE_NAME_PATTERN.test(entry.name))\n .map((entry) => entry.name)\n .sort((a, b) => a.localeCompare(b));\n}\n\nexport function resolveProfileDir(dataDir: string, profile: string): string {\n return path.join(dataDir, profile);\n}\n\nexport interface CrossSyncDirs {\n root: string;\n backups: string;\n exports: string;\n logs: string;\n configFile: string;\n logFile: string;\n}\n\n/** Resolves every CrossSync runtime path (all under `~/.crosssync`). */\nexport function resolveCrossSyncDirs(homeDir?: string): CrossSyncDirs {\n const root = path.join(homeDir ?? resolveHomeDir(), CROSSSYNC_DIR_NAME);\n return {\n root,\n backups: path.join(root, BACKUP_DIR_NAME),\n exports: path.join(root, EXPORT_DIR_NAME),\n logs: path.join(root, LOG_DIR_NAME),\n configFile: path.join(root, CONFIG_FILE_NAME),\n logFile: path.join(root, LOG_DIR_NAME, LOG_FILE_NAME),\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* SQLite \"copy then read\" */\n/* -------------------------------------------------------------------------- */\n\nexport interface SqliteStatement {\n all(...params: unknown[]): unknown[];\n run(...params: unknown[]): unknown;\n}\n\nexport interface SqliteDatabase {\n prepare(sql: string): SqliteStatement;\n exec(sql: string): void;\n close(): void;\n}\n\nexport interface SqliteDriver {\n new (\n filename: string,\n options?: { readonly?: boolean; fileMustExist?: boolean; timeout?: number },\n ): SqliteDatabase;\n}\n\nexport interface ReadSqliteCopyOptions {\n sql: string;\n params?: unknown[];\n /** Prefix used for the temporary directory holding the copy. */\n tempPrefix?: string;\n}\n\nconst requireFromHere = createRequire(__filename);\n\nlet sqliteDriver: SqliteDriver | null = null;\n\n/**\n * Lazily resolves the optional `better-sqlite3` native driver so that the many\n * code paths that never touch browser history keep working without it installed.\n */\nexport function loadSqliteDriver(): SqliteDriver {\n if (sqliteDriver) {\n return sqliteDriver;\n }\n try {\n const loaded = requireFromHere('better-sqlite3') as SqliteDriver | { default: SqliteDriver };\n sqliteDriver = typeof loaded === 'function' ? loaded : loaded.default;\n return sqliteDriver;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Unable to load the \"better-sqlite3\" driver (${reason}). ` +\n 'Run `pnpm install` to build/download the native SQLite driver, then retry.',\n );\n }\n}\n\n/** Injects a driver implementation (used by tests) or resets the cache. */\nexport function setSqliteDriver(driver: SqliteDriver | null): void {\n sqliteDriver = driver;\n}\n\n/**\n * Chromium keeps an exclusive lock on `History` while the browser runs, so we\n * copy it to a temp directory first and read the copy.\n */\nexport function copyDatabaseToTemp(dbPath: string, tempPrefix = 'crosssync-sqlite'): string {\n const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${tempPrefix}-`));\n const target = path.join(tempDir, path.basename(dbPath));\n fs.copyFileSync(dbPath, target);\n return target;\n}\n\n/** Runs a query against a temporary copy of a SQLite database. */\nexport function readSqliteCopy<T = Record<string, unknown>>(\n dbPath: string,\n options: ReadSqliteCopyOptions,\n): T[] {\n if (!pathExists(dbPath)) {\n throw new Error(`SQLite database not found: ${dbPath}`);\n }\n const tempCopy = copyDatabaseToTemp(dbPath, options.tempPrefix);\n const Database = loadSqliteDriver();\n let db: SqliteDatabase | null = null;\n try {\n db = new Database(tempCopy, { readonly: true, fileMustExist: true });\n const statement = db.prepare(options.sql);\n return statement.all(...(options.params ?? [])) as T[];\n } finally {\n try {\n db?.close();\n } catch {\n /* ignore */\n }\n removeDirSafe(path.dirname(tempCopy));\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Type guards */\n/* -------------------------------------------------------------------------- */\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function isBookmarkNode(value: unknown): value is BookmarkNode {\n if (!isPlainObject(value)) {\n return false;\n }\n if (typeof value.id !== 'string' || typeof value.name !== 'string') {\n return false;\n }\n if (value.type !== 'folder' && value.type !== 'url') {\n return false;\n }\n if (value.url !== undefined && typeof value.url !== 'string') {\n return false;\n }\n if (value.children !== undefined) {\n if (!Array.isArray(value.children) || !value.children.every(isBookmarkNode)) {\n return false;\n }\n }\n return true;\n}\n\nexport function isBookmarkFile(value: unknown): value is BookmarkFile {\n if (!isPlainObject(value) || !isPlainObject(value.roots)) {\n return false;\n }\n const roots = value.roots;\n return isBookmarkNode(roots.bookmark_bar) && isBookmarkNode(roots.other);\n}\n\nexport function isHistoryEntry(value: unknown): value is HistoryEntry {\n if (!isPlainObject(value)) {\n return false;\n }\n return (\n typeof value.url === 'string' &&\n typeof value.title === 'string' &&\n typeof value.visitCount === 'number' &&\n typeof value.typedCount === 'number' &&\n typeof value.lastVisitTime === 'number'\n );\n}\n\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === 'string' && (LOG_LEVELS as readonly string[]).includes(value);\n}\n\nexport function isBrowserName(value: unknown): value is BrowserName {\n return typeof value === 'string' && (BROWSERS as readonly string[]).includes(value);\n}\n\nexport function isCliConfig(value: unknown): value is CliConfig {\n if (!isPlainObject(value)) {\n return false;\n }\n const stringKeys = ['dataDir', 'backupDir', 'exportDir', 'logDir', 'profile'];\n if (typeof value.version !== 'number') {\n return false;\n }\n if (!stringKeys.every((key) => typeof value[key] === 'string')) {\n return false;\n }\n if (!isLogLevel(value.logLevel)) {\n return false;\n }\n\n if (!isPlainObject(value.browsers)) {\n return false;\n }\n for (const browser of BROWSERS) {\n const entry = (value.browsers as Record<string, unknown>)[browser];\n if (!isPlainObject(entry) || typeof entry.enabled !== 'boolean') {\n return false;\n }\n }\n\n if (!isPlainObject(value.sync)) {\n return false;\n }\n const sync = value.sync;\n if (typeof sync.bookmarks !== 'boolean' || typeof sync.history !== 'boolean') {\n return false;\n }\n if (!(SYNC_STRATEGIES as readonly string[]).includes(sync.strategy as string)) {\n return false;\n }\n\n if (!isPlainObject(value.schedule)) {\n return false;\n }\n if (\n typeof value.schedule.installed !== 'boolean' ||\n typeof value.schedule.expression !== 'string'\n ) {\n return false;\n }\n\n // `exports` was added after the first config version; missing is valid.\n const exportsValue = value.exports;\n if (exportsValue !== undefined) {\n if (!isPlainObject(exportsValue)) {\n return false;\n }\n const keep = exportsValue.keep;\n if (typeof keep !== 'number' || !Number.isInteger(keep) || keep < 0) {\n return false;\n }\n }\n return true;\n}\n","export * from './constants';\nexport * from './bookmark';\nexport * from './history';\nexport * from './config';\nexport * from './utils';\n\nexport const PACKAGE = '@crosssync/shared';\nexport const VERSION = '0.1.0';\n","import type { BrowserName } from '@crosssync/shared';\n\nexport const CORE_PACKAGE = '@crosssync/core';\nexport const CORE_VERSION = '0.1.0';\n\n/** How many of the most recent backups `pruneBackups` keeps by default. */\nexport const DEFAULT_BACKUP_RETENTION = 10;\n\n/** Maximum number of log entries kept in memory by `Logger`. */\nexport const MAX_BUFFERED_LOG_ENTRIES = 500;\n\n/** Default number of entries returned by `readLogEntries`. */\nexport const DEFAULT_LOG_LIMIT = 100;\n\nexport interface BrowserProcessNames {\n win32: string;\n darwin: string;\n linux: string;\n}\n\n/** Executable / application names used to detect a running browser. */\nexport const BROWSER_PROCESS_NAMES: Record<BrowserName, BrowserProcessNames> = {\n chrome: {\n win32: 'chrome.exe',\n darwin: 'Google Chrome',\n linux: 'chrome',\n },\n edge: {\n win32: 'msedge.exe',\n darwin: 'Microsoft Edge',\n linux: 'msedge',\n },\n};\n","import fs from 'fs';\nimport path from 'path';\n\nimport type { LogLevel } from '@crosssync/shared';\nimport { ensureDir, LOG_LEVELS } from '@crosssync/shared';\n\nimport { DEFAULT_LOG_LIMIT, MAX_BUFFERED_LOG_ENTRIES } from './constants';\n\nexport type { LogLevel };\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: number;\n meta?: Record<string, unknown>;\n}\n\nconst LEVEL_ORDER: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\nexport interface LoggerOptions {\n /** Append JSON-lines entries to this file, consumed by `crosssync logs`. */\n filePath?: string;\n /** Mirror entries to the console. Defaults to true. */\n console?: boolean;\n}\n\n/**\n * Console + JSON-lines file logger.\n *\n * Logging must never break a sync run, so file write failures are swallowed.\n */\nexport class Logger {\n private minLevel: LogLevel;\n private readonly options: Required<LoggerOptions>;\n private readonly buffer: LogEntry[] = [];\n\n constructor(minLevel: LogLevel = 'info', options: LoggerOptions = {}) {\n this.minLevel = LOG_LEVELS.includes(minLevel) ? minLevel : 'info';\n this.options = {\n filePath: options.filePath ?? '',\n console: options.console ?? true,\n };\n }\n\n setLevel(level: LogLevel): void {\n this.minLevel = level;\n }\n\n getLevel(): LogLevel {\n return this.minLevel;\n }\n\n setFile(filePath: string): void {\n this.options.filePath = filePath;\n }\n\n getFile(): string {\n return this.options.filePath;\n }\n\n isEnabled(level: LogLevel): boolean {\n return LEVEL_ORDER[level] >= LEVEL_ORDER[this.minLevel];\n }\n\n debug(message: string, meta?: Record<string, unknown>): void {\n this.log('debug', message, meta);\n }\n\n info(message: string, meta?: Record<string, unknown>): void {\n this.log('info', message, meta);\n }\n\n warn(message: string, meta?: Record<string, unknown>): void {\n this.log('warn', message, meta);\n }\n\n error(message: string, meta?: Record<string, unknown>): void {\n this.log('error', message, meta);\n }\n\n /** Snapshot of the in-memory ring buffer. */\n getEntries(): LogEntry[] {\n return [...this.buffer];\n }\n\n clearBuffer(): void {\n this.buffer.length = 0;\n }\n\n private log(level: LogLevel, message: string, meta?: Record<string, unknown>): void {\n if (!this.isEnabled(level)) {\n return;\n }\n const entry: LogEntry = { level, message, timestamp: Date.now(), meta };\n this.buffer.push(entry);\n if (this.buffer.length > MAX_BUFFERED_LOG_ENTRIES) {\n this.buffer.shift();\n }\n if (this.options.console) {\n writeConsole(entry);\n }\n this.appendToFile(entry);\n }\n\n private appendToFile(entry: LogEntry): void {\n if (!this.options.filePath) {\n return;\n }\n try {\n ensureDir(path.dirname(this.options.filePath));\n fs.appendFileSync(this.options.filePath, `${JSON.stringify(entry)}\\n`, 'utf8');\n } catch {\n /* logging must never break a run */\n }\n }\n}\n\nfunction writeConsole(entry: LogEntry): void {\n const prefix = `[${new Date(entry.timestamp).toISOString()}] [${entry.level.toUpperCase()}]`;\n if (entry.level === 'error') {\n console.error(prefix, entry.message, entry.meta ?? '');\n } else if (entry.level === 'warn') {\n console.warn(prefix, entry.message, entry.meta ?? '');\n } else {\n console.log(prefix, entry.message, entry.meta ?? '');\n }\n}\n\nexport interface ReadLogEntriesOptions {\n limit?: number;\n level?: LogLevel;\n}\n\n/** Reads the most recent JSON-lines entries from a log file. */\nexport function readLogEntries(filePath: string, options: ReadLogEntriesOptions = {}): LogEntry[] {\n let raw: string;\n try {\n raw = fs.readFileSync(filePath, 'utf8');\n } catch {\n return [];\n }\n\n const limit = options.limit ?? DEFAULT_LOG_LIMIT;\n const entries: LogEntry[] = [];\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n const parsed = parseLogEntry(trimmed);\n if (!parsed) {\n continue;\n }\n if (options.level && LEVEL_ORDER[parsed.level] < LEVEL_ORDER[options.level]) {\n continue;\n }\n entries.push(parsed);\n }\n\n return limit > 0 ? entries.slice(-limit) : entries;\n}\n\n/** Removes the log file; used by `crosssync logs --clear`. */\nexport function clearLogFile(filePath: string): void {\n try {\n fs.rmSync(filePath, { force: true });\n } catch {\n /* ignore */\n }\n}\n\nfunction parseLogEntry(line: string): LogEntry | null {\n let value: unknown;\n try {\n value = JSON.parse(line);\n } catch {\n return null;\n }\n if (typeof value !== 'object' || value === null) {\n return null;\n }\n const record = value as Record<string, unknown>;\n if (\n typeof record.level !== 'string' ||\n !LOG_LEVELS.includes(record.level as LogLevel) ||\n typeof record.message !== 'string' ||\n typeof record.timestamp !== 'number'\n ) {\n return null;\n }\n const meta =\n typeof record.meta === 'object' && record.meta !== null\n ? (record.meta as Record<string, unknown>)\n : undefined;\n return {\n level: record.level as LogLevel,\n message: record.message,\n timestamp: record.timestamp,\n meta,\n };\n}\n","import { execFileSync } from 'child_process';\n\nimport type { BrowserName } from '@crosssync/shared';\nimport { BROWSERS } from '@crosssync/shared';\n\nimport { BROWSER_PROCESS_NAMES } from './constants';\n\nexport interface BrowserStatus {\n browser: BrowserName;\n running: boolean;\n processName: string;\n}\n\nexport interface ProcessResult {\n status: number;\n stdout: string;\n}\n\n/** Injectable process runner, so detection is unit-testable. */\nexport type ProcessRunner = (command: string, args: string[]) => ProcessResult;\n\nexport interface BrowserStatusOptions {\n platform?: NodeJS.Platform;\n runner?: ProcessRunner;\n}\n\n/** Executable / application name used to detect the given browser. */\nexport function getProcessName(\n browser: BrowserName,\n platform: NodeJS.Platform = process.platform,\n): string {\n const names = BROWSER_PROCESS_NAMES[browser];\n if (platform === 'win32') {\n return names.win32;\n }\n return platform === 'darwin' ? names.darwin : names.linux;\n}\n\n/** Builds the OS command that lists processes for the given browser. */\nexport function buildProcessQuery(\n browser: BrowserName,\n platform: NodeJS.Platform = process.platform,\n): { command: string; args: string[] } {\n const processName = getProcessName(browser, platform);\n if (platform === 'win32') {\n return {\n command: 'tasklist',\n args: ['/FI', `IMAGENAME eq ${processName}`, '/NH', '/FO', 'CSV'],\n };\n }\n return { command: 'pgrep', args: ['-ix', processName] };\n}\n\n/** Interprets the output of `tasklist` / `pgrep`. */\nexport function parseProcessOutput(\n browser: BrowserName,\n platform: NodeJS.Platform,\n result: ProcessResult,\n): boolean {\n const output = result.stdout ?? '';\n if (platform === 'win32') {\n if (/no tasks are running/i.test(output)) {\n return false;\n }\n return output.toLowerCase().includes(getProcessName(browser, platform).toLowerCase());\n }\n if (result.status !== 0) {\n return false;\n }\n return output.trim().length > 0 && output.split(/\\r?\\n/).some((line) => line.trim().length > 0);\n}\n\nexport function isBrowserRunning(\n browser: BrowserName,\n options: BrowserStatusOptions = {},\n): boolean {\n const platform = options.platform ?? process.platform;\n return parseProcessOutput(browser, platform, runQuery(browser, platform, options.runner));\n}\n\n/** Reports the running state of every supported browser. */\nexport function getRunningBrowsers(options: BrowserStatusOptions = {}): BrowserStatus[] {\n const platform = options.platform ?? process.platform;\n return BROWSERS.map((browser) => ({\n browser,\n running: parseProcessOutput(browser, platform, runQuery(browser, platform, options.runner)),\n processName: getProcessName(browser, platform),\n }));\n}\n\n/** Lists the browsers currently running. */\nexport function getRunningBrowserNames(options: BrowserStatusOptions = {}): BrowserName[] {\n return getRunningBrowsers(options)\n .filter((status) => status.running)\n .map((status) => status.browser);\n}\n\nfunction runQuery(\n browser: BrowserName,\n platform: NodeJS.Platform,\n runner?: ProcessRunner,\n): ProcessResult {\n const { command, args } = buildProcessQuery(browser, platform);\n const execute = runner ?? defaultProcessRunner;\n try {\n return execute(command, args);\n } catch {\n return { status: 1, stdout: '' };\n }\n}\n\nconst defaultProcessRunner: ProcessRunner = (command, args) => {\n try {\n const stdout = execFileSync(command, args, {\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n return { status: 0, stdout: typeof stdout === 'string' ? stdout : String(stdout ?? '') };\n } catch (error) {\n const failure = error as { status?: number | null; stdout?: unknown };\n const stdout = Buffer.isBuffer(failure.stdout)\n ? failure.stdout.toString('utf8')\n : typeof failure.stdout === 'string'\n ? failure.stdout\n : '';\n return { status: typeof failure.status === 'number' ? failure.status : 1, stdout };\n }\n};\n","import path from 'path';\n\nimport type { BookmarkFile, BrowserName, HistoryEntry } from '@crosssync/shared';\nimport {\n BOOKMARKS_FILE_NAME,\n BOOKMARK_ROOT_KEYS,\n countBookmarks,\n HISTORY_FILE_NAME,\n HISTORY_QUERY,\n isBookmarkFile,\n listProfiles,\n parseChromiumTime,\n readJsonFile,\n readSqliteCopy,\n resolveBrowserDataDir,\n resolveProfileDir,\n} from '@crosssync/shared';\n\n/** Raw `urls` row as returned by SQLite (types vary by driver settings). */\nexport interface ChromiumHistoryRow {\n id?: number;\n url: string;\n title?: string | null;\n visit_count?: number;\n typed_count?: number;\n last_visit_time?: number | string | bigint | null;\n}\n\nexport interface BrowserReaderOptions {\n /** Override for the auto-detected \"User Data\" directory. */\n dataDir?: string;\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface BookmarkSource {\n browser: BrowserName;\n profile: string;\n filePath: string;\n file: BookmarkFile;\n}\n\nexport interface HistorySource {\n browser: BrowserName;\n profile: string;\n filePath: string;\n entries: HistoryEntry[];\n}\n\nexport interface BrowserReader {\n browser: BrowserName;\n /** The \"User Data\" directory this reader reads from. */\n dataDir: string;\n /** All Chromium profile directories that exist on disk. */\n profiles(): string[];\n /** Profiles selected by `profile`, which may be `all`. */\n resolveProfiles(profile: string): string[];\n bookmarksPath(profile: string): string;\n historyPath(profile: string): string;\n readBookmarks(profile: string): BookmarkSource;\n readHistory(profile: string): HistorySource;\n}\n\n/** Maps a raw SQLite row into a normalised `HistoryEntry`. */\nexport function toHistoryEntry(row: ChromiumHistoryRow): HistoryEntry {\n return {\n id: typeof row.id === 'number' ? row.id : undefined,\n url: row.url,\n title: row.title ?? '',\n visitCount: toCount(row.visit_count),\n typedCount: toCount(row.typed_count),\n lastVisitTime: toUnixMs(row.last_visit_time),\n };\n}\n\n/** Total node count of a Chromium bookmark file, including root folders. */\nexport function countBookmarkFileNodes(file: BookmarkFile): number {\n let total = 0;\n for (const key of BOOKMARK_ROOT_KEYS) {\n const root = file.roots[key];\n if (root) {\n total += countBookmarks(root);\n }\n }\n return total;\n}\n\n/**\n * Reads bookmarks and history from a Chromium-based browser (Chrome or Edge).\n *\n * The reader only ever reads: history is queried through a temporary copy and\n * bookmark files are parsed from disk. Write-back is handled by `sync`.\n */\nexport function createBrowserReader(\n browser: BrowserName,\n options: BrowserReaderOptions = {},\n): BrowserReader {\n const dataDir =\n options.dataDir ??\n resolveBrowserDataDir(browser, { platform: options.platform, env: options.env });\n\n const bookmarksPath = (profile: string): string =>\n path.join(resolveProfileDir(dataDir, profile), BOOKMARKS_FILE_NAME);\n\n const historyPath = (profile: string): string =>\n path.join(resolveProfileDir(dataDir, profile), HISTORY_FILE_NAME);\n\n const profiles = (): string[] => listProfiles(dataDir);\n\n const resolveSelectedProfiles = (profile: string): string[] => {\n const found = profiles();\n if (profile === 'all') {\n return found;\n }\n return found.includes(profile) ? [profile] : [];\n };\n\n const readBookmarks = (profile: string): BookmarkSource => {\n const filePath = bookmarksPath(profile);\n const file = readJsonFile<BookmarkFile>(filePath);\n if (!isBookmarkFile(file)) {\n throw new Error(`Not a valid Chromium bookmark file: ${filePath}`);\n }\n return { browser, profile, filePath, file };\n };\n\n const readHistory = (profile: string): HistorySource => {\n const filePath = historyPath(profile);\n const rows = readSqliteCopy<ChromiumHistoryRow>(filePath, {\n sql: HISTORY_QUERY,\n tempPrefix: `crosssync-history-${browser}`,\n });\n const entries = rows\n .filter((row) => typeof row.url === 'string' && row.url.length > 0)\n .map(toHistoryEntry);\n return { browser, profile, filePath, entries };\n };\n\n return {\n browser,\n dataDir,\n profiles,\n resolveProfiles: resolveSelectedProfiles,\n bookmarksPath,\n historyPath,\n readBookmarks,\n readHistory,\n };\n}\n\nfunction toCount(value: number | undefined | null): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction toUnixMs(value: number | string | bigint | null | undefined): number {\n if (value === null || value === undefined) {\n return 0;\n }\n if (typeof value === 'bigint') {\n return parseChromiumTime(value.toString());\n }\n return parseChromiumTime(value);\n}\n","import type { BrowserName, CliConfig } from '@crosssync/shared';\nimport { BROWSERS } from '@crosssync/shared';\n\nimport { createBrowserReader, type BrowserReader, type BrowserReaderOptions } from './chromium';\n\nexport * from './chromium';\n\n/** Builds a reader for every browser enabled in the CLI config. */\nexport function createConfiguredBrowserReaders(\n config: CliConfig,\n options: BrowserReaderOptions = {},\n): BrowserReader[] {\n const readers: BrowserReader[] = [];\n for (const browser of BROWSERS) {\n const browserConfig = config.browsers[browser];\n if (!browserConfig.enabled) {\n continue;\n }\n readers.push(\n createBrowserReader(browser, {\n ...options,\n dataDir: browserConfig.dataDir ?? options.dataDir,\n }),\n );\n }\n return readers;\n}\n\n/** Every supported browser, useful for reporting. */\nexport function supportedBrowsers(): readonly BrowserName[] {\n return BROWSERS;\n}\n","import type {\n BookmarkFile,\n BookmarkNode,\n BookmarkRootKey,\n BookmarkRoots,\n BrowserName,\n HistoryEntry,\n} from '@crosssync/shared';\nimport { BOOKMARK_ROOT_KEYS, countBookmarks, parseChromiumTime } from '@crosssync/shared';\n\nexport interface BookmarkMergeInput {\n browser: BrowserName;\n file: BookmarkFile;\n}\n\nexport interface BookmarkMergeStats {\n /** Total nodes in the merged tree, including root folders. */\n total: number;\n /** Nodes taken from a later browser because the accumulated tree lacked the id. */\n added: number;\n /** Nodes replaced by a later browser whose `date_added` was newer. */\n updated: number;\n /** Nodes seen in several browsers with an identical `date_added`. */\n identical: number;\n}\n\nexport interface BookmarkMergeConflict {\n id: string;\n name: string;\n type: BookmarkNode['type'];\n winnerOrigin: BrowserName;\n loserOrigin: BrowserName;\n winnerDateAdded: number;\n loserDateAdded: number;\n}\n\nexport interface BookmarkMergeResult {\n roots: BookmarkRoots;\n stats: BookmarkMergeStats;\n conflicts: BookmarkMergeConflict[];\n}\n\nexport interface HistoryMergeInput {\n browser: BrowserName;\n entries: HistoryEntry[];\n}\n\nexport interface HistoryMergeStats {\n total: number;\n /** Entries seen in more than one browser and collapsed into one. */\n duplicates: number;\n}\n\nexport interface HistoryMergeResult {\n entries: HistoryEntry[];\n stats: HistoryMergeStats;\n}\n\n/** Node wrapped with the browser it came from and an id-indexed child map. */\ninterface TrackedNode {\n node: BookmarkNode;\n origin: BrowserName;\n children: Map<string, TrackedNode>;\n}\n\n/**\n * Merges bookmark files coming from several Chromium browsers.\n *\n * Nodes are matched by `id`; when both browsers know the same id, the node with\n * the newer `date_added` wins (ties keep the earlier input's node).\n */\nexport function mergeBookmarkFiles(inputs: BookmarkMergeInput[]): BookmarkMergeResult {\n if (inputs.length === 0) {\n throw new Error('mergeBookmarkFiles requires at least one input');\n }\n\n const stats: BookmarkMergeStats = { total: 0, added: 0, updated: 0, identical: 0 };\n const conflicts: BookmarkMergeConflict[] = [];\n\n const [first, ...rest] = inputs;\n const roots: Partial<Record<BookmarkRootKey, TrackedNode>> = {};\n for (const key of BOOKMARK_ROOT_KEYS) {\n const root = first.file.roots[key];\n if (root) {\n roots[key] = toTrackedNode(root, first.browser);\n }\n }\n\n for (const input of rest) {\n for (const key of BOOKMARK_ROOT_KEYS) {\n const incoming = input.file.roots[key];\n if (!incoming) {\n continue;\n }\n const existing = roots[key];\n roots[key] = existing\n ? mergeTrackedNode(existing, toTrackedNode(incoming, input.browser), stats, conflicts)\n : toTrackedNode(incoming, input.browser);\n }\n }\n\n const mergedRoots: BookmarkRoots = {\n bookmark_bar: toBookmarkNode(roots.bookmark_bar as TrackedNode),\n other: toBookmarkNode(roots.other as TrackedNode),\n };\n if (roots.synced) {\n mergedRoots.synced = toBookmarkNode(roots.synced);\n }\n\n stats.total =\n countBookmarks(mergedRoots.bookmark_bar) +\n countBookmarks(mergedRoots.other) +\n (mergedRoots.synced ? countBookmarks(mergedRoots.synced) : 0);\n\n return { roots: mergedRoots, stats, conflicts };\n}\n\n/**\n * Merges history entries from several browsers, de-duplicating by URL.\n *\n * `visitCount` / `typedCount` take the maximum seen, the title comes from the\n * most recent visit, and `lastVisitTime` keeps the newest timestamp.\n */\nexport function mergeHistory(inputs: HistoryMergeInput[]): HistoryMergeResult {\n const byUrl = new Map<string, HistoryEntry>();\n let duplicates = 0;\n\n for (const input of inputs) {\n for (const entry of input.entries) {\n const existing = byUrl.get(entry.url);\n if (!existing) {\n byUrl.set(entry.url, { ...entry });\n continue;\n }\n duplicates += 1;\n const newest = entry.lastVisitTime > existing.lastVisitTime ? entry : existing;\n byUrl.set(entry.url, {\n ...existing,\n title: newest.title || existing.title,\n lastVisitTime: Math.max(existing.lastVisitTime, entry.lastVisitTime),\n visitCount: Math.max(existing.visitCount, entry.visitCount),\n typedCount: Math.max(existing.typedCount, entry.typedCount),\n });\n }\n }\n\n const entries = [...byUrl.values()].sort((a, b) => b.lastVisitTime - a.lastVisitTime);\n return { entries, stats: { total: entries.length, duplicates } };\n}\n\nfunction toTrackedNode(node: BookmarkNode, origin: BrowserName): TrackedNode {\n const children = new Map<string, TrackedNode>();\n for (const child of node.children ?? []) {\n children.set(child.id, toTrackedNode(child, origin));\n }\n return { node, origin, children };\n}\n\nfunction toBookmarkNode(tracked: TrackedNode): BookmarkNode {\n const node: BookmarkNode = { ...tracked.node };\n if (node.type === 'folder') {\n node.children = [...tracked.children.values()].map(toBookmarkNode);\n }\n return node;\n}\n\nfunction mergeTrackedNode(\n base: TrackedNode,\n incoming: TrackedNode,\n stats: BookmarkMergeStats,\n conflicts: BookmarkMergeConflict[],\n): TrackedNode {\n const baseDateAdded = parseChromiumTime(base.node.date_added);\n const incomingDateAdded = parseChromiumTime(incoming.node.date_added);\n const winner = incomingDateAdded > baseDateAdded ? incoming : base;\n\n if (base.node.type === 'folder' && incoming.node.type === 'folder') {\n if (incomingDateAdded === baseDateAdded) {\n stats.identical += 1;\n }\n const children = new Map(winner.children);\n for (const [id, incomingChild] of incoming.children) {\n const existing = children.get(id);\n if (existing) {\n children.set(id, mergeTrackedNode(existing, incomingChild, stats, conflicts));\n } else {\n children.set(id, incomingChild);\n stats.added += 1;\n }\n }\n return { node: winner.node, origin: winner.origin, children };\n }\n\n if (incomingDateAdded === baseDateAdded) {\n stats.identical += 1;\n return base;\n }\n\n const loser = winner === incoming ? base : incoming;\n conflicts.push({\n id: base.node.id,\n name: winner.node.name,\n type: winner.node.type,\n winnerOrigin: winner.origin,\n loserOrigin: loser.origin,\n winnerDateAdded: winner === incoming ? incomingDateAdded : baseDateAdded,\n loserDateAdded: winner === incoming ? baseDateAdded : incomingDateAdded,\n });\n\n if (winner === incoming) {\n stats.updated += 1;\n return incoming;\n }\n return base;\n}\n","import fs from 'fs';\nimport path from 'path';\n\nimport type { BrowserName } from '@crosssync/shared';\nimport {\n copyFileSafe,\n ensureDir,\n pathExists,\n readJsonFile,\n writeJsonFileSafe,\n} from '@crosssync/shared';\n\nexport type BackupKind = 'bookmarks' | 'history';\n\nexport interface BackupSource {\n kind: BackupKind;\n browser: BrowserName;\n profile: string;\n /** Absolute path of the file to copy. */\n filePath: string;\n}\n\nexport interface BackupItem {\n kind: BackupKind;\n browser: BrowserName;\n profile: string;\n /** Original location the copy was taken from. */\n source: string;\n /** File name inside the backup directory. */\n file: string;\n bytes: number;\n}\n\nexport interface BackupManifest {\n id: string;\n createdAt: string;\n platform: string;\n items: BackupItem[];\n}\n\nexport interface BackupResult {\n id: string;\n dir: string;\n manifestFile: string;\n manifest: BackupManifest;\n /** False when none of the requested sources existed yet. */\n copied: boolean;\n}\n\nexport interface BackupOptions {\n backupDir: string;\n sources: BackupSource[];\n /** Injectable clock, used by tests. */\n now?: Date;\n platform?: NodeJS.Platform;\n}\n\nexport interface BackupSummary {\n id: string;\n dir: string;\n createdAt: string | null;\n itemCount: number;\n bytes: number;\n}\n\nexport const BACKUP_MANIFEST_FILE = 'manifest.json';\n\n/** `20260116-093000` style id, derived from local time. */\nexport function formatBackupId(date: Date): string {\n return [\n `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}`,\n `${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`,\n ].join('-');\n}\n\n/** File name a source is stored under inside a backup directory. */\nexport function backupFileName(source: BackupSource): string {\n const extension = path.extname(source.filePath);\n return `${source.kind}-${source.browser}-${source.profile}${extension}`;\n}\n\n/**\n * Copies every existing source file into a timestamped backup directory.\n *\n * Throws when a copy fails: `sync` treats a failed backup as a hard stop before\n * anything is written back to a browser.\n */\nexport function createBackup(options: BackupOptions): BackupResult {\n const now = options.now ?? new Date();\n const dir = uniqueDirectory(path.join(options.backupDir, formatBackupId(now)));\n ensureDir(dir);\n\n const items: BackupItem[] = [];\n for (const source of options.sources) {\n if (!pathExists(source.filePath)) {\n continue;\n }\n const fileName = backupFileName(source);\n const target = path.join(dir, fileName);\n copyFileSafe(source.filePath, target);\n items.push({\n kind: source.kind,\n browser: source.browser,\n profile: source.profile,\n source: source.filePath,\n file: fileName,\n bytes: fs.statSync(target).size,\n });\n }\n\n const manifest: BackupManifest = {\n id: path.basename(dir),\n createdAt: now.toISOString(),\n platform: options.platform ?? process.platform,\n items,\n };\n const manifestFile = path.join(dir, BACKUP_MANIFEST_FILE);\n writeJsonFileSafe(manifestFile, manifest);\n\n return { id: manifest.id, dir, manifestFile, manifest, copied: items.length > 0 };\n}\n\n/** Lists backups newest first. */\nexport function listBackups(backupDir: string): BackupSummary[] {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(backupDir, { withFileTypes: true });\n } catch {\n return [];\n }\n\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => summarizeBackup(backupDir, entry.name))\n .sort((a, b) => b.id.localeCompare(a.id));\n}\n\n/** Removes all but the `keep` most recent backups and returns the removed dirs. */\nexport function pruneBackups(backupDir: string, keep: number): string[] {\n if (keep < 0) {\n return [];\n }\n const removals = listBackups(backupDir)\n .slice(keep)\n .map((summary) => summary.dir);\n for (const dir of removals) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n return removals;\n}\n\nfunction summarizeBackup(backupDir: string, id: string): BackupSummary {\n const dir = path.join(backupDir, id);\n const manifest = readJsonFile<BackupManifest>(path.join(dir, BACKUP_MANIFEST_FILE));\n const items = manifest?.items ?? [];\n return {\n id,\n dir,\n createdAt: manifest?.createdAt ?? null,\n itemCount: items.length,\n bytes: items.reduce((total, item) => total + (item.bytes ?? 0), 0),\n };\n}\n\nfunction uniqueDirectory(preferred: string): string {\n if (!pathExists(preferred)) {\n return preferred;\n }\n let suffix = 1;\n let candidate = `${preferred}-${suffix}`;\n while (pathExists(candidate)) {\n suffix += 1;\n candidate = `${preferred}-${suffix}`;\n }\n return candidate;\n}\n\nfunction pad(value: number): string {\n return String(value).padStart(2, '0');\n}\n","import path from 'path';\n\nimport type { BookmarkFile, BrowserName, CliConfig, SyncStrategy } from '@crosssync/shared';\nimport { BROWSERS, ensureDir, pathExists, writeJsonFileSafe } from '@crosssync/shared';\n\nimport { createBackup, formatBackupId, type BackupResult, type BackupSource } from './backup';\nimport { getRunningBrowserNames } from './browser-status';\nimport { Logger } from './logger';\nimport {\n mergeBookmarkFiles,\n mergeHistory,\n type BookmarkMergeResult,\n type HistoryMergeResult,\n} from './merger';\nimport {\n countBookmarkFileNodes,\n createConfiguredBrowserReaders,\n type BookmarkSource,\n type HistorySource,\n} from './readers';\n\nexport interface SyncTargets {\n bookmarks: boolean;\n history: boolean;\n}\n\nexport interface SyncRunOptions {\n config: CliConfig;\n targets: SyncTargets;\n dryRun?: boolean;\n /** Write bookmarks back even when the browser is running. */\n force?: boolean;\n /** Overrides `config.sync.strategy`. */\n strategy?: SyncStrategy;\n logger?: Logger;\n /** Injectable clock, used by tests. */\n now?: Date;\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n /** Overrides browser-running detection, used by tests. */\n browserRunning?: (browser: BrowserName) => boolean;\n}\n\nexport interface BrowserSyncOutcome {\n browser: BrowserName;\n profile: string;\n bookmarksRead: number;\n historyRead: number;\n writtenBack: boolean;\n skippedWriteBackReason: string | null;\n}\n\nexport interface SyncReport {\n startedAt: string;\n finishedAt: string;\n dryRun: boolean;\n strategy: SyncStrategy;\n targets: SyncTargets;\n browsers: BrowserSyncOutcome[];\n backup: BackupResult | null;\n bookmarkMerge: BookmarkMergeResult | null;\n historyMerge: HistoryMergeResult | null;\n exportFiles: string[];\n warnings: string[];\n}\n\n/**\n * Writes a merged bookmark tree back to a Chromium `Bookmarks` file.\n *\n * The `checksum` field is intentionally dropped: Chromium recomputes it, and a\n * stale checksum makes the browser discard externally written changes.\n */\nexport function writeBackBookmarks(filePath: string, file: BookmarkFile): void {\n const payload: BookmarkFile = { roots: file.roots };\n if (typeof file.version === 'number') {\n payload.version = file.version;\n }\n writeJsonFileSafe(filePath, payload);\n}\n\n/**\n * Orchestrates a full sync run:\n *\n * 1. read bookmarks/history from every enabled browser profile\n * 2. back everything up first (a failed backup aborts before any write-back)\n * 3. merge by `id` + `date_added` (bookmarks) and by URL (history)\n * 4. write merged bookmarks back, then export the merged data as JSON\n */\nexport function runSync(options: SyncRunOptions): SyncReport {\n const { config, targets } = options;\n const startedAtMs = Date.now();\n const dryRun = options.dryRun ?? false;\n const strategy = options.strategy ?? config.sync.strategy;\n const logger = options.logger ?? new Logger(config.logLevel, { console: false });\n\n const warnings: string[] = [];\n const browsers: BrowserSyncOutcome[] = [];\n const exportFiles: string[] = [];\n const bookmarkSources: BookmarkSource[] = [];\n const historySources: HistorySource[] = [];\n\n const finish = (\n backup: BackupResult | null,\n bookmarkMerge: BookmarkMergeResult | null,\n historyMerge: HistoryMergeResult | null,\n ): SyncReport => ({\n startedAt: new Date(startedAtMs).toISOString(),\n finishedAt: new Date().toISOString(),\n dryRun,\n strategy,\n targets,\n browsers,\n backup,\n bookmarkMerge,\n historyMerge,\n exportFiles,\n warnings,\n });\n\n const readers = createConfiguredBrowserReaders(config, {\n platform: options.platform,\n env: options.env,\n });\n\n for (const reader of readers) {\n const profiles = reader.resolveProfiles(config.profile);\n if (profiles.length === 0) {\n warnings.push(`No ${reader.browser} profile found under ${reader.dataDir}.`);\n continue;\n }\n\n for (const profile of profiles) {\n const outcome: BrowserSyncOutcome = {\n browser: reader.browser,\n profile,\n bookmarksRead: 0,\n historyRead: 0,\n writtenBack: false,\n skippedWriteBackReason: null,\n };\n\n if (targets.bookmarks && pathExists(reader.bookmarksPath(profile))) {\n try {\n const source = reader.readBookmarks(profile);\n bookmarkSources.push(source);\n outcome.bookmarksRead = countBookmarkFileNodes(source.file);\n } catch (error) {\n const reason = describeError(error);\n outcome.skippedWriteBackReason = reason;\n warnings.push(`Could not read ${reader.browser} bookmarks: ${reason}`);\n }\n }\n\n if (targets.history && pathExists(reader.historyPath(profile))) {\n try {\n const source = reader.readHistory(profile);\n historySources.push(source);\n outcome.historyRead = source.entries.length;\n } catch (error) {\n warnings.push(`Could not read ${reader.browser} history: ${describeError(error)}`);\n }\n }\n\n browsers.push(outcome);\n }\n }\n\n if (bookmarkSources.length === 0 && historySources.length === 0) {\n warnings.push('Nothing to sync: no bookmark or history data was found.');\n return finish(null, null, null);\n }\n\n return syncFoundData({\n options,\n config,\n dryRun,\n strategy,\n logger,\n warnings,\n browsers,\n exportFiles,\n bookmarkSources,\n historySources,\n finish,\n });\n}\n\ntype FinishReport = (\n backup: BackupResult | null,\n bookmarkMerge: BookmarkMergeResult | null,\n historyMerge: HistoryMergeResult | null,\n) => SyncReport;\n\ninterface SyncFoundDataContext {\n options: SyncRunOptions;\n config: CliConfig;\n dryRun: boolean;\n strategy: SyncStrategy;\n logger: Logger;\n warnings: string[];\n browsers: BrowserSyncOutcome[];\n exportFiles: string[];\n bookmarkSources: BookmarkSource[];\n historySources: HistorySource[];\n finish: FinishReport;\n}\n\nfunction syncFoundData(context: SyncFoundDataContext): SyncReport {\n const {\n options,\n config,\n dryRun,\n strategy,\n logger,\n warnings,\n exportFiles,\n bookmarkSources,\n historySources,\n finish,\n } = context;\n\n let backup: BackupResult | null = null;\n if (!dryRun) {\n const sources: BackupSource[] = [\n ...bookmarkSources.map((source) => ({\n kind: 'bookmarks' as const,\n browser: source.browser,\n profile: source.profile,\n filePath: source.filePath,\n })),\n ...historySources.map((source) => ({\n kind: 'history' as const,\n browser: source.browser,\n profile: source.profile,\n filePath: source.filePath,\n })),\n ];\n\n try {\n backup = createBackup({\n backupDir: config.backupDir,\n sources,\n now: options.now,\n platform: options.platform,\n });\n logger.info('Backup created', { dir: backup.dir, files: backup.manifest.items.length });\n } catch (error) {\n warnings.push(`Backup failed; aborting before any write-back: ${describeError(error)}`);\n return finish(null, null, null);\n }\n }\n\n const bookmarkMerge =\n bookmarkSources.length > 0\n ? mergeBookmarkFiles(\n bookmarkSources.map((source) => ({ browser: source.browser, file: source.file })),\n )\n : null;\n\n const historyMerge =\n historySources.length > 0\n ? mergeHistory(\n historySources.map((source) => ({ browser: source.browser, entries: source.entries })),\n )\n : null;\n\n if (bookmarkMerge && strategy === 'merge') {\n if (dryRun) {\n warnings.push('Dry run: bookmark write-back skipped.');\n } else {\n writeBackMergedBookmarks(context, bookmarkMerge);\n }\n } else if (bookmarkMerge) {\n warnings.push('Strategy \"export\": browser bookmark files were left untouched.');\n }\n\n if (historyMerge) {\n warnings.push('History is exported only; CrossSync never writes back to History.sqlite.');\n }\n\n if (!dryRun) {\n ensureDir(config.exportDir);\n const stamp = formatBackupId(options.now ?? new Date());\n if (bookmarkMerge) {\n const file = path.join(config.exportDir, `bookmarks-merged-${stamp}.json`);\n writeJsonFileSafe(file, {\n exportedAt: new Date().toISOString(),\n source: 'crosssync',\n version: 1,\n roots: bookmarkMerge.roots,\n });\n exportFiles.push(file);\n }\n if (historyMerge) {\n const file = path.join(config.exportDir, `history-merged-${stamp}.json`);\n writeJsonFileSafe(file, {\n exportedAt: new Date().toISOString(),\n source: 'crosssync',\n entries: historyMerge.entries,\n });\n exportFiles.push(file);\n }\n }\n\n return finish(backup, bookmarkMerge, historyMerge);\n}\n\n/** Writes the merged tree to every browser that contributed bookmarks. */\nfunction writeBackMergedBookmarks(\n context: SyncFoundDataContext,\n bookmarkMerge: BookmarkMergeResult,\n): void {\n const { options, logger, warnings, browsers, bookmarkSources } = context;\n\n const running: BrowserName[] = options.browserRunning\n ? BROWSERS.filter((browser) => options.browserRunning?.(browser) === true)\n : getRunningBrowserNames({ platform: options.platform });\n\n const byBrowser = new Map<BrowserName, BookmarkSource[]>();\n for (const source of bookmarkSources) {\n const list = byBrowser.get(source.browser) ?? [];\n list.push(source);\n byBrowser.set(source.browser, list);\n }\n\n for (const [browser, sources] of byBrowser) {\n if (running.includes(browser) && !options.force) {\n warnings.push(\n `${browser} is running; skipping bookmark write-back (use --force to override).`,\n );\n for (const outcome of browsers) {\n if (outcome.browser === browser) {\n outcome.skippedWriteBackReason = 'browser-running';\n }\n }\n continue;\n }\n\n for (const source of sources) {\n writeBackBookmarks(source.filePath, {\n roots: bookmarkMerge.roots,\n version: source.file.version ?? 1,\n });\n logger.info('Wrote merged bookmarks', {\n browser,\n profile: source.profile,\n file: source.filePath,\n });\n }\n\n for (const outcome of browsers) {\n if (outcome.browser === browser) {\n outcome.writtenBack = true;\n }\n }\n }\n}\n\nfunction describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","export { CORE_PACKAGE as PACKAGE, CORE_VERSION as VERSION } from './constants';\nexport {\n BROWSER_PROCESS_NAMES,\n DEFAULT_BACKUP_RETENTION,\n DEFAULT_LOG_LIMIT,\n MAX_BUFFERED_LOG_ENTRIES,\n} from './constants';\nexport {\n Logger,\n clearLogFile,\n readLogEntries,\n type LogEntry,\n type LogLevel,\n type LoggerOptions,\n type ReadLogEntriesOptions,\n} from './logger';\nexport {\n buildProcessQuery,\n getProcessName,\n getRunningBrowserNames,\n getRunningBrowsers,\n isBrowserRunning,\n parseProcessOutput,\n type BrowserStatus,\n type BrowserStatusOptions,\n type ProcessResult,\n type ProcessRunner,\n} from './browser-status';\nexport {\n countBookmarkFileNodes,\n createBrowserReader,\n createConfiguredBrowserReaders,\n supportedBrowsers,\n toHistoryEntry,\n type BookmarkSource,\n type BrowserReader,\n type BrowserReaderOptions,\n type ChromiumHistoryRow,\n type HistorySource,\n} from './readers';\nexport {\n mergeBookmarkFiles,\n mergeHistory,\n type BookmarkMergeConflict,\n type BookmarkMergeInput,\n type BookmarkMergeResult,\n type BookmarkMergeStats,\n type HistoryMergeInput,\n type HistoryMergeResult,\n type HistoryMergeStats,\n} from './merger';\nexport {\n BACKUP_MANIFEST_FILE,\n backupFileName,\n createBackup,\n formatBackupId,\n listBackups,\n pruneBackups,\n type BackupItem,\n type BackupKind,\n type BackupManifest,\n type BackupOptions,\n type BackupResult,\n type BackupSource,\n type BackupSummary,\n} from './backup';\nexport {\n runSync,\n writeBackBookmarks,\n type BrowserSyncOutcome,\n type SyncReport,\n type SyncRunOptions,\n type SyncTargets,\n} from './sync';\n","import type { LogLevel } from '@crosssync/shared';\nimport { Command } from 'commander';\n\nimport { CLI_DESCRIPTION, CLI_NAME, CLI_VERSION } from './constants';\nimport { createContext, type CliContext, type CreateContextOptions } from './context';\nimport { runBackupCommand } from './commands/backup';\nimport { runConfigCommand } from './commands/config';\nimport { runInstallCronCommand, runUninstallCronCommand } from './commands/cron';\nimport { runExportCommand } from './commands/export';\nimport { runLogsCommand } from './commands/logs';\nimport { runStatusCommand } from './commands/status';\nimport { runSyncCommand } from './commands/sync';\n\nexport interface GlobalOptions {\n /** Use a different home directory (used by tests). */\n homeDir?: string;\n verbose?: boolean;\n quiet?: boolean;\n}\n\nexport type ContextFactory = (options: GlobalOptions) => CliContext;\n\n/** Builds the CLI context, turning a bad config into a friendly error. */\nexport function createCliContext(options: GlobalOptions = {}): CliContext {\n const logLevel: LogLevel | undefined = options.verbose\n ? 'debug'\n : options.quiet\n ? 'error'\n : undefined;\n const contextOptions: CreateContextOptions = { homeDir: options.homeDir, logLevel };\n return createContext(contextOptions);\n}\n\nexport function buildProgram(contextFactory: ContextFactory = createCliContext): Command {\n const program = new Command();\n\n program\n .name(CLI_NAME)\n .description(CLI_DESCRIPTION)\n .version(CLI_VERSION, '-v, --version', 'print the CrossSync version')\n .option('--home-dir <path>', 'use an alternate home directory')\n .option('--verbose', 'enable debug logging')\n .option('--quiet', 'only log errors');\n\n const withContext = (action: (context: CliContext) => number) => () => {\n const context = contextFactory(program.opts<GlobalOptions>());\n process.exitCode = action(context);\n };\n\n const syncCommand = program\n .command('sync')\n .description('read, merge and write back browser bookmarks/history')\n .option('--bookmarks', 'sync bookmarks only')\n .option('--history', 'sync history only')\n .option('--all', 'sync bookmarks and history (default)')\n .option('--browser <name>', 'chrome, edge or all', 'all')\n .option('--profile <name>', 'profile name or \"all\"')\n .option('--strategy <name>', 'merge (write back) or export (read only)')\n .option('--dry-run', 'show what would happen without touching any file')\n .option('--force', 'write bookmarks back even while the browser is running')\n .option('--json', 'print the report as JSON');\n syncCommand.action(withContext((context) => runSyncCommand(context, syncCommand.opts())));\n\n const backupCommand = program\n .command('backup')\n .description('back up browser bookmark and history files')\n .option('--list', 'list existing backups')\n .option('--prune', 'delete old backups')\n .option('--keep <count>', 'how many backups to keep when pruning');\n backupCommand.action(\n withContext((context) => {\n const options = backupCommand.opts();\n return runBackupCommand(context, {\n list: options.list,\n prune: options.prune,\n keep: options.keep === undefined ? undefined : Number(options.keep),\n });\n }),\n );\n\n const exportCommand = program\n .command('export')\n .description('export merged bookmarks/history as JSON')\n .option('--format <format>', 'output format (json)', 'json')\n .option('--out <dir>', 'directory to write into')\n .option('--browser <name>', 'chrome, edge or all', 'all')\n .option('--profile <name>', 'profile name or \"all\"')\n .option('--stdout', 'print the export instead of writing a file');\n exportCommand.action(withContext((context) => runExportCommand(context, exportCommand.opts())));\n\n const statusCommand = program\n .command('status')\n .description('show browsers, profiles, backups and schedule state')\n .option('--json', 'print the status as JSON');\n statusCommand.action(withContext((context) => runStatusCommand(context, statusCommand.opts())));\n\n const logsCommand = program\n .command('logs')\n .description('print CrossSync log entries')\n .option('--limit <count>', 'number of entries to show', '50')\n .option('--level <level>', 'debug, info, warn or error')\n .option('--clear', 'delete the log file')\n .option('--json', 'print the entries as JSON');\n logsCommand.action(\n withContext((context) => {\n const options = logsCommand.opts();\n return runLogsCommand(context, {\n limit: Number(options.limit),\n level: options.level,\n clear: options.clear,\n json: options.json,\n });\n }),\n );\n\n const installCronCommand = program\n .command('install-cron')\n .description('install a scheduled sync (Task Scheduler, launchd, systemd or cron)')\n .option('--expression <cron>', 'cron expression, e.g. \"0 9 * * *\"')\n .option('--label <name>', 'task/agent/unit name')\n .option('--dry-run', 'print the plan without changing anything');\n installCronCommand.action(\n withContext((context) => runInstallCronCommand(context, installCronCommand.opts())),\n );\n\n const uninstallCronCommand = program\n .command('uninstall-cron')\n .description('remove the installed schedule')\n .option('--label <name>', 'task/agent/unit name')\n .option('--dry-run', 'print the plan without changing anything');\n uninstallCronCommand.action(\n withContext((context) => runUninstallCronCommand(context, uninstallCronCommand.opts())),\n );\n\n const configCommand = program\n .command('config')\n .description('show or edit the CrossSync configuration')\n .option('--path', 'print the config file path')\n .option('--get <key>', 'read a dotted key, e.g. sync.strategy')\n .option('--set <key=value>', 'write a key, e.g. sync.strategy=export')\n .option('--reset', 'restore the default config');\n configCommand.action(withContext((context) => runConfigCommand(context, configCommand.opts())));\n\n return program;\n}\n\nexport function run(argv: string[] = process.argv): void {\n buildProgram().parse(argv);\n}\n\nexport { CLI_NAME, CLI_VERSION };\nexport const PACKAGE = 'crosssync';\nexport const VERSION = CLI_VERSION;\n\nif (require.main === module) {\n run();\n}\n","import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = commander;\n","export const CLI_PACKAGE = 'crosssync';\nexport const CLI_VERSION = '0.1.1';\nexport const CLI_NAME = 'crosssync';\nexport const CLI_DESCRIPTION = 'Cross-browser bookmark & history sync CLI (Chrome + Edge)';\n\n/** Name of the Windows Task Scheduler entry. */\nexport const WINDOWS_TASK_NAME = 'CrossSync';\n\n/** Reverse-DNS label of the launchd agent installed on macOS. */\nexport const MACOS_LAUNCH_AGENT_LABEL = 'com.crosssync.sync';\n\n/** Name of the systemd user timer/service installed on Linux. */\nexport const SYSTEMD_UNIT_NAME = 'crosssync-sync';\n\n/** Marker used to recognise CrossSync lines inside a crontab. */\nexport const CRONTAB_MARKER = '# crosssync';\n\n/** Default arguments passed to `crosssync` by the installed schedule. */\nexport const DEFAULT_SCHEDULE_ARGS = ['sync', '--all'];\n","import path from 'path';\n\nimport type { CliConfig, CrossSyncDirs, LogLevel } from '@crosssync/shared';\nimport {\n createDefaultConfig,\n DEFAULT_EXPORT_RETENTION,\n isCliConfig,\n LOG_FILE_NAME,\n pathExists,\n readJsonFile,\n resolveCrossSyncDirs,\n writeJsonFileSafe,\n} from '@crosssync/shared';\nimport { Logger } from '@crosssync/core';\n\nexport interface CommandIo {\n out(text?: string): void;\n err(text?: string): void;\n}\n\nexport const consoleIo: CommandIo = {\n out: (text = '') => console.log(text),\n err: (text = '') => console.error(text),\n};\n\n/** Captures output for tests. */\nexport function createMemoryIo(): CommandIo & { stdout: string[]; stderr: string[] } {\n const stdout: string[] = [];\n const stderr: string[] = [];\n return {\n stdout,\n stderr,\n out: (text = '') => stdout.push(text),\n err: (text = '') => stderr.push(text),\n };\n}\n\n/** Loads `config.json`, creating it with defaults when missing. */\nexport function loadConfigFile(\n configFile: string,\n dirs: CrossSyncDirs,\n): { config: CliConfig; created: boolean } {\n if (!pathExists(configFile)) {\n const config = createDefaultConfig({\n dataDir: dirs.root,\n backupDir: dirs.backups,\n exportDir: dirs.exports,\n logDir: dirs.logs,\n });\n writeJsonFileSafe(configFile, config);\n return { config, created: true };\n }\n\n const raw = readJsonFile<unknown>(configFile);\n if (!isCliConfig(raw)) {\n throw new Error(\n `Invalid CrossSync config at ${configFile}. Fix or delete the file, then retry.`,\n );\n }\n // Configs written before `exports.keep` existed load with the default.\n const config: CliConfig = raw.exports\n ? raw\n : { ...raw, exports: { keep: DEFAULT_EXPORT_RETENTION } };\n return { config, created: false };\n}\n\nexport function saveConfigFile(configFile: string, config: CliConfig): void {\n writeJsonFileSafe(configFile, config);\n}\n\nexport interface CreateContextOptions {\n /** Overrides the user home directory; used by tests. */\n homeDir?: string;\n logLevel?: LogLevel;\n io?: CommandIo;\n /** Mirror log entries to the console. Defaults to false. */\n console?: boolean;\n}\n\nexport interface CliContext {\n config: CliConfig;\n dirs: CrossSyncDirs;\n logger: Logger;\n io: CommandIo;\n /** True when `config.json` was created during this run. */\n configCreated: boolean;\n}\n\n/** Builds the shared runtime context every command works against. */\nexport function createContext(options: CreateContextOptions = {}): CliContext {\n const dirs = resolveCrossSyncDirs(options.homeDir);\n const { config, created } = loadConfigFile(dirs.configFile, dirs);\n const logger = new Logger(options.logLevel ?? config.logLevel, {\n console: options.console ?? false,\n filePath: path.join(config.logDir, LOG_FILE_NAME),\n });\n return { config, dirs, logger, io: options.io ?? consoleIo, configCreated: created };\n}\n\n/** Re-reads the config so a command can persist changes it just made. */\nexport function reloadConfig(context: CliContext): void {\n const { config } = loadConfigFile(context.dirs.configFile, context.dirs);\n context.config = config;\n}\n","import { pathExists } from '@crosssync/shared';\nimport {\n createBackup,\n createConfiguredBrowserReaders,\n DEFAULT_BACKUP_RETENTION,\n listBackups,\n pruneBackups,\n type BackupSource,\n} from '@crosssync/core';\n\nimport type { CliContext } from '../context';\nimport { describeError } from './read';\n\nexport interface BackupCommandOptions {\n /** List existing backups instead of creating one. */\n list?: boolean;\n /** Delete all but the N most recent backups. */\n prune?: boolean;\n keep?: number;\n /** Keep at most N backups after creating a new one. */\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n now?: Date;\n}\n\nexport function runBackupCommand(context: CliContext, options: BackupCommandOptions = {}): number {\n if (options.list) {\n return listBackupCommand(context);\n }\n if (options.prune) {\n return pruneBackupCommand(context, options.keep ?? DEFAULT_BACKUP_RETENTION);\n }\n return createBackupCommand(context, options);\n}\n\n/** Every bookmark/history file that currently exists, ready to be backed up. */\nexport function collectBackupSources(\n config: CliContext['config'],\n options: BackupCommandOptions = {},\n): BackupSource[] {\n const sources: BackupSource[] = [];\n const readers = createConfiguredBrowserReaders(config, {\n platform: options.platform,\n env: options.env,\n });\n\n for (const reader of readers) {\n for (const profile of reader.resolveProfiles(config.profile)) {\n const bookmarks = reader.bookmarksPath(profile);\n if (pathExists(bookmarks)) {\n sources.push({ kind: 'bookmarks', browser: reader.browser, profile, filePath: bookmarks });\n }\n const history = reader.historyPath(profile);\n if (pathExists(history)) {\n sources.push({ kind: 'history', browser: reader.browser, profile, filePath: history });\n }\n }\n }\n\n return sources;\n}\n\nfunction createBackupCommand(context: CliContext, options: BackupCommandOptions): number {\n const sources = collectBackupSources(context.config, options);\n if (sources.length === 0) {\n context.io.err('No browser bookmark or history files were found to back up.');\n return 1;\n }\n\n try {\n const result = createBackup({\n backupDir: context.config.backupDir,\n sources,\n now: options.now,\n platform: options.platform,\n });\n context.logger.info('Backup created', { dir: result.dir });\n context.io.out(`Backup created: ${result.dir}`);\n context.io.out(` ${result.manifest.items.length} file(s) copied`);\n for (const item of result.manifest.items) {\n context.io.out(` ${item.kind}/${item.browser}/${item.profile} (${item.bytes} bytes)`);\n }\n return 0;\n } catch (error) {\n context.io.err(`Backup failed: ${describeError(error)}`);\n return 1;\n }\n}\n\nfunction listBackupCommand(context: CliContext): number {\n const summaries = listBackups(context.config.backupDir);\n if (summaries.length === 0) {\n context.io.out(`No backups found in ${context.config.backupDir}.`);\n return 0;\n }\n\n context.io.out(`Backups in ${context.config.backupDir}:`);\n for (const summary of summaries) {\n const created = summary.createdAt ?? 'unknown';\n context.io.out(\n ` ${summary.id} ${created} ${summary.itemCount} file(s) ${formatBytes(summary.bytes)}`,\n );\n }\n return 0;\n}\n\nfunction pruneBackupCommand(context: CliContext, keep: number): number {\n const removed = pruneBackups(context.config.backupDir, keep);\n if (removed.length === 0) {\n context.io.out(`Nothing to prune; keeping ${keep} most recent backup(s).`);\n return 0;\n }\n context.io.out(`Removed ${removed.length} backup(s), keeping the ${keep} most recent:`);\n for (const dir of removed) {\n context.io.out(` ${dir}`);\n }\n return 0;\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n }\n if (bytes < 1024 * 1024) {\n return `${(bytes / 1024).toFixed(1)} KiB`;\n }\n return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;\n}\n","import type { BrowserName, CliConfig } from '@crosssync/shared';\nimport { pathExists } from '@crosssync/shared';\nimport {\n createConfiguredBrowserReaders,\n mergeBookmarkFiles,\n mergeHistory,\n type BookmarkMergeResult,\n type HistoryMergeResult,\n} from '@crosssync/core';\n\nexport interface ReadOptions {\n browser?: string[];\n profile?: string;\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface MergedData {\n bookmarkMerge: BookmarkMergeResult | null;\n historyMerge: HistoryMergeResult | null;\n warnings: string[];\n /** Files that were read, for reporting. */\n sources: {\n browser: BrowserName;\n profile: string;\n filePath: string;\n kind: 'bookmarks' | 'history';\n }[];\n}\n\n/**\n * Reads and merges browser data without backing up or writing anything.\n *\n * Shared by `status` and `export`, which must never touch browser files.\n */\nexport function readMergedData(config: CliConfig, options: ReadOptions = {}): MergedData {\n const warnings: string[] = [];\n const sources: MergedData['sources'] = [];\n const bookmarkInputs: {\n browser: BrowserName;\n file: Parameters<typeof mergeBookmarkFiles>[0][number]['file'];\n }[] = [];\n const historyInputs: {\n browser: BrowserName;\n entries: Parameters<typeof mergeHistory>[0][number]['entries'];\n }[] = [];\n\n const readers = createConfiguredBrowserReaders(config, {\n platform: options.platform,\n env: options.env,\n });\n\n for (const reader of readers) {\n if (options.browser && !options.browser.includes(reader.browser)) {\n continue;\n }\n const profiles = reader.resolveProfiles(options.profile ?? config.profile);\n if (profiles.length === 0) {\n warnings.push(`No ${reader.browser} profile found under ${reader.dataDir}.`);\n continue;\n }\n\n for (const profile of profiles) {\n const bookmarksPath = reader.bookmarksPath(profile);\n if (pathExists(bookmarksPath)) {\n try {\n const source = reader.readBookmarks(profile);\n bookmarkInputs.push({ browser: source.browser, file: source.file });\n sources.push({\n browser: source.browser,\n profile,\n filePath: bookmarksPath,\n kind: 'bookmarks',\n });\n } catch (error) {\n warnings.push(`Could not read ${reader.browser} bookmarks: ${describeError(error)}`);\n }\n }\n\n const historyPath = reader.historyPath(profile);\n if (pathExists(historyPath)) {\n try {\n const source = reader.readHistory(profile);\n historyInputs.push({ browser: source.browser, entries: source.entries });\n sources.push({\n browser: source.browser,\n profile,\n filePath: historyPath,\n kind: 'history',\n });\n } catch (error) {\n warnings.push(`Could not read ${reader.browser} history: ${describeError(error)}`);\n }\n }\n }\n }\n\n return {\n bookmarkMerge: bookmarkInputs.length > 0 ? mergeBookmarkFiles(bookmarkInputs) : null,\n historyMerge: historyInputs.length > 0 ? mergeHistory(historyInputs) : null,\n warnings,\n sources,\n };\n}\n\nexport function describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import type { CliConfig } from '@crosssync/shared';\nimport { createDefaultConfig, isCliConfig } from '@crosssync/shared';\n\nimport type { CliContext } from '../context';\nimport { saveConfigFile } from '../context';\n\nexport interface ConfigCommandOptions {\n /** Print the config file path only. */\n path?: boolean;\n /** Read a dotted key, e.g. `sync.strategy`. */\n get?: string;\n /** Write a dotted key, e.g. `sync.strategy=export`. */\n set?: string;\n /** Recreate the default config. */\n reset?: boolean;\n}\n\n/** Reads a dotted key out of a `CliConfig`. */\nexport function getConfigValue(config: CliConfig, dottedPath: string): unknown {\n return dottedPath.split('.').reduce<unknown>((current, key) => {\n if (typeof current !== 'object' || current === null) {\n return undefined;\n }\n return (current as Record<string, unknown>)[key];\n }, config);\n}\n\n/** Converts a CLI string into a boolean/number/null when it looks like one. */\nexport function coerceConfigValue(raw: string): unknown {\n const trimmed = raw.trim();\n if (trimmed === 'true') {\n return true;\n }\n if (trimmed === 'false') {\n return false;\n }\n if (trimmed === 'null') {\n return null;\n }\n if (trimmed !== '' && /^-?\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Number(trimmed);\n }\n return raw;\n}\n\n/** Returns a new config with `dottedPath` set, refusing invalid results. */\nexport function setConfigValue(config: CliConfig, dottedPath: string, value: unknown): CliConfig {\n const keys = dottedPath.split('.');\n if (keys.some((key) => key.length === 0)) {\n throw new Error(`Invalid config key \"${dottedPath}\".`);\n }\n\n const next = JSON.parse(JSON.stringify(config)) as Record<string, unknown>;\n let cursor: Record<string, unknown> = next;\n\n for (const key of keys.slice(0, -1)) {\n const existing = cursor[key];\n if (typeof existing !== 'object' || existing === null || Array.isArray(existing)) {\n cursor[key] = {};\n }\n cursor = cursor[key] as Record<string, unknown>;\n }\n cursor[keys[keys.length - 1]] = value;\n\n if (!isCliConfig(next)) {\n throw new Error(`Refusing to write an invalid config after setting \"${dottedPath}\".`);\n }\n return next;\n}\n\nexport function runConfigCommand(context: CliContext, options: ConfigCommandOptions = {}): number {\n if (options.path) {\n context.io.out(context.dirs.configFile);\n return 0;\n }\n\n if (options.reset) {\n const config = createDefaultConfig({\n dataDir: context.dirs.root,\n backupDir: context.dirs.backups,\n exportDir: context.dirs.exports,\n logDir: context.dirs.logs,\n });\n saveConfigFile(context.dirs.configFile, config);\n context.config = config;\n context.io.out(`Config reset: ${context.dirs.configFile}`);\n return 0;\n }\n\n if (options.get) {\n const value = getConfigValue(context.config, options.get);\n if (value === undefined) {\n context.io.err(`Unknown config key \"${options.get}\".`);\n return 1;\n }\n context.io.out(typeof value === 'string' ? value : JSON.stringify(value));\n return 0;\n }\n\n if (options.set) {\n const separator = options.set.indexOf('=');\n if (separator <= 0) {\n context.io.err('Use --set key=value, e.g. --set sync.strategy=export.');\n return 1;\n }\n const key = options.set.slice(0, separator);\n const rawValue = options.set.slice(separator + 1);\n\n try {\n const next = setConfigValue(context.config, key, coerceConfigValue(rawValue));\n saveConfigFile(context.dirs.configFile, next);\n context.config = next;\n context.io.out(`${key} = ${JSON.stringify(getConfigValue(next, key))}`);\n return 0;\n } catch (error) {\n context.io.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n }\n\n context.io.out(`# ${context.dirs.configFile}`);\n context.io.out(JSON.stringify(context.config, null, 2));\n return 0;\n}\n","import { DEFAULT_CRON_SCHEDULE } from '@crosssync/shared';\n\nimport type { CliContext } from '../context';\nimport { saveConfigFile } from '../context';\nimport { createCronManager, type CronRunner } from '../cron';\n\nexport interface CronCommandOptions {\n /** Cron expression, e.g. `0 9 * * *`. */\n expression?: string;\n /** Print the plan instead of changing anything. */\n dryRun?: boolean;\n label?: string;\n executable?: string;\n platform?: NodeJS.Platform;\n homeDir?: string;\n /** Injectable for tests. */\n runner?: CronRunner;\n}\n\nexport function runInstallCronCommand(\n context: CliContext,\n options: CronCommandOptions = {},\n): number {\n const expression =\n options.expression ?? context.config.schedule.expression ?? DEFAULT_CRON_SCHEDULE;\n\n let manager;\n try {\n manager = createCronManager({\n label: options.label,\n executable: options.executable,\n expression,\n platform: options.platform,\n homeDir: options.homeDir,\n runner: options.runner,\n });\n } catch (error) {\n context.io.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n\n if (options.dryRun) {\n context.io.out(`Dry run: no changes made (platform: ${manager.platform}).`);\n context.io.out(manager.describe('install'));\n return 0;\n }\n\n let result;\n try {\n result = manager.install();\n } catch (error) {\n context.io.err(\n `Failed to install the schedule: ${error instanceof Error ? error.message : String(error)}`,\n );\n return 1;\n }\n\n for (const message of result.messages) {\n if (result.changed) {\n context.io.out(message);\n } else {\n context.io.err(message);\n }\n }\n\n if (!result.changed) {\n return 1;\n }\n\n const next = { ...context.config, schedule: { installed: true, expression } };\n saveConfigFile(context.dirs.configFile, next);\n context.config = next;\n return 0;\n}\n\nexport function runUninstallCronCommand(\n context: CliContext,\n options: CronCommandOptions = {},\n): number {\n const expression = context.config.schedule.expression ?? DEFAULT_CRON_SCHEDULE;\n\n let manager;\n try {\n manager = createCronManager({\n label: options.label,\n executable: options.executable,\n expression,\n platform: options.platform,\n homeDir: options.homeDir,\n runner: options.runner,\n });\n } catch (error) {\n context.io.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n\n if (options.dryRun) {\n context.io.out(`Dry run: no changes made (platform: ${manager.platform}).`);\n context.io.out(manager.describe('uninstall'));\n return 0;\n }\n\n const result = manager.uninstall();\n for (const message of result.messages) {\n if (result.changed) {\n context.io.out(message);\n } else {\n context.io.err(message);\n }\n }\n\n const next = { ...context.config, schedule: { installed: false, expression } };\n saveConfigFile(context.dirs.configFile, next);\n context.config = next;\n\n return 0;\n}\n","import { DEFAULT_CRON_SCHEDULE } from '@crosssync/shared';\n\nimport { createLinuxCronManager } from './linux';\nimport { createMacosCronManager } from './macos';\nimport type { CronManager, CronManagerOptions } from './types';\nimport { createWindowsCronManager } from './windows';\n\nexport * from './types';\nexport * from './schedule';\n\nexport { quotePosixArgument, quoteWindowsArgument, resolveInvocation } from './invocation';\n\nexport { defaultCronRunner, toActionResult } from './runner';\n\nexport { buildScheduleArgs, createWindowsCronManager } from './windows';\nexport { escapeXml, launchAgentPath, renderLaunchAgent, createMacosCronManager } from './macos';\nexport {\n applyCrontabLine,\n buildCrontabLine,\n createLinuxCronManager,\n renderSystemdService,\n renderSystemdTimer,\n shouldUseSystemd,\n systemdUnitPath,\n} from './linux';\n\n/** Picks the scheduler implementation for the current platform. */\nexport function createCronManager(options: CronManagerOptions = {}): CronManager {\n const platform = options.platform ?? process.platform;\n const resolved: CronManagerOptions = {\n expression: options.expression ?? DEFAULT_CRON_SCHEDULE,\n ...options,\n platform,\n };\n\n if (platform === 'win32') {\n return createWindowsCronManager(resolved);\n }\n if (platform === 'darwin') {\n return createMacosCronManager(resolved);\n }\n return createLinuxCronManager(resolved);\n}\n","import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\n\nimport { DEFAULT_CRON_SCHEDULE, ensureDir, pathExists, resolveHomeDir } from '@crosssync/shared';\n\nimport { CRONTAB_MARKER, SYSTEMD_UNIT_NAME } from '../constants';\nimport { quotePosixArgument, resolveInvocation } from './invocation';\nimport { defaultCronRunner, toActionResult } from './runner';\nimport { parseCronExpression, toSystemdCalendar } from './schedule';\nimport type { CronManager, CronManagerOptions, CronRunner } from './types';\n\n/** `~/.config/systemd/user/<unit>.<kind>` */\nexport function systemdUnitPath(unit: string, kind: 'service' | 'timer', homeDir?: string): string {\n return path.join(homeDir ?? resolveHomeDir(), '.config', 'systemd', 'user', `${unit}.${kind}`);\n}\n\nexport function renderSystemdService(program: string, args: string[]): string {\n const execStart = [program, ...args].map(quotePosixArgument).join(' ');\n return [\n '[Unit]',\n 'Description=CrossSync browser bookmark & history sync',\n '',\n '[Service]',\n 'Type=oneshot',\n `ExecStart=${execStart}`,\n '',\n ].join('\\n');\n}\n\nexport function renderSystemdTimer(expression: string, unit: string): string {\n const spec = parseCronExpression(expression);\n return [\n '[Unit]',\n `Description=Run CrossSync (${unit}) on a schedule`,\n '',\n '[Timer]',\n `OnCalendar=${toSystemdCalendar(spec)}`,\n 'Persistent=true',\n '',\n '[Install]',\n 'WantedBy=timers.target',\n '',\n ].join('\\n');\n}\n\n/** Replaces CrossSync's crontab entry, keeping every other line intact. */\nexport function applyCrontabLine(existing: string, line: string | null): string {\n const kept = existing\n .split(/\\r?\\n/)\n .filter((entry) => entry.trim().length > 0 && !entry.includes(CRONTAB_MARKER));\n if (line) {\n kept.push(line);\n }\n return kept.length > 0 ? `${kept.join('\\n')}\\n` : '';\n}\n\nexport function buildCrontabLine(expression: string, commandLine: string): string {\n return `${expression} ${commandLine} ${CRONTAB_MARKER}`;\n}\n\n/** True when the schedule should be installed as a systemd user timer. */\nexport function shouldUseSystemd(options: CronManagerOptions, program: string): boolean {\n if (options.useSystemd === true) {\n return true;\n }\n if (options.useSystemd === false) {\n return false;\n }\n // systemd requires an absolute ExecStart path; otherwise fall back to crontab.\n return path.isAbsolute(program) && pathExists('/run/systemd/system');\n}\n\n/**\n * Installs the schedule as a systemd user timer when available, otherwise as a\n * crontab entry. `describe()` lets `install-cron --dry-run` show the plan.\n */\nexport function createLinuxCronManager(options: CronManagerOptions = {}): CronManager {\n const expression = options.expression ?? DEFAULT_CRON_SCHEDULE;\n const invocation = resolveInvocation(options);\n const runner = options.runner ?? defaultCronRunner;\n const homeDir = options.homeDir ?? resolveHomeDir();\n const useSystemd = shouldUseSystemd(options, invocation.program);\n const unit = options.label ?? SYSTEMD_UNIT_NAME;\n const servicePath = systemdUnitPath(unit, 'service', homeDir);\n const timerPath = systemdUnitPath(unit, 'timer', homeDir);\n const cronLine = buildCrontabLine(expression, invocation.posixCommandLine);\n\n return {\n platform: 'linux',\n label: unit,\n\n describe(action) {\n if (useSystemd) {\n if (action === 'install') {\n return [\n `Write systemd user timer (${expression}):`,\n ` ${servicePath}`,\n ` ${timerPath}`,\n ' systemctl --user daemon-reload',\n ` systemctl --user enable --now ${unit}.timer`,\n ].join('\\n');\n }\n return [\n 'Disable systemd user timer:',\n ` systemctl --user disable --now ${unit}.timer`,\n `Remove files: ${servicePath}, ${timerPath}`,\n ' systemctl --user daemon-reload',\n ].join('\\n');\n }\n\n if (action === 'install') {\n return ['Add crontab entry:', ` ${cronLine}`].join('\\n');\n }\n return `Remove the crontab entry containing \"${CRONTAB_MARKER}\".`;\n },\n\n install() {\n if (useSystemd) {\n ensureDir(path.dirname(servicePath));\n fs.writeFileSync(\n servicePath,\n renderSystemdService(invocation.program, invocation.args),\n 'utf8',\n );\n fs.writeFileSync(timerPath, renderSystemdTimer(expression, unit), 'utf8');\n\n const reload = runner('systemctl', ['--user', 'daemon-reload']);\n if (reload.status !== 0) {\n return toActionResult(reload, '', 'systemctl --user daemon-reload failed');\n }\n const result = runner('systemctl', ['--user', 'enable', '--now', `${unit}.timer`]);\n return toActionResult(\n result,\n `systemd timer \"${unit}.timer\" installed.`,\n 'systemctl --user enable failed',\n );\n }\n\n const current = runner('crontab', ['-l']);\n const next = applyCrontabLine(current.status === 0 ? current.stdout : '', cronLine);\n return writeCrontab(next, runner, `crontab entry for ${unit} installed.`);\n },\n\n uninstall() {\n if (useSystemd) {\n runner('systemctl', ['--user', 'disable', '--now', `${unit}.timer`]);\n let existed = false;\n for (const file of [servicePath, timerPath]) {\n if (pathExists(file)) {\n existed = true;\n fs.rmSync(file, { force: true });\n }\n }\n runner('systemctl', ['--user', 'daemon-reload']);\n return {\n changed: existed,\n messages: [\n existed\n ? `systemd timer \"${unit}.timer\" removed.`\n : `No systemd timer named \"${unit}.timer\" was installed.`,\n ],\n };\n }\n\n const current = runner('crontab', ['-l']);\n const before = current.status === 0 ? current.stdout : '';\n const next = applyCrontabLine(before, null);\n if (next === before) {\n return { changed: false, messages: [`No crontab entry for ${unit} was installed.`] };\n }\n return writeCrontab(next, runner, `crontab entry for ${unit} removed.`);\n },\n };\n}\n\nfunction writeCrontab(\n content: string,\n runner: CronRunner,\n successMessage: string,\n): { changed: boolean; messages: string[] } {\n const tempFile = path.join(os.tmpdir(), `crosssync-crontab-${process.pid}.txt`);\n fs.writeFileSync(tempFile, content, 'utf8');\n try {\n const result = runner('crontab', [tempFile]);\n return toActionResult(result, successMessage, 'crontab failed');\n } finally {\n fs.rmSync(tempFile, { force: true });\n }\n}\n","import { CLI_NAME, DEFAULT_SCHEDULE_ARGS } from '../constants';\nimport type { CronInvocation, CronManagerOptions } from './types';\n\n/** Quotes a value for `schtasks /TR`, which re-parses the string itself. */\nexport function quoteWindowsArgument(value: string): string {\n return /[\\s\"]/.test(value) ? `\"${value.replace(/\"/g, '\\\\\"')}\"` : value;\n}\n\n/** Quotes a value for POSIX shells (crontab / systemd ExecStart). */\nexport function quotePosixArgument(value: string): string {\n if (value === '') {\n return \"''\";\n }\n return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * Works out what the schedule should execute.\n *\n * When CrossSync runs from source (`node dist/index.js`) the schedule has to go\n * through Node; when it runs from the installed `crosssync` bin the bin is used.\n */\nexport function resolveInvocation(options: CronManagerOptions = {}): CronInvocation {\n const args = options.args ?? [...DEFAULT_SCHEDULE_ARGS];\n let program: string;\n let fullArgs: string[];\n\n if (options.executable) {\n program = options.executable;\n fullArgs = args;\n } else {\n const script = process.argv[1];\n if (script && /\\.[cm]?js$/.test(script)) {\n program = process.execPath;\n fullArgs = [script, ...args];\n } else {\n program = CLI_NAME;\n fullArgs = args;\n }\n }\n\n return {\n program,\n args: fullArgs,\n windowsCommandLine: [program, ...fullArgs].map(quoteWindowsArgument).join(' '),\n posixCommandLine: [program, ...fullArgs].map(quotePosixArgument).join(' '),\n };\n}\n","import { execFileSync } from 'child_process';\n\nimport type { CronActionResult, CronProcessResult, CronRunner } from './types';\n\n/** Runs a command, capturing output instead of throwing. */\nexport const defaultCronRunner: CronRunner = (command, args) => {\n try {\n const stdout = execFileSync(command, args, {\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n return { status: 0, stdout: String(stdout ?? ''), stderr: '' };\n } catch (error) {\n const failure = error as { status?: number | null; stdout?: unknown; stderr?: unknown };\n return {\n status: typeof failure.status === 'number' ? failure.status : 1,\n stdout: toText(failure.stdout),\n stderr: toText(failure.stderr),\n };\n }\n};\n\nfunction toText(value: unknown): string {\n if (Buffer.isBuffer(value)) {\n return value.toString('utf8');\n }\n return typeof value === 'string' ? value : '';\n}\n\n/** Turns a process result into a `CronActionResult`. */\nexport function toActionResult(\n result: CronProcessResult,\n successMessage: string,\n failurePrefix: string,\n): CronActionResult {\n if (result.status === 0) {\n return { changed: true, messages: [successMessage] };\n }\n const detail = (result.stderr || result.stdout).trim();\n return {\n changed: false,\n messages: [`${failurePrefix} (exit ${result.status})${detail ? `: ${detail}` : ''}`],\n };\n}\n","export interface CronSpec {\n minute: string;\n hour: string;\n dayOfMonth: string;\n month: string;\n dayOfWeek: string;\n}\n\nconst FIELD_PATTERN = /^(\\*|\\d+)(?:-(\\d+))?(?:\\/(\\d+))?$/;\n\nconst CRON_WEEKDAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const;\n\nconst WINDOWS_WEEKDAY_NAMES = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] as const;\n\n/** Parses a 5-field cron expression, rejecting anything out of range. */\nexport function parseCronExpression(expression: string): CronSpec {\n const parts = expression.trim().split(/\\s+/).filter(Boolean);\n if (parts.length !== 5) {\n throw new Error(\n `Invalid cron expression \"${expression}\": expected 5 fields (minute hour day month weekday).`,\n );\n }\n\n const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;\n validateField(minute, 0, 59, 'minute', expression);\n validateField(hour, 0, 23, 'hour', expression);\n validateField(dayOfMonth, 1, 31, 'day of month', expression);\n validateField(month, 1, 12, 'month', expression);\n validateField(dayOfWeek, 0, 7, 'day of week', expression);\n\n return { minute, hour, dayOfMonth, month, dayOfWeek };\n}\n\nexport function isWildcard(field: string): boolean {\n return field === '*';\n}\n\n/** The hour/minute pair, when both are plain numbers. */\nexport function toFixedTime(spec: CronSpec): { hour: number; minute: number } {\n if (!/^\\d+$/.test(spec.hour) || !/^\\d+$/.test(spec.minute)) {\n throw new Error(\n `Only fixed times are supported by this scheduler (got hour=\"${spec.hour}\", minute=\"${spec.minute}\"). ` +\n 'Use a schedule such as \"0 9 * * *\".',\n );\n }\n return { hour: Number(spec.hour), minute: Number(spec.minute) };\n}\n\nexport function formatTime(hour: number, minute: number): string {\n return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;\n}\n\n/** A single numeric day of week (0 and 7 both mean Sunday). */\nexport function toWeekday(spec: CronSpec): number | null {\n if (isWildcard(spec.dayOfWeek)) {\n return null;\n }\n if (!/^\\d+$/.test(spec.dayOfWeek)) {\n throw new Error(`Only a single numeric day of week is supported (got \"${spec.dayOfWeek}\").`);\n }\n return Number(spec.dayOfWeek) % 7;\n}\n\nexport function cronWeekdayName(day: number): string {\n return CRON_WEEKDAY_NAMES[day % 7];\n}\n\nexport function windowsWeekdayName(day: number): string {\n return WINDOWS_WEEKDAY_NAMES[day % 7];\n}\n\n/** Maps a cron spec onto a systemd `OnCalendar=` value. */\nexport function toSystemdCalendar(spec: CronSpec): string {\n const { hour, minute } = toFixedTime(spec);\n const time = `${formatTime(hour, minute)}:00`;\n const weekday = toWeekday(spec);\n\n if (weekday !== null) {\n return `${cronWeekdayName(weekday)} *-*-* ${time}`;\n }\n if (!isWildcard(spec.dayOfMonth) && /^\\d+$/.test(spec.dayOfMonth)) {\n const month = isWildcard(spec.month) ? '*' : String(Number(spec.month)).padStart(2, '0');\n return `*-${month}-${String(Number(spec.dayOfMonth)).padStart(2, '0')} ${time}`;\n }\n return `*-*-* ${time}`;\n}\n\n/** True when the spec runs once a day at a fixed time. */\nexport function isDaily(spec: CronSpec): boolean {\n return isWildcard(spec.dayOfMonth) && isWildcard(spec.month) && isWildcard(spec.dayOfWeek);\n}\n\n/** True when the spec runs weekly on a single weekday at a fixed time. */\nexport function isWeekly(spec: CronSpec): boolean {\n return isWildcard(spec.dayOfMonth) && isWildcard(spec.month) && !isWildcard(spec.dayOfWeek);\n}\n\nfunction validateField(\n field: string,\n min: number,\n max: number,\n name: string,\n expression: string,\n): void {\n for (const part of field.split(',')) {\n const match = FIELD_PATTERN.exec(part);\n if (!match) {\n throw new Error(`Invalid cron expression \"${expression}\": bad ${name} field \"${part}\".`);\n }\n const [, startRaw, endRaw, stepRaw] = match;\n const start = startRaw === '*' ? min : Number(startRaw);\n const end = endRaw ? Number(endRaw) : start;\n const step = stepRaw ? Number(stepRaw) : 1;\n\n if (start < min || start > max || end < min || end > max) {\n throw new Error(\n `Invalid cron expression \"${expression}\": ${name} \"${part}\" is outside ${min}-${max}.`,\n );\n }\n if (end < start) {\n throw new Error(\n `Invalid cron expression \"${expression}\": ${name} range \"${part}\" is reversed.`,\n );\n }\n if (step < 1) {\n throw new Error(`Invalid cron expression \"${expression}\": ${name} step must be >= 1.`);\n }\n }\n}\n","import fs from 'fs';\nimport path from 'path';\n\nimport { DEFAULT_CRON_SCHEDULE, ensureDir, resolveHomeDir } from '@crosssync/shared';\n\nimport { MACOS_LAUNCH_AGENT_LABEL } from '../constants';\nimport { resolveInvocation } from './invocation';\nimport { defaultCronRunner, toActionResult } from './runner';\nimport { isWildcard, parseCronExpression, toFixedTime, toWeekday } from './schedule';\nimport type { CronManager, CronManagerOptions } from './types';\n\n/** Escapes a value for inclusion in a plist `<string>` element. */\nexport function escapeXml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/** Path of the launchd agent written by CrossSync. */\nexport function launchAgentPath(label: string, homeDir?: string): string {\n return path.join(homeDir ?? resolveHomeDir(), 'Library', 'LaunchAgents', `${label}.plist`);\n}\n\n/** Renders the `com.crosssync.sync.plist` LaunchAgent. */\nexport function renderLaunchAgent(options: {\n label: string;\n expression: string;\n program: string;\n args: string[];\n logDir: string;\n}): string {\n const spec = parseCronExpression(options.expression);\n const { hour, minute } = toFixedTime(spec);\n\n const calendar: string[] = [\n ' <key>Hour</key>',\n ` <integer>${hour}</integer>`,\n ' <key>Minute</key>',\n ` <integer>${minute}</integer>`,\n ];\n\n const weekday = toWeekday(spec);\n if (weekday !== null) {\n calendar.push(' <key>Weekday</key>', ` <integer>${weekday}</integer>`);\n }\n if (!isWildcard(spec.dayOfMonth) && /^\\d+$/.test(spec.dayOfMonth)) {\n calendar.push(' <key>Day</key>', ` <integer>${Number(spec.dayOfMonth)}</integer>`);\n }\n if (!isWildcard(spec.month) && /^\\d+$/.test(spec.month)) {\n calendar.push(' <key>Month</key>', ` <integer>${Number(spec.month)}</integer>`);\n }\n\n const programArguments = [options.program, ...options.args]\n .map((value) => ` <string>${escapeXml(value)}</string>`)\n .join('\\n');\n\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\">',\n '<dict>',\n ' <key>Label</key>',\n ` <string>${escapeXml(options.label)}</string>`,\n ' <key>ProgramArguments</key>',\n ' <array>',\n programArguments,\n ' </array>',\n ' <key>StartCalendarInterval</key>',\n ' <dict>',\n calendar.join('\\n'),\n ' </dict>',\n ' <key>RunAtLoad</key>',\n ' <false/>',\n ' <key>StandardOutPath</key>',\n ` <string>${escapeXml(path.join(options.logDir, 'launchd.out.log'))}</string>`,\n ' <key>StandardErrorPath</key>',\n ` <string>${escapeXml(path.join(options.logDir, 'launchd.err.log'))}</string>`,\n '</dict>',\n '</plist>',\n '',\n ].join('\\n');\n}\n\n/**\n * Installs the schedule as a per-user launchd agent.\n *\n * launchd only understands calendar intervals, so a fixed time is required.\n */\nexport function createMacosCronManager(options: CronManagerOptions = {}): CronManager {\n const label = options.label ?? MACOS_LAUNCH_AGENT_LABEL;\n const expression = options.expression ?? DEFAULT_CRON_SCHEDULE;\n const invocation = resolveInvocation(options);\n const runner = options.runner ?? defaultCronRunner;\n const homeDir = options.homeDir ?? resolveHomeDir();\n const plistPath = launchAgentPath(label, homeDir);\n const logDir = path.join(homeDir, '.crosssync', 'logs');\n\n const render = (): string =>\n renderLaunchAgent({\n label,\n expression,\n program: invocation.program,\n args: invocation.args,\n logDir,\n });\n\n return {\n platform: 'darwin',\n label,\n\n describe(action) {\n if (action === 'install') {\n return [\n `Write launchd agent: ${plistPath}`,\n ` launchctl load -w ${plistPath}`,\n '',\n render().trimEnd(),\n ].join('\\n');\n }\n return [\n `Unload launchd agent:`,\n ` launchctl unload -w ${plistPath}`,\n `Remove file: ${plistPath}`,\n ].join('\\n');\n },\n\n install() {\n ensureDir(path.dirname(plistPath));\n fs.writeFileSync(plistPath, render(), 'utf8');\n runner('launchctl', ['unload', '-w', plistPath]);\n const result = runner('launchctl', ['load', '-w', plistPath]);\n return toActionResult(result, `launchd agent \"${label}\" installed.`, 'launchctl load failed');\n },\n\n uninstall() {\n const result = runner('launchctl', ['unload', '-w', plistPath]);\n const existed = fs.existsSync(plistPath);\n if (existed) {\n fs.rmSync(plistPath, { force: true });\n }\n if (!existed && result.status !== 0) {\n return { changed: false, messages: [`No launchd agent named \"${label}\" was installed.`] };\n }\n return { changed: existed, messages: [`launchd agent \"${label}\" removed.`] };\n },\n };\n}\n","import { DEFAULT_CRON_SCHEDULE } from '@crosssync/shared';\n\nimport { WINDOWS_TASK_NAME } from '../constants';\nimport { resolveInvocation } from './invocation';\nimport { defaultCronRunner, toActionResult } from './runner';\nimport {\n formatTime,\n isDaily,\n isWeekly,\n parseCronExpression,\n toFixedTime,\n toWeekday,\n windowsWeekdayName,\n} from './schedule';\nimport type { CronManager, CronManagerOptions } from './types';\n\nconst UNSUPPORTED_MESSAGE =\n 'Windows Task Scheduler supports daily or weekly CrossSync schedules only. ' +\n 'Use an expression such as \"0 9 * * *\" or \"0 9 * * 1\".';\n\n/**\n * Installs the schedule through Task Scheduler (`schtasks`).\n *\n * `schtasks` cannot express arbitrary cron expressions, so only daily and\n * weekly schedules at a fixed time are accepted.\n */\nexport function createWindowsCronManager(options: CronManagerOptions = {}): CronManager {\n const label = options.label ?? WINDOWS_TASK_NAME;\n const expression = options.expression ?? DEFAULT_CRON_SCHEDULE;\n const invocation = resolveInvocation(options);\n const runner = options.runner ?? defaultCronRunner;\n\n const scheduleArgs = buildScheduleArgs(expression);\n\n return {\n platform: 'win32',\n label,\n\n describe(action) {\n if (action === 'install') {\n return [\n `Register scheduled task \"${label}\" (${expression}):`,\n ` schtasks ${['/Create', '/F', '/TN', label, ...scheduleArgs, '/TR', invocation.windowsCommandLine].join(' ')}`,\n ].join('\\n');\n }\n return [\n `Remove scheduled task \"${label}\":`,\n ` schtasks ${['/Delete', '/F', '/TN', label].join(' ')}`,\n ].join('\\n');\n },\n\n install() {\n const result = runner('schtasks', [\n '/Create',\n '/F',\n '/TN',\n label,\n ...scheduleArgs,\n '/TR',\n invocation.windowsCommandLine,\n ]);\n return toActionResult(result, `Scheduled task \"${label}\" installed.`, 'schtasks failed');\n },\n\n uninstall() {\n const result = runner('schtasks', ['/Delete', '/F', '/TN', label]);\n if (result.status !== 0) {\n // `schtasks` exits non-zero (with a localized message) when the task is\n // absent, so treat any failure as \"nothing to remove\" to stay idempotent.\n return {\n changed: false,\n messages: [`No scheduled task named \"${label}\" was removed.`],\n };\n }\n return { changed: true, messages: [`Scheduled task \"${label}\" removed.`] };\n },\n };\n}\n\n/** Builds the `/SC ...` arguments for a cron expression. */\nexport function buildScheduleArgs(expression: string): string[] {\n const spec = parseCronExpression(expression);\n const { hour, minute } = toFixedTime(spec);\n const time = formatTime(hour, minute);\n\n if (isDaily(spec)) {\n return ['/SC', 'DAILY', '/ST', time];\n }\n if (isWeekly(spec)) {\n const weekday = toWeekday(spec);\n return ['/SC', 'WEEKLY', '/D', windowsWeekdayName(weekday ?? 0), '/ST', time];\n }\n throw new Error(UNSUPPORTED_MESSAGE);\n}\n","import path from 'path';\n\nimport type { BookmarkRoots, HistoryEntry } from '@crosssync/shared';\nimport {\n ensureDir,\n pathExists,\n readJsonFile,\n resolveExportRetention,\n writeJsonFileSafe,\n} from '@crosssync/shared';\nimport { formatBackupId, type BookmarkMergeStats, type HistoryMergeStats } from '@crosssync/core';\n\nimport type { CliContext } from '../context';\nimport { collectExportFiles, pruneExports } from '../export-files';\nimport { describeError, readMergedData, type MergedData } from './read';\nimport { resolveBrowsers } from './sync';\n\nexport interface ExportCommandOptions {\n /** Only `json` is supported. */\n format?: string;\n /** Directory to write into; defaults to the configured export dir. */\n out?: string;\n browser?: string;\n profile?: string;\n /** Write to stdout instead of a file. */\n stdout?: boolean;\n now?: Date;\n platform?: NodeJS.Platform;\n}\n\nexport interface ExportPayload {\n exportedAt: string;\n source: 'crosssync';\n version: number;\n bookmarks: { stats: BookmarkMergeStats; roots: BookmarkRoots } | null;\n history: { stats: HistoryMergeStats; entries: HistoryEntry[] } | null;\n}\n\nexport function buildExportPayload(data: MergedData, exportedAt = new Date()): ExportPayload {\n return {\n exportedAt: exportedAt.toISOString(),\n source: 'crosssync',\n version: 1,\n bookmarks: data.bookmarkMerge\n ? { stats: data.bookmarkMerge.stats, roots: data.bookmarkMerge.roots }\n : null,\n history: data.historyMerge\n ? { stats: data.historyMerge.stats, entries: data.historyMerge.entries }\n : null,\n };\n}\n\n/** Reads and merges browser data, then writes it out as JSON. Never writes back. */\nexport function runExportCommand(context: CliContext, options: ExportCommandOptions = {}): number {\n const format = (options.format ?? 'json').toLowerCase();\n if (format !== 'json') {\n context.io.err(`Unsupported export format \"${format}\". Only \"json\" is supported.`);\n return 1;\n }\n\n let data: MergedData;\n try {\n data = readMergedData(context.config, {\n browser: resolveBrowsers(options.browser),\n profile: options.profile,\n platform: options.platform,\n });\n } catch (error) {\n context.io.err(`Export failed: ${describeError(error)}`);\n return 1;\n }\n\n for (const warning of data.warnings) {\n context.io.err(`warning: ${warning}`);\n }\n\n if (!data.bookmarkMerge && !data.historyMerge) {\n context.io.err('Nothing to export: no bookmark or history data was found.');\n return 1;\n }\n\n const payload = buildExportPayload(data, options.now ?? new Date());\n\n if (options.stdout) {\n context.io.out(JSON.stringify(payload, null, 2));\n return 0;\n }\n\n const outDir = options.out ?? context.config.exportDir;\n const target = path.join(\n outDir,\n `crosssync-export-${formatBackupId(options.now ?? new Date())}.json`,\n );\n\n try {\n ensureDir(outDir);\n writeJsonFileSafe(target, payload);\n } catch (error) {\n context.io.err(`Export failed: ${describeError(error)}`);\n return 1;\n }\n\n // Only the managed export directory is pruned; custom --out dirs are left alone.\n if (path.resolve(outDir) === path.resolve(context.config.exportDir)) {\n const removed = pruneExports(outDir, resolveExportRetention(context.config));\n if (removed.length > 0) {\n context.logger.info('Pruned old exports', { removed: removed.length });\n }\n }\n\n context.logger.info('Export written', { file: target });\n context.io.out(`Export written: ${target}`);\n if (data.bookmarkMerge) {\n context.io.out(` bookmarks: ${data.bookmarkMerge.stats.total} nodes`);\n }\n if (data.historyMerge) {\n context.io.out(` history: ${data.historyMerge.stats.total} entries`);\n }\n return 0;\n}\n\nexport interface ExportSummary {\n count: number;\n latest: string | null;\n /** Newest first, capped by `limit`. */\n files: string[];\n}\n\n/** Summarises the CrossSync export files written into a directory. */\nexport function listExports(exportDir: string, limit = 5): ExportSummary {\n const files = collectExportFiles(exportDir);\n return {\n count: files.length,\n latest: files.length > 0 ? files[0].file : null,\n files: files.slice(0, limit).map((entry) => entry.file),\n };\n}\n\n/** Reads an exported payload back from disk. */\nexport function readExportFile(filePath: string): ExportPayload | null {\n if (!pathExists(filePath)) {\n return null;\n }\n return readJsonFile<ExportPayload>(filePath);\n}\n","import fs from 'fs';\nimport path from 'path';\n\n/**\n * Files written by CrossSync:\n * bookmarks-merged-<yyyyMMdd-HHmmss>.json\n * history-merged-<yyyyMMdd-HHmmss>.json\n * crosssync-export-<yyyyMMdd-HHmmss>.json\n */\nconst EXPORT_FILE_PATTERN =\n /^(?:bookmarks-merged|history-merged|crosssync-export)-(\\d{8}-\\d{6})\\.json$/;\n\nexport interface ExportFileInfo {\n /** Absolute path of the export file. */\n file: string;\n /** Sortable `yyyyMMdd-HHmmss` stamp taken from the file name. */\n timestamp: string;\n}\n\n/** Lists CrossSync export files, newest first. Unrelated JSON files are ignored. */\nexport function collectExportFiles(exportDir: string): ExportFileInfo[] {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(exportDir, { withFileTypes: true });\n } catch {\n return [];\n }\n\n const files: ExportFileInfo[] = [];\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n const match = EXPORT_FILE_PATTERN.exec(entry.name);\n if (!match) {\n continue;\n }\n files.push({ file: path.join(exportDir, entry.name), timestamp: match[1] });\n }\n\n return files.sort(\n (a, b) => b.timestamp.localeCompare(a.timestamp) || b.file.localeCompare(a.file),\n );\n}\n\n/**\n * Keeps the `keep` most recent CrossSync export files and deletes the rest.\n * A `keep` of `0` disables cleanup; failures are ignored so they never abort a sync.\n */\nexport function pruneExports(exportDir: string, keep: number): string[] {\n if (!Number.isFinite(keep) || keep <= 0) {\n return [];\n }\n\n const removed: string[] = [];\n for (const entry of collectExportFiles(exportDir).slice(Math.floor(keep))) {\n try {\n fs.rmSync(entry.file, { force: true });\n removed.push(entry.file);\n } catch {\n // Best effort: a locked/unreadable file must not fail the whole sync.\n }\n }\n return removed;\n}\n","import type { BrowserName, CliConfig, SyncStrategy } from '@crosssync/shared';\nimport {\n BROWSERS,\n isBrowserName,\n resolveExportRetention,\n SYNC_STRATEGIES,\n} from '@crosssync/shared';\nimport { runSync, type SyncReport } from '@crosssync/core';\n\nimport type { CliContext } from '../context';\nimport { pruneExports } from '../export-files';\n\nexport interface SyncCommandOptions {\n bookmarks?: boolean;\n history?: boolean;\n all?: boolean;\n dryRun?: boolean;\n force?: boolean;\n /** `chrome`, `edge` or `all`. */\n browser?: string;\n profile?: string;\n /** `merge` or `export`. */\n strategy?: string;\n /** Print the report as JSON. */\n json?: boolean;\n /** Injectable for tests. */\n browserRunning?: (browser: BrowserName) => boolean;\n now?: Date;\n platform?: NodeJS.Platform;\n}\n\nexport interface SyncTargets {\n bookmarks: boolean;\n history: boolean;\n}\n\n/** `--all` (or no flag at all) syncs bookmarks and history. */\nexport function resolveTargets(options: SyncCommandOptions): SyncTargets {\n if (options.all) {\n return { bookmarks: true, history: true };\n }\n const bookmarks = options.bookmarks === true;\n const history = options.history === true;\n if (!bookmarks && !history) {\n return { bookmarks: true, history: true };\n }\n return { bookmarks, history };\n}\n\nexport function resolveBrowsers(value: string | undefined): BrowserName[] {\n if (!value || value === 'all') {\n return [...BROWSERS];\n }\n if (!isBrowserName(value)) {\n throw new Error(`Unknown browser \"${value}\". Use one of: ${BROWSERS.join(', ')}, all.`);\n }\n return [value];\n}\n\nexport function resolveStrategy(value: string | undefined): SyncStrategy | undefined {\n if (!value) {\n return undefined;\n }\n if (!(SYNC_STRATEGIES as readonly string[]).includes(value)) {\n throw new Error(`Unknown strategy \"${value}\". Use one of: ${SYNC_STRATEGIES.join(', ')}.`);\n }\n return value as SyncStrategy;\n}\n\n/** Applies the CLI overrides on top of the stored config. */\nexport function buildSyncConfig(config: CliConfig, options: SyncCommandOptions): CliConfig {\n const enabled = new Set(resolveBrowsers(options.browser));\n return {\n ...config,\n profile: options.profile ?? config.profile,\n browsers: {\n chrome: {\n ...config.browsers.chrome,\n enabled: enabled.has('chrome') && config.browsers.chrome.enabled !== false,\n },\n edge: {\n ...config.browsers.edge,\n enabled: enabled.has('edge') && config.browsers.edge.enabled !== false,\n },\n },\n };\n}\n\nexport function runSyncCommand(context: CliContext, options: SyncCommandOptions = {}): number {\n const targets = resolveTargets(options);\n const strategy = resolveStrategy(options.strategy) ?? context.config.sync.strategy;\n const config = buildSyncConfig(context.config, options);\n\n const report = runSync({\n config,\n targets,\n dryRun: options.dryRun,\n force: options.force,\n strategy,\n logger: context.logger,\n browserRunning: options.browserRunning,\n now: options.now,\n platform: options.platform,\n });\n\n if (!options.dryRun && report.exportFiles.length > 0) {\n const removed = pruneExports(context.config.exportDir, resolveExportRetention(context.config));\n if (removed.length > 0) {\n context.logger.info('Pruned old exports', { removed: removed.length });\n }\n }\n\n if (options.json) {\n context.io.out(JSON.stringify(report, null, 2));\n } else {\n for (const line of formatSyncReport(report)) {\n context.io.out(line);\n }\n }\n\n const failed = report.warnings.some((warning) => warning.startsWith('Backup failed'));\n return failed ? 1 : 0;\n}\n\nexport function formatSyncReport(report: SyncReport): string[] {\n const lines: string[] = [];\n const kinds = [\n report.targets.bookmarks ? 'bookmarks' : null,\n report.targets.history ? 'history' : null,\n ]\n .filter((kind): kind is string => kind !== null)\n .join(' + ');\n\n lines.push(`CrossSync sync (${report.strategy}, ${kinds})${report.dryRun ? ' [dry run]' : ''}`);\n\n for (const outcome of report.browsers) {\n const parts = [`${outcome.browser}/${outcome.profile}`];\n if (report.targets.bookmarks) {\n parts.push(`${outcome.bookmarksRead} bookmark nodes`);\n }\n if (report.targets.history) {\n parts.push(`${outcome.historyRead} history entries`);\n }\n if (outcome.writtenBack) {\n parts.push('written back');\n } else if (outcome.skippedWriteBackReason) {\n parts.push(`write-back skipped (${outcome.skippedWriteBackReason})`);\n }\n lines.push(` ${parts.join(', ')}`);\n }\n\n if (report.bookmarkMerge) {\n const { added, updated, identical, total } = report.bookmarkMerge.stats;\n lines.push(\n ` merged bookmarks: ${total} nodes (added ${added}, updated ${updated}, identical ${identical}, conflicts ${report.bookmarkMerge.conflicts.length})`,\n );\n }\n if (report.historyMerge) {\n lines.push(\n ` merged history: ${report.historyMerge.stats.total} entries (${report.historyMerge.stats.duplicates} duplicates collapsed)`,\n );\n }\n if (report.backup) {\n lines.push(` backup: ${report.backup.dir}`);\n }\n for (const file of report.exportFiles) {\n lines.push(` export: ${file}`);\n }\n if (report.warnings.length > 0) {\n lines.push(' warnings:');\n for (const warning of report.warnings) {\n lines.push(` - ${warning}`);\n }\n }\n\n return lines;\n}\n","import path from 'path';\n\nimport type { LogEntry } from '@crosssync/core';\nimport { clearLogFile, readLogEntries } from '@crosssync/core';\nimport type { LogLevel } from '@crosssync/shared';\nimport { isLogLevel, LOG_FILE_NAME } from '@crosssync/shared';\n\nimport type { CliContext } from '../context';\n\nexport interface LogsCommandOptions {\n /** Maximum number of entries to print (most recent last). */\n limit?: number;\n level?: string;\n clear?: boolean;\n json?: boolean;\n}\n\nexport function currentLogFile(context: CliContext): string {\n return path.join(context.config.logDir, LOG_FILE_NAME);\n}\n\nexport function runLogsCommand(context: CliContext, options: LogsCommandOptions = {}): number {\n const file = currentLogFile(context);\n\n if (options.clear) {\n clearLogFile(file);\n context.io.out(`Cleared ${file}`);\n return 0;\n }\n\n if (options.level !== undefined && !isLogLevel(options.level)) {\n context.io.err(`Unknown log level \"${options.level}\".`);\n return 1;\n }\n\n const entries = readLogEntries(file, {\n limit: options.limit,\n level: options.level as LogLevel | undefined,\n });\n\n if (entries.length === 0) {\n context.io.out(`No log entries in ${file}.`);\n return 0;\n }\n\n if (options.json) {\n context.io.out(JSON.stringify(entries, null, 2));\n return 0;\n }\n\n for (const entry of entries) {\n context.io.out(formatLogEntry(entry));\n }\n return 0;\n}\n\nexport function formatLogEntry(entry: LogEntry): string {\n const timestamp = new Date(entry.timestamp).toISOString();\n const meta =\n entry.meta && Object.keys(entry.meta).length > 0 ? ` ${JSON.stringify(entry.meta)}` : '';\n return `${timestamp} [${entry.level.toUpperCase()}] ${entry.message}${meta}`;\n}\n","import path from 'path';\n\nimport { LOG_FILE_NAME, pathExists } from '@crosssync/shared';\nimport { createBrowserReader, getRunningBrowsers, listBackups } from '@crosssync/core';\n\nimport { CLI_VERSION } from '../constants';\nimport type { CliContext } from '../context';\nimport { listExports } from './export';\n\nexport interface StatusCommandOptions {\n json?: boolean;\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface BrowserProfileStatus {\n profile: string;\n bookmarks: boolean;\n history: boolean;\n}\n\nexport interface BrowserStatusReport {\n browser: string;\n dataDir: string;\n exists: boolean;\n running: boolean;\n profiles: BrowserProfileStatus[];\n}\n\nexport interface StatusReport {\n version: string;\n configFile: string;\n dataDir: string;\n logLevel: string;\n logFile: string;\n profile: string;\n schedule: { installed: boolean; expression: string };\n browsers: BrowserStatusReport[];\n backups: { count: number; latest: string | null; dir: string };\n exports: { count: number; latest: string | null; dir: string };\n}\n\n/** Pure-ish collector used by both `status` and its tests. */\nexport function buildStatusReport(\n context: CliContext,\n options: StatusCommandOptions = {},\n): StatusReport {\n const { config, dirs } = context;\n const running = new Map(\n getRunningBrowsers({ platform: options.platform }).map((status) => [\n status.browser,\n status.running,\n ]),\n );\n\n const browsers: BrowserStatusReport[] = [];\n for (const browser of Object.keys(config.browsers) as (keyof typeof config.browsers)[]) {\n const browserConfig = config.browsers[browser];\n const dataDir = browserConfig.dataDir ?? '';\n const profiles: BrowserProfileStatus[] = [];\n\n if (browserConfig.enabled) {\n const reader = createReader(browser, browserConfig.dataDir, options);\n for (const profile of reader.resolveProfiles(config.profile)) {\n profiles.push({\n profile,\n bookmarks: pathExists(reader.bookmarksPath(profile)),\n history: pathExists(reader.historyPath(profile)),\n });\n }\n browsers.push({\n browser,\n dataDir: reader.dataDir,\n exists: pathExists(reader.dataDir),\n running: running.get(browser) ?? false,\n profiles,\n });\n } else {\n browsers.push({\n browser,\n dataDir,\n exists: false,\n running: running.get(browser) ?? false,\n profiles: [],\n });\n }\n }\n\n const backups = listBackups(config.backupDir);\n const exports = listExports(config.exportDir, 1);\n\n return {\n version: CLI_VERSION,\n configFile: dirs.configFile,\n dataDir: config.dataDir,\n logLevel: config.logLevel,\n logFile: path.join(config.logDir, LOG_FILE_NAME),\n profile: config.profile,\n schedule: { ...config.schedule },\n browsers,\n backups: {\n count: backups.length,\n latest: backups.length > 0 ? backups[0].dir : null,\n dir: config.backupDir,\n },\n exports: { count: exports.count, latest: exports.latest, dir: config.exportDir },\n };\n}\n\nfunction createReader(\n browser: keyof CliContext['config']['browsers'],\n dataDir: string | undefined,\n options: StatusCommandOptions,\n) {\n return createBrowserReader(browser, {\n dataDir,\n platform: options.platform,\n env: options.env,\n });\n}\n\nexport function runStatusCommand(context: CliContext, options: StatusCommandOptions = {}): number {\n const report = buildStatusReport(context, options);\n\n if (options.json) {\n context.io.out(JSON.stringify(report, null, 2));\n return 0;\n }\n\n const io = context.io;\n io.out(`CrossSync ${report.version}`);\n io.out(` config: ${report.configFile}`);\n io.out(` data dir: ${report.dataDir}`);\n io.out(` profile: ${report.profile}`);\n io.out(` log level: ${report.logLevel}`);\n io.out(` log file: ${report.logFile}`);\n io.out(\n ` schedule: ${report.schedule.installed ? `installed (${report.schedule.expression})` : 'not installed'}`,\n );\n\n io.out(' browsers:');\n for (const entry of report.browsers) {\n io.out(\n ` ${entry.browser}: ${entry.exists ? entry.dataDir : `not found (${entry.dataDir})`}` +\n `${entry.running ? ' [running]' : ''}`,\n );\n for (const profile of entry.profiles) {\n const files = [\n profile.bookmarks ? 'Bookmarks' : null,\n profile.history ? 'History' : null,\n ].filter((name): name is string => name !== null);\n io.out(` ${profile.profile}: ${files.length > 0 ? files.join(', ') : 'no data files'}`);\n }\n }\n\n io.out(` backups: ${report.backups.count} (latest: ${report.backups.latest ?? 'none'})`);\n io.out(` exports: ${report.exports.count} (latest: ${report.exports.latest ?? 'none'})`);\n return 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,8CAAAA,UAAA;AAAA;AAGA,QAAMC,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,cAAM,OAAO;AAEb,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAC7B,aAAK,OAAO;AACZ,aAAK,WAAW;AAChB,aAAK,cAAc;AAAA,MACrB;AAAA,IACF;AAKA,QAAMC,wBAAN,cAAmCD,gBAAe;AAAA;AAAA;AAAA;AAAA;AAAA,MAKhD,YAAY,SAAS;AACnB,cAAM,GAAG,6BAA6B,OAAO;AAE7C,cAA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,IAAI,OAAiB,QAAQ,MAAY;AACvD,eAAa,EAAE,MAAM,IAAI;AAC3B;AAGO,IAAM,UAAU;AAChB,IAAM,UAAU;AAEvB,IAAI,QAAQ,SAAS,QAAQ;AAC3B,MAAI;AACN;","names":["exports","CommanderError","InvalidArgumentError","exports","InvalidArgumentError","Argument","exports","Help","cmd","exports","InvalidArgumentError","Option","str","exports","exports","path","fs","process","Argument","CommanderError","Help","Option","Command","option","exports","Argument","Command","CommanderError","InvalidArgumentError","Help","Option","exports","exports","exports","exports","resolveExportRetention","createDefaultConfig","exports","readJsonFile","writeJsonFileSafe","pathExists","ensureDir","resolveHomeDir","resolveCrossSyncDirs","isLogLevel","isBrowserName","isCliConfig","exports","exports","exports","readLogEntries","clearLogFile","Logger","exports","getRunningBrowsers","exports","createBrowserReader","exports","createConfiguredBrowserReaders","exports","mergeBookmarkFiles","mergeHistory","exports","formatBackupId","createBackup","listBackups","pruneBackups","exports","runSync","describeError","exports","commander","config","path","import_shared","import_core","import_shared","import_core","import_shared","import_shared","import_shared","import_path","import_shared","program","path","program","fs","os","import_fs","import_path","import_shared","path","fs","import_shared","import_path","import_shared","import_core","import_fs","import_path","fs","path","import_shared","import_core","path","import_path","import_core","import_shared","path","import_path","import_shared","import_core","exports","path","program"]}
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/commander/lib/error.js","../../../node_modules/commander/lib/argument.js","../../../node_modules/commander/lib/help.js","../../../node_modules/commander/lib/option.js","../../../node_modules/commander/lib/suggestSimilar.js","../../../node_modules/commander/lib/command.js","../../../node_modules/commander/index.js","../../shared/src/constants.ts","../../shared/src/bookmark.ts","../../shared/src/history.ts","../../shared/src/config.ts","../../shared/src/utils.ts","../../shared/src/index.ts","../../core/src/constants.ts","../../core/src/logger.ts","../../core/src/browser-status.ts","../../core/src/readers/chromium.ts","../../core/src/readers/index.ts","../../core/src/merger.ts","../../core/src/backup.ts","../../core/src/sync.ts","../../core/src/index.ts","../src/index.ts","../../../node_modules/commander/esm.mjs","../src/constants.ts","../src/context.ts","../src/commands/backup.ts","../src/commands/read.ts","../src/commands/config.ts","../src/commands/cron.ts","../src/cron/index.ts","../src/cron/linux.ts","../src/cron/invocation.ts","../src/cron/runner.ts","../src/cron/schedule.ts","../src/cron/macos.ts","../src/cron/windows.ts","../src/commands/export.ts","../src/export-files.ts","../src/commands/sync.ts","../src/commands/logs.ts","../src/commands/profiles.ts","../src/commands/status.ts"],"sourcesContent":["/**\n * CommanderError class\n */\nclass CommanderError extends Error {\n /**\n * Constructs the CommanderError class\n * @param {number} exitCode suggested exit code which could be used with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n */\n constructor(exitCode, code, message) {\n super(message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n this.code = code;\n this.exitCode = exitCode;\n this.nestedError = undefined;\n }\n}\n\n/**\n * InvalidArgumentError class\n */\nclass InvalidArgumentError extends CommanderError {\n /**\n * Constructs the InvalidArgumentError class\n * @param {string} [message] explanation of why argument is invalid\n */\n constructor(message) {\n super(1, 'commander.invalidArgument', message);\n // properly capture stack trace in Node.js\n Error.captureStackTrace(this, this.constructor);\n this.name = this.constructor.name;\n }\n}\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Argument {\n /**\n * Initialize a new command argument with the given name and description.\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @param {string} name\n * @param {string} [description]\n */\n\n constructor(name, description) {\n this.description = description || '';\n this.variadic = false;\n this.parseArg = undefined;\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.argChoices = undefined;\n\n switch (name[0]) {\n case '<': // e.g. <required>\n this.required = true;\n this._name = name.slice(1, -1);\n break;\n case '[': // e.g. [optional]\n this.required = false;\n this._name = name.slice(1, -1);\n break;\n default:\n this.required = true;\n this._name = name;\n break;\n }\n\n if (this._name.length > 3 && this._name.slice(-3) === '...') {\n this.variadic = true;\n this._name = this._name.slice(0, -3);\n }\n }\n\n /**\n * Return argument name.\n *\n * @return {string}\n */\n\n name() {\n return this._name;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Argument}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI command arguments into argument values.\n *\n * @param {Function} [fn]\n * @return {Argument}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Only allow argument value to be one of choices.\n *\n * @param {string[]} values\n * @return {Argument}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Make argument required.\n *\n * @returns {Argument}\n */\n argRequired() {\n this.required = true;\n return this;\n }\n\n /**\n * Make argument optional.\n *\n * @returns {Argument}\n */\n argOptional() {\n this.required = false;\n return this;\n }\n}\n\n/**\n * Takes an argument and returns its human readable equivalent for help usage.\n *\n * @param {Argument} arg\n * @return {string}\n * @private\n */\n\nfunction humanReadableArgName(arg) {\n const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');\n\n return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';\n}\n\nexports.Argument = Argument;\nexports.humanReadableArgName = humanReadableArgName;\n","const { humanReadableArgName } = require('./argument.js');\n\n/**\n * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`\n * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types\n * @typedef { import(\"./argument.js\").Argument } Argument\n * @typedef { import(\"./command.js\").Command } Command\n * @typedef { import(\"./option.js\").Option } Option\n */\n\n// Although this is a class, methods are static in style to allow override using subclass or just functions.\nclass Help {\n constructor() {\n this.helpWidth = undefined;\n this.sortSubcommands = false;\n this.sortOptions = false;\n this.showGlobalOptions = false;\n }\n\n /**\n * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.\n *\n * @param {Command} cmd\n * @returns {Command[]}\n */\n\n visibleCommands(cmd) {\n const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);\n const helpCommand = cmd._getHelpCommand();\n if (helpCommand && !helpCommand._hidden) {\n visibleCommands.push(helpCommand);\n }\n if (this.sortSubcommands) {\n visibleCommands.sort((a, b) => {\n // @ts-ignore: because overloaded return type\n return a.name().localeCompare(b.name());\n });\n }\n return visibleCommands;\n }\n\n /**\n * Compare options for sort.\n *\n * @param {Option} a\n * @param {Option} b\n * @returns {number}\n */\n compareOptions(a, b) {\n const getSortKey = (option) => {\n // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.\n return option.short\n ? option.short.replace(/^-/, '')\n : option.long.replace(/^--/, '');\n };\n return getSortKey(a).localeCompare(getSortKey(b));\n }\n\n /**\n * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleOptions(cmd) {\n const visibleOptions = cmd.options.filter((option) => !option.hidden);\n // Built-in help option.\n const helpOption = cmd._getHelpOption();\n if (helpOption && !helpOption.hidden) {\n // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.\n const removeShort = helpOption.short && cmd._findOption(helpOption.short);\n const removeLong = helpOption.long && cmd._findOption(helpOption.long);\n if (!removeShort && !removeLong) {\n visibleOptions.push(helpOption); // no changes needed\n } else if (helpOption.long && !removeLong) {\n visibleOptions.push(\n cmd.createOption(helpOption.long, helpOption.description),\n );\n } else if (helpOption.short && !removeShort) {\n visibleOptions.push(\n cmd.createOption(helpOption.short, helpOption.description),\n );\n }\n }\n if (this.sortOptions) {\n visibleOptions.sort(this.compareOptions);\n }\n return visibleOptions;\n }\n\n /**\n * Get an array of the visible global options. (Not including help.)\n *\n * @param {Command} cmd\n * @returns {Option[]}\n */\n\n visibleGlobalOptions(cmd) {\n if (!this.showGlobalOptions) return [];\n\n const globalOptions = [];\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n const visibleOptions = ancestorCmd.options.filter(\n (option) => !option.hidden,\n );\n globalOptions.push(...visibleOptions);\n }\n if (this.sortOptions) {\n globalOptions.sort(this.compareOptions);\n }\n return globalOptions;\n }\n\n /**\n * Get an array of the arguments if any have a description.\n *\n * @param {Command} cmd\n * @returns {Argument[]}\n */\n\n visibleArguments(cmd) {\n // Side effect! Apply the legacy descriptions before the arguments are displayed.\n if (cmd._argsDescription) {\n cmd.registeredArguments.forEach((argument) => {\n argument.description =\n argument.description || cmd._argsDescription[argument.name()] || '';\n });\n }\n\n // If there are any arguments with a description then return all the arguments.\n if (cmd.registeredArguments.find((argument) => argument.description)) {\n return cmd.registeredArguments;\n }\n return [];\n }\n\n /**\n * Get the command term to show in the list of subcommands.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandTerm(cmd) {\n // Legacy. Ignores custom usage string, and nested commands.\n const args = cmd.registeredArguments\n .map((arg) => humanReadableArgName(arg))\n .join(' ');\n return (\n cmd._name +\n (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +\n (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option\n (args ? ' ' + args : '')\n );\n }\n\n /**\n * Get the option term to show in the list of options.\n *\n * @param {Option} option\n * @returns {string}\n */\n\n optionTerm(option) {\n return option.flags;\n }\n\n /**\n * Get the argument term to show in the list of arguments.\n *\n * @param {Argument} argument\n * @returns {string}\n */\n\n argumentTerm(argument) {\n return argument.name();\n }\n\n /**\n * Get the longest command term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestSubcommandTermLength(cmd, helper) {\n return helper.visibleCommands(cmd).reduce((max, command) => {\n return Math.max(max, helper.subcommandTerm(command).length);\n }, 0);\n }\n\n /**\n * Get the longest option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestOptionTermLength(cmd, helper) {\n return helper.visibleOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest global option term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestGlobalOptionTermLength(cmd, helper) {\n return helper.visibleGlobalOptions(cmd).reduce((max, option) => {\n return Math.max(max, helper.optionTerm(option).length);\n }, 0);\n }\n\n /**\n * Get the longest argument term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n longestArgumentTermLength(cmd, helper) {\n return helper.visibleArguments(cmd).reduce((max, argument) => {\n return Math.max(max, helper.argumentTerm(argument).length);\n }, 0);\n }\n\n /**\n * Get the command usage to be displayed at the top of the built-in help.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandUsage(cmd) {\n // Usage\n let cmdName = cmd._name;\n if (cmd._aliases[0]) {\n cmdName = cmdName + '|' + cmd._aliases[0];\n }\n let ancestorCmdNames = '';\n for (\n let ancestorCmd = cmd.parent;\n ancestorCmd;\n ancestorCmd = ancestorCmd.parent\n ) {\n ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;\n }\n return ancestorCmdNames + cmdName + ' ' + cmd.usage();\n }\n\n /**\n * Get the description for the command.\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n commandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.description();\n }\n\n /**\n * Get the subcommand summary to show in the list of subcommands.\n * (Fallback to description for backwards compatibility.)\n *\n * @param {Command} cmd\n * @returns {string}\n */\n\n subcommandDescription(cmd) {\n // @ts-ignore: because overloaded return type\n return cmd.summary() || cmd.description();\n }\n\n /**\n * Get the option description to show in the list of options.\n *\n * @param {Option} option\n * @return {string}\n */\n\n optionDescription(option) {\n const extraInfo = [];\n\n if (option.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (option.defaultValue !== undefined) {\n // default for boolean and negated more for programmer than end user,\n // but show true/false for boolean option as may be for hand-rolled env or config processing.\n const showDefault =\n option.required ||\n option.optional ||\n (option.isBoolean() && typeof option.defaultValue === 'boolean');\n if (showDefault) {\n extraInfo.push(\n `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,\n );\n }\n }\n // preset for boolean and negated are more for programmer than end user\n if (option.presetArg !== undefined && option.optional) {\n extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);\n }\n if (option.envVar !== undefined) {\n extraInfo.push(`env: ${option.envVar}`);\n }\n if (extraInfo.length > 0) {\n return `${option.description} (${extraInfo.join(', ')})`;\n }\n\n return option.description;\n }\n\n /**\n * Get the argument description to show in the list of arguments.\n *\n * @param {Argument} argument\n * @return {string}\n */\n\n argumentDescription(argument) {\n const extraInfo = [];\n if (argument.argChoices) {\n extraInfo.push(\n // use stringify to match the display of the default value\n `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,\n );\n }\n if (argument.defaultValue !== undefined) {\n extraInfo.push(\n `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,\n );\n }\n if (extraInfo.length > 0) {\n const extraDescripton = `(${extraInfo.join(', ')})`;\n if (argument.description) {\n return `${argument.description} ${extraDescripton}`;\n }\n return extraDescripton;\n }\n return argument.description;\n }\n\n /**\n * Generate the built-in help text.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {string}\n */\n\n formatHelp(cmd, helper) {\n const termWidth = helper.padWidth(cmd, helper);\n const helpWidth = helper.helpWidth || 80;\n const itemIndentWidth = 2;\n const itemSeparatorWidth = 2; // between term and description\n function formatItem(term, description) {\n if (description) {\n const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;\n return helper.wrap(\n fullText,\n helpWidth - itemIndentWidth,\n termWidth + itemSeparatorWidth,\n );\n }\n return term;\n }\n function formatList(textArray) {\n return textArray.join('\\n').replace(/^/gm, ' '.repeat(itemIndentWidth));\n }\n\n // Usage\n let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];\n\n // Description\n const commandDescription = helper.commandDescription(cmd);\n if (commandDescription.length > 0) {\n output = output.concat([\n helper.wrap(commandDescription, helpWidth, 0),\n '',\n ]);\n }\n\n // Arguments\n const argumentList = helper.visibleArguments(cmd).map((argument) => {\n return formatItem(\n helper.argumentTerm(argument),\n helper.argumentDescription(argument),\n );\n });\n if (argumentList.length > 0) {\n output = output.concat(['Arguments:', formatList(argumentList), '']);\n }\n\n // Options\n const optionList = helper.visibleOptions(cmd).map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (optionList.length > 0) {\n output = output.concat(['Options:', formatList(optionList), '']);\n }\n\n if (this.showGlobalOptions) {\n const globalOptionList = helper\n .visibleGlobalOptions(cmd)\n .map((option) => {\n return formatItem(\n helper.optionTerm(option),\n helper.optionDescription(option),\n );\n });\n if (globalOptionList.length > 0) {\n output = output.concat([\n 'Global Options:',\n formatList(globalOptionList),\n '',\n ]);\n }\n }\n\n // Commands\n const commandList = helper.visibleCommands(cmd).map((cmd) => {\n return formatItem(\n helper.subcommandTerm(cmd),\n helper.subcommandDescription(cmd),\n );\n });\n if (commandList.length > 0) {\n output = output.concat(['Commands:', formatList(commandList), '']);\n }\n\n return output.join('\\n');\n }\n\n /**\n * Calculate the pad width from the maximum term length.\n *\n * @param {Command} cmd\n * @param {Help} helper\n * @returns {number}\n */\n\n padWidth(cmd, helper) {\n return Math.max(\n helper.longestOptionTermLength(cmd, helper),\n helper.longestGlobalOptionTermLength(cmd, helper),\n helper.longestSubcommandTermLength(cmd, helper),\n helper.longestArgumentTermLength(cmd, helper),\n );\n }\n\n /**\n * Wrap the given string to width characters per line, with lines after the first indented.\n * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.\n *\n * @param {string} str\n * @param {number} width\n * @param {number} indent\n * @param {number} [minColumnWidth=40]\n * @return {string}\n *\n */\n\n wrap(str, width, indent, minColumnWidth = 40) {\n // Full \\s characters, minus the linefeeds.\n const indents =\n ' \\\\f\\\\t\\\\v\\u00a0\\u1680\\u2000-\\u200a\\u202f\\u205f\\u3000\\ufeff';\n // Detect manually wrapped and indented strings by searching for line break followed by spaces.\n const manualIndent = new RegExp(`[\\\\n][${indents}]+`);\n if (str.match(manualIndent)) return str;\n // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).\n const columnWidth = width - indent;\n if (columnWidth < minColumnWidth) return str;\n\n const leadingStr = str.slice(0, indent);\n const columnText = str.slice(indent).replace('\\r\\n', '\\n');\n const indentString = ' '.repeat(indent);\n const zeroWidthSpace = '\\u200B';\n const breaks = `\\\\s${zeroWidthSpace}`;\n // Match line end (so empty lines don't collapse),\n // or as much text as will fit in column, or excess text up to first break.\n const regex = new RegExp(\n `\\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`,\n 'g',\n );\n const lines = columnText.match(regex) || [];\n return (\n leadingStr +\n lines\n .map((line, i) => {\n if (line === '\\n') return ''; // preserve empty lines\n return (i > 0 ? indentString : '') + line.trimEnd();\n })\n .join('\\n')\n );\n }\n}\n\nexports.Help = Help;\n","const { InvalidArgumentError } = require('./error.js');\n\nclass Option {\n /**\n * Initialize a new `Option` with the given `flags` and `description`.\n *\n * @param {string} flags\n * @param {string} [description]\n */\n\n constructor(flags, description) {\n this.flags = flags;\n this.description = description || '';\n\n this.required = flags.includes('<'); // A value must be supplied when the option is specified.\n this.optional = flags.includes('['); // A value is optional when the option is specified.\n // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument\n this.variadic = /\\w\\.\\.\\.[>\\]]$/.test(flags); // The option can take multiple values.\n this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.\n const optionFlags = splitOptionFlags(flags);\n this.short = optionFlags.shortFlag;\n this.long = optionFlags.longFlag;\n this.negate = false;\n if (this.long) {\n this.negate = this.long.startsWith('--no-');\n }\n this.defaultValue = undefined;\n this.defaultValueDescription = undefined;\n this.presetArg = undefined;\n this.envVar = undefined;\n this.parseArg = undefined;\n this.hidden = false;\n this.argChoices = undefined;\n this.conflictsWith = [];\n this.implied = undefined;\n }\n\n /**\n * Set the default value, and optionally supply the description to be displayed in the help.\n *\n * @param {*} value\n * @param {string} [description]\n * @return {Option}\n */\n\n default(value, description) {\n this.defaultValue = value;\n this.defaultValueDescription = description;\n return this;\n }\n\n /**\n * Preset to use when option used without option-argument, especially optional but also boolean and negated.\n * The custom processing (parseArg) is called.\n *\n * @example\n * new Option('--color').default('GREYSCALE').preset('RGB');\n * new Option('--donate [amount]').preset('20').argParser(parseFloat);\n *\n * @param {*} arg\n * @return {Option}\n */\n\n preset(arg) {\n this.presetArg = arg;\n return this;\n }\n\n /**\n * Add option name(s) that conflict with this option.\n * An error will be displayed if conflicting options are found during parsing.\n *\n * @example\n * new Option('--rgb').conflicts('cmyk');\n * new Option('--js').conflicts(['ts', 'jsx']);\n *\n * @param {(string | string[])} names\n * @return {Option}\n */\n\n conflicts(names) {\n this.conflictsWith = this.conflictsWith.concat(names);\n return this;\n }\n\n /**\n * Specify implied option values for when this option is set and the implied options are not.\n *\n * The custom processing (parseArg) is not called on the implied values.\n *\n * @example\n * program\n * .addOption(new Option('--log', 'write logging information to file'))\n * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));\n *\n * @param {object} impliedOptionValues\n * @return {Option}\n */\n implies(impliedOptionValues) {\n let newImplied = impliedOptionValues;\n if (typeof impliedOptionValues === 'string') {\n // string is not documented, but easy mistake and we can do what user probably intended.\n newImplied = { [impliedOptionValues]: true };\n }\n this.implied = Object.assign(this.implied || {}, newImplied);\n return this;\n }\n\n /**\n * Set environment variable to check for option value.\n *\n * An environment variable is only used if when processed the current option value is\n * undefined, or the source of the current value is 'default' or 'config' or 'env'.\n *\n * @param {string} name\n * @return {Option}\n */\n\n env(name) {\n this.envVar = name;\n return this;\n }\n\n /**\n * Set the custom handler for processing CLI option arguments into option values.\n *\n * @param {Function} [fn]\n * @return {Option}\n */\n\n argParser(fn) {\n this.parseArg = fn;\n return this;\n }\n\n /**\n * Whether the option is mandatory and must have a value after parsing.\n *\n * @param {boolean} [mandatory=true]\n * @return {Option}\n */\n\n makeOptionMandatory(mandatory = true) {\n this.mandatory = !!mandatory;\n return this;\n }\n\n /**\n * Hide option in help.\n *\n * @param {boolean} [hide=true]\n * @return {Option}\n */\n\n hideHelp(hide = true) {\n this.hidden = !!hide;\n return this;\n }\n\n /**\n * @package\n */\n\n _concatValue(value, previous) {\n if (previous === this.defaultValue || !Array.isArray(previous)) {\n return [value];\n }\n\n return previous.concat(value);\n }\n\n /**\n * Only allow option value to be one of choices.\n *\n * @param {string[]} values\n * @return {Option}\n */\n\n choices(values) {\n this.argChoices = values.slice();\n this.parseArg = (arg, previous) => {\n if (!this.argChoices.includes(arg)) {\n throw new InvalidArgumentError(\n `Allowed choices are ${this.argChoices.join(', ')}.`,\n );\n }\n if (this.variadic) {\n return this._concatValue(arg, previous);\n }\n return arg;\n };\n return this;\n }\n\n /**\n * Return option name.\n *\n * @return {string}\n */\n\n name() {\n if (this.long) {\n return this.long.replace(/^--/, '');\n }\n return this.short.replace(/^-/, '');\n }\n\n /**\n * Return option name, in a camelcase format that can be used\n * as a object attribute key.\n *\n * @return {string}\n */\n\n attributeName() {\n return camelcase(this.name().replace(/^no-/, ''));\n }\n\n /**\n * Check if `arg` matches the short or long flag.\n *\n * @param {string} arg\n * @return {boolean}\n * @package\n */\n\n is(arg) {\n return this.short === arg || this.long === arg;\n }\n\n /**\n * Return whether a boolean option.\n *\n * Options are one of boolean, negated, required argument, or optional argument.\n *\n * @return {boolean}\n * @package\n */\n\n isBoolean() {\n return !this.required && !this.optional && !this.negate;\n }\n}\n\n/**\n * This class is to make it easier to work with dual options, without changing the existing\n * implementation. We support separate dual options for separate positive and negative options,\n * like `--build` and `--no-build`, which share a single option value. This works nicely for some\n * use cases, but is tricky for others where we want separate behaviours despite\n * the single shared option value.\n */\nclass DualOptions {\n /**\n * @param {Option[]} options\n */\n constructor(options) {\n this.positiveOptions = new Map();\n this.negativeOptions = new Map();\n this.dualOptions = new Set();\n options.forEach((option) => {\n if (option.negate) {\n this.negativeOptions.set(option.attributeName(), option);\n } else {\n this.positiveOptions.set(option.attributeName(), option);\n }\n });\n this.negativeOptions.forEach((value, key) => {\n if (this.positiveOptions.has(key)) {\n this.dualOptions.add(key);\n }\n });\n }\n\n /**\n * Did the value come from the option, and not from possible matching dual option?\n *\n * @param {*} value\n * @param {Option} option\n * @returns {boolean}\n */\n valueFromOption(value, option) {\n const optionKey = option.attributeName();\n if (!this.dualOptions.has(optionKey)) return true;\n\n // Use the value to deduce if (probably) came from the option.\n const preset = this.negativeOptions.get(optionKey).presetArg;\n const negativeValue = preset !== undefined ? preset : false;\n return option.negate === (negativeValue === value);\n }\n}\n\n/**\n * Convert string from kebab-case to camelCase.\n *\n * @param {string} str\n * @return {string}\n * @private\n */\n\nfunction camelcase(str) {\n return str.split('-').reduce((str, word) => {\n return str + word[0].toUpperCase() + word.slice(1);\n });\n}\n\n/**\n * Split the short and long flag out of something like '-m,--mixed <value>'\n *\n * @private\n */\n\nfunction splitOptionFlags(flags) {\n let shortFlag;\n let longFlag;\n // Use original very loose parsing to maintain backwards compatibility for now,\n // which allowed for example unintended `-sw, --short-word` [sic].\n const flagParts = flags.split(/[ |,]+/);\n if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1]))\n shortFlag = flagParts.shift();\n longFlag = flagParts.shift();\n // Add support for lone short flag without significantly changing parsing!\n if (!shortFlag && /^-[^-]$/.test(longFlag)) {\n shortFlag = longFlag;\n longFlag = undefined;\n }\n return { shortFlag, longFlag };\n}\n\nexports.Option = Option;\nexports.DualOptions = DualOptions;\n","const maxDistance = 3;\n\nfunction editDistance(a, b) {\n // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance\n // Calculating optimal string alignment distance, no substring is edited more than once.\n // (Simple implementation.)\n\n // Quick early exit, return worst case.\n if (Math.abs(a.length - b.length) > maxDistance)\n return Math.max(a.length, b.length);\n\n // distance between prefix substrings of a and b\n const d = [];\n\n // pure deletions turn a into empty string\n for (let i = 0; i <= a.length; i++) {\n d[i] = [i];\n }\n // pure insertions turn empty string into b\n for (let j = 0; j <= b.length; j++) {\n d[0][j] = j;\n }\n\n // fill matrix\n for (let j = 1; j <= b.length; j++) {\n for (let i = 1; i <= a.length; i++) {\n let cost = 1;\n if (a[i - 1] === b[j - 1]) {\n cost = 0;\n } else {\n cost = 1;\n }\n d[i][j] = Math.min(\n d[i - 1][j] + 1, // deletion\n d[i][j - 1] + 1, // insertion\n d[i - 1][j - 1] + cost, // substitution\n );\n // transposition\n if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {\n d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);\n }\n }\n }\n\n return d[a.length][b.length];\n}\n\n/**\n * Find close matches, restricted to same number of edits.\n *\n * @param {string} word\n * @param {string[]} candidates\n * @returns {string}\n */\n\nfunction suggestSimilar(word, candidates) {\n if (!candidates || candidates.length === 0) return '';\n // remove possible duplicates\n candidates = Array.from(new Set(candidates));\n\n const searchingOptions = word.startsWith('--');\n if (searchingOptions) {\n word = word.slice(2);\n candidates = candidates.map((candidate) => candidate.slice(2));\n }\n\n let similar = [];\n let bestDistance = maxDistance;\n const minSimilarity = 0.4;\n candidates.forEach((candidate) => {\n if (candidate.length <= 1) return; // no one character guesses\n\n const distance = editDistance(word, candidate);\n const length = Math.max(word.length, candidate.length);\n const similarity = (length - distance) / length;\n if (similarity > minSimilarity) {\n if (distance < bestDistance) {\n // better edit distance, throw away previous worse matches\n bestDistance = distance;\n similar = [candidate];\n } else if (distance === bestDistance) {\n similar.push(candidate);\n }\n }\n });\n\n similar.sort((a, b) => a.localeCompare(b));\n if (searchingOptions) {\n similar = similar.map((candidate) => `--${candidate}`);\n }\n\n if (similar.length > 1) {\n return `\\n(Did you mean one of ${similar.join(', ')}?)`;\n }\n if (similar.length === 1) {\n return `\\n(Did you mean ${similar[0]}?)`;\n }\n return '';\n}\n\nexports.suggestSimilar = suggestSimilar;\n","const EventEmitter = require('node:events').EventEmitter;\nconst childProcess = require('node:child_process');\nconst path = require('node:path');\nconst fs = require('node:fs');\nconst process = require('node:process');\n\nconst { Argument, humanReadableArgName } = require('./argument.js');\nconst { CommanderError } = require('./error.js');\nconst { Help } = require('./help.js');\nconst { Option, DualOptions } = require('./option.js');\nconst { suggestSimilar } = require('./suggestSimilar');\n\nclass Command extends EventEmitter {\n /**\n * Initialize a new `Command`.\n *\n * @param {string} [name]\n */\n\n constructor(name) {\n super();\n /** @type {Command[]} */\n this.commands = [];\n /** @type {Option[]} */\n this.options = [];\n this.parent = null;\n this._allowUnknownOption = false;\n this._allowExcessArguments = true;\n /** @type {Argument[]} */\n this.registeredArguments = [];\n this._args = this.registeredArguments; // deprecated old name\n /** @type {string[]} */\n this.args = []; // cli args with options removed\n this.rawArgs = [];\n this.processedArgs = []; // like .args but after custom processing and collecting variadic\n this._scriptPath = null;\n this._name = name || '';\n this._optionValues = {};\n this._optionValueSources = {}; // default, env, cli etc\n this._storeOptionsAsProperties = false;\n this._actionHandler = null;\n this._executableHandler = false;\n this._executableFile = null; // custom name for executable\n this._executableDir = null; // custom search directory for subcommands\n this._defaultCommandName = null;\n this._exitCallback = null;\n this._aliases = [];\n this._combineFlagAndOptionalValue = true;\n this._description = '';\n this._summary = '';\n this._argsDescription = undefined; // legacy\n this._enablePositionalOptions = false;\n this._passThroughOptions = false;\n this._lifeCycleHooks = {}; // a hash of arrays\n /** @type {(boolean | string)} */\n this._showHelpAfterError = false;\n this._showSuggestionAfterError = true;\n\n // see .configureOutput() for docs\n this._outputConfiguration = {\n writeOut: (str) => process.stdout.write(str),\n writeErr: (str) => process.stderr.write(str),\n getOutHelpWidth: () =>\n process.stdout.isTTY ? process.stdout.columns : undefined,\n getErrHelpWidth: () =>\n process.stderr.isTTY ? process.stderr.columns : undefined,\n outputError: (str, write) => write(str),\n };\n\n this._hidden = false;\n /** @type {(Option | null | undefined)} */\n this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled.\n this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited\n /** @type {Command} */\n this._helpCommand = undefined; // lazy initialised, inherited\n this._helpConfiguration = {};\n }\n\n /**\n * Copy settings that are useful to have in common across root command and subcommands.\n *\n * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)\n *\n * @param {Command} sourceCommand\n * @return {Command} `this` command for chaining\n */\n copyInheritedSettings(sourceCommand) {\n this._outputConfiguration = sourceCommand._outputConfiguration;\n this._helpOption = sourceCommand._helpOption;\n this._helpCommand = sourceCommand._helpCommand;\n this._helpConfiguration = sourceCommand._helpConfiguration;\n this._exitCallback = sourceCommand._exitCallback;\n this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;\n this._combineFlagAndOptionalValue =\n sourceCommand._combineFlagAndOptionalValue;\n this._allowExcessArguments = sourceCommand._allowExcessArguments;\n this._enablePositionalOptions = sourceCommand._enablePositionalOptions;\n this._showHelpAfterError = sourceCommand._showHelpAfterError;\n this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;\n\n return this;\n }\n\n /**\n * @returns {Command[]}\n * @private\n */\n\n _getCommandAndAncestors() {\n const result = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n for (let command = this; command; command = command.parent) {\n result.push(command);\n }\n return result;\n }\n\n /**\n * Define a command.\n *\n * There are two styles of command: pay attention to where to put the description.\n *\n * @example\n * // Command implemented using action handler (description is supplied separately to `.command`)\n * program\n * .command('clone <source> [destination]')\n * .description('clone a repository into a newly created directory')\n * .action((source, destination) => {\n * console.log('clone command called');\n * });\n *\n * // Command implemented using separate executable file (description is second parameter to `.command`)\n * program\n * .command('start <service>', 'start named service')\n * .command('stop [service]', 'stop named service, or all if no name supplied');\n *\n * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`\n * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)\n * @param {object} [execOpts] - configuration options (for executable)\n * @return {Command} returns new command for action handler, or `this` for executable command\n */\n\n command(nameAndArgs, actionOptsOrExecDesc, execOpts) {\n let desc = actionOptsOrExecDesc;\n let opts = execOpts;\n if (typeof desc === 'object' && desc !== null) {\n opts = desc;\n desc = null;\n }\n opts = opts || {};\n const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);\n\n const cmd = this.createCommand(name);\n if (desc) {\n cmd.description(desc);\n cmd._executableHandler = true;\n }\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden\n cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor\n if (args) cmd.arguments(args);\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd.copyInheritedSettings(this);\n\n if (desc) return this;\n return cmd;\n }\n\n /**\n * Factory routine to create a new unattached command.\n *\n * See .command() for creating an attached subcommand, which uses this routine to\n * create the command. You can override createCommand to customise subcommands.\n *\n * @param {string} [name]\n * @return {Command} new command\n */\n\n createCommand(name) {\n return new Command(name);\n }\n\n /**\n * You can customise the help with a subclass of Help by overriding createHelp,\n * or by overriding Help properties using configureHelp().\n *\n * @return {Help}\n */\n\n createHelp() {\n return Object.assign(new Help(), this.configureHelp());\n }\n\n /**\n * You can customise the help by overriding Help properties using configureHelp(),\n * or with a subclass of Help by overriding createHelp().\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureHelp(configuration) {\n if (configuration === undefined) return this._helpConfiguration;\n\n this._helpConfiguration = configuration;\n return this;\n }\n\n /**\n * The default output goes to stdout and stderr. You can customise this for special\n * applications. You can also customise the display of errors by overriding outputError.\n *\n * The configuration properties are all functions:\n *\n * // functions to change where being written, stdout and stderr\n * writeOut(str)\n * writeErr(str)\n * // matching functions to specify width for wrapping help\n * getOutHelpWidth()\n * getErrHelpWidth()\n * // functions based on what is being written out\n * outputError(str, write) // used for displaying errors, and not used for displaying help\n *\n * @param {object} [configuration] - configuration options\n * @return {(Command | object)} `this` command for chaining, or stored configuration\n */\n\n configureOutput(configuration) {\n if (configuration === undefined) return this._outputConfiguration;\n\n Object.assign(this._outputConfiguration, configuration);\n return this;\n }\n\n /**\n * Display the help or a custom message after an error occurs.\n *\n * @param {(boolean|string)} [displayHelp]\n * @return {Command} `this` command for chaining\n */\n showHelpAfterError(displayHelp = true) {\n if (typeof displayHelp !== 'string') displayHelp = !!displayHelp;\n this._showHelpAfterError = displayHelp;\n return this;\n }\n\n /**\n * Display suggestion of similar commands for unknown commands, or options for unknown options.\n *\n * @param {boolean} [displaySuggestion]\n * @return {Command} `this` command for chaining\n */\n showSuggestionAfterError(displaySuggestion = true) {\n this._showSuggestionAfterError = !!displaySuggestion;\n return this;\n }\n\n /**\n * Add a prepared subcommand.\n *\n * See .command() for creating an attached subcommand which inherits settings from its parent.\n *\n * @param {Command} cmd - new subcommand\n * @param {object} [opts] - configuration options\n * @return {Command} `this` command for chaining\n */\n\n addCommand(cmd, opts) {\n if (!cmd._name) {\n throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`);\n }\n\n opts = opts || {};\n if (opts.isDefault) this._defaultCommandName = cmd._name;\n if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation\n\n this._registerCommand(cmd);\n cmd.parent = this;\n cmd._checkForBrokenPassThrough();\n\n return this;\n }\n\n /**\n * Factory routine to create a new unattached argument.\n *\n * See .argument() for creating an attached argument, which uses this routine to\n * create the argument. You can override createArgument to return a custom argument.\n *\n * @param {string} name\n * @param {string} [description]\n * @return {Argument} new argument\n */\n\n createArgument(name, description) {\n return new Argument(name, description);\n }\n\n /**\n * Define argument syntax for command.\n *\n * The default is that the argument is required, and you can explicitly\n * indicate this with <> around the name. Put [] around the name for an optional argument.\n *\n * @example\n * program.argument('<input-file>');\n * program.argument('[output-file]');\n *\n * @param {string} name\n * @param {string} [description]\n * @param {(Function|*)} [fn] - custom argument processing function\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n argument(name, description, fn, defaultValue) {\n const argument = this.createArgument(name, description);\n if (typeof fn === 'function') {\n argument.default(defaultValue).argParser(fn);\n } else {\n argument.default(fn);\n }\n this.addArgument(argument);\n return this;\n }\n\n /**\n * Define argument syntax for command, adding multiple at once (without descriptions).\n *\n * See also .argument().\n *\n * @example\n * program.arguments('<cmd> [env]');\n *\n * @param {string} names\n * @return {Command} `this` command for chaining\n */\n\n arguments(names) {\n names\n .trim()\n .split(/ +/)\n .forEach((detail) => {\n this.argument(detail);\n });\n return this;\n }\n\n /**\n * Define argument syntax for command, adding a prepared argument.\n *\n * @param {Argument} argument\n * @return {Command} `this` command for chaining\n */\n addArgument(argument) {\n const previousArgument = this.registeredArguments.slice(-1)[0];\n if (previousArgument && previousArgument.variadic) {\n throw new Error(\n `only the last argument can be variadic '${previousArgument.name()}'`,\n );\n }\n if (\n argument.required &&\n argument.defaultValue !== undefined &&\n argument.parseArg === undefined\n ) {\n throw new Error(\n `a default value for a required argument is never used: '${argument.name()}'`,\n );\n }\n this.registeredArguments.push(argument);\n return this;\n }\n\n /**\n * Customise or override default help command. By default a help command is automatically added if your command has subcommands.\n *\n * @example\n * program.helpCommand('help [cmd]');\n * program.helpCommand('help [cmd]', 'show help');\n * program.helpCommand(false); // suppress default help command\n * program.helpCommand(true); // add help command even if no subcommands\n *\n * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added\n * @param {string} [description] - custom description\n * @return {Command} `this` command for chaining\n */\n\n helpCommand(enableOrNameAndArgs, description) {\n if (typeof enableOrNameAndArgs === 'boolean') {\n this._addImplicitHelpCommand = enableOrNameAndArgs;\n return this;\n }\n\n enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]';\n const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);\n const helpDescription = description ?? 'display help for command';\n\n const helpCommand = this.createCommand(helpName);\n helpCommand.helpOption(false);\n if (helpArgs) helpCommand.arguments(helpArgs);\n if (helpDescription) helpCommand.description(helpDescription);\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n\n return this;\n }\n\n /**\n * Add prepared custom help command.\n *\n * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`\n * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only\n * @return {Command} `this` command for chaining\n */\n addHelpCommand(helpCommand, deprecatedDescription) {\n // If not passed an object, call through to helpCommand for backwards compatibility,\n // as addHelpCommand was originally used like helpCommand is now.\n if (typeof helpCommand !== 'object') {\n this.helpCommand(helpCommand, deprecatedDescription);\n return this;\n }\n\n this._addImplicitHelpCommand = true;\n this._helpCommand = helpCommand;\n return this;\n }\n\n /**\n * Lazy create help command.\n *\n * @return {(Command|null)}\n * @package\n */\n _getHelpCommand() {\n const hasImplicitHelpCommand =\n this._addImplicitHelpCommand ??\n (this.commands.length &&\n !this._actionHandler &&\n !this._findCommand('help'));\n\n if (hasImplicitHelpCommand) {\n if (this._helpCommand === undefined) {\n this.helpCommand(undefined, undefined); // use default name and description\n }\n return this._helpCommand;\n }\n return null;\n }\n\n /**\n * Add hook for life cycle event.\n *\n * @param {string} event\n * @param {Function} listener\n * @return {Command} `this` command for chaining\n */\n\n hook(event, listener) {\n const allowedValues = ['preSubcommand', 'preAction', 'postAction'];\n if (!allowedValues.includes(event)) {\n throw new Error(`Unexpected value for event passed to hook : '${event}'.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n if (this._lifeCycleHooks[event]) {\n this._lifeCycleHooks[event].push(listener);\n } else {\n this._lifeCycleHooks[event] = [listener];\n }\n return this;\n }\n\n /**\n * Register callback to use as replacement for calling process.exit.\n *\n * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing\n * @return {Command} `this` command for chaining\n */\n\n exitOverride(fn) {\n if (fn) {\n this._exitCallback = fn;\n } else {\n this._exitCallback = (err) => {\n if (err.code !== 'commander.executeSubCommandAsync') {\n throw err;\n } else {\n // Async callback from spawn events, not useful to throw.\n }\n };\n }\n return this;\n }\n\n /**\n * Call process.exit, and _exitCallback if defined.\n *\n * @param {number} exitCode exit code for using with process.exit\n * @param {string} code an id string representing the error\n * @param {string} message human-readable description of the error\n * @return never\n * @private\n */\n\n _exit(exitCode, code, message) {\n if (this._exitCallback) {\n this._exitCallback(new CommanderError(exitCode, code, message));\n // Expecting this line is not reached.\n }\n process.exit(exitCode);\n }\n\n /**\n * Register callback `fn` for the command.\n *\n * @example\n * program\n * .command('serve')\n * .description('start service')\n * .action(function() {\n * // do work here\n * });\n *\n * @param {Function} fn\n * @return {Command} `this` command for chaining\n */\n\n action(fn) {\n const listener = (args) => {\n // The .action callback takes an extra parameter which is the command or options.\n const expectedArgsCount = this.registeredArguments.length;\n const actionArgs = args.slice(0, expectedArgsCount);\n if (this._storeOptionsAsProperties) {\n actionArgs[expectedArgsCount] = this; // backwards compatible \"options\"\n } else {\n actionArgs[expectedArgsCount] = this.opts();\n }\n actionArgs.push(this);\n\n return fn.apply(this, actionArgs);\n };\n this._actionHandler = listener;\n return this;\n }\n\n /**\n * Factory routine to create a new unattached option.\n *\n * See .option() for creating an attached option, which uses this routine to\n * create the option. You can override createOption to return a custom option.\n *\n * @param {string} flags\n * @param {string} [description]\n * @return {Option} new option\n */\n\n createOption(flags, description) {\n return new Option(flags, description);\n }\n\n /**\n * Wrap parseArgs to catch 'commander.invalidArgument'.\n *\n * @param {(Option | Argument)} target\n * @param {string} value\n * @param {*} previous\n * @param {string} invalidArgumentMessage\n * @private\n */\n\n _callParseArg(target, value, previous, invalidArgumentMessage) {\n try {\n return target.parseArg(value, previous);\n } catch (err) {\n if (err.code === 'commander.invalidArgument') {\n const message = `${invalidArgumentMessage} ${err.message}`;\n this.error(message, { exitCode: err.exitCode, code: err.code });\n }\n throw err;\n }\n }\n\n /**\n * Check for option flag conflicts.\n * Register option if no conflicts found, or throw on conflict.\n *\n * @param {Option} option\n * @private\n */\n\n _registerOption(option) {\n const matchingOption =\n (option.short && this._findOption(option.short)) ||\n (option.long && this._findOption(option.long));\n if (matchingOption) {\n const matchingFlag =\n option.long && this._findOption(option.long)\n ? option.long\n : option.short;\n throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'\n- already used by option '${matchingOption.flags}'`);\n }\n\n this.options.push(option);\n }\n\n /**\n * Check for command name and alias conflicts with existing commands.\n * Register command if no conflicts found, or throw on conflict.\n *\n * @param {Command} command\n * @private\n */\n\n _registerCommand(command) {\n const knownBy = (cmd) => {\n return [cmd.name()].concat(cmd.aliases());\n };\n\n const alreadyUsed = knownBy(command).find((name) =>\n this._findCommand(name),\n );\n if (alreadyUsed) {\n const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|');\n const newCmd = knownBy(command).join('|');\n throw new Error(\n `cannot add command '${newCmd}' as already have command '${existingCmd}'`,\n );\n }\n\n this.commands.push(command);\n }\n\n /**\n * Add an option.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addOption(option) {\n this._registerOption(option);\n\n const oname = option.name();\n const name = option.attributeName();\n\n // store default value\n if (option.negate) {\n // --no-foo is special and defaults foo to true, unless a --foo option is already defined\n const positiveLongFlag = option.long.replace(/^--no-/, '--');\n if (!this._findOption(positiveLongFlag)) {\n this.setOptionValueWithSource(\n name,\n option.defaultValue === undefined ? true : option.defaultValue,\n 'default',\n );\n }\n } else if (option.defaultValue !== undefined) {\n this.setOptionValueWithSource(name, option.defaultValue, 'default');\n }\n\n // handler for cli and env supplied values\n const handleOptionValue = (val, invalidValueMessage, valueSource) => {\n // val is null for optional option used without an optional-argument.\n // val is undefined for boolean and negated option.\n if (val == null && option.presetArg !== undefined) {\n val = option.presetArg;\n }\n\n // custom processing\n const oldValue = this.getOptionValue(name);\n if (val !== null && option.parseArg) {\n val = this._callParseArg(option, val, oldValue, invalidValueMessage);\n } else if (val !== null && option.variadic) {\n val = option._concatValue(val, oldValue);\n }\n\n // Fill-in appropriate missing values. Long winded but easy to follow.\n if (val == null) {\n if (option.negate) {\n val = false;\n } else if (option.isBoolean() || option.optional) {\n val = true;\n } else {\n val = ''; // not normal, parseArg might have failed or be a mock function for testing\n }\n }\n this.setOptionValueWithSource(name, val, valueSource);\n };\n\n this.on('option:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'cli');\n });\n\n if (option.envVar) {\n this.on('optionEnv:' + oname, (val) => {\n const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;\n handleOptionValue(val, invalidValueMessage, 'env');\n });\n }\n\n return this;\n }\n\n /**\n * Internal implementation shared by .option() and .requiredOption()\n *\n * @return {Command} `this` command for chaining\n * @private\n */\n _optionEx(config, flags, description, fn, defaultValue) {\n if (typeof flags === 'object' && flags instanceof Option) {\n throw new Error(\n 'To add an Option object use addOption() instead of option() or requiredOption()',\n );\n }\n const option = this.createOption(flags, description);\n option.makeOptionMandatory(!!config.mandatory);\n if (typeof fn === 'function') {\n option.default(defaultValue).argParser(fn);\n } else if (fn instanceof RegExp) {\n // deprecated\n const regex = fn;\n fn = (val, def) => {\n const m = regex.exec(val);\n return m ? m[0] : def;\n };\n option.default(defaultValue).argParser(fn);\n } else {\n option.default(fn);\n }\n\n return this.addOption(option);\n }\n\n /**\n * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required\n * option-argument is indicated by `<>` and an optional option-argument by `[]`.\n *\n * See the README for more details, and see also addOption() and requiredOption().\n *\n * @example\n * program\n * .option('-p, --pepper', 'add pepper')\n * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument\n * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default\n * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n option(flags, description, parseArg, defaultValue) {\n return this._optionEx({}, flags, description, parseArg, defaultValue);\n }\n\n /**\n * Add a required option which must have a value after parsing. This usually means\n * the option must be specified on the command line. (Otherwise the same as .option().)\n *\n * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.\n *\n * @param {string} flags\n * @param {string} [description]\n * @param {(Function|*)} [parseArg] - custom option processing function or default value\n * @param {*} [defaultValue]\n * @return {Command} `this` command for chaining\n */\n\n requiredOption(flags, description, parseArg, defaultValue) {\n return this._optionEx(\n { mandatory: true },\n flags,\n description,\n parseArg,\n defaultValue,\n );\n }\n\n /**\n * Alter parsing of short flags with optional values.\n *\n * @example\n * // for `.option('-f,--flag [value]'):\n * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour\n * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`\n *\n * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.\n * @return {Command} `this` command for chaining\n */\n combineFlagAndOptionalValue(combine = true) {\n this._combineFlagAndOptionalValue = !!combine;\n return this;\n }\n\n /**\n * Allow unknown options on the command line.\n *\n * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.\n * @return {Command} `this` command for chaining\n */\n allowUnknownOption(allowUnknown = true) {\n this._allowUnknownOption = !!allowUnknown;\n return this;\n }\n\n /**\n * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.\n *\n * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.\n * @return {Command} `this` command for chaining\n */\n allowExcessArguments(allowExcess = true) {\n this._allowExcessArguments = !!allowExcess;\n return this;\n }\n\n /**\n * Enable positional options. Positional means global options are specified before subcommands which lets\n * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.\n * The default behaviour is non-positional and global options may appear anywhere on the command line.\n *\n * @param {boolean} [positional]\n * @return {Command} `this` command for chaining\n */\n enablePositionalOptions(positional = true) {\n this._enablePositionalOptions = !!positional;\n return this;\n }\n\n /**\n * Pass through options that come after command-arguments rather than treat them as command-options,\n * so actual command-options come before command-arguments. Turning this on for a subcommand requires\n * positional options to have been enabled on the program (parent commands).\n * The default behaviour is non-positional and options may appear before or after command-arguments.\n *\n * @param {boolean} [passThrough] for unknown options.\n * @return {Command} `this` command for chaining\n */\n passThroughOptions(passThrough = true) {\n this._passThroughOptions = !!passThrough;\n this._checkForBrokenPassThrough();\n return this;\n }\n\n /**\n * @private\n */\n\n _checkForBrokenPassThrough() {\n if (\n this.parent &&\n this._passThroughOptions &&\n !this.parent._enablePositionalOptions\n ) {\n throw new Error(\n `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`,\n );\n }\n }\n\n /**\n * Whether to store option values as properties on command object,\n * or store separately (specify false). In both cases the option values can be accessed using .opts().\n *\n * @param {boolean} [storeAsProperties=true]\n * @return {Command} `this` command for chaining\n */\n\n storeOptionsAsProperties(storeAsProperties = true) {\n if (this.options.length) {\n throw new Error('call .storeOptionsAsProperties() before adding options');\n }\n if (Object.keys(this._optionValues).length) {\n throw new Error(\n 'call .storeOptionsAsProperties() before setting option values',\n );\n }\n this._storeOptionsAsProperties = !!storeAsProperties;\n return this;\n }\n\n /**\n * Retrieve option value.\n *\n * @param {string} key\n * @return {object} value\n */\n\n getOptionValue(key) {\n if (this._storeOptionsAsProperties) {\n return this[key];\n }\n return this._optionValues[key];\n }\n\n /**\n * Store option value.\n *\n * @param {string} key\n * @param {object} value\n * @return {Command} `this` command for chaining\n */\n\n setOptionValue(key, value) {\n return this.setOptionValueWithSource(key, value, undefined);\n }\n\n /**\n * Store option value and where the value came from.\n *\n * @param {string} key\n * @param {object} value\n * @param {string} source - expected values are default/config/env/cli/implied\n * @return {Command} `this` command for chaining\n */\n\n setOptionValueWithSource(key, value, source) {\n if (this._storeOptionsAsProperties) {\n this[key] = value;\n } else {\n this._optionValues[key] = value;\n }\n this._optionValueSources[key] = source;\n return this;\n }\n\n /**\n * Get source of option value.\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSource(key) {\n return this._optionValueSources[key];\n }\n\n /**\n * Get source of option value. See also .optsWithGlobals().\n * Expected values are default | config | env | cli | implied\n *\n * @param {string} key\n * @return {string}\n */\n\n getOptionValueSourceWithGlobals(key) {\n // global overwrites local, like optsWithGlobals\n let source;\n this._getCommandAndAncestors().forEach((cmd) => {\n if (cmd.getOptionValueSource(key) !== undefined) {\n source = cmd.getOptionValueSource(key);\n }\n });\n return source;\n }\n\n /**\n * Get user arguments from implied or explicit arguments.\n * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.\n *\n * @private\n */\n\n _prepareUserArgs(argv, parseOptions) {\n if (argv !== undefined && !Array.isArray(argv)) {\n throw new Error('first parameter to parse must be array or undefined');\n }\n parseOptions = parseOptions || {};\n\n // auto-detect argument conventions if nothing supplied\n if (argv === undefined && parseOptions.from === undefined) {\n if (process.versions?.electron) {\n parseOptions.from = 'electron';\n }\n // check node specific options for scenarios where user CLI args follow executable without scriptname\n const execArgv = process.execArgv ?? [];\n if (\n execArgv.includes('-e') ||\n execArgv.includes('--eval') ||\n execArgv.includes('-p') ||\n execArgv.includes('--print')\n ) {\n parseOptions.from = 'eval'; // internal usage, not documented\n }\n }\n\n // default to using process.argv\n if (argv === undefined) {\n argv = process.argv;\n }\n this.rawArgs = argv.slice();\n\n // extract the user args and scriptPath\n let userArgs;\n switch (parseOptions.from) {\n case undefined:\n case 'node':\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n break;\n case 'electron':\n // @ts-ignore: because defaultApp is an unknown property\n if (process.defaultApp) {\n this._scriptPath = argv[1];\n userArgs = argv.slice(2);\n } else {\n userArgs = argv.slice(1);\n }\n break;\n case 'user':\n userArgs = argv.slice(0);\n break;\n case 'eval':\n userArgs = argv.slice(1);\n break;\n default:\n throw new Error(\n `unexpected parse option { from: '${parseOptions.from}' }`,\n );\n }\n\n // Find default name for program from arguments.\n if (!this._name && this._scriptPath)\n this.nameFromFilename(this._scriptPath);\n this._name = this._name || 'program';\n\n return userArgs;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Use parseAsync instead of parse if any of your action handlers are async.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * program.parse(); // parse process.argv and auto-detect electron and special node flags\n * program.parse(process.argv); // assume argv[0] is app and argv[1] is script\n * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv] - optional, defaults to process.argv\n * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron\n * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'\n * @return {Command} `this` command for chaining\n */\n\n parse(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Parse `argv`, setting options and invoking commands when defined.\n *\n * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!\n *\n * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:\n * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that\n * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged\n * - `'user'`: just user arguments\n *\n * @example\n * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags\n * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script\n * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]\n *\n * @param {string[]} [argv]\n * @param {object} [parseOptions]\n * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'\n * @return {Promise}\n */\n\n async parseAsync(argv, parseOptions) {\n const userArgs = this._prepareUserArgs(argv, parseOptions);\n await this._parseCommand([], userArgs);\n\n return this;\n }\n\n /**\n * Execute a sub-command executable.\n *\n * @private\n */\n\n _executeSubCommand(subcommand, args) {\n args = args.slice();\n let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows.\n const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs'];\n\n function findFile(baseDir, baseName) {\n // Look for specified file\n const localBin = path.resolve(baseDir, baseName);\n if (fs.existsSync(localBin)) return localBin;\n\n // Stop looking if candidate already has an expected extension.\n if (sourceExt.includes(path.extname(baseName))) return undefined;\n\n // Try all the extensions.\n const foundExt = sourceExt.find((ext) =>\n fs.existsSync(`${localBin}${ext}`),\n );\n if (foundExt) return `${localBin}${foundExt}`;\n\n return undefined;\n }\n\n // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command.\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // executableFile and executableDir might be full path, or just a name\n let executableFile =\n subcommand._executableFile || `${this._name}-${subcommand._name}`;\n let executableDir = this._executableDir || '';\n if (this._scriptPath) {\n let resolvedScriptPath; // resolve possible symlink for installed npm binary\n try {\n resolvedScriptPath = fs.realpathSync(this._scriptPath);\n } catch (err) {\n resolvedScriptPath = this._scriptPath;\n }\n executableDir = path.resolve(\n path.dirname(resolvedScriptPath),\n executableDir,\n );\n }\n\n // Look for a local file in preference to a command in PATH.\n if (executableDir) {\n let localFile = findFile(executableDir, executableFile);\n\n // Legacy search using prefix of script name instead of command name\n if (!localFile && !subcommand._executableFile && this._scriptPath) {\n const legacyName = path.basename(\n this._scriptPath,\n path.extname(this._scriptPath),\n );\n if (legacyName !== this._name) {\n localFile = findFile(\n executableDir,\n `${legacyName}-${subcommand._name}`,\n );\n }\n }\n executableFile = localFile || executableFile;\n }\n\n launchWithNode = sourceExt.includes(path.extname(executableFile));\n\n let proc;\n if (process.platform !== 'win32') {\n if (launchWithNode) {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n\n proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' });\n } else {\n proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' });\n }\n } else {\n args.unshift(executableFile);\n // add executable arguments to spawn\n args = incrementNodeInspectorPort(process.execArgv).concat(args);\n proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' });\n }\n\n if (!proc.killed) {\n // testing mainly to avoid leak warnings during unit tests with mocked spawn\n const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];\n signals.forEach((signal) => {\n process.on(signal, () => {\n if (proc.killed === false && proc.exitCode === null) {\n // @ts-ignore because signals not typed to known strings\n proc.kill(signal);\n }\n });\n });\n }\n\n // By default terminate process when spawned process terminates.\n const exitCallback = this._exitCallback;\n proc.on('close', (code) => {\n code = code ?? 1; // code is null if spawned process terminated due to a signal\n if (!exitCallback) {\n process.exit(code);\n } else {\n exitCallback(\n new CommanderError(\n code,\n 'commander.executeSubCommandAsync',\n '(close)',\n ),\n );\n }\n });\n proc.on('error', (err) => {\n // @ts-ignore: because err.code is an unknown property\n if (err.code === 'ENOENT') {\n const executableDirMessage = executableDir\n ? `searched for local subcommand relative to directory '${executableDir}'`\n : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory';\n const executableMissing = `'${executableFile}' does not exist\n - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${executableDirMessage}`;\n throw new Error(executableMissing);\n // @ts-ignore: because err.code is an unknown property\n } else if (err.code === 'EACCES') {\n throw new Error(`'${executableFile}' not executable`);\n }\n if (!exitCallback) {\n process.exit(1);\n } else {\n const wrappedError = new CommanderError(\n 1,\n 'commander.executeSubCommandAsync',\n '(error)',\n );\n wrappedError.nestedError = err;\n exitCallback(wrappedError);\n }\n });\n\n // Store the reference to the child process\n this.runningCommand = proc;\n }\n\n /**\n * @private\n */\n\n _dispatchSubcommand(commandName, operands, unknown) {\n const subCommand = this._findCommand(commandName);\n if (!subCommand) this.help({ error: true });\n\n let promiseChain;\n promiseChain = this._chainOrCallSubCommandHook(\n promiseChain,\n subCommand,\n 'preSubcommand',\n );\n promiseChain = this._chainOrCall(promiseChain, () => {\n if (subCommand._executableHandler) {\n this._executeSubCommand(subCommand, operands.concat(unknown));\n } else {\n return subCommand._parseCommand(operands, unknown);\n }\n });\n return promiseChain;\n }\n\n /**\n * Invoke help directly if possible, or dispatch if necessary.\n * e.g. help foo\n *\n * @private\n */\n\n _dispatchHelpCommand(subcommandName) {\n if (!subcommandName) {\n this.help();\n }\n const subCommand = this._findCommand(subcommandName);\n if (subCommand && !subCommand._executableHandler) {\n subCommand.help();\n }\n\n // Fallback to parsing the help flag to invoke the help.\n return this._dispatchSubcommand(\n subcommandName,\n [],\n [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'],\n );\n }\n\n /**\n * Check this.args against expected this.registeredArguments.\n *\n * @private\n */\n\n _checkNumberOfArguments() {\n // too few\n this.registeredArguments.forEach((arg, i) => {\n if (arg.required && this.args[i] == null) {\n this.missingArgument(arg.name());\n }\n });\n // too many\n if (\n this.registeredArguments.length > 0 &&\n this.registeredArguments[this.registeredArguments.length - 1].variadic\n ) {\n return;\n }\n if (this.args.length > this.registeredArguments.length) {\n this._excessArguments(this.args);\n }\n }\n\n /**\n * Process this.args using this.registeredArguments and save as this.processedArgs!\n *\n * @private\n */\n\n _processArguments() {\n const myParseArg = (argument, value, previous) => {\n // Extra processing for nice error message on parsing failure.\n let parsedValue = value;\n if (value !== null && argument.parseArg) {\n const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;\n parsedValue = this._callParseArg(\n argument,\n value,\n previous,\n invalidValueMessage,\n );\n }\n return parsedValue;\n };\n\n this._checkNumberOfArguments();\n\n const processedArgs = [];\n this.registeredArguments.forEach((declaredArg, index) => {\n let value = declaredArg.defaultValue;\n if (declaredArg.variadic) {\n // Collect together remaining arguments for passing together as an array.\n if (index < this.args.length) {\n value = this.args.slice(index);\n if (declaredArg.parseArg) {\n value = value.reduce((processed, v) => {\n return myParseArg(declaredArg, v, processed);\n }, declaredArg.defaultValue);\n }\n } else if (value === undefined) {\n value = [];\n }\n } else if (index < this.args.length) {\n value = this.args[index];\n if (declaredArg.parseArg) {\n value = myParseArg(declaredArg, value, declaredArg.defaultValue);\n }\n }\n processedArgs[index] = value;\n });\n this.processedArgs = processedArgs;\n }\n\n /**\n * Once we have a promise we chain, but call synchronously until then.\n *\n * @param {(Promise|undefined)} promise\n * @param {Function} fn\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCall(promise, fn) {\n // thenable\n if (promise && promise.then && typeof promise.then === 'function') {\n // already have a promise, chain callback\n return promise.then(() => fn());\n }\n // callback might return a promise\n return fn();\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallHooks(promise, event) {\n let result = promise;\n const hooks = [];\n this._getCommandAndAncestors()\n .reverse()\n .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined)\n .forEach((hookedCommand) => {\n hookedCommand._lifeCycleHooks[event].forEach((callback) => {\n hooks.push({ hookedCommand, callback });\n });\n });\n if (event === 'postAction') {\n hooks.reverse();\n }\n\n hooks.forEach((hookDetail) => {\n result = this._chainOrCall(result, () => {\n return hookDetail.callback(hookDetail.hookedCommand, this);\n });\n });\n return result;\n }\n\n /**\n *\n * @param {(Promise|undefined)} promise\n * @param {Command} subCommand\n * @param {string} event\n * @return {(Promise|undefined)}\n * @private\n */\n\n _chainOrCallSubCommandHook(promise, subCommand, event) {\n let result = promise;\n if (this._lifeCycleHooks[event] !== undefined) {\n this._lifeCycleHooks[event].forEach((hook) => {\n result = this._chainOrCall(result, () => {\n return hook(this, subCommand);\n });\n });\n }\n return result;\n }\n\n /**\n * Process arguments in context of this command.\n * Returns action result, in case it is a promise.\n *\n * @private\n */\n\n _parseCommand(operands, unknown) {\n const parsed = this.parseOptions(unknown);\n this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env\n this._parseOptionsImplied();\n operands = operands.concat(parsed.operands);\n unknown = parsed.unknown;\n this.args = operands.concat(unknown);\n\n if (operands && this._findCommand(operands[0])) {\n return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);\n }\n if (\n this._getHelpCommand() &&\n operands[0] === this._getHelpCommand().name()\n ) {\n return this._dispatchHelpCommand(operands[1]);\n }\n if (this._defaultCommandName) {\n this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command\n return this._dispatchSubcommand(\n this._defaultCommandName,\n operands,\n unknown,\n );\n }\n if (\n this.commands.length &&\n this.args.length === 0 &&\n !this._actionHandler &&\n !this._defaultCommandName\n ) {\n // probably missing subcommand and no handler, user needs help (and exit)\n this.help({ error: true });\n }\n\n this._outputHelpIfRequested(parsed.unknown);\n this._checkForMissingMandatoryOptions();\n this._checkForConflictingOptions();\n\n // We do not always call this check to avoid masking a \"better\" error, like unknown command.\n const checkForUnknownOptions = () => {\n if (parsed.unknown.length > 0) {\n this.unknownOption(parsed.unknown[0]);\n }\n };\n\n const commandEvent = `command:${this.name()}`;\n if (this._actionHandler) {\n checkForUnknownOptions();\n this._processArguments();\n\n let promiseChain;\n promiseChain = this._chainOrCallHooks(promiseChain, 'preAction');\n promiseChain = this._chainOrCall(promiseChain, () =>\n this._actionHandler(this.processedArgs),\n );\n if (this.parent) {\n promiseChain = this._chainOrCall(promiseChain, () => {\n this.parent.emit(commandEvent, operands, unknown); // legacy\n });\n }\n promiseChain = this._chainOrCallHooks(promiseChain, 'postAction');\n return promiseChain;\n }\n if (this.parent && this.parent.listenerCount(commandEvent)) {\n checkForUnknownOptions();\n this._processArguments();\n this.parent.emit(commandEvent, operands, unknown); // legacy\n } else if (operands.length) {\n if (this._findCommand('*')) {\n // legacy default command\n return this._dispatchSubcommand('*', operands, unknown);\n }\n if (this.listenerCount('command:*')) {\n // skip option check, emit event for possible misspelling suggestion\n this.emit('command:*', operands, unknown);\n } else if (this.commands.length) {\n this.unknownCommand();\n } else {\n checkForUnknownOptions();\n this._processArguments();\n }\n } else if (this.commands.length) {\n checkForUnknownOptions();\n // This command has subcommands and nothing hooked up at this level, so display help (and exit).\n this.help({ error: true });\n } else {\n checkForUnknownOptions();\n this._processArguments();\n // fall through for caller to handle after calling .parse()\n }\n }\n\n /**\n * Find matching command.\n *\n * @private\n * @return {Command | undefined}\n */\n _findCommand(name) {\n if (!name) return undefined;\n return this.commands.find(\n (cmd) => cmd._name === name || cmd._aliases.includes(name),\n );\n }\n\n /**\n * Return an option matching `arg` if any.\n *\n * @param {string} arg\n * @return {Option}\n * @package\n */\n\n _findOption(arg) {\n return this.options.find((option) => option.is(arg));\n }\n\n /**\n * Display an error message if a mandatory option does not have a value.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n\n _checkForMissingMandatoryOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd.options.forEach((anOption) => {\n if (\n anOption.mandatory &&\n cmd.getOptionValue(anOption.attributeName()) === undefined\n ) {\n cmd.missingMandatoryOptionValue(anOption);\n }\n });\n });\n }\n\n /**\n * Display an error message if conflicting options are used together in this.\n *\n * @private\n */\n _checkForConflictingLocalOptions() {\n const definedNonDefaultOptions = this.options.filter((option) => {\n const optionKey = option.attributeName();\n if (this.getOptionValue(optionKey) === undefined) {\n return false;\n }\n return this.getOptionValueSource(optionKey) !== 'default';\n });\n\n const optionsWithConflicting = definedNonDefaultOptions.filter(\n (option) => option.conflictsWith.length > 0,\n );\n\n optionsWithConflicting.forEach((option) => {\n const conflictingAndDefined = definedNonDefaultOptions.find((defined) =>\n option.conflictsWith.includes(defined.attributeName()),\n );\n if (conflictingAndDefined) {\n this._conflictingOption(option, conflictingAndDefined);\n }\n });\n }\n\n /**\n * Display an error message if conflicting options are used together.\n * Called after checking for help flags in leaf subcommand.\n *\n * @private\n */\n _checkForConflictingOptions() {\n // Walk up hierarchy so can call in subcommand after checking for displaying help.\n this._getCommandAndAncestors().forEach((cmd) => {\n cmd._checkForConflictingLocalOptions();\n });\n }\n\n /**\n * Parse options from `argv` removing known options,\n * and return argv split into operands and unknown arguments.\n *\n * Examples:\n *\n * argv => operands, unknown\n * --known kkk op => [op], []\n * op --known kkk => [op], []\n * sub --unknown uuu op => [sub], [--unknown uuu op]\n * sub -- --unknown uuu op => [sub --unknown uuu op], []\n *\n * @param {string[]} argv\n * @return {{operands: string[], unknown: string[]}}\n */\n\n parseOptions(argv) {\n const operands = []; // operands, not options or values\n const unknown = []; // first unknown option and remaining unknown args\n let dest = operands;\n const args = argv.slice();\n\n function maybeOption(arg) {\n return arg.length > 1 && arg[0] === '-';\n }\n\n // parse options\n let activeVariadicOption = null;\n while (args.length) {\n const arg = args.shift();\n\n // literal\n if (arg === '--') {\n if (dest === unknown) dest.push(arg);\n dest.push(...args);\n break;\n }\n\n if (activeVariadicOption && !maybeOption(arg)) {\n this.emit(`option:${activeVariadicOption.name()}`, arg);\n continue;\n }\n activeVariadicOption = null;\n\n if (maybeOption(arg)) {\n const option = this._findOption(arg);\n // recognised option, call listener to assign value with possible custom processing\n if (option) {\n if (option.required) {\n const value = args.shift();\n if (value === undefined) this.optionMissingArgument(option);\n this.emit(`option:${option.name()}`, value);\n } else if (option.optional) {\n let value = null;\n // historical behaviour is optional value is following arg unless an option\n if (args.length > 0 && !maybeOption(args[0])) {\n value = args.shift();\n }\n this.emit(`option:${option.name()}`, value);\n } else {\n // boolean flag\n this.emit(`option:${option.name()}`);\n }\n activeVariadicOption = option.variadic ? option : null;\n continue;\n }\n }\n\n // Look for combo options following single dash, eat first one if known.\n if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') {\n const option = this._findOption(`-${arg[1]}`);\n if (option) {\n if (\n option.required ||\n (option.optional && this._combineFlagAndOptionalValue)\n ) {\n // option with value following in same argument\n this.emit(`option:${option.name()}`, arg.slice(2));\n } else {\n // boolean option, emit and put back remainder of arg for further processing\n this.emit(`option:${option.name()}`);\n args.unshift(`-${arg.slice(2)}`);\n }\n continue;\n }\n }\n\n // Look for known long flag with value, like --foo=bar\n if (/^--[^=]+=/.test(arg)) {\n const index = arg.indexOf('=');\n const option = this._findOption(arg.slice(0, index));\n if (option && (option.required || option.optional)) {\n this.emit(`option:${option.name()}`, arg.slice(index + 1));\n continue;\n }\n }\n\n // Not a recognised option by this command.\n // Might be a command-argument, or subcommand option, or unknown option, or help command or option.\n\n // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands.\n if (maybeOption(arg)) {\n dest = unknown;\n }\n\n // If using positionalOptions, stop processing our options at subcommand.\n if (\n (this._enablePositionalOptions || this._passThroughOptions) &&\n operands.length === 0 &&\n unknown.length === 0\n ) {\n if (this._findCommand(arg)) {\n operands.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n } else if (\n this._getHelpCommand() &&\n arg === this._getHelpCommand().name()\n ) {\n operands.push(arg);\n if (args.length > 0) operands.push(...args);\n break;\n } else if (this._defaultCommandName) {\n unknown.push(arg);\n if (args.length > 0) unknown.push(...args);\n break;\n }\n }\n\n // If using passThroughOptions, stop processing options at first command-argument.\n if (this._passThroughOptions) {\n dest.push(arg);\n if (args.length > 0) dest.push(...args);\n break;\n }\n\n // add arg\n dest.push(arg);\n }\n\n return { operands, unknown };\n }\n\n /**\n * Return an object containing local option values as key-value pairs.\n *\n * @return {object}\n */\n opts() {\n if (this._storeOptionsAsProperties) {\n // Preserve original behaviour so backwards compatible when still using properties\n const result = {};\n const len = this.options.length;\n\n for (let i = 0; i < len; i++) {\n const key = this.options[i].attributeName();\n result[key] =\n key === this._versionOptionName ? this._version : this[key];\n }\n return result;\n }\n\n return this._optionValues;\n }\n\n /**\n * Return an object containing merged local and global option values as key-value pairs.\n *\n * @return {object}\n */\n optsWithGlobals() {\n // globals overwrite locals\n return this._getCommandAndAncestors().reduce(\n (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),\n {},\n );\n }\n\n /**\n * Display error message and exit (or call exitOverride).\n *\n * @param {string} message\n * @param {object} [errorOptions]\n * @param {string} [errorOptions.code] - an id string representing the error\n * @param {number} [errorOptions.exitCode] - used with process.exit\n */\n error(message, errorOptions) {\n // output handling\n this._outputConfiguration.outputError(\n `${message}\\n`,\n this._outputConfiguration.writeErr,\n );\n if (typeof this._showHelpAfterError === 'string') {\n this._outputConfiguration.writeErr(`${this._showHelpAfterError}\\n`);\n } else if (this._showHelpAfterError) {\n this._outputConfiguration.writeErr('\\n');\n this.outputHelp({ error: true });\n }\n\n // exit handling\n const config = errorOptions || {};\n const exitCode = config.exitCode || 1;\n const code = config.code || 'commander.error';\n this._exit(exitCode, code, message);\n }\n\n /**\n * Apply any option related environment variables, if option does\n * not have a value from cli or client code.\n *\n * @private\n */\n _parseOptionsEnv() {\n this.options.forEach((option) => {\n if (option.envVar && option.envVar in process.env) {\n const optionKey = option.attributeName();\n // Priority check. Do not overwrite cli or options from unknown source (client-code).\n if (\n this.getOptionValue(optionKey) === undefined ||\n ['default', 'config', 'env'].includes(\n this.getOptionValueSource(optionKey),\n )\n ) {\n if (option.required || option.optional) {\n // option can take a value\n // keep very simple, optional always takes value\n this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]);\n } else {\n // boolean\n // keep very simple, only care that envVar defined and not the value\n this.emit(`optionEnv:${option.name()}`);\n }\n }\n }\n });\n }\n\n /**\n * Apply any implied option values, if option is undefined or default value.\n *\n * @private\n */\n _parseOptionsImplied() {\n const dualHelper = new DualOptions(this.options);\n const hasCustomOptionValue = (optionKey) => {\n return (\n this.getOptionValue(optionKey) !== undefined &&\n !['default', 'implied'].includes(this.getOptionValueSource(optionKey))\n );\n };\n this.options\n .filter(\n (option) =>\n option.implied !== undefined &&\n hasCustomOptionValue(option.attributeName()) &&\n dualHelper.valueFromOption(\n this.getOptionValue(option.attributeName()),\n option,\n ),\n )\n .forEach((option) => {\n Object.keys(option.implied)\n .filter((impliedKey) => !hasCustomOptionValue(impliedKey))\n .forEach((impliedKey) => {\n this.setOptionValueWithSource(\n impliedKey,\n option.implied[impliedKey],\n 'implied',\n );\n });\n });\n }\n\n /**\n * Argument `name` is missing.\n *\n * @param {string} name\n * @private\n */\n\n missingArgument(name) {\n const message = `error: missing required argument '${name}'`;\n this.error(message, { code: 'commander.missingArgument' });\n }\n\n /**\n * `Option` is missing an argument.\n *\n * @param {Option} option\n * @private\n */\n\n optionMissingArgument(option) {\n const message = `error: option '${option.flags}' argument missing`;\n this.error(message, { code: 'commander.optionMissingArgument' });\n }\n\n /**\n * `Option` does not have a value, and is a mandatory option.\n *\n * @param {Option} option\n * @private\n */\n\n missingMandatoryOptionValue(option) {\n const message = `error: required option '${option.flags}' not specified`;\n this.error(message, { code: 'commander.missingMandatoryOptionValue' });\n }\n\n /**\n * `Option` conflicts with another option.\n *\n * @param {Option} option\n * @param {Option} conflictingOption\n * @private\n */\n _conflictingOption(option, conflictingOption) {\n // The calling code does not know whether a negated option is the source of the\n // value, so do some work to take an educated guess.\n const findBestOptionFromValue = (option) => {\n const optionKey = option.attributeName();\n const optionValue = this.getOptionValue(optionKey);\n const negativeOption = this.options.find(\n (target) => target.negate && optionKey === target.attributeName(),\n );\n const positiveOption = this.options.find(\n (target) => !target.negate && optionKey === target.attributeName(),\n );\n if (\n negativeOption &&\n ((negativeOption.presetArg === undefined && optionValue === false) ||\n (negativeOption.presetArg !== undefined &&\n optionValue === negativeOption.presetArg))\n ) {\n return negativeOption;\n }\n return positiveOption || option;\n };\n\n const getErrorMessage = (option) => {\n const bestOption = findBestOptionFromValue(option);\n const optionKey = bestOption.attributeName();\n const source = this.getOptionValueSource(optionKey);\n if (source === 'env') {\n return `environment variable '${bestOption.envVar}'`;\n }\n return `option '${bestOption.flags}'`;\n };\n\n const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;\n this.error(message, { code: 'commander.conflictingOption' });\n }\n\n /**\n * Unknown option `flag`.\n *\n * @param {string} flag\n * @private\n */\n\n unknownOption(flag) {\n if (this._allowUnknownOption) return;\n let suggestion = '';\n\n if (flag.startsWith('--') && this._showSuggestionAfterError) {\n // Looping to pick up the global options too\n let candidateFlags = [];\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n do {\n const moreFlags = command\n .createHelp()\n .visibleOptions(command)\n .filter((option) => option.long)\n .map((option) => option.long);\n candidateFlags = candidateFlags.concat(moreFlags);\n command = command.parent;\n } while (command && !command._enablePositionalOptions);\n suggestion = suggestSimilar(flag, candidateFlags);\n }\n\n const message = `error: unknown option '${flag}'${suggestion}`;\n this.error(message, { code: 'commander.unknownOption' });\n }\n\n /**\n * Excess arguments, more than expected.\n *\n * @param {string[]} receivedArgs\n * @private\n */\n\n _excessArguments(receivedArgs) {\n if (this._allowExcessArguments) return;\n\n const expected = this.registeredArguments.length;\n const s = expected === 1 ? '' : 's';\n const forSubcommand = this.parent ? ` for '${this.name()}'` : '';\n const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;\n this.error(message, { code: 'commander.excessArguments' });\n }\n\n /**\n * Unknown command.\n *\n * @private\n */\n\n unknownCommand() {\n const unknownName = this.args[0];\n let suggestion = '';\n\n if (this._showSuggestionAfterError) {\n const candidateNames = [];\n this.createHelp()\n .visibleCommands(this)\n .forEach((command) => {\n candidateNames.push(command.name());\n // just visible alias\n if (command.alias()) candidateNames.push(command.alias());\n });\n suggestion = suggestSimilar(unknownName, candidateNames);\n }\n\n const message = `error: unknown command '${unknownName}'${suggestion}`;\n this.error(message, { code: 'commander.unknownCommand' });\n }\n\n /**\n * Get or set the program version.\n *\n * This method auto-registers the \"-V, --version\" option which will print the version number.\n *\n * You can optionally supply the flags and description to override the defaults.\n *\n * @param {string} [str]\n * @param {string} [flags]\n * @param {string} [description]\n * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments\n */\n\n version(str, flags, description) {\n if (str === undefined) return this._version;\n this._version = str;\n flags = flags || '-V, --version';\n description = description || 'output the version number';\n const versionOption = this.createOption(flags, description);\n this._versionOptionName = versionOption.attributeName();\n this._registerOption(versionOption);\n\n this.on('option:' + versionOption.name(), () => {\n this._outputConfiguration.writeOut(`${str}\\n`);\n this._exit(0, 'commander.version', str);\n });\n return this;\n }\n\n /**\n * Set the description.\n *\n * @param {string} [str]\n * @param {object} [argsDescription]\n * @return {(string|Command)}\n */\n description(str, argsDescription) {\n if (str === undefined && argsDescription === undefined)\n return this._description;\n this._description = str;\n if (argsDescription) {\n this._argsDescription = argsDescription;\n }\n return this;\n }\n\n /**\n * Set the summary. Used when listed as subcommand of parent.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n summary(str) {\n if (str === undefined) return this._summary;\n this._summary = str;\n return this;\n }\n\n /**\n * Set an alias for the command.\n *\n * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.\n *\n * @param {string} [alias]\n * @return {(string|Command)}\n */\n\n alias(alias) {\n if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility\n\n /** @type {Command} */\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let command = this;\n if (\n this.commands.length !== 0 &&\n this.commands[this.commands.length - 1]._executableHandler\n ) {\n // assume adding alias for last added executable subcommand, rather than this\n command = this.commands[this.commands.length - 1];\n }\n\n if (alias === command._name)\n throw new Error(\"Command alias can't be the same as its name\");\n const matchingCommand = this.parent?._findCommand(alias);\n if (matchingCommand) {\n // c.f. _registerCommand\n const existingCmd = [matchingCommand.name()]\n .concat(matchingCommand.aliases())\n .join('|');\n throw new Error(\n `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`,\n );\n }\n\n command._aliases.push(alias);\n return this;\n }\n\n /**\n * Set aliases for the command.\n *\n * Only the first alias is shown in the auto-generated help.\n *\n * @param {string[]} [aliases]\n * @return {(string[]|Command)}\n */\n\n aliases(aliases) {\n // Getter for the array of aliases is the main reason for having aliases() in addition to alias().\n if (aliases === undefined) return this._aliases;\n\n aliases.forEach((alias) => this.alias(alias));\n return this;\n }\n\n /**\n * Set / get the command usage `str`.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n usage(str) {\n if (str === undefined) {\n if (this._usage) return this._usage;\n\n const args = this.registeredArguments.map((arg) => {\n return humanReadableArgName(arg);\n });\n return []\n .concat(\n this.options.length || this._helpOption !== null ? '[options]' : [],\n this.commands.length ? '[command]' : [],\n this.registeredArguments.length ? args : [],\n )\n .join(' ');\n }\n\n this._usage = str;\n return this;\n }\n\n /**\n * Get or set the name of the command.\n *\n * @param {string} [str]\n * @return {(string|Command)}\n */\n\n name(str) {\n if (str === undefined) return this._name;\n this._name = str;\n return this;\n }\n\n /**\n * Set the name of the command from script filename, such as process.argv[1],\n * or require.main.filename, or __filename.\n *\n * (Used internally and public although not documented in README.)\n *\n * @example\n * program.nameFromFilename(require.main.filename);\n *\n * @param {string} filename\n * @return {Command}\n */\n\n nameFromFilename(filename) {\n this._name = path.basename(filename, path.extname(filename));\n\n return this;\n }\n\n /**\n * Get or set the directory for searching for executable subcommands of this command.\n *\n * @example\n * program.executableDir(__dirname);\n * // or\n * program.executableDir('subcommands');\n *\n * @param {string} [path]\n * @return {(string|null|Command)}\n */\n\n executableDir(path) {\n if (path === undefined) return this._executableDir;\n this._executableDir = path;\n return this;\n }\n\n /**\n * Return program help documentation.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout\n * @return {string}\n */\n\n helpInformation(contextOptions) {\n const helper = this.createHelp();\n if (helper.helpWidth === undefined) {\n helper.helpWidth =\n contextOptions && contextOptions.error\n ? this._outputConfiguration.getErrHelpWidth()\n : this._outputConfiguration.getOutHelpWidth();\n }\n return helper.formatHelp(this, helper);\n }\n\n /**\n * @private\n */\n\n _getHelpContext(contextOptions) {\n contextOptions = contextOptions || {};\n const context = { error: !!contextOptions.error };\n let write;\n if (context.error) {\n write = (arg) => this._outputConfiguration.writeErr(arg);\n } else {\n write = (arg) => this._outputConfiguration.writeOut(arg);\n }\n context.write = contextOptions.write || write;\n context.command = this;\n return context;\n }\n\n /**\n * Output help information for this command.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n outputHelp(contextOptions) {\n let deprecatedCallback;\n if (typeof contextOptions === 'function') {\n deprecatedCallback = contextOptions;\n contextOptions = undefined;\n }\n const context = this._getHelpContext(contextOptions);\n\n this._getCommandAndAncestors()\n .reverse()\n .forEach((command) => command.emit('beforeAllHelp', context));\n this.emit('beforeHelp', context);\n\n let helpInformation = this.helpInformation(context);\n if (deprecatedCallback) {\n helpInformation = deprecatedCallback(helpInformation);\n if (\n typeof helpInformation !== 'string' &&\n !Buffer.isBuffer(helpInformation)\n ) {\n throw new Error('outputHelp callback must return a string or a Buffer');\n }\n }\n context.write(helpInformation);\n\n if (this._getHelpOption()?.long) {\n this.emit(this._getHelpOption().long); // deprecated\n }\n this.emit('afterHelp', context);\n this._getCommandAndAncestors().forEach((command) =>\n command.emit('afterAllHelp', context),\n );\n }\n\n /**\n * You can pass in flags and a description to customise the built-in help option.\n * Pass in false to disable the built-in help option.\n *\n * @example\n * program.helpOption('-?, --help' 'show help'); // customise\n * program.helpOption(false); // disable\n *\n * @param {(string | boolean)} flags\n * @param {string} [description]\n * @return {Command} `this` command for chaining\n */\n\n helpOption(flags, description) {\n // Support disabling built-in help option.\n if (typeof flags === 'boolean') {\n if (flags) {\n this._helpOption = this._helpOption ?? undefined; // preserve existing option\n } else {\n this._helpOption = null; // disable\n }\n return this;\n }\n\n // Customise flags and description.\n flags = flags ?? '-h, --help';\n description = description ?? 'display help for command';\n this._helpOption = this.createOption(flags, description);\n\n return this;\n }\n\n /**\n * Lazy create help option.\n * Returns null if has been disabled with .helpOption(false).\n *\n * @returns {(Option | null)} the help option\n * @package\n */\n _getHelpOption() {\n // Lazy create help option on demand.\n if (this._helpOption === undefined) {\n this.helpOption(undefined, undefined);\n }\n return this._helpOption;\n }\n\n /**\n * Supply your own option to use for the built-in help option.\n * This is an alternative to using helpOption() to customise the flags and description etc.\n *\n * @param {Option} option\n * @return {Command} `this` command for chaining\n */\n addHelpOption(option) {\n this._helpOption = option;\n return this;\n }\n\n /**\n * Output help information and exit.\n *\n * Outputs built-in help, and custom text added using `.addHelpText()`.\n *\n * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout\n */\n\n help(contextOptions) {\n this.outputHelp(contextOptions);\n let exitCode = process.exitCode || 0;\n if (\n exitCode === 0 &&\n contextOptions &&\n typeof contextOptions !== 'function' &&\n contextOptions.error\n ) {\n exitCode = 1;\n }\n // message: do not have all displayed text available so only passing placeholder.\n this._exit(exitCode, 'commander.help', '(outputHelp)');\n }\n\n /**\n * Add additional text to be displayed with the built-in help.\n *\n * Position is 'before' or 'after' to affect just this command,\n * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.\n *\n * @param {string} position - before or after built-in help\n * @param {(string | Function)} text - string to add, or a function returning a string\n * @return {Command} `this` command for chaining\n */\n addHelpText(position, text) {\n const allowedValues = ['beforeAll', 'before', 'after', 'afterAll'];\n if (!allowedValues.includes(position)) {\n throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${allowedValues.join(\"', '\")}'`);\n }\n const helpEvent = `${position}Help`;\n this.on(helpEvent, (context) => {\n let helpStr;\n if (typeof text === 'function') {\n helpStr = text({ error: context.error, command: context.command });\n } else {\n helpStr = text;\n }\n // Ignore falsy value when nothing to output.\n if (helpStr) {\n context.write(`${helpStr}\\n`);\n }\n });\n return this;\n }\n\n /**\n * Output help information if help flags specified\n *\n * @param {Array} args - array of options to search for help flags\n * @private\n */\n\n _outputHelpIfRequested(args) {\n const helpOption = this._getHelpOption();\n const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));\n if (helpRequested) {\n this.outputHelp();\n // (Do not have all displayed text available so only passing placeholder.)\n this._exit(0, 'commander.helpDisplayed', '(outputHelp)');\n }\n }\n}\n\n/**\n * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command).\n *\n * @param {string[]} args - array of arguments from node.execArgv\n * @returns {string[]}\n * @private\n */\n\nfunction incrementNodeInspectorPort(args) {\n // Testing for these options:\n // --inspect[=[host:]port]\n // --inspect-brk[=[host:]port]\n // --inspect-port=[host:]port\n return args.map((arg) => {\n if (!arg.startsWith('--inspect')) {\n return arg;\n }\n let debugOption;\n let debugHost = '127.0.0.1';\n let debugPort = '9229';\n let match;\n if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {\n // e.g. --inspect\n debugOption = match[1];\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null\n ) {\n debugOption = match[1];\n if (/^\\d+$/.test(match[3])) {\n // e.g. --inspect=1234\n debugPort = match[3];\n } else {\n // e.g. --inspect=localhost\n debugHost = match[3];\n }\n } else if (\n (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\\d+)$/)) !== null\n ) {\n // e.g. --inspect=localhost:1234\n debugOption = match[1];\n debugHost = match[3];\n debugPort = match[4];\n }\n\n if (debugOption && debugPort !== '0') {\n return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;\n }\n return arg;\n });\n}\n\nexports.Command = Command;\n","const { Argument } = require('./lib/argument.js');\nconst { Command } = require('./lib/command.js');\nconst { CommanderError, InvalidArgumentError } = require('./lib/error.js');\nconst { Help } = require('./lib/help.js');\nconst { Option } = require('./lib/option.js');\n\nexports.program = new Command();\n\nexports.createCommand = (name) => new Command(name);\nexports.createOption = (flags, description) => new Option(flags, description);\nexports.createArgument = (name, description) => new Argument(name, description);\n\n/**\n * Expose classes\n */\n\nexports.Command = Command;\nexports.Option = Option;\nexports.Argument = Argument;\nexports.Help = Help;\n\nexports.CommanderError = CommanderError;\nexports.InvalidArgumentError = InvalidArgumentError;\nexports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated\n","export const SHARED_PACKAGE = '@crosssync/shared';\nexport const SHARED_VERSION = '0.1.0';\n\n/** Log levels, ordered from most to least verbose. */\nexport const LOG_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type LogLevel = (typeof LOG_LEVELS)[number];\n\n/** Supported Chromium-based browsers. */\nexport const BROWSERS = ['chrome', 'edge'] as const;\nexport type BrowserName = (typeof BROWSERS)[number];\n\n/**\n * Chromium timestamps are microseconds since 1601-01-01T00:00:00Z.\n * This is the offset between that epoch and the Unix epoch, in milliseconds.\n */\nexport const CHROMIUM_EPOCH_OFFSET_MS = 11644473600000;\n\n/** Directory name (created under the user home) holding all CrossSync runtime data. */\nexport const CROSSSYNC_DIR_NAME = '.crosssync';\nexport const BACKUP_DIR_NAME = 'backups';\nexport const EXPORT_DIR_NAME = 'export';\nexport const LOG_DIR_NAME = 'logs';\nexport const CONFIG_FILE_NAME = 'config.json';\nexport const LOG_FILE_NAME = 'crosssync.log';\n\n/** File names inside a Chromium profile directory. */\nexport const BOOKMARKS_FILE_NAME = 'Bookmarks';\nexport const HISTORY_FILE_NAME = 'History';\n\n/** Chromium profile directory names that actually hold user data. */\nexport const PROFILE_NAME_PATTERN = /^(Default|Profile \\d+)$/;\n\nexport const DEFAULT_PROFILE = 'Default';\nexport const DEFAULT_LOG_LEVEL: LogLevel = 'info';\nexport const CONFIG_VERSION = 1;\n\n/** How many of the most recent export files are kept after a successful run. */\nexport const DEFAULT_EXPORT_RETENTION = 10;\n\n/** Cron expression installed by default: every day at 09:00 local time. */\nexport const DEFAULT_CRON_SCHEDULE = '0 9 * * *';\n","/**\n * Types mirroring the Chromium `Bookmarks` JSON file, shared by Chrome and Edge.\n *\n * Chromium writes snake_case keys (`date_added`, `date_modified`, ...) and encodes\n * timestamps as microsecond strings since the Windows epoch (1601-01-01).\n */\n\nexport const BOOKMARK_NODE_TYPES = ['folder', 'url'] as const;\nexport type BookmarkNodeType = (typeof BOOKMARK_NODE_TYPES)[number];\n\nexport interface BookmarkNode {\n /** Chromium-managed numeric id, string encoded. */\n id: string;\n /** Display name. Root folders use localized names. */\n name: string;\n type: BookmarkNodeType;\n /** Present on `folder` nodes only. */\n children?: BookmarkNode[];\n /** Present on `url` nodes only. */\n url?: string;\n /** Chromium GUID; regenerated when absent. */\n guid?: string;\n /** Microseconds since the Windows epoch, string encoded. */\n date_added?: string;\n date_modified?: string;\n date_last_used?: string;\n meta_info?: Record<string, unknown>;\n}\n\n/** Fixed top-level folders of a Chromium bookmark file. */\nexport const BOOKMARK_ROOT_KEYS = ['bookmark_bar', 'other', 'synced'] as const;\nexport type BookmarkRootKey = (typeof BOOKMARK_ROOT_KEYS)[number];\n\nexport interface BookmarkRoots {\n bookmark_bar: BookmarkNode;\n other: BookmarkNode;\n synced?: BookmarkNode;\n}\n\nexport interface BookmarkFile {\n /** Chrome validates this MD5 field; CrossSync drops it on write-back. */\n checksum?: string;\n roots: BookmarkRoots;\n version?: number;\n}\n\n/** A bookmark node together with the folder path leading to it. */\nexport interface FlatBookmark {\n node: BookmarkNode;\n /** Folder names from the root down to (excluding) the node itself. */\n folderPath: string[];\n}\n\nexport function isBookmarkFolder(node: BookmarkNode): boolean {\n return node.type === 'folder';\n}\n\nexport function isBookmarkUrl(node: BookmarkNode): boolean {\n return node.type === 'url';\n}\n\n/** Depth-first traversal of a bookmark tree. */\nexport function walkBookmarkTree(node: BookmarkNode, visit: (node: BookmarkNode) => void): void {\n visit(node);\n for (const child of node.children ?? []) {\n walkBookmarkTree(child, visit);\n }\n}\n\n/** Flattens a bookmark tree into a list of nodes while keeping their folder path. */\nexport function flattenBookmarks(root: BookmarkNode, folderPath: string[] = []): FlatBookmark[] {\n const result: FlatBookmark[] = [{ node: root, folderPath }];\n const nextPath = root.type === 'folder' ? [...folderPath, root.name] : folderPath;\n for (const child of root.children ?? []) {\n result.push(...flattenBookmarks(child, nextPath));\n }\n return result;\n}\n\n/** Counts nodes in a bookmark tree, optionally filtered by node type. */\nexport function countBookmarks(root: BookmarkNode, type?: BookmarkNodeType): number {\n let total = 0;\n walkBookmarkTree(root, (node) => {\n if (!type || node.type === type) {\n total += 1;\n }\n });\n return total;\n}\n","/**\n * Types mirroring the Chromium `History` SQLite database (`urls` table).\n *\n * Chromium stores `last_visit_time` as microseconds since the Windows epoch and\n * `visit_count` / `typed_count` as integers. CrossSync normalises the timestamp\n * to Unix milliseconds so downstream code never deals with the Chromium epoch.\n */\n\nexport interface HistoryEntry {\n /** Chromium `urls.id`; absent for entries built in memory. */\n id?: number;\n url: string;\n title: string;\n visitCount: number;\n typedCount: number;\n /** Unix epoch milliseconds. */\n lastVisitTime: number;\n}\n\n/** A `History` file together with the profile it was read from. */\nexport interface HistoryFile {\n browser: string;\n profile: string;\n entries: HistoryEntry[];\n}\n\nexport const HISTORY_QUERY = [\n 'SELECT id, url, title, visit_count, typed_count, last_visit_time',\n 'FROM urls',\n \"WHERE url IS NOT NULL AND url != ''\",\n 'ORDER BY last_visit_time DESC',\n].join(' ');\n","import type { BrowserName, LogLevel } from './constants';\nimport {\n CONFIG_VERSION,\n DEFAULT_CRON_SCHEDULE,\n DEFAULT_EXPORT_RETENTION,\n DEFAULT_LOG_LEVEL,\n DEFAULT_PROFILE,\n} from './constants';\n\n/** Whether a run may write merged bookmarks back into the browser files. */\nexport const SYNC_STRATEGIES = ['merge', 'export'] as const;\nexport type SyncStrategy = (typeof SYNC_STRATEGIES)[number];\n\nexport interface BrowserConfig {\n enabled: boolean;\n /** Override for the auto-detected browser \"User Data\" directory. */\n dataDir?: string;\n}\n\nexport interface SyncConfig {\n bookmarks: boolean;\n history: boolean;\n /** `merge` = merge then write back; `export` = read-only, write merged output only. */\n strategy: SyncStrategy;\n}\n\nexport interface ScheduleConfig {\n /** True when a scheduled task/timer has been installed. */\n installed: boolean;\n /** Cron expression used by the installed schedule. */\n expression: string;\n}\n\nexport interface ExportsConfig {\n /** How many of the most recent export files to keep; `0` disables cleanup. */\n keep: number;\n}\n\nexport interface CliConfig {\n version: number;\n /** Absolute path of the CrossSync data directory (`~/.crosssync`). */\n dataDir: string;\n backupDir: string;\n exportDir: string;\n logDir: string;\n logLevel: LogLevel;\n /** Chromium profile to sync: `Default`, `Profile 1`, ... or `all`. */\n profile: string;\n browsers: Record<BrowserName, BrowserConfig>;\n sync: SyncConfig;\n schedule: ScheduleConfig;\n /** Optional so configs written by older versions keep loading. */\n exports?: ExportsConfig;\n}\n\n/** Reads `exports.keep`, falling back to the default for older config files. */\nexport function resolveExportRetention(config: Pick<CliConfig, 'exports'>): number {\n return config.exports?.keep ?? DEFAULT_EXPORT_RETENTION;\n}\n\n/**\n * Splits a configured `profile` value into unique names.\n * A comma-separated list lets one config sync several profiles at once.\n */\nexport function parseProfileList(value: string): string[] {\n const names: string[] = [];\n for (const part of value.split(',')) {\n const name = part.trim();\n if (name.length > 0 && !names.includes(name)) {\n names.push(name);\n }\n }\n return names;\n}\n\n/** Adds profile names to a configured value, preserving the `all` sentinel. */\nexport function addProfilesToSelection(current: string, additions: readonly string[]): string {\n if (current.trim() === 'all') {\n return 'all';\n }\n const names = parseProfileList(current);\n for (const name of additions) {\n if (name.trim().length > 0 && !names.includes(name.trim())) {\n names.push(name.trim());\n }\n }\n return names.join(',');\n}\n\nexport interface CreateDefaultConfigOptions {\n dataDir: string;\n backupDir: string;\n exportDir: string;\n logDir: string;\n profile?: string;\n logLevel?: LogLevel;\n}\n\nexport function createDefaultConfig(options: CreateDefaultConfigOptions): CliConfig {\n return {\n version: CONFIG_VERSION,\n dataDir: options.dataDir,\n backupDir: options.backupDir,\n exportDir: options.exportDir,\n logDir: options.logDir,\n logLevel: options.logLevel ?? DEFAULT_LOG_LEVEL,\n profile: options.profile ?? DEFAULT_PROFILE,\n browsers: {\n chrome: { enabled: true },\n edge: { enabled: true },\n },\n sync: {\n bookmarks: true,\n history: true,\n strategy: 'merge',\n },\n schedule: {\n installed: false,\n expression: DEFAULT_CRON_SCHEDULE,\n },\n exports: {\n keep: DEFAULT_EXPORT_RETENTION,\n },\n };\n}\n","import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\nimport { createRequire } from 'module';\n\nimport type { BookmarkFile, BookmarkNode } from './bookmark';\nimport { SYNC_STRATEGIES, type CliConfig } from './config';\nimport type { BrowserName, LogLevel } from './constants';\nimport {\n BACKUP_DIR_NAME,\n BROWSERS,\n CHROMIUM_EPOCH_OFFSET_MS,\n CONFIG_FILE_NAME,\n CROSSSYNC_DIR_NAME,\n EXPORT_DIR_NAME,\n LOG_DIR_NAME,\n LOG_FILE_NAME,\n LOG_LEVELS,\n PROFILE_NAME_PATTERN,\n} from './constants';\nimport type { HistoryEntry } from './history';\n\n/* -------------------------------------------------------------------------- */\n/* JSON helpers */\n/* -------------------------------------------------------------------------- */\n\nexport function safeJsonParse<T>(input: string): T | null {\n try {\n return JSON.parse(input) as T;\n } catch {\n return null;\n }\n}\n\nexport function readJsonFile<T>(filePath: string): T | null {\n try {\n return safeJsonParse<T>(fs.readFileSync(filePath, 'utf8'));\n } catch {\n return null;\n }\n}\n\n/**\n * Writes JSON via a temporary file in the same directory followed by a rename,\n * so a partial write can never corrupt an existing file.\n */\nexport function writeJsonFileSafe(filePath: string, data: unknown): void {\n const dir = path.dirname(filePath);\n ensureDir(dir);\n const tempFile = path.join(dir, `${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`);\n try {\n fs.writeFileSync(tempFile, `${JSON.stringify(data, null, 2)}\\n`, 'utf8');\n fs.renameSync(tempFile, filePath);\n } catch (error) {\n safeUnlink(tempFile);\n throw error;\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Filesystem helpers */\n/* -------------------------------------------------------------------------- */\n\nexport function pathExists(target: string): boolean {\n try {\n fs.accessSync(target);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function ensureDir(dir: string): string {\n fs.mkdirSync(dir, { recursive: true });\n return dir;\n}\n\nexport function safeUnlink(target: string): void {\n try {\n fs.unlinkSync(target);\n } catch {\n /* ignore: the file may already be gone */\n }\n}\n\nexport function removeDirSafe(dir: string): void {\n try {\n fs.rmSync(dir, { recursive: true, force: true });\n } catch {\n /* ignore: best effort cleanup */\n }\n}\n\n/** Copies a (possibly locked) file to a new location, then renames it into place. */\nexport function copyFileSafe(source: string, destination: string): void {\n ensureDir(path.dirname(destination));\n const tempFile = `${destination}.${process.pid}.${Date.now()}.tmp`;\n try {\n fs.copyFileSync(source, tempFile);\n fs.renameSync(tempFile, destination);\n } catch (error) {\n safeUnlink(tempFile);\n throw error;\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Chromium time conversion */\n/* -------------------------------------------------------------------------- */\n\n/** Converts a Chromium microsecond timestamp into Unix epoch milliseconds. */\nexport function parseChromiumTime(value: string | number | null | undefined): number {\n if (value === null || value === undefined || value === '') {\n return 0;\n }\n const micros = typeof value === 'number' ? value : Number(value);\n if (!Number.isFinite(micros)) {\n return 0;\n }\n return Math.round(micros / 1000) - CHROMIUM_EPOCH_OFFSET_MS;\n}\n\n/** Converts Unix epoch milliseconds into a Chromium microsecond timestamp string. */\nexport function toChromiumTime(unixMs: number): string {\n return String((unixMs + CHROMIUM_EPOCH_OFFSET_MS) * 1000);\n}\n\n/* -------------------------------------------------------------------------- */\n/* Cross-platform path resolution */\n/* -------------------------------------------------------------------------- */\n\nexport function resolveHomeDir(\n env: NodeJS.ProcessEnv = process.env,\n platform: NodeJS.Platform = process.platform,\n): string {\n if (platform === 'win32' && env.USERPROFILE) {\n return env.USERPROFILE;\n }\n if (env.HOME) {\n return env.HOME;\n }\n try {\n return os.homedir();\n } catch {\n return process.cwd();\n }\n}\n\ntype BrowserPathSegments = Record<'win32' | 'darwin' | 'linux', string[]>;\n\nconst BROWSER_PATH_SEGMENTS: Record<BrowserName, BrowserPathSegments> = {\n chrome: {\n win32: ['Google', 'Chrome', 'User Data'],\n darwin: ['Library', 'Application Support', 'Google', 'Chrome'],\n linux: ['.config', 'google-chrome'],\n },\n edge: {\n win32: ['Microsoft', 'Edge', 'User Data'],\n darwin: ['Library', 'Application Support', 'Microsoft Edge'],\n linux: ['.config', 'microsoft-edge'],\n },\n};\n\nexport interface ResolveBrowserDataDirOptions {\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n homeDir?: string;\n}\n\n/** Resolves the \"User Data\" directory of a Chromium browser for the current OS. */\nexport function resolveBrowserDataDir(\n browser: BrowserName,\n options: ResolveBrowserDataDirOptions = {},\n): string {\n const platform = options.platform ?? process.platform;\n const env = options.env ?? process.env;\n const home = options.homeDir ?? resolveHomeDir(env, platform);\n const segments = BROWSER_PATH_SEGMENTS[browser];\n\n if (platform === 'win32') {\n const localAppData = env.LOCALAPPDATA ?? path.join(home, 'AppData', 'Local');\n return path.join(localAppData, ...segments.win32);\n }\n const key = platform === 'darwin' ? 'darwin' : 'linux';\n return path.join(home, ...segments[key]);\n}\n\n/** Lists the Chromium profile directory names found inside a \"User Data\" directory. */\nexport function listProfiles(dataDir: string): string[] {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dataDir, { withFileTypes: true });\n } catch {\n return [];\n }\n return entries\n .filter((entry) => entry.isDirectory() && PROFILE_NAME_PATTERN.test(entry.name))\n .map((entry) => entry.name)\n .sort((a, b) => a.localeCompare(b));\n}\n\nexport function resolveProfileDir(dataDir: string, profile: string): string {\n return path.join(dataDir, profile);\n}\n\nexport interface CrossSyncDirs {\n root: string;\n backups: string;\n exports: string;\n logs: string;\n configFile: string;\n logFile: string;\n}\n\n/** Resolves every CrossSync runtime path (all under `~/.crosssync`). */\nexport function resolveCrossSyncDirs(homeDir?: string): CrossSyncDirs {\n const root = path.join(homeDir ?? resolveHomeDir(), CROSSSYNC_DIR_NAME);\n return {\n root,\n backups: path.join(root, BACKUP_DIR_NAME),\n exports: path.join(root, EXPORT_DIR_NAME),\n logs: path.join(root, LOG_DIR_NAME),\n configFile: path.join(root, CONFIG_FILE_NAME),\n logFile: path.join(root, LOG_DIR_NAME, LOG_FILE_NAME),\n };\n}\n\n/* -------------------------------------------------------------------------- */\n/* SQLite \"copy then read\" */\n/* -------------------------------------------------------------------------- */\n\nexport interface SqliteStatement {\n all(...params: unknown[]): unknown[];\n run(...params: unknown[]): unknown;\n}\n\nexport interface SqliteDatabase {\n prepare(sql: string): SqliteStatement;\n exec(sql: string): void;\n close(): void;\n}\n\nexport interface SqliteDriver {\n new (\n filename: string,\n options?: { readonly?: boolean; fileMustExist?: boolean; timeout?: number },\n ): SqliteDatabase;\n}\n\nexport interface ReadSqliteCopyOptions {\n sql: string;\n params?: unknown[];\n /** Prefix used for the temporary directory holding the copy. */\n tempPrefix?: string;\n}\n\nconst requireFromHere = createRequire(__filename);\n\nlet sqliteDriver: SqliteDriver | null = null;\n\n/**\n * Lazily resolves the optional `better-sqlite3` native driver so that the many\n * code paths that never touch browser history keep working without it installed.\n */\nexport function loadSqliteDriver(): SqliteDriver {\n if (sqliteDriver) {\n return sqliteDriver;\n }\n try {\n const loaded = requireFromHere('better-sqlite3') as SqliteDriver | { default: SqliteDriver };\n sqliteDriver = typeof loaded === 'function' ? loaded : loaded.default;\n return sqliteDriver;\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(\n `Unable to load the \"better-sqlite3\" driver (${reason}). ` +\n 'Run `pnpm install` to build/download the native SQLite driver, then retry.',\n );\n }\n}\n\n/** Injects a driver implementation (used by tests) or resets the cache. */\nexport function setSqliteDriver(driver: SqliteDriver | null): void {\n sqliteDriver = driver;\n}\n\n/**\n * Chromium keeps an exclusive lock on `History` while the browser runs, so we\n * copy it to a temp directory first and read the copy.\n */\nexport function copyDatabaseToTemp(dbPath: string, tempPrefix = 'crosssync-sqlite'): string {\n const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), `${tempPrefix}-`));\n const target = path.join(tempDir, path.basename(dbPath));\n fs.copyFileSync(dbPath, target);\n return target;\n}\n\n/** Runs a query against a temporary copy of a SQLite database. */\nexport function readSqliteCopy<T = Record<string, unknown>>(\n dbPath: string,\n options: ReadSqliteCopyOptions,\n): T[] {\n if (!pathExists(dbPath)) {\n throw new Error(`SQLite database not found: ${dbPath}`);\n }\n const tempCopy = copyDatabaseToTemp(dbPath, options.tempPrefix);\n const Database = loadSqliteDriver();\n let db: SqliteDatabase | null = null;\n try {\n db = new Database(tempCopy, { readonly: true, fileMustExist: true });\n const statement = db.prepare(options.sql);\n return statement.all(...(options.params ?? [])) as T[];\n } finally {\n try {\n db?.close();\n } catch {\n /* ignore */\n }\n removeDirSafe(path.dirname(tempCopy));\n }\n}\n\n/* -------------------------------------------------------------------------- */\n/* Type guards */\n/* -------------------------------------------------------------------------- */\n\nexport function isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function isBookmarkNode(value: unknown): value is BookmarkNode {\n if (!isPlainObject(value)) {\n return false;\n }\n if (typeof value.id !== 'string' || typeof value.name !== 'string') {\n return false;\n }\n if (value.type !== 'folder' && value.type !== 'url') {\n return false;\n }\n if (value.url !== undefined && typeof value.url !== 'string') {\n return false;\n }\n if (value.children !== undefined) {\n if (!Array.isArray(value.children) || !value.children.every(isBookmarkNode)) {\n return false;\n }\n }\n return true;\n}\n\nexport function isBookmarkFile(value: unknown): value is BookmarkFile {\n if (!isPlainObject(value) || !isPlainObject(value.roots)) {\n return false;\n }\n const roots = value.roots;\n return isBookmarkNode(roots.bookmark_bar) && isBookmarkNode(roots.other);\n}\n\nexport function isHistoryEntry(value: unknown): value is HistoryEntry {\n if (!isPlainObject(value)) {\n return false;\n }\n return (\n typeof value.url === 'string' &&\n typeof value.title === 'string' &&\n typeof value.visitCount === 'number' &&\n typeof value.typedCount === 'number' &&\n typeof value.lastVisitTime === 'number'\n );\n}\n\nexport function isLogLevel(value: unknown): value is LogLevel {\n return typeof value === 'string' && (LOG_LEVELS as readonly string[]).includes(value);\n}\n\nexport function isBrowserName(value: unknown): value is BrowserName {\n return typeof value === 'string' && (BROWSERS as readonly string[]).includes(value);\n}\n\nexport function isCliConfig(value: unknown): value is CliConfig {\n if (!isPlainObject(value)) {\n return false;\n }\n const stringKeys = ['dataDir', 'backupDir', 'exportDir', 'logDir', 'profile'];\n if (typeof value.version !== 'number') {\n return false;\n }\n if (!stringKeys.every((key) => typeof value[key] === 'string')) {\n return false;\n }\n if (!isLogLevel(value.logLevel)) {\n return false;\n }\n\n if (!isPlainObject(value.browsers)) {\n return false;\n }\n for (const browser of BROWSERS) {\n const entry = (value.browsers as Record<string, unknown>)[browser];\n if (!isPlainObject(entry) || typeof entry.enabled !== 'boolean') {\n return false;\n }\n }\n\n if (!isPlainObject(value.sync)) {\n return false;\n }\n const sync = value.sync;\n if (typeof sync.bookmarks !== 'boolean' || typeof sync.history !== 'boolean') {\n return false;\n }\n if (!(SYNC_STRATEGIES as readonly string[]).includes(sync.strategy as string)) {\n return false;\n }\n\n if (!isPlainObject(value.schedule)) {\n return false;\n }\n if (\n typeof value.schedule.installed !== 'boolean' ||\n typeof value.schedule.expression !== 'string'\n ) {\n return false;\n }\n\n // `exports` was added after the first config version; missing is valid.\n const exportsValue = value.exports;\n if (exportsValue !== undefined) {\n if (!isPlainObject(exportsValue)) {\n return false;\n }\n const keep = exportsValue.keep;\n if (typeof keep !== 'number' || !Number.isInteger(keep) || keep < 0) {\n return false;\n }\n }\n return true;\n}\n","export * from './constants';\nexport * from './bookmark';\nexport * from './history';\nexport * from './config';\nexport * from './utils';\n\nexport const PACKAGE = '@crosssync/shared';\nexport const VERSION = '0.1.0';\n","import type { BrowserName } from '@crosssync/shared';\n\nexport const CORE_PACKAGE = '@crosssync/core';\nexport const CORE_VERSION = '0.1.0';\n\n/** How many of the most recent backups `pruneBackups` keeps by default. */\nexport const DEFAULT_BACKUP_RETENTION = 10;\n\n/** Maximum number of log entries kept in memory by `Logger`. */\nexport const MAX_BUFFERED_LOG_ENTRIES = 500;\n\n/** Default number of entries returned by `readLogEntries`. */\nexport const DEFAULT_LOG_LIMIT = 100;\n\nexport interface BrowserProcessNames {\n win32: string;\n darwin: string;\n linux: string;\n}\n\n/** Executable / application names used to detect a running browser. */\nexport const BROWSER_PROCESS_NAMES: Record<BrowserName, BrowserProcessNames> = {\n chrome: {\n win32: 'chrome.exe',\n darwin: 'Google Chrome',\n linux: 'chrome',\n },\n edge: {\n win32: 'msedge.exe',\n darwin: 'Microsoft Edge',\n linux: 'msedge',\n },\n};\n","import fs from 'fs';\nimport path from 'path';\n\nimport type { LogLevel } from '@crosssync/shared';\nimport { ensureDir, LOG_LEVELS } from '@crosssync/shared';\n\nimport { DEFAULT_LOG_LIMIT, MAX_BUFFERED_LOG_ENTRIES } from './constants';\n\nexport type { LogLevel };\n\nexport interface LogEntry {\n level: LogLevel;\n message: string;\n timestamp: number;\n meta?: Record<string, unknown>;\n}\n\nconst LEVEL_ORDER: Record<LogLevel, number> = {\n debug: 0,\n info: 1,\n warn: 2,\n error: 3,\n};\n\nexport interface LoggerOptions {\n /** Append JSON-lines entries to this file, consumed by `crosssync logs`. */\n filePath?: string;\n /** Mirror entries to the console. Defaults to true. */\n console?: boolean;\n}\n\n/**\n * Console + JSON-lines file logger.\n *\n * Logging must never break a sync run, so file write failures are swallowed.\n */\nexport class Logger {\n private minLevel: LogLevel;\n private readonly options: Required<LoggerOptions>;\n private readonly buffer: LogEntry[] = [];\n\n constructor(minLevel: LogLevel = 'info', options: LoggerOptions = {}) {\n this.minLevel = LOG_LEVELS.includes(minLevel) ? minLevel : 'info';\n this.options = {\n filePath: options.filePath ?? '',\n console: options.console ?? true,\n };\n }\n\n setLevel(level: LogLevel): void {\n this.minLevel = level;\n }\n\n getLevel(): LogLevel {\n return this.minLevel;\n }\n\n setFile(filePath: string): void {\n this.options.filePath = filePath;\n }\n\n getFile(): string {\n return this.options.filePath;\n }\n\n isEnabled(level: LogLevel): boolean {\n return LEVEL_ORDER[level] >= LEVEL_ORDER[this.minLevel];\n }\n\n debug(message: string, meta?: Record<string, unknown>): void {\n this.log('debug', message, meta);\n }\n\n info(message: string, meta?: Record<string, unknown>): void {\n this.log('info', message, meta);\n }\n\n warn(message: string, meta?: Record<string, unknown>): void {\n this.log('warn', message, meta);\n }\n\n error(message: string, meta?: Record<string, unknown>): void {\n this.log('error', message, meta);\n }\n\n /** Snapshot of the in-memory ring buffer. */\n getEntries(): LogEntry[] {\n return [...this.buffer];\n }\n\n clearBuffer(): void {\n this.buffer.length = 0;\n }\n\n private log(level: LogLevel, message: string, meta?: Record<string, unknown>): void {\n if (!this.isEnabled(level)) {\n return;\n }\n const entry: LogEntry = { level, message, timestamp: Date.now(), meta };\n this.buffer.push(entry);\n if (this.buffer.length > MAX_BUFFERED_LOG_ENTRIES) {\n this.buffer.shift();\n }\n if (this.options.console) {\n writeConsole(entry);\n }\n this.appendToFile(entry);\n }\n\n private appendToFile(entry: LogEntry): void {\n if (!this.options.filePath) {\n return;\n }\n try {\n ensureDir(path.dirname(this.options.filePath));\n fs.appendFileSync(this.options.filePath, `${JSON.stringify(entry)}\\n`, 'utf8');\n } catch {\n /* logging must never break a run */\n }\n }\n}\n\nfunction writeConsole(entry: LogEntry): void {\n const prefix = `[${new Date(entry.timestamp).toISOString()}] [${entry.level.toUpperCase()}]`;\n if (entry.level === 'error') {\n console.error(prefix, entry.message, entry.meta ?? '');\n } else if (entry.level === 'warn') {\n console.warn(prefix, entry.message, entry.meta ?? '');\n } else {\n console.log(prefix, entry.message, entry.meta ?? '');\n }\n}\n\nexport interface ReadLogEntriesOptions {\n limit?: number;\n level?: LogLevel;\n}\n\n/** Reads the most recent JSON-lines entries from a log file. */\nexport function readLogEntries(filePath: string, options: ReadLogEntriesOptions = {}): LogEntry[] {\n let raw: string;\n try {\n raw = fs.readFileSync(filePath, 'utf8');\n } catch {\n return [];\n }\n\n const limit = options.limit ?? DEFAULT_LOG_LIMIT;\n const entries: LogEntry[] = [];\n for (const line of raw.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (!trimmed) {\n continue;\n }\n const parsed = parseLogEntry(trimmed);\n if (!parsed) {\n continue;\n }\n if (options.level && LEVEL_ORDER[parsed.level] < LEVEL_ORDER[options.level]) {\n continue;\n }\n entries.push(parsed);\n }\n\n return limit > 0 ? entries.slice(-limit) : entries;\n}\n\n/** Removes the log file; used by `crosssync logs --clear`. */\nexport function clearLogFile(filePath: string): void {\n try {\n fs.rmSync(filePath, { force: true });\n } catch {\n /* ignore */\n }\n}\n\nfunction parseLogEntry(line: string): LogEntry | null {\n let value: unknown;\n try {\n value = JSON.parse(line);\n } catch {\n return null;\n }\n if (typeof value !== 'object' || value === null) {\n return null;\n }\n const record = value as Record<string, unknown>;\n if (\n typeof record.level !== 'string' ||\n !LOG_LEVELS.includes(record.level as LogLevel) ||\n typeof record.message !== 'string' ||\n typeof record.timestamp !== 'number'\n ) {\n return null;\n }\n const meta =\n typeof record.meta === 'object' && record.meta !== null\n ? (record.meta as Record<string, unknown>)\n : undefined;\n return {\n level: record.level as LogLevel,\n message: record.message,\n timestamp: record.timestamp,\n meta,\n };\n}\n","import { execFileSync } from 'child_process';\n\nimport type { BrowserName } from '@crosssync/shared';\nimport { BROWSERS } from '@crosssync/shared';\n\nimport { BROWSER_PROCESS_NAMES } from './constants';\n\nexport interface BrowserStatus {\n browser: BrowserName;\n running: boolean;\n processName: string;\n}\n\nexport interface ProcessResult {\n status: number;\n stdout: string;\n}\n\n/** Injectable process runner, so detection is unit-testable. */\nexport type ProcessRunner = (command: string, args: string[]) => ProcessResult;\n\nexport interface BrowserStatusOptions {\n platform?: NodeJS.Platform;\n runner?: ProcessRunner;\n}\n\n/** Executable / application name used to detect the given browser. */\nexport function getProcessName(\n browser: BrowserName,\n platform: NodeJS.Platform = process.platform,\n): string {\n const names = BROWSER_PROCESS_NAMES[browser];\n if (platform === 'win32') {\n return names.win32;\n }\n return platform === 'darwin' ? names.darwin : names.linux;\n}\n\n/** Builds the OS command that lists processes for the given browser. */\nexport function buildProcessQuery(\n browser: BrowserName,\n platform: NodeJS.Platform = process.platform,\n): { command: string; args: string[] } {\n const processName = getProcessName(browser, platform);\n if (platform === 'win32') {\n return {\n command: 'tasklist',\n args: ['/FI', `IMAGENAME eq ${processName}`, '/NH', '/FO', 'CSV'],\n };\n }\n return { command: 'pgrep', args: ['-ix', processName] };\n}\n\n/** Interprets the output of `tasklist` / `pgrep`. */\nexport function parseProcessOutput(\n browser: BrowserName,\n platform: NodeJS.Platform,\n result: ProcessResult,\n): boolean {\n const output = result.stdout ?? '';\n if (platform === 'win32') {\n if (/no tasks are running/i.test(output)) {\n return false;\n }\n return output.toLowerCase().includes(getProcessName(browser, platform).toLowerCase());\n }\n if (result.status !== 0) {\n return false;\n }\n return output.trim().length > 0 && output.split(/\\r?\\n/).some((line) => line.trim().length > 0);\n}\n\nexport function isBrowserRunning(\n browser: BrowserName,\n options: BrowserStatusOptions = {},\n): boolean {\n const platform = options.platform ?? process.platform;\n return parseProcessOutput(browser, platform, runQuery(browser, platform, options.runner));\n}\n\n/** Reports the running state of every supported browser. */\nexport function getRunningBrowsers(options: BrowserStatusOptions = {}): BrowserStatus[] {\n const platform = options.platform ?? process.platform;\n return BROWSERS.map((browser) => ({\n browser,\n running: parseProcessOutput(browser, platform, runQuery(browser, platform, options.runner)),\n processName: getProcessName(browser, platform),\n }));\n}\n\n/** Lists the browsers currently running. */\nexport function getRunningBrowserNames(options: BrowserStatusOptions = {}): BrowserName[] {\n return getRunningBrowsers(options)\n .filter((status) => status.running)\n .map((status) => status.browser);\n}\n\nfunction runQuery(\n browser: BrowserName,\n platform: NodeJS.Platform,\n runner?: ProcessRunner,\n): ProcessResult {\n const { command, args } = buildProcessQuery(browser, platform);\n const execute = runner ?? defaultProcessRunner;\n try {\n return execute(command, args);\n } catch {\n return { status: 1, stdout: '' };\n }\n}\n\nconst defaultProcessRunner: ProcessRunner = (command, args) => {\n try {\n const stdout = execFileSync(command, args, {\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'ignore'],\n });\n return { status: 0, stdout: typeof stdout === 'string' ? stdout : String(stdout ?? '') };\n } catch (error) {\n const failure = error as { status?: number | null; stdout?: unknown };\n const stdout = Buffer.isBuffer(failure.stdout)\n ? failure.stdout.toString('utf8')\n : typeof failure.stdout === 'string'\n ? failure.stdout\n : '';\n return { status: typeof failure.status === 'number' ? failure.status : 1, stdout };\n }\n};\n","import path from 'path';\n\nimport type { BookmarkFile, BrowserName, HistoryEntry } from '@crosssync/shared';\nimport {\n BOOKMARKS_FILE_NAME,\n BOOKMARK_ROOT_KEYS,\n countBookmarks,\n HISTORY_FILE_NAME,\n HISTORY_QUERY,\n isBookmarkFile,\n listProfiles,\n parseChromiumTime,\n parseProfileList,\n readJsonFile,\n readSqliteCopy,\n resolveBrowserDataDir,\n resolveProfileDir,\n} from '@crosssync/shared';\n\n/** Raw `urls` row as returned by SQLite (types vary by driver settings). */\nexport interface ChromiumHistoryRow {\n id?: number;\n url: string;\n title?: string | null;\n visit_count?: number;\n typed_count?: number;\n last_visit_time?: number | string | bigint | null;\n}\n\nexport interface BrowserReaderOptions {\n /** Override for the auto-detected \"User Data\" directory. */\n dataDir?: string;\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface BookmarkSource {\n browser: BrowserName;\n profile: string;\n filePath: string;\n file: BookmarkFile;\n}\n\nexport interface HistorySource {\n browser: BrowserName;\n profile: string;\n filePath: string;\n entries: HistoryEntry[];\n}\n\nexport interface BrowserReader {\n browser: BrowserName;\n /** The \"User Data\" directory this reader reads from. */\n dataDir: string;\n /** All Chromium profile directories that exist on disk. */\n profiles(): string[];\n /** Profiles selected by `profile`, which may be `all`. */\n resolveProfiles(profile: string): string[];\n bookmarksPath(profile: string): string;\n historyPath(profile: string): string;\n readBookmarks(profile: string): BookmarkSource;\n readHistory(profile: string): HistorySource;\n}\n\n/** Maps a raw SQLite row into a normalised `HistoryEntry`. */\nexport function toHistoryEntry(row: ChromiumHistoryRow): HistoryEntry {\n return {\n id: typeof row.id === 'number' ? row.id : undefined,\n url: row.url,\n title: row.title ?? '',\n visitCount: toCount(row.visit_count),\n typedCount: toCount(row.typed_count),\n lastVisitTime: toUnixMs(row.last_visit_time),\n };\n}\n\n/** Total node count of a Chromium bookmark file, including root folders. */\nexport function countBookmarkFileNodes(file: BookmarkFile): number {\n let total = 0;\n for (const key of BOOKMARK_ROOT_KEYS) {\n const root = file.roots[key];\n if (root) {\n total += countBookmarks(root);\n }\n }\n return total;\n}\n\n/**\n * Reads bookmarks and history from a Chromium-based browser (Chrome or Edge).\n *\n * The reader only ever reads: history is queried through a temporary copy and\n * bookmark files are parsed from disk. Write-back is handled by `sync`.\n */\nexport function createBrowserReader(\n browser: BrowserName,\n options: BrowserReaderOptions = {},\n): BrowserReader {\n const dataDir =\n options.dataDir ??\n resolveBrowserDataDir(browser, { platform: options.platform, env: options.env });\n\n const bookmarksPath = (profile: string): string =>\n path.join(resolveProfileDir(dataDir, profile), BOOKMARKS_FILE_NAME);\n\n const historyPath = (profile: string): string =>\n path.join(resolveProfileDir(dataDir, profile), HISTORY_FILE_NAME);\n\n const profiles = (): string[] => listProfiles(dataDir);\n\n const resolveSelectedProfiles = (profile: string): string[] => {\n const found = profiles();\n if (profile.trim() === 'all') {\n return found;\n }\n const requested = parseProfileList(profile);\n return requested.filter((name) => found.includes(name));\n };\n\n const readBookmarks = (profile: string): BookmarkSource => {\n const filePath = bookmarksPath(profile);\n const file = readJsonFile<BookmarkFile>(filePath);\n if (!isBookmarkFile(file)) {\n throw new Error(`Not a valid Chromium bookmark file: ${filePath}`);\n }\n return { browser, profile, filePath, file };\n };\n\n const readHistory = (profile: string): HistorySource => {\n const filePath = historyPath(profile);\n const rows = readSqliteCopy<ChromiumHistoryRow>(filePath, {\n sql: HISTORY_QUERY,\n tempPrefix: `crosssync-history-${browser}`,\n });\n const entries = rows\n .filter((row) => typeof row.url === 'string' && row.url.length > 0)\n .map(toHistoryEntry);\n return { browser, profile, filePath, entries };\n };\n\n return {\n browser,\n dataDir,\n profiles,\n resolveProfiles: resolveSelectedProfiles,\n bookmarksPath,\n historyPath,\n readBookmarks,\n readHistory,\n };\n}\n\nfunction toCount(value: number | undefined | null): number {\n return typeof value === 'number' && Number.isFinite(value) ? value : 0;\n}\n\nfunction toUnixMs(value: number | string | bigint | null | undefined): number {\n if (value === null || value === undefined) {\n return 0;\n }\n if (typeof value === 'bigint') {\n return parseChromiumTime(value.toString());\n }\n return parseChromiumTime(value);\n}\n","import type { BrowserName, CliConfig } from '@crosssync/shared';\nimport { BROWSERS } from '@crosssync/shared';\n\nimport { createBrowserReader, type BrowserReader, type BrowserReaderOptions } from './chromium';\n\nexport * from './chromium';\n\n/** Builds a reader for every browser enabled in the CLI config. */\nexport function createConfiguredBrowserReaders(\n config: CliConfig,\n options: BrowserReaderOptions = {},\n): BrowserReader[] {\n const readers: BrowserReader[] = [];\n for (const browser of BROWSERS) {\n const browserConfig = config.browsers[browser];\n if (!browserConfig.enabled) {\n continue;\n }\n readers.push(\n createBrowserReader(browser, {\n ...options,\n dataDir: browserConfig.dataDir ?? options.dataDir,\n }),\n );\n }\n return readers;\n}\n\n/** Every supported browser, useful for reporting. */\nexport function supportedBrowsers(): readonly BrowserName[] {\n return BROWSERS;\n}\n","import type {\n BookmarkFile,\n BookmarkNode,\n BookmarkRootKey,\n BookmarkRoots,\n BrowserName,\n HistoryEntry,\n} from '@crosssync/shared';\nimport { BOOKMARK_ROOT_KEYS, countBookmarks, parseChromiumTime } from '@crosssync/shared';\n\nexport interface BookmarkMergeInput {\n browser: BrowserName;\n file: BookmarkFile;\n}\n\nexport interface BookmarkMergeStats {\n /** Total nodes in the merged tree, including root folders. */\n total: number;\n /** Nodes taken from a later browser because the accumulated tree lacked the id. */\n added: number;\n /** Nodes replaced by a later browser whose `date_added` was newer. */\n updated: number;\n /** Nodes seen in several browsers with an identical `date_added`. */\n identical: number;\n}\n\nexport interface BookmarkMergeConflict {\n id: string;\n name: string;\n type: BookmarkNode['type'];\n winnerOrigin: BrowserName;\n loserOrigin: BrowserName;\n winnerDateAdded: number;\n loserDateAdded: number;\n}\n\nexport interface BookmarkMergeResult {\n roots: BookmarkRoots;\n stats: BookmarkMergeStats;\n conflicts: BookmarkMergeConflict[];\n}\n\nexport interface HistoryMergeInput {\n browser: BrowserName;\n entries: HistoryEntry[];\n}\n\nexport interface HistoryMergeStats {\n total: number;\n /** Entries seen in more than one browser and collapsed into one. */\n duplicates: number;\n}\n\nexport interface HistoryMergeResult {\n entries: HistoryEntry[];\n stats: HistoryMergeStats;\n}\n\n/** Node wrapped with the browser it came from and an id-indexed child map. */\ninterface TrackedNode {\n node: BookmarkNode;\n origin: BrowserName;\n children: Map<string, TrackedNode>;\n}\n\n/**\n * Merges bookmark files coming from several Chromium browsers.\n *\n * Nodes are matched by `id`; when both browsers know the same id, the node with\n * the newer `date_added` wins (ties keep the earlier input's node).\n */\nexport function mergeBookmarkFiles(inputs: BookmarkMergeInput[]): BookmarkMergeResult {\n if (inputs.length === 0) {\n throw new Error('mergeBookmarkFiles requires at least one input');\n }\n\n const stats: BookmarkMergeStats = { total: 0, added: 0, updated: 0, identical: 0 };\n const conflicts: BookmarkMergeConflict[] = [];\n\n const [first, ...rest] = inputs;\n const roots: Partial<Record<BookmarkRootKey, TrackedNode>> = {};\n for (const key of BOOKMARK_ROOT_KEYS) {\n const root = first.file.roots[key];\n if (root) {\n roots[key] = toTrackedNode(root, first.browser);\n }\n }\n\n for (const input of rest) {\n for (const key of BOOKMARK_ROOT_KEYS) {\n const incoming = input.file.roots[key];\n if (!incoming) {\n continue;\n }\n const existing = roots[key];\n roots[key] = existing\n ? mergeTrackedNode(existing, toTrackedNode(incoming, input.browser), stats, conflicts)\n : toTrackedNode(incoming, input.browser);\n }\n }\n\n const mergedRoots: BookmarkRoots = {\n bookmark_bar: toBookmarkNode(roots.bookmark_bar as TrackedNode),\n other: toBookmarkNode(roots.other as TrackedNode),\n };\n if (roots.synced) {\n mergedRoots.synced = toBookmarkNode(roots.synced);\n }\n\n stats.total =\n countBookmarks(mergedRoots.bookmark_bar) +\n countBookmarks(mergedRoots.other) +\n (mergedRoots.synced ? countBookmarks(mergedRoots.synced) : 0);\n\n return { roots: mergedRoots, stats, conflicts };\n}\n\n/**\n * Merges history entries from several browsers, de-duplicating by URL.\n *\n * `visitCount` / `typedCount` take the maximum seen, the title comes from the\n * most recent visit, and `lastVisitTime` keeps the newest timestamp.\n */\nexport function mergeHistory(inputs: HistoryMergeInput[]): HistoryMergeResult {\n const byUrl = new Map<string, HistoryEntry>();\n let duplicates = 0;\n\n for (const input of inputs) {\n for (const entry of input.entries) {\n const existing = byUrl.get(entry.url);\n if (!existing) {\n byUrl.set(entry.url, { ...entry });\n continue;\n }\n duplicates += 1;\n const newest = entry.lastVisitTime > existing.lastVisitTime ? entry : existing;\n byUrl.set(entry.url, {\n ...existing,\n title: newest.title || existing.title,\n lastVisitTime: Math.max(existing.lastVisitTime, entry.lastVisitTime),\n visitCount: Math.max(existing.visitCount, entry.visitCount),\n typedCount: Math.max(existing.typedCount, entry.typedCount),\n });\n }\n }\n\n const entries = [...byUrl.values()].sort((a, b) => b.lastVisitTime - a.lastVisitTime);\n return { entries, stats: { total: entries.length, duplicates } };\n}\n\nfunction toTrackedNode(node: BookmarkNode, origin: BrowserName): TrackedNode {\n const children = new Map<string, TrackedNode>();\n for (const child of node.children ?? []) {\n children.set(child.id, toTrackedNode(child, origin));\n }\n return { node, origin, children };\n}\n\nfunction toBookmarkNode(tracked: TrackedNode): BookmarkNode {\n const node: BookmarkNode = { ...tracked.node };\n if (node.type === 'folder') {\n node.children = [...tracked.children.values()].map(toBookmarkNode);\n }\n return node;\n}\n\nfunction mergeTrackedNode(\n base: TrackedNode,\n incoming: TrackedNode,\n stats: BookmarkMergeStats,\n conflicts: BookmarkMergeConflict[],\n): TrackedNode {\n const baseDateAdded = parseChromiumTime(base.node.date_added);\n const incomingDateAdded = parseChromiumTime(incoming.node.date_added);\n const winner = incomingDateAdded > baseDateAdded ? incoming : base;\n\n if (base.node.type === 'folder' && incoming.node.type === 'folder') {\n if (incomingDateAdded === baseDateAdded) {\n stats.identical += 1;\n }\n const children = new Map(winner.children);\n for (const [id, incomingChild] of incoming.children) {\n const existing = children.get(id);\n if (existing) {\n children.set(id, mergeTrackedNode(existing, incomingChild, stats, conflicts));\n } else {\n children.set(id, incomingChild);\n stats.added += 1;\n }\n }\n return { node: winner.node, origin: winner.origin, children };\n }\n\n if (incomingDateAdded === baseDateAdded) {\n stats.identical += 1;\n return base;\n }\n\n const loser = winner === incoming ? base : incoming;\n conflicts.push({\n id: base.node.id,\n name: winner.node.name,\n type: winner.node.type,\n winnerOrigin: winner.origin,\n loserOrigin: loser.origin,\n winnerDateAdded: winner === incoming ? incomingDateAdded : baseDateAdded,\n loserDateAdded: winner === incoming ? baseDateAdded : incomingDateAdded,\n });\n\n if (winner === incoming) {\n stats.updated += 1;\n return incoming;\n }\n return base;\n}\n","import fs from 'fs';\nimport path from 'path';\n\nimport type { BrowserName } from '@crosssync/shared';\nimport {\n copyFileSafe,\n ensureDir,\n pathExists,\n readJsonFile,\n writeJsonFileSafe,\n} from '@crosssync/shared';\n\nexport type BackupKind = 'bookmarks' | 'history';\n\nexport interface BackupSource {\n kind: BackupKind;\n browser: BrowserName;\n profile: string;\n /** Absolute path of the file to copy. */\n filePath: string;\n}\n\nexport interface BackupItem {\n kind: BackupKind;\n browser: BrowserName;\n profile: string;\n /** Original location the copy was taken from. */\n source: string;\n /** File name inside the backup directory. */\n file: string;\n bytes: number;\n}\n\nexport interface BackupManifest {\n id: string;\n createdAt: string;\n platform: string;\n items: BackupItem[];\n}\n\nexport interface BackupResult {\n id: string;\n dir: string;\n manifestFile: string;\n manifest: BackupManifest;\n /** False when none of the requested sources existed yet. */\n copied: boolean;\n}\n\nexport interface BackupOptions {\n backupDir: string;\n sources: BackupSource[];\n /** Injectable clock, used by tests. */\n now?: Date;\n platform?: NodeJS.Platform;\n}\n\nexport interface BackupSummary {\n id: string;\n dir: string;\n createdAt: string | null;\n itemCount: number;\n bytes: number;\n}\n\nexport const BACKUP_MANIFEST_FILE = 'manifest.json';\n\n/** `20260116-093000` style id, derived from local time. */\nexport function formatBackupId(date: Date): string {\n return [\n `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}`,\n `${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`,\n ].join('-');\n}\n\n/** File name a source is stored under inside a backup directory. */\nexport function backupFileName(source: BackupSource): string {\n const extension = path.extname(source.filePath);\n return `${source.kind}-${source.browser}-${source.profile}${extension}`;\n}\n\n/**\n * Copies every existing source file into a timestamped backup directory.\n *\n * Throws when a copy fails: `sync` treats a failed backup as a hard stop before\n * anything is written back to a browser.\n */\nexport function createBackup(options: BackupOptions): BackupResult {\n const now = options.now ?? new Date();\n const dir = uniqueDirectory(path.join(options.backupDir, formatBackupId(now)));\n ensureDir(dir);\n\n const items: BackupItem[] = [];\n for (const source of options.sources) {\n if (!pathExists(source.filePath)) {\n continue;\n }\n const fileName = backupFileName(source);\n const target = path.join(dir, fileName);\n copyFileSafe(source.filePath, target);\n items.push({\n kind: source.kind,\n browser: source.browser,\n profile: source.profile,\n source: source.filePath,\n file: fileName,\n bytes: fs.statSync(target).size,\n });\n }\n\n const manifest: BackupManifest = {\n id: path.basename(dir),\n createdAt: now.toISOString(),\n platform: options.platform ?? process.platform,\n items,\n };\n const manifestFile = path.join(dir, BACKUP_MANIFEST_FILE);\n writeJsonFileSafe(manifestFile, manifest);\n\n return { id: manifest.id, dir, manifestFile, manifest, copied: items.length > 0 };\n}\n\n/** Lists backups newest first. */\nexport function listBackups(backupDir: string): BackupSummary[] {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(backupDir, { withFileTypes: true });\n } catch {\n return [];\n }\n\n return entries\n .filter((entry) => entry.isDirectory())\n .map((entry) => summarizeBackup(backupDir, entry.name))\n .sort((a, b) => b.id.localeCompare(a.id));\n}\n\n/** Removes all but the `keep` most recent backups and returns the removed dirs. */\nexport function pruneBackups(backupDir: string, keep: number): string[] {\n if (keep < 0) {\n return [];\n }\n const removals = listBackups(backupDir)\n .slice(keep)\n .map((summary) => summary.dir);\n for (const dir of removals) {\n fs.rmSync(dir, { recursive: true, force: true });\n }\n return removals;\n}\n\nfunction summarizeBackup(backupDir: string, id: string): BackupSummary {\n const dir = path.join(backupDir, id);\n const manifest = readJsonFile<BackupManifest>(path.join(dir, BACKUP_MANIFEST_FILE));\n const items = manifest?.items ?? [];\n return {\n id,\n dir,\n createdAt: manifest?.createdAt ?? null,\n itemCount: items.length,\n bytes: items.reduce((total, item) => total + (item.bytes ?? 0), 0),\n };\n}\n\nfunction uniqueDirectory(preferred: string): string {\n if (!pathExists(preferred)) {\n return preferred;\n }\n let suffix = 1;\n let candidate = `${preferred}-${suffix}`;\n while (pathExists(candidate)) {\n suffix += 1;\n candidate = `${preferred}-${suffix}`;\n }\n return candidate;\n}\n\nfunction pad(value: number): string {\n return String(value).padStart(2, '0');\n}\n","import path from 'path';\n\nimport type { BookmarkFile, BrowserName, CliConfig, SyncStrategy } from '@crosssync/shared';\nimport { BROWSERS, ensureDir, pathExists, writeJsonFileSafe } from '@crosssync/shared';\n\nimport { createBackup, formatBackupId, type BackupResult, type BackupSource } from './backup';\nimport { getRunningBrowserNames } from './browser-status';\nimport { Logger } from './logger';\nimport {\n mergeBookmarkFiles,\n mergeHistory,\n type BookmarkMergeResult,\n type HistoryMergeResult,\n} from './merger';\nimport {\n countBookmarkFileNodes,\n createConfiguredBrowserReaders,\n type BookmarkSource,\n type HistorySource,\n} from './readers';\n\nexport interface SyncTargets {\n bookmarks: boolean;\n history: boolean;\n}\n\nexport interface SyncRunOptions {\n config: CliConfig;\n targets: SyncTargets;\n dryRun?: boolean;\n /** Write bookmarks back even when the browser is running. */\n force?: boolean;\n /** Overrides `config.sync.strategy`. */\n strategy?: SyncStrategy;\n logger?: Logger;\n /** Injectable clock, used by tests. */\n now?: Date;\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n /** Overrides browser-running detection, used by tests. */\n browserRunning?: (browser: BrowserName) => boolean;\n}\n\nexport interface BrowserSyncOutcome {\n browser: BrowserName;\n profile: string;\n bookmarksRead: number;\n historyRead: number;\n writtenBack: boolean;\n skippedWriteBackReason: string | null;\n}\n\nexport interface SyncReport {\n startedAt: string;\n finishedAt: string;\n dryRun: boolean;\n strategy: SyncStrategy;\n targets: SyncTargets;\n browsers: BrowserSyncOutcome[];\n backup: BackupResult | null;\n bookmarkMerge: BookmarkMergeResult | null;\n historyMerge: HistoryMergeResult | null;\n exportFiles: string[];\n warnings: string[];\n}\n\n/**\n * Writes a merged bookmark tree back to a Chromium `Bookmarks` file.\n *\n * The `checksum` field is intentionally dropped: Chromium recomputes it, and a\n * stale checksum makes the browser discard externally written changes.\n */\nexport function writeBackBookmarks(filePath: string, file: BookmarkFile): void {\n const payload: BookmarkFile = { roots: file.roots };\n if (typeof file.version === 'number') {\n payload.version = file.version;\n }\n writeJsonFileSafe(filePath, payload);\n}\n\n/**\n * Orchestrates a full sync run:\n *\n * 1. read bookmarks/history from every enabled browser profile\n * 2. back everything up first (a failed backup aborts before any write-back)\n * 3. merge by `id` + `date_added` (bookmarks) and by URL (history)\n * 4. write merged bookmarks back, then export the merged data as JSON\n */\nexport function runSync(options: SyncRunOptions): SyncReport {\n const { config, targets } = options;\n const startedAtMs = Date.now();\n const dryRun = options.dryRun ?? false;\n const strategy = options.strategy ?? config.sync.strategy;\n const logger = options.logger ?? new Logger(config.logLevel, { console: false });\n\n const warnings: string[] = [];\n const browsers: BrowserSyncOutcome[] = [];\n const exportFiles: string[] = [];\n const bookmarkSources: BookmarkSource[] = [];\n const historySources: HistorySource[] = [];\n\n const finish = (\n backup: BackupResult | null,\n bookmarkMerge: BookmarkMergeResult | null,\n historyMerge: HistoryMergeResult | null,\n ): SyncReport => ({\n startedAt: new Date(startedAtMs).toISOString(),\n finishedAt: new Date().toISOString(),\n dryRun,\n strategy,\n targets,\n browsers,\n backup,\n bookmarkMerge,\n historyMerge,\n exportFiles,\n warnings,\n });\n\n const readers = createConfiguredBrowserReaders(config, {\n platform: options.platform,\n env: options.env,\n });\n\n for (const reader of readers) {\n const profiles = reader.resolveProfiles(config.profile);\n if (profiles.length === 0) {\n const available = reader.profiles();\n const suffix = available.length > 0 ? ` Available: ${available.join(', ')}.` : '';\n warnings.push(`No ${reader.browser} profile found under ${reader.dataDir}.${suffix}`);\n continue;\n }\n\n for (const profile of profiles) {\n const outcome: BrowserSyncOutcome = {\n browser: reader.browser,\n profile,\n bookmarksRead: 0,\n historyRead: 0,\n writtenBack: false,\n skippedWriteBackReason: null,\n };\n\n if (targets.bookmarks && pathExists(reader.bookmarksPath(profile))) {\n try {\n const source = reader.readBookmarks(profile);\n bookmarkSources.push(source);\n outcome.bookmarksRead = countBookmarkFileNodes(source.file);\n } catch (error) {\n const reason = describeError(error);\n outcome.skippedWriteBackReason = reason;\n warnings.push(`Could not read ${reader.browser} bookmarks: ${reason}`);\n }\n }\n\n if (targets.history && pathExists(reader.historyPath(profile))) {\n try {\n const source = reader.readHistory(profile);\n historySources.push(source);\n outcome.historyRead = source.entries.length;\n } catch (error) {\n warnings.push(`Could not read ${reader.browser} history: ${describeError(error)}`);\n }\n }\n\n browsers.push(outcome);\n }\n }\n\n if (bookmarkSources.length === 0 && historySources.length === 0) {\n warnings.push('Nothing to sync: no bookmark or history data was found.');\n return finish(null, null, null);\n }\n\n return syncFoundData({\n options,\n config,\n dryRun,\n strategy,\n logger,\n warnings,\n browsers,\n exportFiles,\n bookmarkSources,\n historySources,\n finish,\n });\n}\n\ntype FinishReport = (\n backup: BackupResult | null,\n bookmarkMerge: BookmarkMergeResult | null,\n historyMerge: HistoryMergeResult | null,\n) => SyncReport;\n\ninterface SyncFoundDataContext {\n options: SyncRunOptions;\n config: CliConfig;\n dryRun: boolean;\n strategy: SyncStrategy;\n logger: Logger;\n warnings: string[];\n browsers: BrowserSyncOutcome[];\n exportFiles: string[];\n bookmarkSources: BookmarkSource[];\n historySources: HistorySource[];\n finish: FinishReport;\n}\n\nfunction syncFoundData(context: SyncFoundDataContext): SyncReport {\n const {\n options,\n config,\n dryRun,\n strategy,\n logger,\n warnings,\n exportFiles,\n bookmarkSources,\n historySources,\n finish,\n } = context;\n\n let backup: BackupResult | null = null;\n if (!dryRun) {\n const sources: BackupSource[] = [\n ...bookmarkSources.map((source) => ({\n kind: 'bookmarks' as const,\n browser: source.browser,\n profile: source.profile,\n filePath: source.filePath,\n })),\n ...historySources.map((source) => ({\n kind: 'history' as const,\n browser: source.browser,\n profile: source.profile,\n filePath: source.filePath,\n })),\n ];\n\n try {\n backup = createBackup({\n backupDir: config.backupDir,\n sources,\n now: options.now,\n platform: options.platform,\n });\n logger.info('Backup created', { dir: backup.dir, files: backup.manifest.items.length });\n } catch (error) {\n warnings.push(`Backup failed; aborting before any write-back: ${describeError(error)}`);\n return finish(null, null, null);\n }\n }\n\n const bookmarkMerge =\n bookmarkSources.length > 0\n ? mergeBookmarkFiles(\n bookmarkSources.map((source) => ({ browser: source.browser, file: source.file })),\n )\n : null;\n\n const historyMerge =\n historySources.length > 0\n ? mergeHistory(\n historySources.map((source) => ({ browser: source.browser, entries: source.entries })),\n )\n : null;\n\n if (bookmarkMerge && strategy === 'merge') {\n if (dryRun) {\n warnings.push('Dry run: bookmark write-back skipped.');\n } else {\n writeBackMergedBookmarks(context, bookmarkMerge);\n }\n } else if (bookmarkMerge) {\n warnings.push('Strategy \"export\": browser bookmark files were left untouched.');\n }\n\n if (historyMerge) {\n warnings.push('History is exported only; CrossSync never writes back to History.sqlite.');\n }\n\n if (!dryRun) {\n ensureDir(config.exportDir);\n const stamp = formatBackupId(options.now ?? new Date());\n if (bookmarkMerge) {\n const file = path.join(config.exportDir, `bookmarks-merged-${stamp}.json`);\n writeJsonFileSafe(file, {\n exportedAt: new Date().toISOString(),\n source: 'crosssync',\n version: 1,\n roots: bookmarkMerge.roots,\n });\n exportFiles.push(file);\n }\n if (historyMerge) {\n const file = path.join(config.exportDir, `history-merged-${stamp}.json`);\n writeJsonFileSafe(file, {\n exportedAt: new Date().toISOString(),\n source: 'crosssync',\n entries: historyMerge.entries,\n });\n exportFiles.push(file);\n }\n }\n\n return finish(backup, bookmarkMerge, historyMerge);\n}\n\n/** Writes the merged tree to every browser that contributed bookmarks. */\nfunction writeBackMergedBookmarks(\n context: SyncFoundDataContext,\n bookmarkMerge: BookmarkMergeResult,\n): void {\n const { options, logger, warnings, browsers, bookmarkSources } = context;\n\n const running: BrowserName[] = options.browserRunning\n ? BROWSERS.filter((browser) => options.browserRunning?.(browser) === true)\n : getRunningBrowserNames({ platform: options.platform });\n\n const byBrowser = new Map<BrowserName, BookmarkSource[]>();\n for (const source of bookmarkSources) {\n const list = byBrowser.get(source.browser) ?? [];\n list.push(source);\n byBrowser.set(source.browser, list);\n }\n\n for (const [browser, sources] of byBrowser) {\n if (running.includes(browser) && !options.force) {\n warnings.push(\n `${browser} is running; skipping bookmark write-back (use --force to override).`,\n );\n for (const outcome of browsers) {\n if (outcome.browser === browser) {\n outcome.skippedWriteBackReason = 'browser-running';\n }\n }\n continue;\n }\n\n for (const source of sources) {\n writeBackBookmarks(source.filePath, {\n roots: bookmarkMerge.roots,\n version: source.file.version ?? 1,\n });\n logger.info('Wrote merged bookmarks', {\n browser,\n profile: source.profile,\n file: source.filePath,\n });\n }\n\n for (const outcome of browsers) {\n if (outcome.browser === browser) {\n outcome.writtenBack = true;\n }\n }\n }\n}\n\nfunction describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","export { CORE_PACKAGE as PACKAGE, CORE_VERSION as VERSION } from './constants';\nexport {\n BROWSER_PROCESS_NAMES,\n DEFAULT_BACKUP_RETENTION,\n DEFAULT_LOG_LIMIT,\n MAX_BUFFERED_LOG_ENTRIES,\n} from './constants';\nexport {\n Logger,\n clearLogFile,\n readLogEntries,\n type LogEntry,\n type LogLevel,\n type LoggerOptions,\n type ReadLogEntriesOptions,\n} from './logger';\nexport {\n buildProcessQuery,\n getProcessName,\n getRunningBrowserNames,\n getRunningBrowsers,\n isBrowserRunning,\n parseProcessOutput,\n type BrowserStatus,\n type BrowserStatusOptions,\n type ProcessResult,\n type ProcessRunner,\n} from './browser-status';\nexport {\n countBookmarkFileNodes,\n createBrowserReader,\n createConfiguredBrowserReaders,\n supportedBrowsers,\n toHistoryEntry,\n type BookmarkSource,\n type BrowserReader,\n type BrowserReaderOptions,\n type ChromiumHistoryRow,\n type HistorySource,\n} from './readers';\nexport {\n mergeBookmarkFiles,\n mergeHistory,\n type BookmarkMergeConflict,\n type BookmarkMergeInput,\n type BookmarkMergeResult,\n type BookmarkMergeStats,\n type HistoryMergeInput,\n type HistoryMergeResult,\n type HistoryMergeStats,\n} from './merger';\nexport {\n BACKUP_MANIFEST_FILE,\n backupFileName,\n createBackup,\n formatBackupId,\n listBackups,\n pruneBackups,\n type BackupItem,\n type BackupKind,\n type BackupManifest,\n type BackupOptions,\n type BackupResult,\n type BackupSource,\n type BackupSummary,\n} from './backup';\nexport {\n runSync,\n writeBackBookmarks,\n type BrowserSyncOutcome,\n type SyncReport,\n type SyncRunOptions,\n type SyncTargets,\n} from './sync';\n","import type { LogLevel } from '@crosssync/shared';\nimport { Command } from 'commander';\n\nimport { CLI_DESCRIPTION, CLI_NAME, CLI_VERSION } from './constants';\nimport { createContext, type CliContext, type CreateContextOptions } from './context';\nimport { runBackupCommand } from './commands/backup';\nimport { runConfigCommand } from './commands/config';\nimport { runInstallCronCommand, runUninstallCronCommand } from './commands/cron';\nimport { runExportCommand } from './commands/export';\nimport { runLogsCommand } from './commands/logs';\nimport { runProfilesCommand } from './commands/profiles';\nimport { runStatusCommand } from './commands/status';\nimport { runSyncCommand } from './commands/sync';\n\nexport interface GlobalOptions {\n /** Use a different home directory (used by tests). */\n homeDir?: string;\n verbose?: boolean;\n quiet?: boolean;\n}\n\nexport type ContextFactory = (options: GlobalOptions) => CliContext;\n\n/** Builds the CLI context, turning a bad config into a friendly error. */\nexport function createCliContext(options: GlobalOptions = {}): CliContext {\n const logLevel: LogLevel | undefined = options.verbose\n ? 'debug'\n : options.quiet\n ? 'error'\n : undefined;\n const contextOptions: CreateContextOptions = { homeDir: options.homeDir, logLevel };\n return createContext(contextOptions);\n}\n\nexport function buildProgram(contextFactory: ContextFactory = createCliContext): Command {\n const program = new Command();\n\n program\n .name(CLI_NAME)\n .description(CLI_DESCRIPTION)\n .version(CLI_VERSION, '-v, --version', 'print the CrossSync version')\n .option('--home-dir <path>', 'use an alternate home directory')\n .option('--verbose', 'enable debug logging')\n .option('--quiet', 'only log errors');\n\n const withContext = (action: (context: CliContext) => number | Promise<number>) => async () => {\n const context = contextFactory(program.opts<GlobalOptions>());\n try {\n process.exitCode = await action(context);\n } catch (error) {\n context.io.err(error instanceof Error ? error.message : String(error));\n process.exitCode = 1;\n }\n };\n\n const syncCommand = program\n .command('sync')\n .description('read, merge and write back browser bookmarks/history')\n .option('--bookmarks', 'sync bookmarks only')\n .option('--history', 'sync history only')\n .option('--all', 'sync bookmarks and history (default)')\n .option('--browser <name>', 'chrome, edge or all', 'all')\n .option('--profile <names>', 'profile name(s), comma-separated, or \"all\"')\n .option('--strategy <name>', 'merge (write back) or export (read only)')\n .option('--dry-run', 'show what would happen without touching any file')\n .option('--force', 'write bookmarks back even while the browser is running')\n .option('--json', 'print the report as JSON');\n syncCommand.action(withContext((context) => runSyncCommand(context, syncCommand.opts())));\n\n const backupCommand = program\n .command('backup')\n .description('back up browser bookmark and history files')\n .option('--list', 'list existing backups')\n .option('--prune', 'delete old backups')\n .option('--keep <count>', 'how many backups to keep when pruning');\n backupCommand.action(\n withContext((context) => {\n const options = backupCommand.opts();\n return runBackupCommand(context, {\n list: options.list,\n prune: options.prune,\n keep: options.keep === undefined ? undefined : Number(options.keep),\n });\n }),\n );\n\n const exportCommand = program\n .command('export')\n .description('export merged bookmarks/history as JSON')\n .option('--format <format>', 'output format (json)', 'json')\n .option('--out <dir>', 'directory to write into')\n .option('--browser <name>', 'chrome, edge or all', 'all')\n .option('--profile <names>', 'profile name(s), comma-separated, or \"all\"')\n .option('--stdout', 'print the export instead of writing a file');\n exportCommand.action(withContext((context) => runExportCommand(context, exportCommand.opts())));\n\n const statusCommand = program\n .command('status')\n .description('show browsers, profiles, backups and schedule state')\n .option('--json', 'print the status as JSON');\n statusCommand.action(withContext((context) => runStatusCommand(context, statusCommand.opts())));\n\n const profilesCommand = program\n .command('profiles')\n .description('list available Chromium profiles or change the synced selection')\n .option('--list', 'list profiles and the current selection (default)')\n .option('--set <names>', 'replace the selection, e.g. \"Default,Profile 11\" or \"all\"')\n .option('--add <names>', 'add profiles to the selection')\n .option('--remove <names>', 'remove profiles from the selection')\n .option('--all', 'select every available profile')\n .option('--reset', 'reset the selection to \"Default\"')\n .option('--browser <name>', 'limit listing to chrome, edge or all', 'all');\n profilesCommand.action(\n withContext((context) => runProfilesCommand(context, profilesCommand.opts())),\n );\n\n const logsCommand = program\n .command('logs')\n .description('print CrossSync log entries')\n .option('--limit <count>', 'number of entries to show', '50')\n .option('--level <level>', 'debug, info, warn or error')\n .option('--clear', 'delete the log file')\n .option('--json', 'print the entries as JSON');\n logsCommand.action(\n withContext((context) => {\n const options = logsCommand.opts();\n return runLogsCommand(context, {\n limit: Number(options.limit),\n level: options.level,\n clear: options.clear,\n json: options.json,\n });\n }),\n );\n\n const installCronCommand = program\n .command('install-cron')\n .description('install a scheduled sync (Task Scheduler, launchd, systemd or cron)')\n .option('--expression <cron>', 'cron expression, e.g. \"0 9 * * *\"')\n .option('--label <name>', 'task/agent/unit name')\n .option('--dry-run', 'print the plan without changing anything');\n installCronCommand.action(\n withContext((context) => runInstallCronCommand(context, installCronCommand.opts())),\n );\n\n const uninstallCronCommand = program\n .command('uninstall-cron')\n .description('remove the installed schedule')\n .option('--label <name>', 'task/agent/unit name')\n .option('--dry-run', 'print the plan without changing anything');\n uninstallCronCommand.action(\n withContext((context) => runUninstallCronCommand(context, uninstallCronCommand.opts())),\n );\n\n const configCommand = program\n .command('config')\n .description('show or edit the CrossSync configuration')\n .option('--path', 'print the config file path')\n .option('--get <key>', 'read a dotted key, e.g. sync.strategy')\n .option('--set <key=value>', 'write a key, e.g. sync.strategy=export')\n .option('--reset', 'restore the default config');\n configCommand.action(withContext((context) => runConfigCommand(context, configCommand.opts())));\n\n return program;\n}\n\nexport async function run(argv: string[] = process.argv): Promise<void> {\n await buildProgram().parseAsync(argv);\n}\n\nexport { CLI_NAME, CLI_VERSION };\nexport const PACKAGE = 'crosssync';\nexport const VERSION = CLI_VERSION;\n\nif (require.main === module) {\n void run();\n}\n","import commander from './index.js';\n\n// wrapper to provide named exports for ESM.\nexport const {\n program,\n createCommand,\n createArgument,\n createOption,\n CommanderError,\n InvalidArgumentError,\n InvalidOptionArgumentError, // deprecated old name\n Command,\n Argument,\n Option,\n Help,\n} = commander;\n","export const CLI_PACKAGE = 'crosssync';\nexport const CLI_VERSION = '0.1.2';\nexport const CLI_NAME = 'crosssync';\nexport const CLI_DESCRIPTION = 'Cross-browser bookmark & history sync CLI (Chrome + Edge)';\n\n/** Name of the Windows Task Scheduler entry. */\nexport const WINDOWS_TASK_NAME = 'CrossSync';\n\n/** Reverse-DNS label of the launchd agent installed on macOS. */\nexport const MACOS_LAUNCH_AGENT_LABEL = 'com.crosssync.sync';\n\n/** Name of the systemd user timer/service installed on Linux. */\nexport const SYSTEMD_UNIT_NAME = 'crosssync-sync';\n\n/** Marker used to recognise CrossSync lines inside a crontab. */\nexport const CRONTAB_MARKER = '# crosssync';\n\n/** Default arguments passed to `crosssync` by the installed schedule. */\nexport const DEFAULT_SCHEDULE_ARGS = ['sync', '--all'];\n","import path from 'path';\n\nimport type { CliConfig, CrossSyncDirs, LogLevel } from '@crosssync/shared';\nimport {\n createDefaultConfig,\n DEFAULT_EXPORT_RETENTION,\n isCliConfig,\n LOG_FILE_NAME,\n pathExists,\n readJsonFile,\n resolveCrossSyncDirs,\n writeJsonFileSafe,\n} from '@crosssync/shared';\nimport { Logger } from '@crosssync/core';\n\nexport interface CommandIo {\n out(text?: string): void;\n err(text?: string): void;\n}\n\nexport const consoleIo: CommandIo = {\n out: (text = '') => console.log(text),\n err: (text = '') => console.error(text),\n};\n\n/** Captures output for tests. */\nexport function createMemoryIo(): CommandIo & { stdout: string[]; stderr: string[] } {\n const stdout: string[] = [];\n const stderr: string[] = [];\n return {\n stdout,\n stderr,\n out: (text = '') => stdout.push(text),\n err: (text = '') => stderr.push(text),\n };\n}\n\n/** Loads `config.json`, creating it with defaults when missing. */\nexport function loadConfigFile(\n configFile: string,\n dirs: CrossSyncDirs,\n): { config: CliConfig; created: boolean } {\n if (!pathExists(configFile)) {\n const config = createDefaultConfig({\n dataDir: dirs.root,\n backupDir: dirs.backups,\n exportDir: dirs.exports,\n logDir: dirs.logs,\n });\n writeJsonFileSafe(configFile, config);\n return { config, created: true };\n }\n\n const raw = readJsonFile<unknown>(configFile);\n if (!isCliConfig(raw)) {\n throw new Error(\n `Invalid CrossSync config at ${configFile}. Fix or delete the file, then retry.`,\n );\n }\n // Configs written before `exports.keep` existed load with the default.\n const config: CliConfig = raw.exports\n ? raw\n : { ...raw, exports: { keep: DEFAULT_EXPORT_RETENTION } };\n return { config, created: false };\n}\n\nexport function saveConfigFile(configFile: string, config: CliConfig): void {\n writeJsonFileSafe(configFile, config);\n}\n\nexport interface CreateContextOptions {\n /** Overrides the user home directory; used by tests. */\n homeDir?: string;\n logLevel?: LogLevel;\n io?: CommandIo;\n /** Mirror log entries to the console. Defaults to false. */\n console?: boolean;\n}\n\nexport interface CliContext {\n config: CliConfig;\n dirs: CrossSyncDirs;\n logger: Logger;\n io: CommandIo;\n /** True when `config.json` was created during this run. */\n configCreated: boolean;\n}\n\n/** Builds the shared runtime context every command works against. */\nexport function createContext(options: CreateContextOptions = {}): CliContext {\n const dirs = resolveCrossSyncDirs(options.homeDir);\n const { config, created } = loadConfigFile(dirs.configFile, dirs);\n const logger = new Logger(options.logLevel ?? config.logLevel, {\n console: options.console ?? false,\n filePath: path.join(config.logDir, LOG_FILE_NAME),\n });\n return { config, dirs, logger, io: options.io ?? consoleIo, configCreated: created };\n}\n\n/** Re-reads the config so a command can persist changes it just made. */\nexport function reloadConfig(context: CliContext): void {\n const { config } = loadConfigFile(context.dirs.configFile, context.dirs);\n context.config = config;\n}\n","import { pathExists } from '@crosssync/shared';\nimport {\n createBackup,\n createConfiguredBrowserReaders,\n DEFAULT_BACKUP_RETENTION,\n listBackups,\n pruneBackups,\n type BackupSource,\n} from '@crosssync/core';\n\nimport type { CliContext } from '../context';\nimport { describeError } from './read';\n\nexport interface BackupCommandOptions {\n /** List existing backups instead of creating one. */\n list?: boolean;\n /** Delete all but the N most recent backups. */\n prune?: boolean;\n keep?: number;\n /** Keep at most N backups after creating a new one. */\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n now?: Date;\n}\n\nexport function runBackupCommand(context: CliContext, options: BackupCommandOptions = {}): number {\n if (options.list) {\n return listBackupCommand(context);\n }\n if (options.prune) {\n return pruneBackupCommand(context, options.keep ?? DEFAULT_BACKUP_RETENTION);\n }\n return createBackupCommand(context, options);\n}\n\n/** Every bookmark/history file that currently exists, ready to be backed up. */\nexport function collectBackupSources(\n config: CliContext['config'],\n options: BackupCommandOptions = {},\n): BackupSource[] {\n const sources: BackupSource[] = [];\n const readers = createConfiguredBrowserReaders(config, {\n platform: options.platform,\n env: options.env,\n });\n\n for (const reader of readers) {\n for (const profile of reader.resolveProfiles(config.profile)) {\n const bookmarks = reader.bookmarksPath(profile);\n if (pathExists(bookmarks)) {\n sources.push({ kind: 'bookmarks', browser: reader.browser, profile, filePath: bookmarks });\n }\n const history = reader.historyPath(profile);\n if (pathExists(history)) {\n sources.push({ kind: 'history', browser: reader.browser, profile, filePath: history });\n }\n }\n }\n\n return sources;\n}\n\nfunction createBackupCommand(context: CliContext, options: BackupCommandOptions): number {\n const sources = collectBackupSources(context.config, options);\n if (sources.length === 0) {\n context.io.err('No browser bookmark or history files were found to back up.');\n return 1;\n }\n\n try {\n const result = createBackup({\n backupDir: context.config.backupDir,\n sources,\n now: options.now,\n platform: options.platform,\n });\n context.logger.info('Backup created', { dir: result.dir });\n context.io.out(`Backup created: ${result.dir}`);\n context.io.out(` ${result.manifest.items.length} file(s) copied`);\n for (const item of result.manifest.items) {\n context.io.out(` ${item.kind}/${item.browser}/${item.profile} (${item.bytes} bytes)`);\n }\n return 0;\n } catch (error) {\n context.io.err(`Backup failed: ${describeError(error)}`);\n return 1;\n }\n}\n\nfunction listBackupCommand(context: CliContext): number {\n const summaries = listBackups(context.config.backupDir);\n if (summaries.length === 0) {\n context.io.out(`No backups found in ${context.config.backupDir}.`);\n return 0;\n }\n\n context.io.out(`Backups in ${context.config.backupDir}:`);\n for (const summary of summaries) {\n const created = summary.createdAt ?? 'unknown';\n context.io.out(\n ` ${summary.id} ${created} ${summary.itemCount} file(s) ${formatBytes(summary.bytes)}`,\n );\n }\n return 0;\n}\n\nfunction pruneBackupCommand(context: CliContext, keep: number): number {\n const removed = pruneBackups(context.config.backupDir, keep);\n if (removed.length === 0) {\n context.io.out(`Nothing to prune; keeping ${keep} most recent backup(s).`);\n return 0;\n }\n context.io.out(`Removed ${removed.length} backup(s), keeping the ${keep} most recent:`);\n for (const dir of removed) {\n context.io.out(` ${dir}`);\n }\n return 0;\n}\n\nexport function formatBytes(bytes: number): string {\n if (bytes < 1024) {\n return `${bytes} B`;\n }\n if (bytes < 1024 * 1024) {\n return `${(bytes / 1024).toFixed(1)} KiB`;\n }\n return `${(bytes / (1024 * 1024)).toFixed(1)} MiB`;\n}\n","import type { BrowserName, CliConfig } from '@crosssync/shared';\nimport { pathExists } from '@crosssync/shared';\nimport {\n createConfiguredBrowserReaders,\n mergeBookmarkFiles,\n mergeHistory,\n type BookmarkMergeResult,\n type HistoryMergeResult,\n} from '@crosssync/core';\n\nexport interface ReadOptions {\n browser?: string[];\n profile?: string;\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface MergedData {\n bookmarkMerge: BookmarkMergeResult | null;\n historyMerge: HistoryMergeResult | null;\n warnings: string[];\n /** Files that were read, for reporting. */\n sources: {\n browser: BrowserName;\n profile: string;\n filePath: string;\n kind: 'bookmarks' | 'history';\n }[];\n}\n\n/**\n * Reads and merges browser data without backing up or writing anything.\n *\n * Shared by `status` and `export`, which must never touch browser files.\n */\nexport function readMergedData(config: CliConfig, options: ReadOptions = {}): MergedData {\n const warnings: string[] = [];\n const sources: MergedData['sources'] = [];\n const bookmarkInputs: {\n browser: BrowserName;\n file: Parameters<typeof mergeBookmarkFiles>[0][number]['file'];\n }[] = [];\n const historyInputs: {\n browser: BrowserName;\n entries: Parameters<typeof mergeHistory>[0][number]['entries'];\n }[] = [];\n\n const readers = createConfiguredBrowserReaders(config, {\n platform: options.platform,\n env: options.env,\n });\n\n for (const reader of readers) {\n if (options.browser && !options.browser.includes(reader.browser)) {\n continue;\n }\n const profiles = reader.resolveProfiles(options.profile ?? config.profile);\n if (profiles.length === 0) {\n const available = reader.profiles();\n const suffix = available.length > 0 ? ` Available: ${available.join(', ')}.` : '';\n warnings.push(`No ${reader.browser} profile found under ${reader.dataDir}.${suffix}`);\n continue;\n }\n\n for (const profile of profiles) {\n const bookmarksPath = reader.bookmarksPath(profile);\n if (pathExists(bookmarksPath)) {\n try {\n const source = reader.readBookmarks(profile);\n bookmarkInputs.push({ browser: source.browser, file: source.file });\n sources.push({\n browser: source.browser,\n profile,\n filePath: bookmarksPath,\n kind: 'bookmarks',\n });\n } catch (error) {\n warnings.push(`Could not read ${reader.browser} bookmarks: ${describeError(error)}`);\n }\n }\n\n const historyPath = reader.historyPath(profile);\n if (pathExists(historyPath)) {\n try {\n const source = reader.readHistory(profile);\n historyInputs.push({ browser: source.browser, entries: source.entries });\n sources.push({\n browser: source.browser,\n profile,\n filePath: historyPath,\n kind: 'history',\n });\n } catch (error) {\n warnings.push(`Could not read ${reader.browser} history: ${describeError(error)}`);\n }\n }\n }\n }\n\n return {\n bookmarkMerge: bookmarkInputs.length > 0 ? mergeBookmarkFiles(bookmarkInputs) : null,\n historyMerge: historyInputs.length > 0 ? mergeHistory(historyInputs) : null,\n warnings,\n sources,\n };\n}\n\nexport function describeError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n","import type { CliConfig } from '@crosssync/shared';\nimport { createDefaultConfig, isCliConfig } from '@crosssync/shared';\n\nimport type { CliContext } from '../context';\nimport { saveConfigFile } from '../context';\n\nexport interface ConfigCommandOptions {\n /** Print the config file path only. */\n path?: boolean;\n /** Read a dotted key, e.g. `sync.strategy`. */\n get?: string;\n /** Write a dotted key, e.g. `sync.strategy=export`. */\n set?: string;\n /** Recreate the default config. */\n reset?: boolean;\n}\n\n/** Reads a dotted key out of a `CliConfig`. */\nexport function getConfigValue(config: CliConfig, dottedPath: string): unknown {\n return dottedPath.split('.').reduce<unknown>((current, key) => {\n if (typeof current !== 'object' || current === null) {\n return undefined;\n }\n return (current as Record<string, unknown>)[key];\n }, config);\n}\n\n/** Converts a CLI string into a boolean/number/null when it looks like one. */\nexport function coerceConfigValue(raw: string): unknown {\n const trimmed = raw.trim();\n if (trimmed === 'true') {\n return true;\n }\n if (trimmed === 'false') {\n return false;\n }\n if (trimmed === 'null') {\n return null;\n }\n if (trimmed !== '' && /^-?\\d+(\\.\\d+)?$/.test(trimmed)) {\n return Number(trimmed);\n }\n return raw;\n}\n\n/** Returns a new config with `dottedPath` set, refusing invalid results. */\nexport function setConfigValue(config: CliConfig, dottedPath: string, value: unknown): CliConfig {\n const keys = dottedPath.split('.');\n if (keys.some((key) => key.length === 0)) {\n throw new Error(`Invalid config key \"${dottedPath}\".`);\n }\n\n const next = JSON.parse(JSON.stringify(config)) as Record<string, unknown>;\n let cursor: Record<string, unknown> = next;\n\n for (const key of keys.slice(0, -1)) {\n const existing = cursor[key];\n if (typeof existing !== 'object' || existing === null || Array.isArray(existing)) {\n cursor[key] = {};\n }\n cursor = cursor[key] as Record<string, unknown>;\n }\n cursor[keys[keys.length - 1]] = value;\n\n if (!isCliConfig(next)) {\n throw new Error(`Refusing to write an invalid config after setting \"${dottedPath}\".`);\n }\n return next;\n}\n\nexport function runConfigCommand(context: CliContext, options: ConfigCommandOptions = {}): number {\n if (options.path) {\n context.io.out(context.dirs.configFile);\n return 0;\n }\n\n if (options.reset) {\n const config = createDefaultConfig({\n dataDir: context.dirs.root,\n backupDir: context.dirs.backups,\n exportDir: context.dirs.exports,\n logDir: context.dirs.logs,\n });\n saveConfigFile(context.dirs.configFile, config);\n context.config = config;\n context.io.out(`Config reset: ${context.dirs.configFile}`);\n return 0;\n }\n\n if (options.get) {\n const value = getConfigValue(context.config, options.get);\n if (value === undefined) {\n context.io.err(`Unknown config key \"${options.get}\".`);\n return 1;\n }\n context.io.out(typeof value === 'string' ? value : JSON.stringify(value));\n return 0;\n }\n\n if (options.set) {\n const separator = options.set.indexOf('=');\n if (separator <= 0) {\n context.io.err('Use --set key=value, e.g. --set sync.strategy=export.');\n return 1;\n }\n const key = options.set.slice(0, separator);\n const rawValue = options.set.slice(separator + 1);\n\n try {\n const next = setConfigValue(context.config, key, coerceConfigValue(rawValue));\n saveConfigFile(context.dirs.configFile, next);\n context.config = next;\n context.io.out(`${key} = ${JSON.stringify(getConfigValue(next, key))}`);\n return 0;\n } catch (error) {\n context.io.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n }\n\n context.io.out(`# ${context.dirs.configFile}`);\n context.io.out(JSON.stringify(context.config, null, 2));\n return 0;\n}\n","import { DEFAULT_CRON_SCHEDULE } from '@crosssync/shared';\n\nimport type { CliContext } from '../context';\nimport { saveConfigFile } from '../context';\nimport { createCronManager, type CronRunner } from '../cron';\n\nexport interface CronCommandOptions {\n /** Cron expression, e.g. `0 9 * * *`. */\n expression?: string;\n /** Print the plan instead of changing anything. */\n dryRun?: boolean;\n label?: string;\n executable?: string;\n platform?: NodeJS.Platform;\n homeDir?: string;\n /** Injectable for tests. */\n runner?: CronRunner;\n}\n\nexport function runInstallCronCommand(\n context: CliContext,\n options: CronCommandOptions = {},\n): number {\n const expression =\n options.expression ?? context.config.schedule.expression ?? DEFAULT_CRON_SCHEDULE;\n\n let manager;\n try {\n manager = createCronManager({\n label: options.label,\n executable: options.executable,\n expression,\n platform: options.platform,\n homeDir: options.homeDir,\n runner: options.runner,\n });\n } catch (error) {\n context.io.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n\n if (options.dryRun) {\n context.io.out(`Dry run: no changes made (platform: ${manager.platform}).`);\n context.io.out(manager.describe('install'));\n return 0;\n }\n\n let result;\n try {\n result = manager.install();\n } catch (error) {\n context.io.err(\n `Failed to install the schedule: ${error instanceof Error ? error.message : String(error)}`,\n );\n return 1;\n }\n\n for (const message of result.messages) {\n if (result.changed) {\n context.io.out(message);\n } else {\n context.io.err(message);\n }\n }\n\n if (!result.changed) {\n return 1;\n }\n\n const next = { ...context.config, schedule: { installed: true, expression } };\n saveConfigFile(context.dirs.configFile, next);\n context.config = next;\n return 0;\n}\n\nexport function runUninstallCronCommand(\n context: CliContext,\n options: CronCommandOptions = {},\n): number {\n const expression = context.config.schedule.expression ?? DEFAULT_CRON_SCHEDULE;\n\n let manager;\n try {\n manager = createCronManager({\n label: options.label,\n executable: options.executable,\n expression,\n platform: options.platform,\n homeDir: options.homeDir,\n runner: options.runner,\n });\n } catch (error) {\n context.io.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n\n if (options.dryRun) {\n context.io.out(`Dry run: no changes made (platform: ${manager.platform}).`);\n context.io.out(manager.describe('uninstall'));\n return 0;\n }\n\n const result = manager.uninstall();\n for (const message of result.messages) {\n if (result.changed) {\n context.io.out(message);\n } else {\n context.io.err(message);\n }\n }\n\n const next = { ...context.config, schedule: { installed: false, expression } };\n saveConfigFile(context.dirs.configFile, next);\n context.config = next;\n\n return 0;\n}\n","import { DEFAULT_CRON_SCHEDULE } from '@crosssync/shared';\n\nimport { createLinuxCronManager } from './linux';\nimport { createMacosCronManager } from './macos';\nimport type { CronManager, CronManagerOptions } from './types';\nimport { createWindowsCronManager } from './windows';\n\nexport * from './types';\nexport * from './schedule';\n\nexport { quotePosixArgument, quoteWindowsArgument, resolveInvocation } from './invocation';\n\nexport { defaultCronRunner, toActionResult } from './runner';\n\nexport { buildScheduleArgs, createWindowsCronManager } from './windows';\nexport { escapeXml, launchAgentPath, renderLaunchAgent, createMacosCronManager } from './macos';\nexport {\n applyCrontabLine,\n buildCrontabLine,\n createLinuxCronManager,\n renderSystemdService,\n renderSystemdTimer,\n shouldUseSystemd,\n systemdUnitPath,\n} from './linux';\n\n/** Picks the scheduler implementation for the current platform. */\nexport function createCronManager(options: CronManagerOptions = {}): CronManager {\n const platform = options.platform ?? process.platform;\n const resolved: CronManagerOptions = {\n expression: options.expression ?? DEFAULT_CRON_SCHEDULE,\n ...options,\n platform,\n };\n\n if (platform === 'win32') {\n return createWindowsCronManager(resolved);\n }\n if (platform === 'darwin') {\n return createMacosCronManager(resolved);\n }\n return createLinuxCronManager(resolved);\n}\n","import fs from 'fs';\nimport os from 'os';\nimport path from 'path';\n\nimport { DEFAULT_CRON_SCHEDULE, ensureDir, pathExists, resolveHomeDir } from '@crosssync/shared';\n\nimport { CRONTAB_MARKER, SYSTEMD_UNIT_NAME } from '../constants';\nimport { quotePosixArgument, resolveInvocation } from './invocation';\nimport { defaultCronRunner, toActionResult } from './runner';\nimport { parseCronExpression, toSystemdCalendar } from './schedule';\nimport type { CronManager, CronManagerOptions, CronRunner } from './types';\n\n/** `~/.config/systemd/user/<unit>.<kind>` */\nexport function systemdUnitPath(unit: string, kind: 'service' | 'timer', homeDir?: string): string {\n return path.join(homeDir ?? resolveHomeDir(), '.config', 'systemd', 'user', `${unit}.${kind}`);\n}\n\nexport function renderSystemdService(program: string, args: string[]): string {\n const execStart = [program, ...args].map(quotePosixArgument).join(' ');\n return [\n '[Unit]',\n 'Description=CrossSync browser bookmark & history sync',\n '',\n '[Service]',\n 'Type=oneshot',\n `ExecStart=${execStart}`,\n '',\n ].join('\\n');\n}\n\nexport function renderSystemdTimer(expression: string, unit: string): string {\n const spec = parseCronExpression(expression);\n return [\n '[Unit]',\n `Description=Run CrossSync (${unit}) on a schedule`,\n '',\n '[Timer]',\n `OnCalendar=${toSystemdCalendar(spec)}`,\n 'Persistent=true',\n '',\n '[Install]',\n 'WantedBy=timers.target',\n '',\n ].join('\\n');\n}\n\n/** Replaces CrossSync's crontab entry, keeping every other line intact. */\nexport function applyCrontabLine(existing: string, line: string | null): string {\n const kept = existing\n .split(/\\r?\\n/)\n .filter((entry) => entry.trim().length > 0 && !entry.includes(CRONTAB_MARKER));\n if (line) {\n kept.push(line);\n }\n return kept.length > 0 ? `${kept.join('\\n')}\\n` : '';\n}\n\nexport function buildCrontabLine(expression: string, commandLine: string): string {\n return `${expression} ${commandLine} ${CRONTAB_MARKER}`;\n}\n\n/** True when the schedule should be installed as a systemd user timer. */\nexport function shouldUseSystemd(options: CronManagerOptions, program: string): boolean {\n if (options.useSystemd === true) {\n return true;\n }\n if (options.useSystemd === false) {\n return false;\n }\n // systemd requires an absolute ExecStart path; otherwise fall back to crontab.\n return path.isAbsolute(program) && pathExists('/run/systemd/system');\n}\n\n/**\n * Installs the schedule as a systemd user timer when available, otherwise as a\n * crontab entry. `describe()` lets `install-cron --dry-run` show the plan.\n */\nexport function createLinuxCronManager(options: CronManagerOptions = {}): CronManager {\n const expression = options.expression ?? DEFAULT_CRON_SCHEDULE;\n const invocation = resolveInvocation(options);\n const runner = options.runner ?? defaultCronRunner;\n const homeDir = options.homeDir ?? resolveHomeDir();\n const useSystemd = shouldUseSystemd(options, invocation.program);\n const unit = options.label ?? SYSTEMD_UNIT_NAME;\n const servicePath = systemdUnitPath(unit, 'service', homeDir);\n const timerPath = systemdUnitPath(unit, 'timer', homeDir);\n const cronLine = buildCrontabLine(expression, invocation.posixCommandLine);\n\n return {\n platform: 'linux',\n label: unit,\n\n describe(action) {\n if (useSystemd) {\n if (action === 'install') {\n return [\n `Write systemd user timer (${expression}):`,\n ` ${servicePath}`,\n ` ${timerPath}`,\n ' systemctl --user daemon-reload',\n ` systemctl --user enable --now ${unit}.timer`,\n ].join('\\n');\n }\n return [\n 'Disable systemd user timer:',\n ` systemctl --user disable --now ${unit}.timer`,\n `Remove files: ${servicePath}, ${timerPath}`,\n ' systemctl --user daemon-reload',\n ].join('\\n');\n }\n\n if (action === 'install') {\n return ['Add crontab entry:', ` ${cronLine}`].join('\\n');\n }\n return `Remove the crontab entry containing \"${CRONTAB_MARKER}\".`;\n },\n\n install() {\n if (useSystemd) {\n ensureDir(path.dirname(servicePath));\n fs.writeFileSync(\n servicePath,\n renderSystemdService(invocation.program, invocation.args),\n 'utf8',\n );\n fs.writeFileSync(timerPath, renderSystemdTimer(expression, unit), 'utf8');\n\n const reload = runner('systemctl', ['--user', 'daemon-reload']);\n if (reload.status !== 0) {\n return toActionResult(reload, '', 'systemctl --user daemon-reload failed');\n }\n const result = runner('systemctl', ['--user', 'enable', '--now', `${unit}.timer`]);\n return toActionResult(\n result,\n `systemd timer \"${unit}.timer\" installed.`,\n 'systemctl --user enable failed',\n );\n }\n\n const current = runner('crontab', ['-l']);\n const next = applyCrontabLine(current.status === 0 ? current.stdout : '', cronLine);\n return writeCrontab(next, runner, `crontab entry for ${unit} installed.`);\n },\n\n uninstall() {\n if (useSystemd) {\n runner('systemctl', ['--user', 'disable', '--now', `${unit}.timer`]);\n let existed = false;\n for (const file of [servicePath, timerPath]) {\n if (pathExists(file)) {\n existed = true;\n fs.rmSync(file, { force: true });\n }\n }\n runner('systemctl', ['--user', 'daemon-reload']);\n return {\n changed: existed,\n messages: [\n existed\n ? `systemd timer \"${unit}.timer\" removed.`\n : `No systemd timer named \"${unit}.timer\" was installed.`,\n ],\n };\n }\n\n const current = runner('crontab', ['-l']);\n const before = current.status === 0 ? current.stdout : '';\n const next = applyCrontabLine(before, null);\n if (next === before) {\n return { changed: false, messages: [`No crontab entry for ${unit} was installed.`] };\n }\n return writeCrontab(next, runner, `crontab entry for ${unit} removed.`);\n },\n };\n}\n\nfunction writeCrontab(\n content: string,\n runner: CronRunner,\n successMessage: string,\n): { changed: boolean; messages: string[] } {\n const tempFile = path.join(os.tmpdir(), `crosssync-crontab-${process.pid}.txt`);\n fs.writeFileSync(tempFile, content, 'utf8');\n try {\n const result = runner('crontab', [tempFile]);\n return toActionResult(result, successMessage, 'crontab failed');\n } finally {\n fs.rmSync(tempFile, { force: true });\n }\n}\n","import { CLI_NAME, DEFAULT_SCHEDULE_ARGS } from '../constants';\nimport type { CronInvocation, CronManagerOptions } from './types';\n\n/** Quotes a value for `schtasks /TR`, which re-parses the string itself. */\nexport function quoteWindowsArgument(value: string): string {\n return /[\\s\"]/.test(value) ? `\"${value.replace(/\"/g, '\\\\\"')}\"` : value;\n}\n\n/** Quotes a value for POSIX shells (crontab / systemd ExecStart). */\nexport function quotePosixArgument(value: string): string {\n if (value === '') {\n return \"''\";\n }\n return /^[A-Za-z0-9_@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\\\''`)}'`;\n}\n\n/**\n * Works out what the schedule should execute.\n *\n * When CrossSync runs from source (`node dist/index.js`) the schedule has to go\n * through Node; when it runs from the installed `crosssync` bin the bin is used.\n */\nexport function resolveInvocation(options: CronManagerOptions = {}): CronInvocation {\n const args = options.args ?? [...DEFAULT_SCHEDULE_ARGS];\n let program: string;\n let fullArgs: string[];\n\n if (options.executable) {\n program = options.executable;\n fullArgs = args;\n } else {\n const script = process.argv[1];\n if (script && /\\.[cm]?js$/.test(script)) {\n program = process.execPath;\n fullArgs = [script, ...args];\n } else {\n program = CLI_NAME;\n fullArgs = args;\n }\n }\n\n return {\n program,\n args: fullArgs,\n windowsCommandLine: [program, ...fullArgs].map(quoteWindowsArgument).join(' '),\n posixCommandLine: [program, ...fullArgs].map(quotePosixArgument).join(' '),\n };\n}\n","import { execFileSync } from 'child_process';\n\nimport type { CronActionResult, CronProcessResult, CronRunner } from './types';\n\n/** Runs a command, capturing output instead of throwing. */\nexport const defaultCronRunner: CronRunner = (command, args) => {\n try {\n const stdout = execFileSync(command, args, {\n encoding: 'utf8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n return { status: 0, stdout: String(stdout ?? ''), stderr: '' };\n } catch (error) {\n const failure = error as { status?: number | null; stdout?: unknown; stderr?: unknown };\n return {\n status: typeof failure.status === 'number' ? failure.status : 1,\n stdout: toText(failure.stdout),\n stderr: toText(failure.stderr),\n };\n }\n};\n\nfunction toText(value: unknown): string {\n if (Buffer.isBuffer(value)) {\n return value.toString('utf8');\n }\n return typeof value === 'string' ? value : '';\n}\n\n/** Turns a process result into a `CronActionResult`. */\nexport function toActionResult(\n result: CronProcessResult,\n successMessage: string,\n failurePrefix: string,\n): CronActionResult {\n if (result.status === 0) {\n return { changed: true, messages: [successMessage] };\n }\n const detail = (result.stderr || result.stdout).trim();\n return {\n changed: false,\n messages: [`${failurePrefix} (exit ${result.status})${detail ? `: ${detail}` : ''}`],\n };\n}\n","export interface CronSpec {\n minute: string;\n hour: string;\n dayOfMonth: string;\n month: string;\n dayOfWeek: string;\n}\n\nconst FIELD_PATTERN = /^(\\*|\\d+)(?:-(\\d+))?(?:\\/(\\d+))?$/;\n\nconst CRON_WEEKDAY_NAMES = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const;\n\nconst WINDOWS_WEEKDAY_NAMES = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'] as const;\n\n/** Parses a 5-field cron expression, rejecting anything out of range. */\nexport function parseCronExpression(expression: string): CronSpec {\n const parts = expression.trim().split(/\\s+/).filter(Boolean);\n if (parts.length !== 5) {\n throw new Error(\n `Invalid cron expression \"${expression}\": expected 5 fields (minute hour day month weekday).`,\n );\n }\n\n const [minute, hour, dayOfMonth, month, dayOfWeek] = parts;\n validateField(minute, 0, 59, 'minute', expression);\n validateField(hour, 0, 23, 'hour', expression);\n validateField(dayOfMonth, 1, 31, 'day of month', expression);\n validateField(month, 1, 12, 'month', expression);\n validateField(dayOfWeek, 0, 7, 'day of week', expression);\n\n return { minute, hour, dayOfMonth, month, dayOfWeek };\n}\n\nexport function isWildcard(field: string): boolean {\n return field === '*';\n}\n\n/** The hour/minute pair, when both are plain numbers. */\nexport function toFixedTime(spec: CronSpec): { hour: number; minute: number } {\n if (!/^\\d+$/.test(spec.hour) || !/^\\d+$/.test(spec.minute)) {\n throw new Error(\n `Only fixed times are supported by this scheduler (got hour=\"${spec.hour}\", minute=\"${spec.minute}\"). ` +\n 'Use a schedule such as \"0 9 * * *\".',\n );\n }\n return { hour: Number(spec.hour), minute: Number(spec.minute) };\n}\n\nexport function formatTime(hour: number, minute: number): string {\n return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;\n}\n\n/** A single numeric day of week (0 and 7 both mean Sunday). */\nexport function toWeekday(spec: CronSpec): number | null {\n if (isWildcard(spec.dayOfWeek)) {\n return null;\n }\n if (!/^\\d+$/.test(spec.dayOfWeek)) {\n throw new Error(`Only a single numeric day of week is supported (got \"${spec.dayOfWeek}\").`);\n }\n return Number(spec.dayOfWeek) % 7;\n}\n\nexport function cronWeekdayName(day: number): string {\n return CRON_WEEKDAY_NAMES[day % 7];\n}\n\nexport function windowsWeekdayName(day: number): string {\n return WINDOWS_WEEKDAY_NAMES[day % 7];\n}\n\n/** Maps a cron spec onto a systemd `OnCalendar=` value. */\nexport function toSystemdCalendar(spec: CronSpec): string {\n const { hour, minute } = toFixedTime(spec);\n const time = `${formatTime(hour, minute)}:00`;\n const weekday = toWeekday(spec);\n\n if (weekday !== null) {\n return `${cronWeekdayName(weekday)} *-*-* ${time}`;\n }\n if (!isWildcard(spec.dayOfMonth) && /^\\d+$/.test(spec.dayOfMonth)) {\n const month = isWildcard(spec.month) ? '*' : String(Number(spec.month)).padStart(2, '0');\n return `*-${month}-${String(Number(spec.dayOfMonth)).padStart(2, '0')} ${time}`;\n }\n return `*-*-* ${time}`;\n}\n\n/** True when the spec runs once a day at a fixed time. */\nexport function isDaily(spec: CronSpec): boolean {\n return isWildcard(spec.dayOfMonth) && isWildcard(spec.month) && isWildcard(spec.dayOfWeek);\n}\n\n/** True when the spec runs weekly on a single weekday at a fixed time. */\nexport function isWeekly(spec: CronSpec): boolean {\n return isWildcard(spec.dayOfMonth) && isWildcard(spec.month) && !isWildcard(spec.dayOfWeek);\n}\n\nfunction validateField(\n field: string,\n min: number,\n max: number,\n name: string,\n expression: string,\n): void {\n for (const part of field.split(',')) {\n const match = FIELD_PATTERN.exec(part);\n if (!match) {\n throw new Error(`Invalid cron expression \"${expression}\": bad ${name} field \"${part}\".`);\n }\n const [, startRaw, endRaw, stepRaw] = match;\n const start = startRaw === '*' ? min : Number(startRaw);\n const end = endRaw ? Number(endRaw) : start;\n const step = stepRaw ? Number(stepRaw) : 1;\n\n if (start < min || start > max || end < min || end > max) {\n throw new Error(\n `Invalid cron expression \"${expression}\": ${name} \"${part}\" is outside ${min}-${max}.`,\n );\n }\n if (end < start) {\n throw new Error(\n `Invalid cron expression \"${expression}\": ${name} range \"${part}\" is reversed.`,\n );\n }\n if (step < 1) {\n throw new Error(`Invalid cron expression \"${expression}\": ${name} step must be >= 1.`);\n }\n }\n}\n","import fs from 'fs';\nimport path from 'path';\n\nimport { DEFAULT_CRON_SCHEDULE, ensureDir, resolveHomeDir } from '@crosssync/shared';\n\nimport { MACOS_LAUNCH_AGENT_LABEL } from '../constants';\nimport { resolveInvocation } from './invocation';\nimport { defaultCronRunner, toActionResult } from './runner';\nimport { isWildcard, parseCronExpression, toFixedTime, toWeekday } from './schedule';\nimport type { CronManager, CronManagerOptions } from './types';\n\n/** Escapes a value for inclusion in a plist `<string>` element. */\nexport function escapeXml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''');\n}\n\n/** Path of the launchd agent written by CrossSync. */\nexport function launchAgentPath(label: string, homeDir?: string): string {\n return path.join(homeDir ?? resolveHomeDir(), 'Library', 'LaunchAgents', `${label}.plist`);\n}\n\n/** Renders the `com.crosssync.sync.plist` LaunchAgent. */\nexport function renderLaunchAgent(options: {\n label: string;\n expression: string;\n program: string;\n args: string[];\n logDir: string;\n}): string {\n const spec = parseCronExpression(options.expression);\n const { hour, minute } = toFixedTime(spec);\n\n const calendar: string[] = [\n ' <key>Hour</key>',\n ` <integer>${hour}</integer>`,\n ' <key>Minute</key>',\n ` <integer>${minute}</integer>`,\n ];\n\n const weekday = toWeekday(spec);\n if (weekday !== null) {\n calendar.push(' <key>Weekday</key>', ` <integer>${weekday}</integer>`);\n }\n if (!isWildcard(spec.dayOfMonth) && /^\\d+$/.test(spec.dayOfMonth)) {\n calendar.push(' <key>Day</key>', ` <integer>${Number(spec.dayOfMonth)}</integer>`);\n }\n if (!isWildcard(spec.month) && /^\\d+$/.test(spec.month)) {\n calendar.push(' <key>Month</key>', ` <integer>${Number(spec.month)}</integer>`);\n }\n\n const programArguments = [options.program, ...options.args]\n .map((value) => ` <string>${escapeXml(value)}</string>`)\n .join('\\n');\n\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">',\n '<plist version=\"1.0\">',\n '<dict>',\n ' <key>Label</key>',\n ` <string>${escapeXml(options.label)}</string>`,\n ' <key>ProgramArguments</key>',\n ' <array>',\n programArguments,\n ' </array>',\n ' <key>StartCalendarInterval</key>',\n ' <dict>',\n calendar.join('\\n'),\n ' </dict>',\n ' <key>RunAtLoad</key>',\n ' <false/>',\n ' <key>StandardOutPath</key>',\n ` <string>${escapeXml(path.join(options.logDir, 'launchd.out.log'))}</string>`,\n ' <key>StandardErrorPath</key>',\n ` <string>${escapeXml(path.join(options.logDir, 'launchd.err.log'))}</string>`,\n '</dict>',\n '</plist>',\n '',\n ].join('\\n');\n}\n\n/**\n * Installs the schedule as a per-user launchd agent.\n *\n * launchd only understands calendar intervals, so a fixed time is required.\n */\nexport function createMacosCronManager(options: CronManagerOptions = {}): CronManager {\n const label = options.label ?? MACOS_LAUNCH_AGENT_LABEL;\n const expression = options.expression ?? DEFAULT_CRON_SCHEDULE;\n const invocation = resolveInvocation(options);\n const runner = options.runner ?? defaultCronRunner;\n const homeDir = options.homeDir ?? resolveHomeDir();\n const plistPath = launchAgentPath(label, homeDir);\n const logDir = path.join(homeDir, '.crosssync', 'logs');\n\n const render = (): string =>\n renderLaunchAgent({\n label,\n expression,\n program: invocation.program,\n args: invocation.args,\n logDir,\n });\n\n return {\n platform: 'darwin',\n label,\n\n describe(action) {\n if (action === 'install') {\n return [\n `Write launchd agent: ${plistPath}`,\n ` launchctl load -w ${plistPath}`,\n '',\n render().trimEnd(),\n ].join('\\n');\n }\n return [\n `Unload launchd agent:`,\n ` launchctl unload -w ${plistPath}`,\n `Remove file: ${plistPath}`,\n ].join('\\n');\n },\n\n install() {\n ensureDir(path.dirname(plistPath));\n fs.writeFileSync(plistPath, render(), 'utf8');\n runner('launchctl', ['unload', '-w', plistPath]);\n const result = runner('launchctl', ['load', '-w', plistPath]);\n return toActionResult(result, `launchd agent \"${label}\" installed.`, 'launchctl load failed');\n },\n\n uninstall() {\n const result = runner('launchctl', ['unload', '-w', plistPath]);\n const existed = fs.existsSync(plistPath);\n if (existed) {\n fs.rmSync(plistPath, { force: true });\n }\n if (!existed && result.status !== 0) {\n return { changed: false, messages: [`No launchd agent named \"${label}\" was installed.`] };\n }\n return { changed: existed, messages: [`launchd agent \"${label}\" removed.`] };\n },\n };\n}\n","import { DEFAULT_CRON_SCHEDULE } from '@crosssync/shared';\n\nimport { WINDOWS_TASK_NAME } from '../constants';\nimport { resolveInvocation } from './invocation';\nimport { defaultCronRunner, toActionResult } from './runner';\nimport {\n formatTime,\n isDaily,\n isWeekly,\n parseCronExpression,\n toFixedTime,\n toWeekday,\n windowsWeekdayName,\n} from './schedule';\nimport type { CronManager, CronManagerOptions } from './types';\n\nconst UNSUPPORTED_MESSAGE =\n 'Windows Task Scheduler supports daily or weekly CrossSync schedules only. ' +\n 'Use an expression such as \"0 9 * * *\" or \"0 9 * * 1\".';\n\n/**\n * Installs the schedule through Task Scheduler (`schtasks`).\n *\n * `schtasks` cannot express arbitrary cron expressions, so only daily and\n * weekly schedules at a fixed time are accepted.\n */\nexport function createWindowsCronManager(options: CronManagerOptions = {}): CronManager {\n const label = options.label ?? WINDOWS_TASK_NAME;\n const expression = options.expression ?? DEFAULT_CRON_SCHEDULE;\n const invocation = resolveInvocation(options);\n const runner = options.runner ?? defaultCronRunner;\n\n const scheduleArgs = buildScheduleArgs(expression);\n\n return {\n platform: 'win32',\n label,\n\n describe(action) {\n if (action === 'install') {\n return [\n `Register scheduled task \"${label}\" (${expression}):`,\n ` schtasks ${['/Create', '/F', '/TN', label, ...scheduleArgs, '/TR', invocation.windowsCommandLine].join(' ')}`,\n ].join('\\n');\n }\n return [\n `Remove scheduled task \"${label}\":`,\n ` schtasks ${['/Delete', '/F', '/TN', label].join(' ')}`,\n ].join('\\n');\n },\n\n install() {\n const result = runner('schtasks', [\n '/Create',\n '/F',\n '/TN',\n label,\n ...scheduleArgs,\n '/TR',\n invocation.windowsCommandLine,\n ]);\n return toActionResult(result, `Scheduled task \"${label}\" installed.`, 'schtasks failed');\n },\n\n uninstall() {\n const result = runner('schtasks', ['/Delete', '/F', '/TN', label]);\n if (result.status !== 0) {\n // `schtasks` exits non-zero (with a localized message) when the task is\n // absent, so treat any failure as \"nothing to remove\" to stay idempotent.\n return {\n changed: false,\n messages: [`No scheduled task named \"${label}\" was removed.`],\n };\n }\n return { changed: true, messages: [`Scheduled task \"${label}\" removed.`] };\n },\n };\n}\n\n/** Builds the `/SC ...` arguments for a cron expression. */\nexport function buildScheduleArgs(expression: string): string[] {\n const spec = parseCronExpression(expression);\n const { hour, minute } = toFixedTime(spec);\n const time = formatTime(hour, minute);\n\n if (isDaily(spec)) {\n return ['/SC', 'DAILY', '/ST', time];\n }\n if (isWeekly(spec)) {\n const weekday = toWeekday(spec);\n return ['/SC', 'WEEKLY', '/D', windowsWeekdayName(weekday ?? 0), '/ST', time];\n }\n throw new Error(UNSUPPORTED_MESSAGE);\n}\n","import path from 'path';\n\nimport type { BookmarkRoots, HistoryEntry } from '@crosssync/shared';\nimport {\n ensureDir,\n pathExists,\n readJsonFile,\n resolveExportRetention,\n writeJsonFileSafe,\n} from '@crosssync/shared';\nimport { formatBackupId, type BookmarkMergeStats, type HistoryMergeStats } from '@crosssync/core';\n\nimport type { CliContext } from '../context';\nimport { collectExportFiles, pruneExports } from '../export-files';\nimport { describeError, readMergedData, type MergedData } from './read';\nimport { resolveBrowsers } from './sync';\n\nexport interface ExportCommandOptions {\n /** Only `json` is supported. */\n format?: string;\n /** Directory to write into; defaults to the configured export dir. */\n out?: string;\n browser?: string;\n profile?: string;\n /** Write to stdout instead of a file. */\n stdout?: boolean;\n now?: Date;\n platform?: NodeJS.Platform;\n}\n\nexport interface ExportPayload {\n exportedAt: string;\n source: 'crosssync';\n version: number;\n bookmarks: { stats: BookmarkMergeStats; roots: BookmarkRoots } | null;\n history: { stats: HistoryMergeStats; entries: HistoryEntry[] } | null;\n}\n\nexport function buildExportPayload(data: MergedData, exportedAt = new Date()): ExportPayload {\n return {\n exportedAt: exportedAt.toISOString(),\n source: 'crosssync',\n version: 1,\n bookmarks: data.bookmarkMerge\n ? { stats: data.bookmarkMerge.stats, roots: data.bookmarkMerge.roots }\n : null,\n history: data.historyMerge\n ? { stats: data.historyMerge.stats, entries: data.historyMerge.entries }\n : null,\n };\n}\n\n/** Reads and merges browser data, then writes it out as JSON. Never writes back. */\nexport function runExportCommand(context: CliContext, options: ExportCommandOptions = {}): number {\n const format = (options.format ?? 'json').toLowerCase();\n if (format !== 'json') {\n context.io.err(`Unsupported export format \"${format}\". Only \"json\" is supported.`);\n return 1;\n }\n\n let data: MergedData;\n try {\n data = readMergedData(context.config, {\n browser: resolveBrowsers(options.browser),\n profile: options.profile,\n platform: options.platform,\n });\n } catch (error) {\n context.io.err(`Export failed: ${describeError(error)}`);\n return 1;\n }\n\n for (const warning of data.warnings) {\n context.io.err(`warning: ${warning}`);\n }\n\n if (!data.bookmarkMerge && !data.historyMerge) {\n context.io.err('Nothing to export: no bookmark or history data was found.');\n return 1;\n }\n\n const payload = buildExportPayload(data, options.now ?? new Date());\n\n if (options.stdout) {\n context.io.out(JSON.stringify(payload, null, 2));\n return 0;\n }\n\n const outDir = options.out ?? context.config.exportDir;\n const target = path.join(\n outDir,\n `crosssync-export-${formatBackupId(options.now ?? new Date())}.json`,\n );\n\n try {\n ensureDir(outDir);\n writeJsonFileSafe(target, payload);\n } catch (error) {\n context.io.err(`Export failed: ${describeError(error)}`);\n return 1;\n }\n\n // Only the managed export directory is pruned; custom --out dirs are left alone.\n if (path.resolve(outDir) === path.resolve(context.config.exportDir)) {\n const removed = pruneExports(outDir, resolveExportRetention(context.config));\n if (removed.length > 0) {\n context.logger.info('Pruned old exports', { removed: removed.length });\n }\n }\n\n context.logger.info('Export written', { file: target });\n context.io.out(`Export written: ${target}`);\n if (data.bookmarkMerge) {\n context.io.out(` bookmarks: ${data.bookmarkMerge.stats.total} nodes`);\n }\n if (data.historyMerge) {\n context.io.out(` history: ${data.historyMerge.stats.total} entries`);\n }\n return 0;\n}\n\nexport interface ExportSummary {\n count: number;\n latest: string | null;\n /** Newest first, capped by `limit`. */\n files: string[];\n}\n\n/** Summarises the CrossSync export files written into a directory. */\nexport function listExports(exportDir: string, limit = 5): ExportSummary {\n const files = collectExportFiles(exportDir);\n return {\n count: files.length,\n latest: files.length > 0 ? files[0].file : null,\n files: files.slice(0, limit).map((entry) => entry.file),\n };\n}\n\n/** Reads an exported payload back from disk. */\nexport function readExportFile(filePath: string): ExportPayload | null {\n if (!pathExists(filePath)) {\n return null;\n }\n return readJsonFile<ExportPayload>(filePath);\n}\n","import fs from 'fs';\nimport path from 'path';\n\n/**\n * Files written by CrossSync:\n * bookmarks-merged-<yyyyMMdd-HHmmss>.json\n * history-merged-<yyyyMMdd-HHmmss>.json\n * crosssync-export-<yyyyMMdd-HHmmss>.json\n */\nconst EXPORT_FILE_PATTERN =\n /^(?:bookmarks-merged|history-merged|crosssync-export)-(\\d{8}-\\d{6})\\.json$/;\n\nexport interface ExportFileInfo {\n /** Absolute path of the export file. */\n file: string;\n /** Sortable `yyyyMMdd-HHmmss` stamp taken from the file name. */\n timestamp: string;\n}\n\n/** Lists CrossSync export files, newest first. Unrelated JSON files are ignored. */\nexport function collectExportFiles(exportDir: string): ExportFileInfo[] {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(exportDir, { withFileTypes: true });\n } catch {\n return [];\n }\n\n const files: ExportFileInfo[] = [];\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n const match = EXPORT_FILE_PATTERN.exec(entry.name);\n if (!match) {\n continue;\n }\n files.push({ file: path.join(exportDir, entry.name), timestamp: match[1] });\n }\n\n return files.sort(\n (a, b) => b.timestamp.localeCompare(a.timestamp) || b.file.localeCompare(a.file),\n );\n}\n\n/**\n * Keeps the `keep` most recent CrossSync export files and deletes the rest.\n * A `keep` of `0` disables cleanup; failures are ignored so they never abort a sync.\n */\nexport function pruneExports(exportDir: string, keep: number): string[] {\n if (!Number.isFinite(keep) || keep <= 0) {\n return [];\n }\n\n const removed: string[] = [];\n for (const entry of collectExportFiles(exportDir).slice(Math.floor(keep))) {\n try {\n fs.rmSync(entry.file, { force: true });\n removed.push(entry.file);\n } catch {\n // Best effort: a locked/unreadable file must not fail the whole sync.\n }\n }\n return removed;\n}\n","import * as readline from 'node:readline/promises';\n\nimport type { BrowserName, CliConfig, SyncStrategy } from '@crosssync/shared';\nimport {\n addProfilesToSelection,\n BROWSERS,\n isBrowserName,\n resolveExportRetention,\n SYNC_STRATEGIES,\n} from '@crosssync/shared';\nimport { createConfiguredBrowserReaders, runSync, type SyncReport } from '@crosssync/core';\n\nimport type { CliContext } from '../context';\nimport { saveConfigFile } from '../context';\nimport { pruneExports } from '../export-files';\n\nexport interface SyncCommandOptions {\n bookmarks?: boolean;\n history?: boolean;\n all?: boolean;\n dryRun?: boolean;\n force?: boolean;\n /** `chrome`, `edge` or `all`. */\n browser?: string;\n profile?: string;\n /** `merge` or `export`. */\n strategy?: string;\n /** Print the report as JSON. */\n json?: boolean;\n /** Injectable for tests. */\n browserRunning?: (browser: BrowserName) => boolean;\n /** Asked when the configured profile cannot be found for a browser. */\n selectProfiles?: ProfileSelector;\n now?: Date;\n platform?: NodeJS.Platform;\n}\n\nexport interface ProfileSelectionRequest {\n browser: BrowserName;\n dataDir: string;\n /** Profiles that actually exist on disk. */\n available: string[];\n /** The currently configured profile value. */\n current: string;\n}\n\n/** Returns the chosen profiles, or null/[] to skip that browser. */\nexport type ProfileSelector = (request: ProfileSelectionRequest) => Promise<string[] | null>;\n\nexport interface SyncTargets {\n bookmarks: boolean;\n history: boolean;\n}\n\n/** `--all` (or no flag at all) syncs bookmarks and history. */\nexport function resolveTargets(options: SyncCommandOptions): SyncTargets {\n if (options.all) {\n return { bookmarks: true, history: true };\n }\n const bookmarks = options.bookmarks === true;\n const history = options.history === true;\n if (!bookmarks && !history) {\n return { bookmarks: true, history: true };\n }\n return { bookmarks, history };\n}\n\nexport function resolveBrowsers(value: string | undefined): BrowserName[] {\n if (!value || value === 'all') {\n return [...BROWSERS];\n }\n if (!isBrowserName(value)) {\n throw new Error(`Unknown browser \"${value}\". Use one of: ${BROWSERS.join(', ')}, all.`);\n }\n return [value];\n}\n\nexport function resolveStrategy(value: string | undefined): SyncStrategy | undefined {\n if (!value) {\n return undefined;\n }\n if (!(SYNC_STRATEGIES as readonly string[]).includes(value)) {\n throw new Error(`Unknown strategy \"${value}\". Use one of: ${SYNC_STRATEGIES.join(', ')}.`);\n }\n return value as SyncStrategy;\n}\n\n/** Applies the CLI overrides on top of the stored config. */\nexport function buildSyncConfig(config: CliConfig, options: SyncCommandOptions): CliConfig {\n const enabled = new Set(resolveBrowsers(options.browser));\n return {\n ...config,\n profile: options.profile ?? config.profile,\n browsers: {\n chrome: {\n ...config.browsers.chrome,\n enabled: enabled.has('chrome') && config.browsers.chrome.enabled !== false,\n },\n edge: {\n ...config.browsers.edge,\n enabled: enabled.has('edge') && config.browsers.edge.enabled !== false,\n },\n },\n };\n}\n\n/**\n * When the configured profile does not exist for a browser, interactively list\n * the profiles that do exist and persist the user's choice. The chosen names are\n * merged into the configured comma-separated list, so other browsers keep their\n * own profiles.\n */\nasync function ensureProfilesSelected(\n context: CliContext,\n options: SyncCommandOptions,\n): Promise<void> {\n if (options.profile !== undefined || options.json) {\n return;\n }\n const interactive =\n options.selectProfiles !== undefined ||\n (process.stdin.isTTY === true && process.stdout.isTTY === true);\n if (!interactive) {\n return;\n }\n\n const effective = buildSyncConfig(context.config, options);\n const readers = createConfiguredBrowserReaders(effective, { platform: options.platform });\n const select = options.selectProfiles ?? promptForProfiles;\n let changed = false;\n\n for (const reader of readers) {\n if (reader.resolveProfiles(context.config.profile).length > 0) {\n continue;\n }\n const available = reader.profiles();\n if (available.length === 0) {\n continue;\n }\n\n const selected = await select({\n browser: reader.browser,\n dataDir: reader.dataDir,\n available,\n current: context.config.profile,\n });\n if (!selected || selected.length === 0) {\n continue;\n }\n\n const valid = selected.filter((name) => available.includes(name));\n if (valid.length === 0) {\n continue;\n }\n context.config.profile = addProfilesToSelection(context.config.profile, valid);\n changed = true;\n }\n\n if (changed) {\n saveConfigFile(context.dirs.configFile, context.config);\n context.io.out(`Profile selection saved: ${context.config.profile}`);\n }\n}\n\n/** Default interactive selector, used when stdin is a terminal. */\nexport async function promptForProfiles(\n request: ProfileSelectionRequest,\n): Promise<string[] | null> {\n const output = process.stdout;\n output.write(`\\nNo ${request.browser} profile matched \"${request.current}\".\\n`);\n output.write(`Available ${request.browser} profiles in ${request.dataDir}:\\n`);\n request.available.forEach((name, index) => {\n output.write(` ${index + 1}) ${name}\\n`);\n });\n\n const rl = readline.createInterface({ input: process.stdin, output });\n try {\n for (;;) {\n const answer = await rl.question(\n 'Select profiles (comma-separated numbers or names, \"all\", empty to skip): ',\n );\n const parsed = parseProfileAnswer(answer, request.available);\n if (parsed !== undefined) {\n return parsed;\n }\n output.write('Invalid selection; please try again.\\n');\n }\n } catch {\n return null;\n } finally {\n rl.close();\n }\n}\n\n/**\n * Parses a prompt answer.\n * Returns an empty result (`null`) to skip, or `undefined` for invalid input.\n */\nexport function parseProfileAnswer(\n answer: string,\n available: readonly string[],\n): string[] | null | undefined {\n const trimmed = answer.trim();\n if (trimmed.length === 0) {\n return null;\n }\n if (trimmed.toLowerCase() === 'all') {\n return [...available];\n }\n\n const selected: string[] = [];\n for (const token of trimmed.split(',')) {\n const value = token.trim();\n if (value.length === 0) {\n continue;\n }\n if (/^\\d+$/.test(value)) {\n const index = Number(value) - 1;\n if (index < 0 || index >= available.length) {\n return undefined;\n }\n const name = available[index];\n if (!selected.includes(name)) {\n selected.push(name);\n }\n continue;\n }\n if (!available.includes(value)) {\n return undefined;\n }\n if (!selected.includes(value)) {\n selected.push(value);\n }\n }\n\n return selected.length > 0 ? selected : undefined;\n}\n\nexport async function runSyncCommand(\n context: CliContext,\n options: SyncCommandOptions = {},\n): Promise<number> {\n const targets = resolveTargets(options);\n const strategy = resolveStrategy(options.strategy) ?? context.config.sync.strategy;\n\n await ensureProfilesSelected(context, options);\n\n const config = buildSyncConfig(context.config, options);\n\n const report = runSync({\n config,\n targets,\n dryRun: options.dryRun,\n force: options.force,\n strategy,\n logger: context.logger,\n browserRunning: options.browserRunning,\n now: options.now,\n platform: options.platform,\n });\n\n if (!options.dryRun && report.exportFiles.length > 0) {\n const removed = pruneExports(context.config.exportDir, resolveExportRetention(context.config));\n if (removed.length > 0) {\n context.logger.info('Pruned old exports', { removed: removed.length });\n }\n }\n\n if (options.json) {\n context.io.out(JSON.stringify(report, null, 2));\n } else {\n for (const line of formatSyncReport(report)) {\n context.io.out(line);\n }\n }\n\n const failed = report.warnings.some((warning) => warning.startsWith('Backup failed'));\n return failed ? 1 : 0;\n}\n\nexport function formatSyncReport(report: SyncReport): string[] {\n const lines: string[] = [];\n const kinds = [\n report.targets.bookmarks ? 'bookmarks' : null,\n report.targets.history ? 'history' : null,\n ]\n .filter((kind): kind is string => kind !== null)\n .join(' + ');\n\n lines.push(`CrossSync sync (${report.strategy}, ${kinds})${report.dryRun ? ' [dry run]' : ''}`);\n\n for (const outcome of report.browsers) {\n const parts = [`${outcome.browser}/${outcome.profile}`];\n if (report.targets.bookmarks) {\n parts.push(`${outcome.bookmarksRead} bookmark nodes`);\n }\n if (report.targets.history) {\n parts.push(`${outcome.historyRead} history entries`);\n }\n if (outcome.writtenBack) {\n parts.push('written back');\n } else if (outcome.skippedWriteBackReason) {\n parts.push(`write-back skipped (${outcome.skippedWriteBackReason})`);\n }\n lines.push(` ${parts.join(', ')}`);\n }\n\n if (report.bookmarkMerge) {\n const { added, updated, identical, total } = report.bookmarkMerge.stats;\n lines.push(\n ` merged bookmarks: ${total} nodes (added ${added}, updated ${updated}, identical ${identical}, conflicts ${report.bookmarkMerge.conflicts.length})`,\n );\n }\n if (report.historyMerge) {\n lines.push(\n ` merged history: ${report.historyMerge.stats.total} entries (${report.historyMerge.stats.duplicates} duplicates collapsed)`,\n );\n }\n if (report.backup) {\n lines.push(` backup: ${report.backup.dir}`);\n }\n for (const file of report.exportFiles) {\n lines.push(` export: ${file}`);\n }\n if (report.warnings.length > 0) {\n lines.push(' warnings:');\n for (const warning of report.warnings) {\n lines.push(` - ${warning}`);\n }\n }\n\n return lines;\n}\n","import path from 'path';\n\nimport type { LogEntry } from '@crosssync/core';\nimport { clearLogFile, readLogEntries } from '@crosssync/core';\nimport type { LogLevel } from '@crosssync/shared';\nimport { isLogLevel, LOG_FILE_NAME } from '@crosssync/shared';\n\nimport type { CliContext } from '../context';\n\nexport interface LogsCommandOptions {\n /** Maximum number of entries to print (most recent last). */\n limit?: number;\n level?: string;\n clear?: boolean;\n json?: boolean;\n}\n\nexport function currentLogFile(context: CliContext): string {\n return path.join(context.config.logDir, LOG_FILE_NAME);\n}\n\nexport function runLogsCommand(context: CliContext, options: LogsCommandOptions = {}): number {\n const file = currentLogFile(context);\n\n if (options.clear) {\n clearLogFile(file);\n context.io.out(`Cleared ${file}`);\n return 0;\n }\n\n if (options.level !== undefined && !isLogLevel(options.level)) {\n context.io.err(`Unknown log level \"${options.level}\".`);\n return 1;\n }\n\n const entries = readLogEntries(file, {\n limit: options.limit,\n level: options.level as LogLevel | undefined,\n });\n\n if (entries.length === 0) {\n context.io.out(`No log entries in ${file}.`);\n return 0;\n }\n\n if (options.json) {\n context.io.out(JSON.stringify(entries, null, 2));\n return 0;\n }\n\n for (const entry of entries) {\n context.io.out(formatLogEntry(entry));\n }\n return 0;\n}\n\nexport function formatLogEntry(entry: LogEntry): string {\n const timestamp = new Date(entry.timestamp).toISOString();\n const meta =\n entry.meta && Object.keys(entry.meta).length > 0 ? ` ${JSON.stringify(entry.meta)}` : '';\n return `${timestamp} [${entry.level.toUpperCase()}] ${entry.message}${meta}`;\n}\n","import {\n addProfilesToSelection,\n BROWSERS,\n DEFAULT_PROFILE,\n isBrowserName,\n parseProfileList,\n PROFILE_NAME_PATTERN,\n} from '@crosssync/shared';\nimport { createBrowserReader, createConfiguredBrowserReaders } from '@crosssync/core';\n\nimport type { CliContext } from '../context';\nimport { saveConfigFile } from '../context';\n\nexport interface ProfilesCommandOptions {\n list?: boolean;\n set?: string;\n add?: string;\n remove?: string;\n all?: boolean;\n reset?: boolean;\n browser?: string;\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n}\n\n/** Parses a comma-separated list of profile names, or the `all` sentinel. */\nexport function parseProfileNames(value: string): string[] | 'all' {\n if (value.trim().toLowerCase() === 'all') {\n return 'all';\n }\n const names = parseProfileList(value);\n if (names.length === 0) {\n throw new Error('Profile list is empty.');\n }\n for (const name of names) {\n if (!PROFILE_NAME_PATTERN.test(name)) {\n throw new Error(`Invalid profile name \"${name}\". Use \"Default\" or \"Profile N\".`);\n }\n }\n return names;\n}\n\n/** Lists available profiles for each browser, marking the current selection. */\nfunction listProfiles(context: CliContext, options: ProfilesCommandOptions): number {\n const filter = options.browser ?? 'all';\n if (filter !== 'all' && !isBrowserName(filter)) {\n context.io.err(`Unknown browser \"${filter}\". Use one of: ${BROWSERS.join(', ')}, all.`);\n return 1;\n }\n\n const selection = context.config.profile;\n const selected = selection.trim() === 'all' ? null : parseProfileList(selection);\n\n for (const browser of BROWSERS) {\n if (filter !== 'all' && browser !== filter) {\n continue;\n }\n const browserConfig = context.config.browsers[browser];\n const reader = createBrowserReader(browser, {\n dataDir: browserConfig.dataDir,\n platform: options.platform,\n env: options.env,\n });\n const available = reader.profiles();\n\n context.io.out(`${browser}: ${reader.dataDir}${browserConfig.enabled ? '' : ' [disabled]'}`);\n if (available.length === 0) {\n context.io.out(' (no profiles found)');\n continue;\n }\n for (const name of available) {\n const isSelected = selected === null || selected.includes(name);\n context.io.out(` ${name}${isSelected ? ' [selected]' : ''}`);\n }\n const missing = selected?.filter((name) => !available.includes(name)) ?? [];\n if (missing.length > 0) {\n context.io.out(` (configured but not found: ${missing.join(', ')})`);\n }\n }\n\n context.io.out(`Selected profile(s): ${selection}`);\n return 0;\n}\n\n/** Expands `all` into the profiles that currently exist, for `--remove`. */\nfunction expandAllProfiles(context: CliContext, options: ProfilesCommandOptions): string[] {\n const names: string[] = [];\n const readers = createConfiguredBrowserReaders(context.config, {\n platform: options.platform,\n env: options.env,\n });\n for (const reader of readers) {\n for (const name of reader.profiles()) {\n if (!names.includes(name)) {\n names.push(name);\n }\n }\n }\n return names;\n}\n\nfunction removeProfiles(\n context: CliContext,\n current: string,\n names: string[] | 'all',\n options: ProfilesCommandOptions,\n): string {\n if (names === 'all') {\n throw new Error('Refusing to remove every profile; use --reset or --set instead.');\n }\n const base = current.trim() === 'all' ? expandAllProfiles(context, options).join(',') : current;\n const remaining = parseProfileList(base).filter((name) => !names.includes(name));\n if (remaining.length === parseProfileList(base).length) {\n throw new Error(`None of the selected profiles matched: ${names.join(', ')}.`);\n }\n if (remaining.length === 0) {\n throw new Error('Refusing to remove every profile; use --reset or --set instead.');\n }\n return remaining.join(',');\n}\n\nexport function runProfilesCommand(\n context: CliContext,\n options: ProfilesCommandOptions = {},\n): number {\n const mutating =\n options.set !== undefined ||\n options.add !== undefined ||\n options.remove !== undefined ||\n options.all === true ||\n options.reset === true;\n\n if (!mutating) {\n return listProfiles(context, options);\n }\n\n if (options.browser !== undefined && options.browser !== 'all') {\n context.io.err('--browser only applies when listing; profile changes are global.');\n return 1;\n }\n\n try {\n let next = context.config.profile;\n if (options.reset) {\n next = DEFAULT_PROFILE;\n } else if (options.all) {\n next = 'all';\n } else if (options.set !== undefined) {\n const names = parseProfileNames(options.set);\n next = names === 'all' ? 'all' : names.join(',');\n } else if (options.add !== undefined) {\n const names = parseProfileNames(options.add);\n next = names === 'all' ? 'all' : addProfilesToSelection(next, names);\n } else if (options.remove !== undefined) {\n next = removeProfiles(context, next, parseProfileNames(options.remove), options);\n }\n\n const nextConfig = { ...context.config, profile: next };\n saveConfigFile(context.dirs.configFile, nextConfig);\n context.config = nextConfig;\n context.io.out(`profile = ${JSON.stringify(next)}`);\n return 0;\n } catch (error) {\n context.io.err(error instanceof Error ? error.message : String(error));\n return 1;\n }\n}\n","import path from 'path';\n\nimport { LOG_FILE_NAME, pathExists } from '@crosssync/shared';\nimport { createBrowserReader, getRunningBrowsers, listBackups } from '@crosssync/core';\n\nimport { CLI_VERSION } from '../constants';\nimport type { CliContext } from '../context';\nimport { listExports } from './export';\n\nexport interface StatusCommandOptions {\n json?: boolean;\n platform?: NodeJS.Platform;\n env?: NodeJS.ProcessEnv;\n}\n\nexport interface BrowserProfileStatus {\n profile: string;\n bookmarks: boolean;\n history: boolean;\n}\n\nexport interface BrowserStatusReport {\n browser: string;\n dataDir: string;\n exists: boolean;\n running: boolean;\n profiles: BrowserProfileStatus[];\n}\n\nexport interface StatusReport {\n version: string;\n configFile: string;\n dataDir: string;\n logLevel: string;\n logFile: string;\n profile: string;\n schedule: { installed: boolean; expression: string };\n browsers: BrowserStatusReport[];\n backups: { count: number; latest: string | null; dir: string };\n exports: { count: number; latest: string | null; dir: string };\n}\n\n/** Pure-ish collector used by both `status` and its tests. */\nexport function buildStatusReport(\n context: CliContext,\n options: StatusCommandOptions = {},\n): StatusReport {\n const { config, dirs } = context;\n const running = new Map(\n getRunningBrowsers({ platform: options.platform }).map((status) => [\n status.browser,\n status.running,\n ]),\n );\n\n const browsers: BrowserStatusReport[] = [];\n for (const browser of Object.keys(config.browsers) as (keyof typeof config.browsers)[]) {\n const browserConfig = config.browsers[browser];\n const dataDir = browserConfig.dataDir ?? '';\n const profiles: BrowserProfileStatus[] = [];\n\n if (browserConfig.enabled) {\n const reader = createReader(browser, browserConfig.dataDir, options);\n for (const profile of reader.resolveProfiles(config.profile)) {\n profiles.push({\n profile,\n bookmarks: pathExists(reader.bookmarksPath(profile)),\n history: pathExists(reader.historyPath(profile)),\n });\n }\n browsers.push({\n browser,\n dataDir: reader.dataDir,\n exists: pathExists(reader.dataDir),\n running: running.get(browser) ?? false,\n profiles,\n });\n } else {\n browsers.push({\n browser,\n dataDir,\n exists: false,\n running: running.get(browser) ?? false,\n profiles: [],\n });\n }\n }\n\n const backups = listBackups(config.backupDir);\n const exports = listExports(config.exportDir, 1);\n\n return {\n version: CLI_VERSION,\n configFile: dirs.configFile,\n dataDir: config.dataDir,\n logLevel: config.logLevel,\n logFile: path.join(config.logDir, LOG_FILE_NAME),\n profile: config.profile,\n schedule: { ...config.schedule },\n browsers,\n backups: {\n count: backups.length,\n latest: backups.length > 0 ? backups[0].dir : null,\n dir: config.backupDir,\n },\n exports: { count: exports.count, latest: exports.latest, dir: config.exportDir },\n };\n}\n\nfunction createReader(\n browser: keyof CliContext['config']['browsers'],\n dataDir: string | undefined,\n options: StatusCommandOptions,\n) {\n return createBrowserReader(browser, {\n dataDir,\n platform: options.platform,\n env: options.env,\n });\n}\n\nexport function runStatusCommand(context: CliContext, options: StatusCommandOptions = {}): number {\n const report = buildStatusReport(context, options);\n\n if (options.json) {\n context.io.out(JSON.stringify(report, null, 2));\n return 0;\n }\n\n const io = context.io;\n io.out(`CrossSync ${report.version}`);\n io.out(` config: ${report.configFile}`);\n io.out(` data dir: ${report.dataDir}`);\n io.out(` profile: ${report.profile}`);\n io.out(` log level: ${report.logLevel}`);\n io.out(` log file: ${report.logFile}`);\n io.out(\n ` schedule: ${report.schedule.installed ? `installed (${report.schedule.expression})` : 'not installed'}`,\n );\n\n io.out(' browsers:');\n for (const entry of report.browsers) {\n io.out(\n ` ${entry.browser}: ${entry.exists ? entry.dataDir : `not found (${entry.dataDir})`}` +\n `${entry.running ? ' [running]' : ''}`,\n );\n for (const profile of entry.profiles) {\n const files = [\n profile.bookmarks ? 'Bookmarks' : null,\n profile.history ? 'History' : null,\n ].filter((name): name is string => name !== null);\n io.out(` ${profile.profile}: ${files.length > 0 ? files.join(', ') : 'no data files'}`);\n }\n }\n\n io.out(` backups: ${report.backups.count} (latest: ${report.backups.latest ?? 'none'})`);\n io.out(` exports: ${report.exports.count} (latest: ${report.exports.latest ?? 'none'})`);\n return 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,8CAAAA,UAAA;AAAA;AAGA,QAAMC,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjC,YAAY,UAAU,MAAM,SAAS;AACnC,cAAM,OAAO;AAEb,cAAM,kBAAkB,MAAM,KAAK,WAAW;AAC9C,aAAK,OAAO,KAAK,YAAY;AAC7B,aAAK,OAAO;AACZ,aAAK,WAAW;AAChB,aAAK,cAAc;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AC/C,OAAO,aAAa,0CAA0C;AACjE,uBAAqB;AAAA,IACnB,YAAY,CAAC,YAAY,wBAAwB,SAAS,qBAAqB,KAAK,CAAC,CAAC;AAAA,EACxF;AAEA,QAAM,gBAAgBA,SACnB,QAAQ,QAAQ,EAChB,YAAY,0CAA0C,EACtD,OAAO,UAAU,4BAA4B,EAC7C,OAAO,eAAe,uCAAuC,EAC7D,OAAO,qBAAqB,wCAAwC,EACpE,OAAO,WAAW,4BAA4B;AACjD,gBAAc,OAAO,YAAY,CAAC,YAAY,iBAAiB,SAAS,cAAc,KAAK,CAAC,CAAC,CAAC;AAE9F,SAAOA;AACT;AAEA,eAAsB,IAAI,OAAiB,QAAQ,MAAqB;AACtE,QAAM,aAAa,EAAE,WAAW,IAAI;AACtC;AAGO,IAAM,UAAU;AAChB,IAAM,UAAU;AAEvB,IAAI,QAAQ,SAAS,QAAQ;AAC3B,OAAK,IAAI;AACX;","names":["exports","CommanderError","InvalidArgumentError","exports","InvalidArgumentError","Argument","exports","Help","cmd","exports","InvalidArgumentError","Option","str","exports","exports","path","fs","process","Argument","CommanderError","Help","Option","Command","option","exports","Argument","Command","CommanderError","InvalidArgumentError","Help","Option","exports","exports","exports","exports","resolveExportRetention","parseProfileList","addProfilesToSelection","createDefaultConfig","exports","readJsonFile","writeJsonFileSafe","pathExists","ensureDir","resolveHomeDir","listProfiles","resolveCrossSyncDirs","isLogLevel","isBrowserName","isCliConfig","exports","exports","exports","readLogEntries","clearLogFile","Logger","exports","getRunningBrowsers","exports","createBrowserReader","exports","createConfiguredBrowserReaders","exports","mergeBookmarkFiles","mergeHistory","exports","formatBackupId","createBackup","listBackups","pruneBackups","exports","runSync","describeError","exports","commander","config","path","import_shared","import_core","import_shared","import_core","import_shared","import_shared","import_shared","import_path","import_shared","program","path","program","fs","os","import_fs","import_path","import_shared","path","fs","import_shared","import_path","import_shared","import_core","import_fs","import_path","fs","path","import_shared","import_core","path","import_path","import_core","import_shared","path","import_shared","import_core","import_path","import_shared","import_core","exports","path","program"]}
|