@khester/dataverse-codegen 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +133 -0
- package/dist/cli.cjs +5481 -0
- package/dist/cli.cjs.map +1 -0
- package/dist/cli.d.cts +1 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.mjs +5488 -0
- package/dist/cli.mjs.map +1 -0
- package/dist/index.cjs +1428 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +241 -0
- package/dist/index.d.ts +241 -0
- package/dist/index.mjs +1406 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +59 -0
package/dist/cli.mjs.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/tsup/assets/esm_shims.js","../../../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","../../api-client/src/index.ts","../../api-client/src/fetch-client.ts","../../api-client/src/xrm-client.ts","../../api-client/src/mock-client.ts","../../api-client/src/factory.ts","../src/cli.ts","../../../node_modules/commander/esm.mjs","../../entity-gen/src/utils/naming.ts","../../entity-gen/src/templates/sanitize.ts","../../entity-gen/src/templates/header.ts","../../entity-gen/src/utils/typeMapping.ts","../../entity-gen/src/templates/constants.ts","../../entity-gen/src/templates/model.ts","../../entity-gen/src/templates/hooks.ts","../../entity-gen/src/templates/sampleData.ts","../../entity-gen/src/generator.ts","../src/connection.ts","../../dev-tools/src/auth/envLoader.ts","../../dev-tools/src/auth/getToken.ts","../../dev-tools/src/proxy/viteProxy.ts","../../dev-tools/src/proxy/craProxy.ts","../src/metadata/fetch.ts","../src/metadata/adapter.ts","../src/metadata/typedCast.ts","../src/metadata/http.ts","../src/validate.ts","../src/metadata/links.ts","../src/io/write.ts","../src/templates/apiService.ts","../src/seed.ts","../src/design/parse.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\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","/**\n * @dynamics-ui-kit/api-client\n * Unified Dataverse/Dynamics 365 API client.\n */\n\n// Client interface\nexport type { IDataverseClient } from './interfaces';\n\n// Client implementations\nexport { FetchClient } from './fetch-client';\nexport { XrmClient } from './xrm-client';\nexport { MockClient } from './mock-client';\nexport type { MockDataConfig } from './mock-client';\n\n// Factory\nexport { createClient, getEnvironmentInfo } from './factory';\n\n// Types\nexport type {\n ODataResponse,\n BatchDeleteResult,\n BatchUpdateRecord,\n BatchUpdateResult,\n BatchCreateResult,\n ViewUpdateData,\n ViewCreateData,\n ClientOptions,\n EnvironmentInfo,\n Logger,\n EntityMetadata,\n AttributeMetadata,\n ViewMetadata,\n DisplayNameInfo,\n // Relationship types\n RelationshipType,\n OneToManyRelationshipMetadata,\n ManyToOneRelationshipMetadata,\n RelationshipMetadata,\n NormalizedRelationship,\n // Global option set types\n GlobalOptionSetMetadata,\n GlobalOptionSetOption,\n} from './types';\n","/**\n * @dynamics-ui-kit/api-client\n * Bearer token client for local development with real Dynamics data.\n */\n\nimport type { IDataverseClient } from './interfaces';\n\n/** A single OData collection page. */\ninterface ODataPage<T> {\n value?: T[];\n '@odata.nextLink'?: string;\n}\nimport type {\n BatchDeleteResult,\n BatchUpdateRecord,\n BatchUpdateResult,\n BatchCreateResult,\n ViewUpdateData,\n ViewCreateData,\n EntityMetadata,\n AttributeMetadata,\n ViewMetadata,\n Logger,\n RelationshipMetadata,\n OneToManyRelationshipMetadata,\n ManyToOneRelationshipMetadata,\n GlobalOptionSetMetadata,\n} from './types';\n\n/**\n * Dataverse client using fetch with Bearer token authentication.\n * Used for local development against real Dynamics 365 data.\n */\nexport class FetchClient implements IDataverseClient {\n private baseUrl: string;\n private token: string;\n private log: Logger;\n\n constructor(baseUrl: string, token: string, logger?: Logger) {\n this.baseUrl = baseUrl.replace(/\\/$/, '');\n this.token = token;\n this.log = logger ?? console;\n }\n\n /** Update the token (e.g., after refresh) */\n setToken(token: string): void {\n this.token = token;\n }\n\n private getHeaders(): HeadersInit {\n return {\n 'Authorization': `Bearer ${this.token}`,\n 'Content-Type': 'application/json; charset=utf-8',\n 'Accept': 'application/json',\n 'OData-MaxVersion': '4.0',\n 'OData-Version': '4.0',\n 'Prefer': 'odata.include-annotations=\"*\"',\n };\n }\n\n private buildUrl(path: string, id?: string, options?: string): string {\n let url = `${this.baseUrl}/api/data/v9.2/${path}`;\n if (id) {\n url += `(${id.replace(/[{}]/g, '')})`;\n }\n if (options) {\n url += options.startsWith('?') ? options : `?${options}`;\n }\n return url;\n }\n\n private async handleResponse<T>(response: Response): Promise<T> {\n if (!response.ok) {\n let errorMessage = `HTTP ${response.status}: ${response.statusText}`;\n try {\n const errorBody = await response.json();\n if (errorBody.error?.message) {\n errorMessage = errorBody.error.message;\n } else if (errorBody.Message) {\n errorMessage = errorBody.Message;\n }\n } catch {\n // Response wasn't JSON\n }\n\n if (response.status === 401) {\n errorMessage += ' (Token may be expired)';\n } else if (response.status === 403) {\n errorMessage += ' (Insufficient permissions)';\n } else if (response.status === 404) {\n errorMessage += ' (Entity or record not found)';\n }\n\n throw new Error(errorMessage);\n }\n\n if (response.status === 204) {\n return {} as T;\n }\n\n return response.json();\n }\n\n /**\n * GET a collection endpoint, following `@odata.nextLink` so wide results\n * (e.g. an entity with hundreds of attributes, or large metadata sets) are\n * not silently truncated at the server page cap.\n */\n private async fetchAllPages<T>(url: string): Promise<T[]> {\n const out: T[] = [];\n let next: string | undefined = url;\n while (next) {\n const response: Response = await fetch(next, { method: 'GET', headers: this.getHeaders() });\n const page = await this.handleResponse<ODataPage<T>>(response);\n if (page.value) out.push(...page.value);\n next = page['@odata.nextLink'];\n }\n return out;\n }\n\n private extractIdFromResponse(response: Response, _entitySetName: string): string | null {\n const entityIdHeader = response.headers.get('OData-EntityId');\n if (entityIdHeader) {\n const match = entityIdHeader.match(/\\(([0-9a-f-]+)\\)/i);\n if (match) return match[1];\n }\n return null;\n }\n\n // CRUD Operations\n\n async retrieve<T = Record<string, unknown>>(entitySetName: string, id: string, options?: string): Promise<T> {\n const url = this.buildUrl(entitySetName, id, options);\n this.log.log(`[FetchClient] GET ${url}`);\n const response = await fetch(url, { method: 'GET', headers: this.getHeaders() });\n return this.handleResponse<T>(response);\n }\n\n async retrieveMultiple<T = Record<string, unknown>>(entitySetName: string, options?: string): Promise<{ value: T[] }> {\n const url = this.buildUrl(entitySetName, undefined, options);\n this.log.log(`[FetchClient] GET ${url}`);\n const response = await fetch(url, { method: 'GET', headers: this.getHeaders() });\n return this.handleResponse<{ value: T[] }>(response);\n }\n\n async create(entitySetName: string, data: Record<string, unknown>): Promise<{ id: string }> {\n const url = this.buildUrl(entitySetName);\n this.log.log(`[FetchClient] POST ${url}`);\n const response = await fetch(url, {\n method: 'POST',\n headers: { ...this.getHeaders(), 'Prefer': 'return=representation' },\n body: JSON.stringify(data),\n });\n\n if (!response.ok) {\n return this.handleResponse(response);\n }\n\n const id = this.extractIdFromResponse(response, entitySetName);\n if (id) return { id };\n\n try {\n const body = await response.json();\n const primaryKey = entitySetName.slice(0, -1) + 'id';\n const recordId = body[primaryKey] || body.id;\n if (recordId) return { id: recordId };\n } catch { /* empty */ }\n\n throw new Error('Could not determine created record ID');\n }\n\n async update(entitySetName: string, id: string, data: Record<string, unknown>): Promise<void> {\n const url = this.buildUrl(entitySetName, id);\n this.log.log(`[FetchClient] PATCH ${url}`);\n const response = await fetch(url, {\n method: 'PATCH',\n headers: this.getHeaders(),\n body: JSON.stringify(data),\n });\n await this.handleResponse<void>(response);\n }\n\n async delete(entitySetName: string, id: string): Promise<void> {\n const url = this.buildUrl(entitySetName, id);\n this.log.log(`[FetchClient] DELETE ${url}`);\n const response = await fetch(url, { method: 'DELETE', headers: this.getHeaders() });\n await this.handleResponse<void>(response);\n }\n\n // Batch Operations\n\n async batchDelete(entitySetName: string, ids: string[]): Promise<BatchDeleteResult> {\n const succeeded: string[] = [];\n const failed: Array<{ id: string; error: string }> = [];\n for (const id of ids) {\n try {\n await this.delete(entitySetName, id);\n succeeded.push(id);\n } catch (err) {\n failed.push({ id, error: err instanceof Error ? err.message : 'Delete failed' });\n }\n }\n return { succeeded, failed };\n }\n\n async batchUpdate(entitySetName: string, records: BatchUpdateRecord[]): Promise<BatchUpdateResult> {\n const succeeded: string[] = [];\n const failed: Array<{ id: string; error: string }> = [];\n for (const record of records) {\n try {\n await this.update(entitySetName, record.id, record.data);\n succeeded.push(record.id);\n } catch (err) {\n failed.push({ id: record.id, error: err instanceof Error ? err.message : 'Update failed' });\n }\n }\n return { succeeded, failed };\n }\n\n async batchCreate(entitySetName: string, records: Array<Record<string, unknown>>): Promise<BatchCreateResult> {\n const succeeded: Array<{ id: string; data: Record<string, unknown> }> = [];\n const failed: Array<{ rowNumber: number; error: string }> = [];\n for (let i = 0; i < records.length; i++) {\n try {\n const result = await this.create(entitySetName, records[i]);\n succeeded.push({ id: result.id, data: records[i] });\n } catch (err) {\n failed.push({ rowNumber: i + 1, error: err instanceof Error ? err.message : 'Create failed' });\n }\n }\n return { succeeded, failed };\n }\n\n // Metadata Operations\n\n async getEntityDefinitions(filter?: string): Promise<EntityMetadata[]> {\n const selectFields = [\n 'LogicalName', 'EntitySetName', 'SchemaName', 'DisplayName', 'DisplayCollectionName',\n 'PrimaryIdAttribute', 'PrimaryNameAttribute', 'IsCustomEntity', 'IsActivity',\n 'IsValidForAdvancedFind', 'ObjectTypeCode',\n ].join(',');\n\n let options = `?$select=${selectFields}`;\n if (filter) {\n options += `&$filter=${encodeURIComponent(filter)}`;\n }\n\n const url = `${this.baseUrl}/api/data/v9.2/EntityDefinitions${options}`;\n this.log.log(`[FetchClient] GET ${url}`);\n return this.fetchAllPages<EntityMetadata>(url);\n }\n\n async getAttributeMetadata(entityLogicalName: string, filter?: string): Promise<AttributeMetadata[]> {\n const selectFields = [\n 'LogicalName', 'SchemaName', 'DisplayName', 'Description', 'AttributeType',\n 'AttributeTypeName', 'RequiredLevel', 'IsValidForRead', 'IsValidForCreate',\n 'IsValidForUpdate', 'IsPrimaryId', 'IsPrimaryName',\n ].join(',');\n\n const defaultFilter = 'IsValidForRead eq true';\n const combinedFilter = filter ? `${defaultFilter} and ${filter}` : defaultFilter;\n\n const url = `${this.baseUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/Attributes?$select=${selectFields}&$filter=${encodeURIComponent(combinedFilter)}`;\n this.log.log(`[FetchClient] GET ${url}`);\n const baseAttributes = await this.fetchAllPages<AttributeMetadata>(url);\n\n // Fetch additional metadata for picklist, multi-select, and lookup attributes\n const attributesWithExtras = await Promise.all(\n baseAttributes.map(async (attr) => {\n if (\n attr.AttributeType === 'Picklist' ||\n attr.AttributeType === 'State' ||\n attr.AttributeType === 'Status' ||\n attr.AttributeType === 'MultiSelectPicklist'\n ) {\n try {\n const castType =\n attr.AttributeType === 'State' ? 'StateAttributeMetadata' :\n attr.AttributeType === 'Status' ? 'StatusAttributeMetadata' :\n attr.AttributeType === 'MultiSelectPicklist' ? 'MultiSelectPicklistAttributeMetadata' :\n 'PicklistAttributeMetadata';\n const optionSetUrl = `${this.baseUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/Attributes(LogicalName='${attr.LogicalName}')/Microsoft.Dynamics.CRM.${castType}?$select=LogicalName&$expand=OptionSet`;\n const optionResponse = await fetch(optionSetUrl, { method: 'GET', headers: this.getHeaders() });\n if (optionResponse.ok) {\n const optionResult = await optionResponse.json();\n return { ...attr, OptionSet: optionResult.OptionSet };\n }\n } catch (err) {\n this.log.warn(`[FetchClient] Could not fetch options for ${attr.LogicalName}:`, err);\n }\n }\n if (attr.AttributeType === 'Lookup') {\n try {\n const lookupUrl = `${this.baseUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/Attributes(LogicalName='${attr.LogicalName}')/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets`;\n const lookupResponse = await fetch(lookupUrl, { method: 'GET', headers: this.getHeaders() });\n if (lookupResponse.ok) {\n const lookupResult = await lookupResponse.json();\n return { ...attr, Targets: lookupResult.Targets };\n }\n } catch (err) {\n this.log.warn(`[FetchClient] Could not fetch targets for ${attr.LogicalName}:`, err);\n }\n }\n return attr;\n })\n );\n\n return attributesWithExtras;\n }\n\n async getRelationshipMetadata(entityLogicalName: string): Promise<RelationshipMetadata[]> {\n const selectFields = [\n 'MetadataId', 'SchemaName', 'RelationshipType',\n 'ReferencedEntity', 'ReferencedAttribute',\n 'ReferencingEntity', 'ReferencingAttribute',\n 'IsCustomRelationship',\n 'ReferencingEntityNavigationPropertyName', 'ReferencedEntityNavigationPropertyName',\n ].join(',');\n\n // Fetch OneToMany and ManyToOne relationships in parallel\n const [oneToManyResponse, manyToOneResponse] = await Promise.all([\n fetch(\n `${this.baseUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/OneToManyRelationships?$select=${selectFields}`,\n { method: 'GET', headers: this.getHeaders() }\n ),\n fetch(\n `${this.baseUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/ManyToOneRelationships?$select=${selectFields}`,\n { method: 'GET', headers: this.getHeaders() }\n ),\n ]);\n\n const oneToMany = await this.handleResponse<{ value: OneToManyRelationshipMetadata[] }>(oneToManyResponse);\n const manyToOne = await this.handleResponse<{ value: ManyToOneRelationshipMetadata[] }>(manyToOneResponse);\n\n this.log.log(`[FetchClient] Loaded ${oneToMany.value.length} OneToMany and ${manyToOne.value.length} ManyToOne relationships for ${entityLogicalName}`);\n\n return [...oneToMany.value, ...manyToOne.value];\n }\n\n // View Operations\n\n async getViews(entityLogicalName: string): Promise<ViewMetadata[]> {\n const selectFields = 'savedqueryid,name,fetchxml,layoutxml,isdefault,returnedtypecode,description';\n const userQuerySelectFields = 'userqueryid,name,fetchxml,layoutxml,returnedtypecode,description';\n\n const [systemViewsResponse, personalViewsResponse] = await Promise.all([\n fetch(\n `${this.baseUrl}/api/data/v9.2/savedqueries?$select=${selectFields}&$filter=returnedtypecode eq '${entityLogicalName}' and querytype eq 0 and statecode eq 0`,\n { method: 'GET', headers: this.getHeaders() }\n ),\n fetch(\n `${this.baseUrl}/api/data/v9.2/userqueries?$select=${userQuerySelectFields}&$filter=returnedtypecode eq '${entityLogicalName}' and statecode eq 0`,\n { method: 'GET', headers: this.getHeaders() }\n ),\n ]);\n\n const systemViews = await this.handleResponse<{ value: Array<{\n savedqueryid: string; name: string; fetchxml: string; layoutxml?: string;\n isdefault?: boolean; returnedtypecode: string; description?: string;\n }> }>(systemViewsResponse);\n\n const personalViews = await this.handleResponse<{ value: Array<{\n userqueryid: string; name: string; fetchxml: string; layoutxml?: string;\n returnedtypecode: string; description?: string;\n }> }>(personalViewsResponse);\n\n const views: ViewMetadata[] = [\n ...systemViews.value.map(v => ({\n id: v.savedqueryid, name: v.name, fetchxml: v.fetchxml, layoutxml: v.layoutxml,\n isDefault: v.isdefault || false, isPersonal: false,\n returnedtypecode: v.returnedtypecode, description: v.description,\n })),\n ...personalViews.value.map(v => ({\n id: v.userqueryid, name: v.name, fetchxml: v.fetchxml, layoutxml: v.layoutxml,\n isDefault: false, isPersonal: true,\n returnedtypecode: v.returnedtypecode, description: v.description,\n })),\n ];\n\n views.sort((a, b) => {\n if (a.isDefault && !b.isDefault) return -1;\n if (!a.isDefault && b.isDefault) return 1;\n return a.name.localeCompare(b.name);\n });\n\n return views;\n }\n\n async updateView(isPersonal: boolean, viewId: string, data: ViewUpdateData): Promise<void> {\n const entitySet = isPersonal ? 'userqueries' : 'savedqueries';\n const url = this.buildUrl(entitySet, viewId);\n this.log.log(`[FetchClient] PATCH ${url}`);\n const response = await fetch(url, { method: 'PATCH', headers: this.getHeaders(), body: JSON.stringify(data) });\n await this.handleResponse<void>(response);\n }\n\n async createView(entityLogicalName: string, data: ViewCreateData): Promise<{ id: string }> {\n const url = this.buildUrl('userqueries');\n const payload = {\n name: data.name, returnedtypecode: entityLogicalName,\n fetchxml: data.fetchxml, layoutxml: data.layoutxml,\n querytype: 0, statecode: 0,\n ...(data.description && { description: data.description }),\n };\n this.log.log(`[FetchClient] POST ${url}`);\n const response = await fetch(url, {\n method: 'POST',\n headers: { ...this.getHeaders(), 'Prefer': 'return=representation' },\n body: JSON.stringify(payload),\n });\n if (!response.ok) return this.handleResponse(response);\n const id = this.extractIdFromResponse(response, 'userqueries');\n if (id) return { id };\n try {\n const body = await response.json();\n if (body.userqueryid || body.id) return { id: body.userqueryid || body.id };\n } catch { /* empty */ }\n throw new Error('Could not determine created view ID');\n }\n\n async deleteView(isPersonal: boolean, viewId: string): Promise<void> {\n const entitySet = isPersonal ? 'userqueries' : 'savedqueries';\n await this.delete(entitySet, viewId);\n }\n\n async publishEntity(entityLogicalName: string): Promise<void> {\n const url = `${this.baseUrl}/api/data/v9.2/PublishXml`;\n const parameterXml = `<importexportxml><entities><entity>${entityLogicalName}</entity></entities></importexportxml>`;\n this.log.log(`[FetchClient] POST ${url} - Publishing ${entityLogicalName}`);\n const response = await fetch(url, {\n method: 'POST', headers: this.getHeaders(),\n body: JSON.stringify({ ParameterXml: parameterXml }),\n });\n await this.handleResponse<void>(response);\n }\n\n // Global Option Set Operations\n\n async getGlobalOptionSets(): Promise<GlobalOptionSetMetadata[]> {\n const url = `${this.baseUrl}/api/data/v9.2/GlobalOptionSetDefinitions`;\n this.log.log(`[FetchClient] GET ${url}`);\n const all = await this.fetchAllPages<GlobalOptionSetMetadata>(url);\n\n // Filter to only Picklist type global option sets\n return all.filter(os => os.OptionSetType === 'Picklist' && os.IsGlobal);\n }\n}\n","/**\n * @dynamics-ui-kit/api-client\n * Production client using Xrm.WebApi inside Dynamics 365.\n */\n\nimport type { IDataverseClient } from './interfaces';\nimport type {\n BatchDeleteResult,\n BatchUpdateRecord,\n BatchUpdateResult,\n BatchCreateResult,\n ViewUpdateData,\n ViewCreateData,\n EntityMetadata,\n AttributeMetadata,\n ViewMetadata,\n Logger,\n RelationshipMetadata,\n OneToManyRelationshipMetadata,\n ManyToOneRelationshipMetadata,\n GlobalOptionSetMetadata,\n} from './types';\n\n/**\n * Dataverse client using Xrm.WebApi for production Dynamics 365 environment.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype XrmGlobal = any;\n\nexport class XrmClient implements IDataverseClient {\n private xrm: XrmGlobal;\n private log: Logger;\n\n constructor(xrm: XrmGlobal, logger?: Logger) {\n this.xrm = xrm;\n this.log = logger ?? console;\n }\n\n private getClientUrl(): string {\n return this.xrm.Utility.getGlobalContext().getClientUrl();\n }\n\n // CRUD Operations\n\n async retrieve<T = Record<string, unknown>>(entitySetName: string, id: string, options?: string): Promise<T> {\n const cleanId = id.replace(/[{}]/g, '');\n const result = await this.xrm.WebApi.retrieveRecord(entitySetName, cleanId, options);\n return result as T;\n }\n\n async retrieveMultiple<T = Record<string, unknown>>(entitySetName: string, options?: string): Promise<{ value: T[] }> {\n const result = await this.xrm.WebApi.retrieveMultipleRecords(entitySetName, options);\n return { value: result.entities as T[] };\n }\n\n async create(entitySetName: string, data: Record<string, unknown>): Promise<{ id: string }> {\n const result = await this.xrm.WebApi.createRecord(entitySetName, data);\n return { id: result.id };\n }\n\n async update(entitySetName: string, id: string, data: Record<string, unknown>): Promise<void> {\n await this.xrm.WebApi.updateRecord(entitySetName, id.replace(/[{}]/g, ''), data);\n }\n\n async delete(entitySetName: string, id: string): Promise<void> {\n await this.xrm.WebApi.deleteRecord(entitySetName, id.replace(/[{}]/g, ''));\n }\n\n // Batch Operations\n\n async batchDelete(entitySetName: string, ids: string[]): Promise<BatchDeleteResult> {\n const succeeded: string[] = [];\n const failed: Array<{ id: string; error: string }> = [];\n for (const id of ids) {\n try {\n await this.delete(entitySetName, id);\n succeeded.push(id);\n } catch (err) {\n failed.push({ id, error: err instanceof Error ? err.message : 'Delete failed' });\n }\n }\n return { succeeded, failed };\n }\n\n async batchUpdate(entitySetName: string, records: BatchUpdateRecord[]): Promise<BatchUpdateResult> {\n const succeeded: string[] = [];\n const failed: Array<{ id: string; error: string }> = [];\n for (const record of records) {\n try {\n await this.update(entitySetName, record.id, record.data);\n succeeded.push(record.id);\n } catch (err) {\n failed.push({ id: record.id, error: err instanceof Error ? err.message : 'Update failed' });\n }\n }\n return { succeeded, failed };\n }\n\n async batchCreate(entitySetName: string, records: Array<Record<string, unknown>>): Promise<BatchCreateResult> {\n const succeeded: Array<{ id: string; data: Record<string, unknown> }> = [];\n const failed: Array<{ rowNumber: number; error: string }> = [];\n for (let i = 0; i < records.length; i++) {\n try {\n const result = await this.create(entitySetName, records[i]);\n succeeded.push({ id: result.id, data: records[i] });\n } catch (err) {\n failed.push({ rowNumber: i + 1, error: err instanceof Error ? err.message : 'Create failed' });\n }\n }\n return { succeeded, failed };\n }\n\n // Metadata Operations\n\n async getEntityDefinitions(filter?: string): Promise<EntityMetadata[]> {\n const selectFields = [\n 'LogicalName', 'EntitySetName', 'SchemaName', 'DisplayName', 'DisplayCollectionName',\n 'PrimaryIdAttribute', 'PrimaryNameAttribute', 'IsCustomEntity', 'IsActivity',\n 'IsValidForAdvancedFind', 'ObjectTypeCode',\n ].join(',');\n\n let options = `?$select=${selectFields}`;\n if (filter) options += `&$filter=${filter}`;\n\n const result = await this.xrm.WebApi.retrieveMultipleRecords('EntityDefinitions', options);\n return result.entities as EntityMetadata[];\n }\n\n async getAttributeMetadata(entityLogicalName: string, filter?: string): Promise<AttributeMetadata[]> {\n const selectFields = [\n 'LogicalName', 'SchemaName', 'DisplayName', 'Description', 'AttributeType',\n 'AttributeTypeName', 'RequiredLevel', 'IsValidForRead', 'IsValidForCreate',\n 'IsValidForUpdate', 'IsPrimaryId', 'IsPrimaryName',\n ].join(',');\n\n const defaultFilter = 'IsValidForRead eq true';\n const combinedFilter = filter ? `${defaultFilter} and ${filter}` : defaultFilter;\n const clientUrl = this.getClientUrl();\n const url = `${clientUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/Attributes?$select=${selectFields}&$filter=${combinedFilter}`;\n\n const response = await fetch(url, {\n method: 'GET',\n headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },\n });\n\n if (!response.ok) throw new Error(`Failed to fetch attribute metadata: ${response.statusText}`);\n const result = await response.json();\n const attributes = result.value as AttributeMetadata[];\n\n const attributesWithExtras = await Promise.all(\n attributes.map(async (attr) => {\n if (attr.AttributeType === 'Picklist' || attr.AttributeType === 'State' || attr.AttributeType === 'Status') {\n try {\n const castType = attr.AttributeType === 'State' ? 'StateAttributeMetadata' :\n attr.AttributeType === 'Status' ? 'StatusAttributeMetadata' : 'PicklistAttributeMetadata';\n const optionSetUrl = `${clientUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/Attributes(LogicalName='${attr.LogicalName}')/Microsoft.Dynamics.CRM.${castType}?$select=LogicalName&$expand=OptionSet`;\n const optionResponse = await fetch(optionSetUrl, {\n method: 'GET',\n headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },\n });\n if (optionResponse.ok) {\n const optionResult = await optionResponse.json();\n return { ...attr, OptionSet: optionResult.OptionSet };\n }\n } catch (err) {\n this.log.warn(`Could not fetch options for ${attr.LogicalName}:`, err);\n }\n }\n if (attr.AttributeType === 'Lookup') {\n try {\n const lookupUrl = `${clientUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/Attributes(LogicalName='${attr.LogicalName}')/Microsoft.Dynamics.CRM.LookupAttributeMetadata?$select=LogicalName,Targets`;\n const lookupResponse = await fetch(lookupUrl, {\n method: 'GET',\n headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },\n });\n if (lookupResponse.ok) {\n const lookupResult = await lookupResponse.json();\n return { ...attr, Targets: lookupResult.Targets };\n }\n } catch (err) {\n this.log.warn(`Could not fetch targets for ${attr.LogicalName}:`, err);\n }\n }\n return attr;\n })\n );\n\n return attributesWithExtras;\n }\n\n async getRelationshipMetadata(entityLogicalName: string): Promise<RelationshipMetadata[]> {\n const clientUrl = this.getClientUrl();\n const selectFields = [\n 'MetadataId', 'SchemaName', 'RelationshipType',\n 'ReferencedEntity', 'ReferencedAttribute',\n 'ReferencingEntity', 'ReferencingAttribute',\n 'IsCustomRelationship',\n 'ReferencingEntityNavigationPropertyName', 'ReferencedEntityNavigationPropertyName',\n ].join(',');\n\n // Fetch OneToMany and ManyToOne relationships in parallel\n const [oneToManyResponse, manyToOneResponse] = await Promise.all([\n fetch(\n `${clientUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/OneToManyRelationships?$select=${selectFields}`,\n { method: 'GET', headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' } }\n ),\n fetch(\n `${clientUrl}/api/data/v9.2/EntityDefinitions(LogicalName='${entityLogicalName}')/ManyToOneRelationships?$select=${selectFields}`,\n { method: 'GET', headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' } }\n ),\n ]);\n\n if (!oneToManyResponse.ok) throw new Error(`Failed to fetch OneToMany relationships: ${oneToManyResponse.statusText}`);\n if (!manyToOneResponse.ok) throw new Error(`Failed to fetch ManyToOne relationships: ${manyToOneResponse.statusText}`);\n\n const oneToMany = await oneToManyResponse.json() as { value: OneToManyRelationshipMetadata[] };\n const manyToOne = await manyToOneResponse.json() as { value: ManyToOneRelationshipMetadata[] };\n\n this.log.log(`[XrmClient] Loaded ${oneToMany.value.length} OneToMany and ${manyToOne.value.length} ManyToOne relationships for ${entityLogicalName}`);\n\n return [...oneToMany.value, ...manyToOne.value];\n }\n\n // View Operations\n\n async getViews(entityLogicalName: string): Promise<ViewMetadata[]> {\n const clientUrl = this.getClientUrl();\n const selectFields = 'savedqueryid,name,fetchxml,layoutxml,isdefault,returnedtypecode,description';\n const userQuerySelectFields = 'userqueryid,name,fetchxml,layoutxml,returnedtypecode,description';\n\n const [systemViewsResponse, personalViewsResponse] = await Promise.all([\n fetch(\n `${clientUrl}/api/data/v9.2/savedqueries?$select=${selectFields}&$filter=returnedtypecode eq '${entityLogicalName}' and querytype eq 0 and statecode eq 0`,\n { method: 'GET', headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' } }\n ),\n fetch(\n `${clientUrl}/api/data/v9.2/userqueries?$select=${userQuerySelectFields}&$filter=returnedtypecode eq '${entityLogicalName}' and statecode eq 0`,\n { method: 'GET', headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' } }\n ),\n ]);\n\n if (!systemViewsResponse.ok) throw new Error(`Failed to fetch system views: ${systemViewsResponse.statusText}`);\n if (!personalViewsResponse.ok) throw new Error(`Failed to fetch personal views: ${personalViewsResponse.statusText}`);\n\n const systemViews = await systemViewsResponse.json() as { value: Array<{\n savedqueryid: string; name: string; fetchxml: string; layoutxml?: string;\n isdefault?: boolean; returnedtypecode: string; description?: string;\n }> };\n\n const personalViews = await personalViewsResponse.json() as { value: Array<{\n userqueryid: string; name: string; fetchxml: string; layoutxml?: string;\n returnedtypecode: string; description?: string;\n }> };\n\n const views: ViewMetadata[] = [\n ...systemViews.value.map(v => ({\n id: v.savedqueryid, name: v.name, fetchxml: v.fetchxml, layoutxml: v.layoutxml,\n isDefault: v.isdefault || false, isPersonal: false,\n returnedtypecode: v.returnedtypecode, description: v.description,\n })),\n ...personalViews.value.map(v => ({\n id: v.userqueryid, name: v.name, fetchxml: v.fetchxml, layoutxml: v.layoutxml,\n isDefault: false, isPersonal: true,\n returnedtypecode: v.returnedtypecode, description: v.description,\n })),\n ];\n\n views.sort((a, b) => {\n if (a.isDefault && !b.isDefault) return -1;\n if (!a.isDefault && b.isDefault) return 1;\n return a.name.localeCompare(b.name);\n });\n\n return views;\n }\n\n async updateView(isPersonal: boolean, viewId: string, data: ViewUpdateData): Promise<void> {\n const entityName = isPersonal ? 'userquery' : 'savedquery';\n await this.xrm.WebApi.updateRecord(entityName, viewId.replace(/[{}]/g, ''), data);\n }\n\n async createView(entityLogicalName: string, data: ViewCreateData): Promise<{ id: string }> {\n const payload = {\n name: data.name, returnedtypecode: entityLogicalName,\n fetchxml: data.fetchxml, layoutxml: data.layoutxml,\n querytype: 0, statecode: 0,\n ...(data.description && { description: data.description }),\n };\n const result = await this.xrm.WebApi.createRecord('userquery', payload);\n return { id: result.id };\n }\n\n async deleteView(isPersonal: boolean, viewId: string): Promise<void> {\n const entityName = isPersonal ? 'userquery' : 'savedquery';\n await this.xrm.WebApi.deleteRecord(entityName, viewId.replace(/[{}]/g, ''));\n }\n\n async publishEntity(entityLogicalName: string): Promise<void> {\n const clientUrl = this.getClientUrl();\n const url = `${clientUrl}/api/data/v9.2/PublishXml`;\n const parameterXml = `<importexportxml><entities><entity>${entityLogicalName}</entity></entities></importexportxml>`;\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Accept': 'application/json', 'Content-Type': 'application/json; charset=utf-8', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },\n body: JSON.stringify({ ParameterXml: parameterXml }),\n });\n if (!response.ok) throw new Error(`Failed to publish entity: ${response.statusText}`);\n }\n\n // Global Option Set Operations\n\n async getGlobalOptionSets(): Promise<GlobalOptionSetMetadata[]> {\n const clientUrl = this.getClientUrl();\n const url = `${clientUrl}/api/data/v9.2/GlobalOptionSetDefinitions`;\n const response = await fetch(url, {\n method: 'GET',\n headers: { 'Accept': 'application/json', 'OData-MaxVersion': '4.0', 'OData-Version': '4.0' },\n });\n if (!response.ok) throw new Error(`Failed to fetch global option sets: ${response.statusText}`);\n const result = await response.json() as { value: GlobalOptionSetMetadata[] };\n return result.value.filter(os => os.OptionSetType === 'Picklist' && os.IsGlobal);\n }\n}\n","/**\n * @dynamics-ui-kit/api-client\n * Mock client for offline development and testing.\n */\n\nimport type { IDataverseClient } from './interfaces';\nimport type {\n BatchDeleteResult,\n BatchUpdateRecord,\n BatchUpdateResult,\n BatchCreateResult,\n ViewUpdateData,\n ViewCreateData,\n EntityMetadata,\n AttributeMetadata,\n ViewMetadata,\n Logger,\n RelationshipMetadata,\n GlobalOptionSetMetadata,\n} from './types';\n\nfunction generateId(): string {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n}\n\nexport interface MockDataConfig {\n /** Initial records keyed by entity set name */\n records?: Record<string, Record<string, unknown>[]>;\n /** Entity definitions */\n entityDefinitions?: EntityMetadata[];\n /** Attribute metadata keyed by entity logical name */\n attributeMetadata?: Record<string, AttributeMetadata[]>;\n /** Views keyed by entity logical name */\n views?: Record<string, ViewMetadata[]>;\n /** Relationship metadata keyed by entity logical name */\n relationshipMetadata?: Record<string, RelationshipMetadata[]>;\n /** Global option sets */\n globalOptionSets?: GlobalOptionSetMetadata[];\n /** Simulated network delay in ms */\n delayMs?: number;\n}\n\n/**\n * Mock Dataverse client for offline development and testing.\n * Accepts configurable mock data.\n */\nexport class MockClient implements IDataverseClient {\n private dataStore: Record<string, Record<string, unknown>[]>;\n private entityDefs: EntityMetadata[];\n private attrMeta: Record<string, AttributeMetadata[]>;\n private viewStore: Record<string, ViewMetadata[]>;\n private relMeta: Record<string, RelationshipMetadata[]>;\n private globalOptionSets: GlobalOptionSetMetadata[];\n private delayMs: number;\n private log: Logger;\n\n constructor(config?: MockDataConfig, logger?: Logger) {\n this.dataStore = config?.records ?? {};\n this.entityDefs = config?.entityDefinitions ?? [];\n this.attrMeta = config?.attributeMetadata ?? {};\n this.viewStore = config?.views ?? {};\n this.relMeta = config?.relationshipMetadata ?? {};\n this.globalOptionSets = config?.globalOptionSets ?? [];\n this.delayMs = config?.delayMs ?? 0;\n this.log = logger ?? console;\n }\n\n private async delay(): Promise<void> {\n if (this.delayMs > 0) {\n return new Promise(resolve => setTimeout(resolve, this.delayMs));\n }\n }\n\n // CRUD Operations\n\n async retrieve<T = Record<string, unknown>>(entitySetName: string, id: string): Promise<T> {\n await this.delay();\n const records = this.dataStore[entitySetName] ?? [];\n const pkField = entitySetName.slice(0, -1) + 'id';\n const record = records.find(r => r[pkField] === id || r.id === id);\n if (!record) throw new Error(`Record ${id} not found in ${entitySetName}`);\n return record as T;\n }\n\n async retrieveMultiple<T = Record<string, unknown>>(entitySetName: string): Promise<{ value: T[] }> {\n await this.delay();\n return { value: (this.dataStore[entitySetName] ?? []) as T[] };\n }\n\n async create(entitySetName: string, data: Record<string, unknown>): Promise<{ id: string }> {\n await this.delay();\n const id = generateId();\n const pkField = entitySetName.slice(0, -1) + 'id';\n const record = { ...data, [pkField]: id };\n if (!this.dataStore[entitySetName]) this.dataStore[entitySetName] = [];\n this.dataStore[entitySetName].push(record);\n return { id };\n }\n\n async update(entitySetName: string, id: string, data: Record<string, unknown>): Promise<void> {\n await this.delay();\n const records = this.dataStore[entitySetName] ?? [];\n const pkField = entitySetName.slice(0, -1) + 'id';\n const index = records.findIndex(r => r[pkField] === id || r.id === id);\n if (index === -1) throw new Error(`Record ${id} not found in ${entitySetName}`);\n this.dataStore[entitySetName][index] = { ...records[index], ...data };\n }\n\n async delete(entitySetName: string, id: string): Promise<void> {\n await this.delay();\n const records = this.dataStore[entitySetName] ?? [];\n const pkField = entitySetName.slice(0, -1) + 'id';\n const index = records.findIndex(r => r[pkField] === id || r.id === id);\n if (index === -1) throw new Error(`Record ${id} not found in ${entitySetName}`);\n this.dataStore[entitySetName].splice(index, 1);\n }\n\n // Batch Operations\n\n async batchDelete(entitySetName: string, ids: string[]): Promise<BatchDeleteResult> {\n const succeeded: string[] = [];\n const failed: Array<{ id: string; error: string }> = [];\n for (const id of ids) {\n try { await this.delete(entitySetName, id); succeeded.push(id); }\n catch (err) { failed.push({ id, error: err instanceof Error ? err.message : 'Delete failed' }); }\n }\n return { succeeded, failed };\n }\n\n async batchUpdate(entitySetName: string, records: BatchUpdateRecord[]): Promise<BatchUpdateResult> {\n const succeeded: string[] = [];\n const failed: Array<{ id: string; error: string }> = [];\n for (const record of records) {\n try { await this.update(entitySetName, record.id, record.data); succeeded.push(record.id); }\n catch (err) { failed.push({ id: record.id, error: err instanceof Error ? err.message : 'Update failed' }); }\n }\n return { succeeded, failed };\n }\n\n async batchCreate(entitySetName: string, records: Array<Record<string, unknown>>): Promise<BatchCreateResult> {\n const succeeded: Array<{ id: string; data: Record<string, unknown> }> = [];\n const failed: Array<{ rowNumber: number; error: string }> = [];\n for (let i = 0; i < records.length; i++) {\n try {\n const result = await this.create(entitySetName, records[i]);\n succeeded.push({ id: result.id, data: records[i] });\n } catch (err) {\n failed.push({ rowNumber: i + 1, error: err instanceof Error ? err.message : 'Create failed' });\n }\n }\n return { succeeded, failed };\n }\n\n // Metadata Operations\n\n async getEntityDefinitions(_filter?: string): Promise<EntityMetadata[]> {\n await this.delay();\n return this.entityDefs;\n }\n\n async getAttributeMetadata(entityLogicalName: string): Promise<AttributeMetadata[]> {\n await this.delay();\n return this.attrMeta[entityLogicalName] ?? [];\n }\n\n async getRelationshipMetadata(entityLogicalName: string): Promise<RelationshipMetadata[]> {\n await this.delay();\n return this.relMeta[entityLogicalName] ?? [];\n }\n\n // View Operations\n\n async getViews(entityLogicalName: string): Promise<ViewMetadata[]> {\n await this.delay();\n return this.viewStore[entityLogicalName] ?? [];\n }\n\n async updateView(_isPersonal: boolean, viewId: string, data: ViewUpdateData): Promise<void> {\n await this.delay();\n for (const entity of Object.keys(this.viewStore)) {\n const views = this.viewStore[entity];\n const idx = views.findIndex(v => v.id === viewId);\n if (idx !== -1) {\n this.viewStore[entity][idx] = { ...views[idx], ...data };\n return;\n }\n }\n throw new Error(`View ${viewId} not found`);\n }\n\n async createView(entityLogicalName: string, data: ViewCreateData): Promise<{ id: string }> {\n await this.delay();\n const id = generateId();\n const view: ViewMetadata = {\n id, name: data.name, fetchxml: data.fetchxml, layoutxml: data.layoutxml,\n isDefault: false, isPersonal: true, returnedtypecode: entityLogicalName,\n description: data.description,\n };\n if (!this.viewStore[entityLogicalName]) this.viewStore[entityLogicalName] = [];\n this.viewStore[entityLogicalName].push(view);\n return { id };\n }\n\n async deleteView(_isPersonal: boolean, viewId: string): Promise<void> {\n await this.delay();\n for (const entity of Object.keys(this.viewStore)) {\n const views = this.viewStore[entity];\n const idx = views.findIndex(v => v.id === viewId);\n if (idx !== -1) {\n this.viewStore[entity].splice(idx, 1);\n return;\n }\n }\n throw new Error(`View ${viewId} not found`);\n }\n\n async publishEntity(): Promise<void> {\n await this.delay();\n this.log.log('[MockClient] publishEntity called (no-op in mock mode)');\n }\n\n // Global Option Set Operations\n\n async getGlobalOptionSets(): Promise<GlobalOptionSetMetadata[]> {\n await this.delay();\n return this.globalOptionSets;\n }\n}\n","/**\n * @dynamics-ui-kit/api-client\n * Factory for auto-detecting environment and creating the appropriate client.\n */\n\nimport type { IDataverseClient } from './interfaces';\nimport type { ClientOptions, EnvironmentInfo } from './types';\nimport { FetchClient } from './fetch-client';\nimport { XrmClient } from './xrm-client';\nimport { MockClient } from './mock-client';\nimport type { MockDataConfig } from './mock-client';\n\n/**\n * Create a Dataverse client based on the current environment.\n *\n * Detection priority:\n * 1. Explicit options (baseUrl + token → FetchClient, xrm → XrmClient)\n * 2. Window globals (__DYNAMICS_URL + __DYNAMICS_TOKEN → FetchClient)\n * 3. Xrm global present → XrmClient\n * 4. Fallback → MockClient\n */\nexport function createClient(options?: ClientOptions & { mockData?: MockDataConfig }): IDataverseClient {\n const logger = options?.logger;\n\n // Explicit FetchClient\n if (options?.baseUrl && options?.token) {\n return new FetchClient(options.baseUrl, options.token, logger);\n }\n\n // Explicit XrmClient\n if (options?.xrm) {\n return new XrmClient(options.xrm, logger);\n }\n\n // Auto-detect: check window globals\n if (typeof window !== 'undefined') {\n const win = window as { __DYNAMICS_URL?: string; __DYNAMICS_TOKEN?: string };\n if (win.__DYNAMICS_URL && win.__DYNAMICS_TOKEN) {\n return new FetchClient(win.__DYNAMICS_URL, win.__DYNAMICS_TOKEN, logger);\n }\n }\n\n // Auto-detect: check for Xrm global\n if (typeof globalThis !== 'undefined' && typeof (globalThis as Record<string, unknown>).Xrm !== 'undefined') {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return new XrmClient((globalThis as Record<string, unknown>).Xrm as any, logger);\n }\n\n // Fallback to mock\n return new MockClient(options?.mockData, logger);\n}\n\n/**\n * Get information about the current environment.\n */\nexport function getEnvironmentInfo(): EnvironmentInfo {\n const hostname = typeof window !== 'undefined' ? window.location?.hostname ?? 'unknown' : 'node';\n const hasXrm = typeof globalThis !== 'undefined' && typeof (globalThis as Record<string, unknown>).Xrm !== 'undefined';\n const win = typeof window !== 'undefined' ? window as { __DYNAMICS_URL?: string; __DYNAMICS_TOKEN?: string } : {};\n const hasToken = !!(win.__DYNAMICS_URL && win.__DYNAMICS_TOKEN);\n\n let type: EnvironmentInfo['type'] = 'mock';\n if (hasToken) type = 'fetch';\n else if (hasXrm) type = 'xrm';\n\n return { type, hostname, baseUrl: win.__DYNAMICS_URL, hasToken, hasXrm };\n}\n","#!/usr/bin/env node\n/**\n * dvgen — Dataverse codegen CLI.\n *\n * Independent, composable subcommands run inside a client project:\n * dvgen constants --entity <e> → src/constants/<Entity>Constants.ts\n * dvgen models --entity <e> → src/models/<Entity>.ts\n * dvgen api → src/services/* CRUD layer\n * dvgen design <file>.design.json → constants + models for every entity\n * the exported forms target (optional --api/--seed)\n * dvgen seed:pull --entity <e> → src/sampleData/<entity>.json\n * dvgen seed:push --entity <e> → push fixtures to Dataverse\n * dvgen test-retrieve --entity <e> → exercise generated retrieves\n */\n\nimport { Command } from 'commander';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { join } from 'node:path';\nimport {\n generateConstantsFile,\n generateModelFile,\n toEntityClassName,\n} from '@dynamics-ui-kit/entity-gen';\nimport { resolveConnection } from './connection';\nimport { fetchEntityMetadata } from './metadata/fetch';\nimport { deriveParentLookupLinks } from './metadata/links';\nimport { safeWrite, type WriteResult } from './io/write';\nimport { API_SERVICE_FILES } from './templates/apiService';\nimport { getEntityRefs, pullRows, toODataFixture, pushRows, stripForCreate } from './seed';\nimport { parseDesignFile, collectEntities } from './design/parse';\n\nconst VERSION = '0.1.0';\n\n// Fail fast on Node < 18 — the metadata/fetch path relies on the global fetch\n// (Node 18+). npm's `engines` check is advisory; this is a hard guard.\nconst NODE_MAJOR = Number(process.versions.node.split('.')[0]);\nif (NODE_MAJOR < 18) {\n // eslint-disable-next-line no-console\n console.error(`dvgen requires Node >= 18 (found ${process.versions.node}). Try \\`nvm use 20\\`.`);\n process.exit(1);\n}\n\n/** Default IApiService import for generated models — relative, matching client convention. */\nconst DEFAULT_API_SERVICE_IMPORT = '../services/IApiService';\n\ninterface CommonOpts {\n entity: string;\n out: string;\n url?: string;\n token?: string;\n envFile?: string;\n /** Commander maps `--no-augment` to `augment: false` (defaults true). */\n augment?: boolean;\n dryRun?: boolean;\n force?: boolean;\n diff?: boolean;\n}\n\nconst program = new Command();\nprogram\n .name('dvgen')\n .description(\n 'Dataverse codegen — scaffold constants, models, a CRUD API layer, and test data into a client project.',\n )\n .version(VERSION);\n\nfunction withCommonOptions(cmd: Command): Command {\n return cmd\n .requiredOption('--entity <logical>', 'Entity logical name (e.g. account, stn_order)')\n .option('--out <dir>', 'Output base directory', 'src')\n .option('--url <url>', 'Dataverse org URL (else from env / .env file)')\n .option('--token <token>', 'Bearer token (else from env, else Azure CLI)')\n .option('--env-file <path>', 'Path to a .env file to read URL/token from')\n .option('--no-augment', 'Skip typed-cast metadata augmentation (MaxLength/Precision/...)')\n .option('--dry-run', 'Report what would be written without writing')\n .option('--force', 'Overwrite existing files (default: skip existing files)')\n .option('--diff', 'Print a diff against the existing file before writing');\n}\n\nfunction withConnOptions(cmd: Command): Command {\n return cmd\n .option('--url <url>', 'Dataverse org URL (else from env / .env file)')\n .option('--token <token>', 'Bearer token (else from env, else Azure CLI)')\n .option('--env-file <path>', 'Path to a .env file to read URL/token from');\n}\n\nfunction readFixtureRows(file: string, entity: string): Record<string, unknown>[] {\n try {\n const parsed = JSON.parse(readFileSync(file, 'utf8')) as { value?: Record<string, unknown>[] };\n return parsed.value ?? [];\n } catch (e) {\n throw new Error(\n `Could not read fixture ${file} (run 'dvgen seed:pull --entity ${entity}' first): ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n}\n\nfunction previewFields(rows: Record<string, unknown>[]): string {\n if (!rows[0]) return '(no rows)';\n return Object.keys(rows[0]).filter((k) => !k.includes('@')).slice(0, 12).join(', ');\n}\n\nconst RESULT_LABEL: Record<WriteResult, string> = {\n created: 'created',\n overwritten: 'overwritten',\n 'skipped-exists': 'skipped (exists — pass --force to overwrite)',\n unchanged: 'unchanged',\n 'dry-run': 'dry-run (not written)',\n};\n\nfunction reportWrite(path: string, result: WriteResult): void {\n const mark = result === 'skipped-exists' ? '⚠' : '✓';\n // eslint-disable-next-line no-console\n console.log(` ${mark} ${path} — ${RESULT_LABEL[result]}`);\n}\n\n/** Resolve connection + fetch (augmented) metadata once, shared by commands. */\nasync function loadEntity(opts: CommonOpts) {\n const { client, url, token, tokenSource } = resolveConnection(opts);\n // eslint-disable-next-line no-console\n console.log(`Connected: ${url} (token: ${tokenSource})`);\n const entity = await fetchEntityMetadata(client, opts.entity, {\n augment: opts.augment === false ? undefined : { baseUrl: url, token },\n });\n return { entity, client, className: toEntityClassName(entity.LogicalName) };\n}\n\nwithCommonOptions(program.command('constants'))\n .description('Generate <Entity>Constants.ts (field constants + option-set enums) from live org metadata')\n .action(async (opts: CommonOpts) => {\n const { entity, className } = await loadEntity(opts);\n const path = join(opts.out, 'constants', `${className}Constants.ts`);\n reportWrite(path, safeWrite(path, generateConstantsFile(entity, VERSION), opts));\n });\n\nwithCommonOptions(program.command('models'))\n .description('Generate <Entity>.ts model (interface + class + fromRaw + validate + CRUD/retrieve)')\n .option(\n '--api-service <import>',\n 'Module specifier for IApiService in the generated model',\n DEFAULT_API_SERVICE_IMPORT,\n )\n .option('--with-retrieve', 'Also emit retrieveWithRelated() with commented parent-lookup <link-entity> scaffolds')\n .action(async (opts: CommonOpts & { apiService: string; withRetrieve?: boolean }) => {\n const { entity, className, client } = await loadEntity(opts);\n\n // For --with-retrieve, derive parent-lookup (many-to-one) joins from\n // relationship metadata to pre-fill the retrieve scaffold.\n const links = opts.withRetrieve ? await deriveParentLookupLinks(client, entity) : [];\n if (opts.withRetrieve) {\n // eslint-disable-next-line no-console\n console.log(` ↳ ${links.length} parent-lookup join scaffold(s) from relationships`);\n }\n\n // Generated models import their constants file. Warn (don't fail) if it's\n // missing — the extensionless import resolves either .ts or .tsx.\n const cdir = join(opts.out, 'constants');\n const hasConstants =\n existsSync(join(cdir, `${className}Constants.ts`)) ||\n existsSync(join(cdir, `${className}Constants.tsx`));\n if (!hasConstants) {\n // eslint-disable-next-line no-console\n console.warn(\n ` ⚠no ${className}Constants.{ts,tsx} in ${cdir} — the model imports it; ` +\n `run 'dvgen constants --entity ${opts.entity}' first.`,\n );\n }\n\n const path = join(opts.out, 'models', `${className}.ts`);\n const content = generateModelFile(entity, opts.apiService, VERSION, {\n withRetrieve: opts.withRetrieve,\n links,\n });\n reportWrite(path, safeWrite(path, content, opts));\n });\n\nprogram\n .command('api')\n .description('Scaffold a self-contained IApiService CRUD layer into src/services (no live org needed)')\n .option('--out <dir>', 'Output base directory', 'src')\n .option('--dry-run', 'Report what would be written without writing')\n .option('--force', 'Overwrite existing files (default: skip existing files)')\n .option('--diff', 'Print a diff against the existing file before writing')\n .action((opts: { out: string; dryRun?: boolean; force?: boolean; diff?: boolean }) => {\n for (const file of API_SERVICE_FILES) {\n const path = join(opts.out, file.path);\n reportWrite(path, safeWrite(path, file.content, opts));\n }\n });\n\n// ─── design ───────────────────────────────────────────────────────────────────\ninterface DesignOpts {\n out: string;\n url?: string;\n token?: string;\n envFile?: string;\n augment?: boolean;\n withRetrieve?: boolean;\n api?: boolean;\n seed?: boolean;\n dryRun?: boolean;\n force?: boolean;\n diff?: boolean;\n}\n\nwithConnOptions(\n program\n .command('design')\n .description(\n 'Scaffold the Dataverse layer (constants + models, optional api/seed) for every entity referenced by a *.design.json exported from the form designer',\n )\n .argument('<file>', 'Path to an exported *.design.json')\n .option('--out <dir>', 'Output base directory', 'src')\n .option('--no-augment', 'Skip typed-cast metadata augmentation (MaxLength/Precision/...)')\n .option('--with-retrieve', 'Emit retrieveWithRelated() with parent-lookup <link-entity> scaffolds')\n .option('--api', 'Also scaffold the shared IApiService CRUD layer once')\n .option('--seed', 'Also pull sample data into sampleData/<entity>.json for each entity')\n .option('--dry-run', 'Report what would be written without writing')\n .option('--force', 'Overwrite existing files (default: skip existing files)')\n .option('--diff', 'Print a diff against the existing file before writing'),\n).action(async (file: string, opts: DesignOpts) => {\n if (!existsSync(file)) {\n throw new Error(`Design file not found: ${file}`);\n }\n const design = parseDesignFile(readFileSync(file, 'utf8'));\n const { entities, skipped } = collectEntities(design);\n\n for (const s of skipped) {\n // eslint-disable-next-line no-console\n console.warn(` ⚠skipped entity candidate ${JSON.stringify(s.name)} (${s.reason})`);\n }\n if (entities.length === 0) {\n // eslint-disable-next-line no-console\n console.log(\n 'No target entities found in the design. Set a \"Target entity\" on each form in the ' +\n 'designer (or run `dvgen constants --entity <e>` directly).',\n );\n return;\n }\n\n // eslint-disable-next-line no-console\n console.log(\n `Design \"${design.name ?? file}\": ${entities.length} entit${entities.length === 1 ? 'y' : 'ies'} — ${entities\n .map((e) => e.logicalName)\n .join(', ')}`,\n );\n\n const { client, url, token, tokenSource } = resolveConnection(opts);\n // eslint-disable-next-line no-console\n console.log(`Connected: ${url} (token: ${tokenSource})`);\n\n const writeOpts = { dryRun: opts.dryRun, force: opts.force, diff: opts.diff };\n\n // Shared CRUD layer once (not per entity).\n if (opts.api) {\n // eslint-disable-next-line no-console\n console.log('\\nAPI service layer:');\n for (const f of API_SERVICE_FILES) {\n const p = join(opts.out, f.path);\n reportWrite(p, safeWrite(p, f.content, writeOpts));\n }\n }\n\n for (const ref of entities) {\n // eslint-disable-next-line no-console\n console.log(`\\n${ref.logicalName} (${ref.sources.join('; ')})`);\n const entity = await fetchEntityMetadata(client, ref.logicalName, {\n augment: opts.augment === false ? undefined : { baseUrl: url, token },\n });\n const className = toEntityClassName(entity.LogicalName);\n\n const cpath = join(opts.out, 'constants', `${className}Constants.ts`);\n reportWrite(cpath, safeWrite(cpath, generateConstantsFile(entity, VERSION), writeOpts));\n\n const links = opts.withRetrieve ? await deriveParentLookupLinks(client, entity) : [];\n if (opts.withRetrieve) {\n // eslint-disable-next-line no-console\n console.log(` ↳ ${links.length} parent-lookup join scaffold(s)`);\n }\n const mpath = join(opts.out, 'models', `${className}.ts`);\n const model = generateModelFile(entity, DEFAULT_API_SERVICE_IMPORT, VERSION, {\n withRetrieve: opts.withRetrieve,\n links,\n });\n reportWrite(mpath, safeWrite(mpath, model, writeOpts));\n\n if (opts.seed && !opts.dryRun) {\n try {\n const { entitySetName } = await getEntityRefs(client, ref.logicalName);\n const rows = await pullRows(client, entitySetName, { top: 10 });\n const spath = join(opts.out, 'sampleData', `${ref.logicalName}.json`);\n reportWrite(spath, safeWrite(spath, toODataFixture(url, entitySetName, rows), writeOpts));\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(` ⚠seed:pull failed for ${ref.logicalName}: ${e instanceof Error ? e.message : String(e)}`);\n }\n }\n }\n\n // eslint-disable-next-line no-console\n console.log(`\\nDone — scaffolded ${entities.length} entit${entities.length === 1 ? 'y' : 'ies'}.`);\n});\n\n// ─── seed:pull ──────────────────────────────────────────────────────────────\nwithConnOptions(\n program\n .command('seed:pull')\n .description('Pull live rows into src/sampleData/<entity>.json (OData fixture)')\n .requiredOption('--entity <logical>', 'Entity logical name')\n .option('--out <dir>', 'Output base directory', 'src')\n .option('--top <n>', 'Max rows to pull', '10')\n .option('--select <cols>', 'Comma-separated $select columns')\n .option('--filter <odata>', 'OData $filter expression')\n .option('--dry-run', 'Report without writing')\n .option('--force', 'Overwrite an existing fixture')\n .option('--diff', 'Diff against the existing fixture'),\n).action(\n async (opts: {\n entity: string;\n out: string;\n top: string;\n select?: string;\n filter?: string;\n url?: string;\n token?: string;\n envFile?: string;\n dryRun?: boolean;\n force?: boolean;\n diff?: boolean;\n }) => {\n const { client, url } = resolveConnection(opts);\n // eslint-disable-next-line no-console\n console.log(`Connected: ${url}`);\n const { entitySetName } = await getEntityRefs(client, opts.entity);\n const rows = await pullRows(client, entitySetName, {\n top: Number(opts.top),\n select: opts.select,\n filter: opts.filter,\n });\n // eslint-disable-next-line no-console\n console.log(` ↳ pulled ${rows.length} row(s) from ${entitySetName}`);\n const path = join(opts.out, 'sampleData', `${opts.entity}.json`);\n reportWrite(path, safeWrite(path, toODataFixture(url, entitySetName, rows), opts));\n },\n);\n\n// ─── seed:push ────────────────────────────────────────────────────────────────\nwithConnOptions(\n program\n .command('seed:push')\n .description('Create records in Dataverse from a sampleData fixture (annotations/id/lookups stripped)')\n .requiredOption('--entity <logical>', 'Entity logical name')\n .option('--out <dir>', 'Base directory holding sampleData/', 'src')\n .option('--file <path>', 'Explicit fixture file (overrides --out/sampleData)')\n .option('--top <n>', 'Only push the first N rows')\n .option('--dry-run', 'Preview what would be created without writing to Dataverse'),\n).action(\n async (opts: {\n entity: string;\n out: string;\n file?: string;\n top?: string;\n url?: string;\n token?: string;\n envFile?: string;\n dryRun?: boolean;\n }) => {\n const file = opts.file ?? join(opts.out, 'sampleData', `${opts.entity}.json`);\n let rows = readFixtureRows(file, opts.entity);\n if (opts.top) rows = rows.slice(0, Number(opts.top));\n const { client } = resolveConnection(opts);\n const { entitySetName, primaryIdAttribute } = await getEntityRefs(client, opts.entity);\n if (opts.dryRun) {\n const dropped = rows[0] ? stripForCreate(rows[0], primaryIdAttribute).droppedLookups : [];\n // eslint-disable-next-line no-console\n console.log(` dry-run: would create ${rows.length} record(s) in ${entitySetName}`);\n // eslint-disable-next-line no-console\n console.log(` lookup fields skipped (need @odata.bind): ${dropped.join(', ') || '(none)'}`);\n return;\n }\n const res = await pushRows(client, entitySetName, primaryIdAttribute, rows);\n // eslint-disable-next-line no-console\n console.log(` ✓ created ${res.created}/${rows.length} in ${entitySetName}`);\n if (res.droppedLookupFields.length) {\n // eslint-disable-next-line no-console\n console.log(` ⚠lookup fields skipped (need @odata.bind): ${res.droppedLookupFields.join(', ')}`);\n }\n if (res.failed.length) {\n // eslint-disable-next-line no-console\n console.log(` ✗ ${res.failed.length} failed:`);\n // eslint-disable-next-line no-console\n res.failed.slice(0, 5).forEach((f) => console.log(` [${f.index}] ${f.error}`));\n }\n },\n);\n\n// ─── test-retrieve ────────────────────────────────────────────────────────────\nwithConnOptions(\n program\n .command('test-retrieve')\n .description('Smoke-test retrieve: read fixtures (default) or query the org (--live)')\n .requiredOption('--entity <logical>', 'Entity logical name')\n .option('--out <dir>', 'Base directory holding sampleData/', 'src')\n .option('--live', 'Query the org instead of reading fixtures')\n .option('--top <n>', 'Max rows (live)', '5'),\n).action(\n async (opts: {\n entity: string;\n out: string;\n live?: boolean;\n top: string;\n url?: string;\n token?: string;\n envFile?: string;\n }) => {\n if (opts.live) {\n const { client, url } = resolveConnection(opts);\n // eslint-disable-next-line no-console\n console.log(`Connected: ${url}`);\n const { entitySetName } = await getEntityRefs(client, opts.entity);\n const rows = await pullRows(client, entitySetName, { top: Number(opts.top) });\n // eslint-disable-next-line no-console\n console.log(` ✓ live retrieve: ${rows.length} row(s) from ${entitySetName}`);\n // eslint-disable-next-line no-console\n console.log(` fields: ${previewFields(rows)}`);\n } else {\n const file = join(opts.out, 'sampleData', `${opts.entity}.json`);\n const rows = readFixtureRows(file, opts.entity);\n // eslint-disable-next-line no-console\n console.log(` ✓ fixture ${file}: ${rows.length} row(s)`);\n // eslint-disable-next-line no-console\n console.log(` fields: ${previewFields(rows)}`);\n }\n },\n);\n\nprogram.parseAsync(process.argv).catch((err: unknown) => {\n // eslint-disable-next-line no-console\n console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);\n process.exit(1);\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","/**\n * Naming utilities for @dynamics-ui-kit/entity-gen.\n *\n * Dataverse logical names use snake_case with publisher prefixes\n * (`stn_customerid`); display names are free-form (\"Sales Order\n * Number\"). Generated TypeScript needs PascalCase classes,\n * camelCase properties, and identifier-safe enum keys.\n *\n * All helpers in this file are pure — same input → same output —\n * which is important because the generator's output should be\n * stable for diff review.\n */\n\nimport type { AttributeMetadataInput, DisplayNameInfo } from '../types';\n\nconst RESERVED_TS_WORDS = new Set([\n // ECMA-262 reserved words\n 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger',\n 'default', 'delete', 'do', 'else', 'enum', 'export', 'extends', 'false',\n 'finally', 'for', 'function', 'if', 'import', 'in', 'instanceof', 'new',\n 'null', 'return', 'super', 'switch', 'this', 'throw', 'true', 'try',\n 'typeof', 'var', 'void', 'while', 'with', 'yield',\n // Strict-mode reserved + TypeScript future-reserved\n 'as', 'implements', 'interface', 'let', 'package', 'private', 'protected',\n 'public', 'static',\n // Strict-mode forbidden identifiers (ECMA-262 §13.1) — using these as a\n // variable / property name throws SyntaxError in any module-context file\n // (which all generated `.ts` files are).\n 'arguments', 'eval',\n // Contextual / future-reserved that the TypeScript parser rejects as a\n // declared property name in certain positions. Cheap to defang.\n 'await', 'async', 'of', 'from', 'target',\n]);\n\n/**\n * Pick the first usable label out of a Dataverse DisplayNameInfo,\n * falling back to a caller-supplied string (typically the logical name).\n */\nexport function getDisplayLabel(\n displayName: DisplayNameInfo | undefined,\n fallback: string\n): string {\n return (\n displayName?.UserLocalizedLabel?.Label ||\n displayName?.LocalizedLabels?.[0]?.Label ||\n fallback\n );\n}\n\n/**\n * Strip a publisher prefix from a logical name: `stn_customerid` →\n * `customerid`. If there's no underscore, return as-is.\n */\nexport function stripPublisherPrefix(logicalName: string): string {\n const idx = logicalName.indexOf('_');\n if (idx === -1) return logicalName;\n // Don't strip well-known framework prefixes that aren't publisher\n // prefixes (e.g. \"_value\", \"_OData...\").\n const candidate = logicalName.slice(idx + 1);\n return candidate || logicalName;\n}\n\n/**\n * Convert any free-form string to PascalCase. Drops non-alphanumeric\n * characters, treats space/underscore/hyphen as word breaks. If the\n * result would start with a digit, prefix `_`.\n */\nexport function toPascalCase(s: string): string {\n const pascal =\n s\n .replace(/[^a-zA-Z0-9\\s_-]/g, ' ')\n .split(/[\\s_-]+/)\n .filter(Boolean)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase())\n .join('') || 'Untitled';\n return /^\\d/.test(pascal) ? `_${pascal}` : pascal;\n}\n\n/**\n * PascalCase but preserves inner capitalization from the source — useful\n * when the source already encodes intent (\"orderID\" should stay\n * \"OrderID\", not become \"Orderid\").\n */\nexport function toPascalCasePreserving(s: string): string {\n const cleaned = s.replace(/[^a-zA-Z0-9\\s_-]/g, ' ');\n const parts = cleaned.split(/[\\s_-]+/).filter(Boolean);\n if (parts.length === 0) return 'Untitled';\n const joined = parts\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join('');\n return /^\\d/.test(joined) ? `_${joined}` : joined;\n}\n\n/**\n * camelCase from any free-form string. Identifier-safe; reserved\n * words are suffixed with `_`.\n */\nexport function toCamelCase(s: string): string {\n const pascal = toPascalCase(s);\n const camel = pascal.charAt(0).toLowerCase() + pascal.slice(1);\n return RESERVED_TS_WORDS.has(camel) ? `${camel}_` : camel;\n}\n\n/**\n * Sanitize a display label for use as an enum key. Strips non-alphanumeric\n * characters, prefixes leading digits with `_`. Empty/all-junk inputs\n * fall back to `Option_${value}`.\n */\nexport function toEnumKey(label: string, valueFallback: number): string {\n const cleaned = label\n .replace(/[^a-zA-Z0-9\\s_]/g, '')\n .split(/[\\s_]+/)\n .filter(Boolean)\n .map((w) => w.charAt(0).toUpperCase() + w.slice(1))\n .join('');\n if (!cleaned) return `Option_${valueFallback}`;\n return /^\\d/.test(cleaned) ? `_${cleaned}` : cleaned;\n}\n\n/**\n * Build a constants-class property name from the attribute. Preserves\n * intent from the display name when available, falling back to the\n * publisher-stripped logical name. Collisions get a numeric suffix.\n */\nexport function toConstantPropertyName(\n displayName: string | undefined,\n logicalName: string\n): string {\n // Prefer the display name when it's meaningful; otherwise derive from\n // the logical name minus publisher prefix.\n const source =\n displayName && displayName.trim().length > 0\n ? displayName\n : stripPublisherPrefix(logicalName);\n return toPascalCase(source);\n}\n\n/**\n * Make a class name from an entity logical name. `stn_order` → `Order`.\n */\nexport function toEntityClassName(logicalName: string): string {\n return toPascalCase(stripPublisherPrefix(logicalName));\n}\n\n/**\n * Detect attributes whose generated model-property name would collide\n * with another's after applying the display-name-then-publisher-prefix\n * rule the templates use. Returns a map keyed by the colliding property\n * name, with the attributes that resolve to it. Only groups with ≥2\n * attributes are returned.\n *\n * The collision is real: `deduplicateNames` will silently suffix the\n * later one with `_2` etc., and because attribute order from the\n * metadata API isn't stable across runs, which attribute \"wins\" the\n * unsuffixed name can flip between regenerations. Callers use this to\n * surface a JSDoc warning on each affected property and to log once\n * per generation.\n */\nexport function detectPropertyNameCollisions(\n attrs: AttributeMetadataInput[]\n): Map<string, AttributeMetadataInput[]> {\n const groups = new Map<string, AttributeMetadataInput[]>();\n for (const attr of attrs) {\n const propName = toCamelCase(\n getDisplayLabel(attr.DisplayName, '') || stripPublisherPrefix(attr.LogicalName)\n );\n const existing = groups.get(propName);\n if (existing) {\n existing.push(attr);\n } else {\n groups.set(propName, [attr]);\n }\n }\n for (const [key, group] of groups) {\n if (group.length < 2) groups.delete(key);\n }\n return groups;\n}\n\n/**\n * Disambiguate a set of property names by appending numeric suffixes\n * to repeated entries. Stable order — first occurrence keeps the\n * unsuffixed name.\n */\nexport function deduplicateNames(names: string[]): string[] {\n const seen = new Map<string, number>();\n return names.map((name) => {\n const count = seen.get(name) ?? 0;\n seen.set(name, count + 1);\n return count === 0 ? name : `${name}_${count + 1}`;\n });\n}\n","/* eslint-disable no-irregular-whitespace -- the `*​/` sequences in JSDoc\n below contain an intentional U+200B zero-width space between `*` and `/`\n so they don't close the surrounding JSDoc block. Removing them would\n break the comment grammar. */\n/**\n * Codegen-XSS guards for emitted TypeScript.\n *\n * Two threat surfaces:\n *\n * 1. JSDoc lines. A user-controlled value containing `*​/` would\n * close the surrounding `/** … *​/` block, allowing the\n * following content to land as executable JS. Newlines push\n * following text outside the leading ` * ` prefix — same\n * problem.\n * 2. String literals. `JSON.stringify` already escapes `\"`, `\\`,\n * and control characters correctly, so we use it everywhere\n * we emit a user-controlled value as a string literal. This\n * file does not provide a separate helper for that case —\n * use `JSON.stringify(value)` at the call site instead.\n *\n * Both helpers here are pure and side-effect-free.\n */\n\n// Line-terminator set per ECMA-262 §11.3: `\\n`, `\\r`, U+2028\n// (LINE SEPARATOR), U+2029 (PARAGRAPH SEPARATOR). Constructed via\n// `new RegExp(string)` because esbuild's literal regex tokenizer\n// treats U+2028 / U+2029 as actual line terminators that end the\n// regex prematurely if written `/[…]/g` with the chars in source.\nconst LINE_TERMINATORS = new RegExp('[\\\\r\\\\n\\\\u2028\\\\u2029]+', 'g');\n\n/**\n * Neutralize `*​/` and every JS line-terminator for safe interpolation\n * onto a single `* …` line inside a JSDoc block. Preserves punctuation\n * and unicode — the JSDoc body can hold rich free-form content, we\n * only need to defang the threat sequences.\n *\n * A `\\r` alone (Mac-classic) or a lone U+2028 will end a single-line\n * `//` comment and let the following text escape into executable JS,\n * so all four line terminators must be defanged.\n */\nexport function sanitizeForJsDocLine(value: string): string {\n return String(value)\n .replace(/\\*\\//g, '*\\\\/')\n .replace(LINE_TERMINATORS, ' ');\n}\n","/**\n * Shared file-header banner emitted at the top of every generated file.\n *\n * The version field is optional — when provided, it surfaces stale\n * generated output during diff review. The banner intentionally\n * does NOT include a timestamp; deterministic output is a hard\n * requirement (generated files get committed and need to round-trip\n * cleanly through CI / code review).\n */\n\nimport { sanitizeForJsDocLine } from './sanitize';\n\nexport function buildHeaderComment(\n title: string,\n generatorVersion: string | undefined\n): string {\n const lines: string[] = [];\n lines.push('/**');\n lines.push(` * ${sanitizeForJsDocLine(title)}`);\n lines.push(' *');\n lines.push(' * Auto-generated by @dynamics-ui-kit/entity-gen.');\n if (generatorVersion) {\n lines.push(` * Generator version: ${sanitizeForJsDocLine(generatorVersion)}`);\n }\n lines.push(' * Do not edit by hand — regenerate by re-running the generator.');\n lines.push(' */');\n return lines.join('\\n');\n}\n","/**\n * Maps Dataverse `AttributeType` strings to the TypeScript types\n * generated model classes should declare.\n *\n * Dataverse attribute types come in two flavors in EntityDefinitions\n * responses: the legacy enum-style string (`\"String\"`, `\"Lookup\"`) and\n * the `AttributeTypeName.Value` ending in `\"Type\"` (`\"StringType\"`,\n * `\"LookupType\"`). This helper accepts either.\n *\n * Returned categories:\n *\n * - `'string'` — emit `string`\n * - `'number'` — emit `number` (integer, decimal, money, double)\n * - `'boolean'` — emit `boolean`\n * - `'dateString'` — emit `string` (we use ISO strings, not `Date`)\n * - `'optionset'` — emit `number`; generator will also emit a\n * typed `enum` for the attribute's options\n * - `'multi-optionset'` — emit `number[]`\n * - `'lookup'` — emit two model props: `<name>?: string` (id)\n * and `<name>Name?: string` (formatted display)\n * - `'unsupported'` — emit `unknown` plus a TODO comment\n */\n\nexport type AttributeCategory =\n | 'string'\n | 'number'\n | 'boolean'\n | 'dateString'\n | 'optionset'\n | 'multi-optionset'\n | 'lookup'\n | 'unsupported';\n\nconst TYPE_MAP: Record<string, AttributeCategory> = {\n // Strings\n String: 'string',\n Memo: 'string',\n EntityName: 'string',\n Uniqueidentifier: 'string',\n PartyList: 'string',\n\n // Numbers\n Integer: 'number',\n BigInt: 'number',\n Decimal: 'number',\n Double: 'number',\n Money: 'number',\n\n // Boolean\n Boolean: 'boolean',\n\n // Date / time\n DateTime: 'dateString',\n\n // Option set family\n Picklist: 'optionset',\n State: 'optionset',\n Status: 'optionset',\n MultiSelectPicklist: 'multi-optionset',\n\n // Lookups\n Lookup: 'lookup',\n Customer: 'lookup',\n Owner: 'lookup',\n\n // Known unsupported types\n Virtual: 'unsupported',\n CalendarRules: 'unsupported',\n ManagedProperty: 'unsupported',\n Image: 'unsupported',\n File: 'unsupported',\n};\n\n/**\n * Categorize a Dataverse attribute type. Accepts either the legacy\n * string (`\"String\"`) or the `…Type` form (`\"StringType\"`).\n */\nexport function categorizeAttributeType(\n attributeType: string | undefined\n): AttributeCategory {\n if (!attributeType) return 'unsupported';\n const normalized = attributeType.endsWith('Type')\n ? attributeType.slice(0, -'Type'.length)\n : attributeType;\n return TYPE_MAP[normalized] ?? 'unsupported';\n}\n\n/**\n * The TypeScript type literal a model property should declare for a\n * given attribute category. The model class always declares the\n * primary key as `string` (non-optional) — that case is handled by\n * the model template, not here.\n */\nexport function tsTypeForCategory(category: AttributeCategory): string {\n switch (category) {\n case 'string':\n return 'string';\n case 'number':\n return 'number';\n case 'boolean':\n return 'boolean';\n case 'dateString':\n return 'string';\n case 'optionset':\n return 'number';\n case 'multi-optionset':\n return 'number[]';\n case 'lookup':\n return 'string';\n case 'unsupported':\n return 'unknown';\n }\n}\n","/* eslint-disable no-irregular-whitespace -- the `*​/` sequences in JSDoc\n examples below contain an intentional U+200B zero-width space between `*`\n and `/` so they don't close the surrounding JSDoc block. */\n/**\n * `<Entity>Constants.ts` template.\n *\n * Emits:\n * - Static class with `EntityName`, `EntityCollectionName`,\n * `LogicalName`, `EntitySetName`, `PrimaryKey`, `PrimaryName`,\n * and one `<Property>: string = \"<logical_name>\"` constant per\n * attribute.\n * - JSDoc above each attribute carrying type, required level,\n * and type-specific detail (max length, precision, targets,\n * option set type, datetime behavior).\n * - `export enum` for every Picklist/State/Status/MultiSelectPicklist\n * attribute that has options.\n *\n * The output is sanitized for safe interpolation: every user-controlled\n * value (display name, option label, target list) flows through\n * `sanitizeForJsDocLine` or `toEnumKey`. The threat model is a\n * Dataverse environment with attacker-influenced display names —\n * `*​/` in a label must not close the surrounding JSDoc block.\n */\n\nimport type {\n EntityMetadataInput,\n AttributeMetadataInput,\n} from '../types';\nimport {\n deduplicateNames,\n getDisplayLabel,\n toConstantPropertyName,\n toEntityClassName,\n toEnumKey,\n} from '../utils/naming';\nimport { sanitizeForJsDocLine } from './sanitize';\nimport { buildHeaderComment } from './header';\nimport { categorizeAttributeType } from '../utils/typeMapping';\n\nexport function generateConstantsFile(\n entity: EntityMetadataInput,\n generatorVersion: string | undefined\n): string {\n const entityClass = toEntityClassName(entity.LogicalName);\n const constantsClass = `${entityClass}Constants`;\n\n // Skip the primary id/name attributes when emitting the per-attribute\n // constants — they get dedicated PrimaryKey/PrimaryName members.\n const regularAttrs = entity.Attributes.filter(\n (a) => !a.IsPrimaryId && !a.IsPrimaryName\n );\n\n const candidateNames = regularAttrs.map((a) =>\n toConstantPropertyName(getDisplayLabel(a.DisplayName, ''), a.LogicalName)\n );\n const finalNames = deduplicateNames(candidateNames);\n\n const lines: string[] = [];\n lines.push(buildHeaderComment(`${constantsClass} — generated entity constants`, generatorVersion));\n lines.push('');\n lines.push(`export class ${constantsClass} {`);\n lines.push(` public static readonly EntityName: string = ${JSON.stringify(entity.LogicalName)};`);\n lines.push(` public static readonly EntityCollectionName: string = ${JSON.stringify(entity.EntitySetName)};`);\n lines.push(` public static readonly LogicalName: string = ${JSON.stringify(entity.LogicalName)};`);\n lines.push(` public static readonly EntitySetName: string = ${JSON.stringify(entity.EntitySetName)};`);\n lines.push('');\n\n // Primary key / primary name.\n //\n // Match the entity's DECLARED PrimaryIdAttribute/PrimaryNameAttribute by\n // logical name first. The `IsPrimaryId`/`IsPrimaryName` flags are NOT unique\n // per entity — Dataverse sets `IsPrimaryId: true` on composite address ids\n // (address1_addressid, address2_addressid, …) alongside the real key, so a\n // bare `.find(a => a.IsPrimaryId)` returns whichever sorts first (e.g.\n // address1_addressid instead of contactid). Fall back to the flag, then a\n // synthetic stub, only if the declared attribute isn't in the readable set.\n const primaryId =\n entity.Attributes.find((a) => a.LogicalName === entity.PrimaryIdAttribute) ??\n entity.Attributes.find((a) => a.IsPrimaryId) ??\n ({ LogicalName: entity.PrimaryIdAttribute, AttributeType: 'Uniqueidentifier' } as AttributeMetadataInput);\n const primaryName =\n entity.Attributes.find((a) => a.LogicalName === entity.PrimaryNameAttribute) ??\n entity.Attributes.find((a) => a.IsPrimaryName) ??\n ({ LogicalName: entity.PrimaryNameAttribute, AttributeType: 'String' } as AttributeMetadataInput);\n\n lines.push(` ${buildAttributeJsDoc(primaryId)}`);\n lines.push(` public static readonly PrimaryKey: string = ${JSON.stringify(primaryId.LogicalName)};`);\n lines.push(` ${buildAttributeJsDoc(primaryName)}`);\n lines.push(` public static readonly PrimaryName: string = ${JSON.stringify(primaryName.LogicalName)};`);\n lines.push('');\n\n regularAttrs.forEach((attr, idx) => {\n const propName = finalNames[idx];\n lines.push(` ${buildAttributeJsDoc(attr)}`);\n lines.push(` public static readonly ${propName}: string = ${JSON.stringify(attr.LogicalName)};`);\n });\n\n lines.push('}');\n lines.push('');\n\n // Emit one enum per option-set-bearing attribute.\n for (let i = 0; i < regularAttrs.length; i += 1) {\n const attr = regularAttrs[i];\n const propName = finalNames[i];\n const options = attr.OptionSet?.Options ?? attr.GlobalOptionSet?.Options;\n if (!options || options.length === 0) continue;\n const category = categorizeAttributeType(attr.AttributeType);\n if (category !== 'optionset' && category !== 'multi-optionset') continue;\n\n const enumName = `${entityClass}${propName}_OptionSet`;\n lines.push(`/** Option set values for \\`${sanitizeForJsDocLine(attr.LogicalName)}\\`. */`);\n lines.push(`export enum ${enumName} {`);\n const usedKeys = new Set<string>();\n for (const option of options) {\n const label = getDisplayLabel(option.Label, `Option_${option.Value}`);\n let key = toEnumKey(label, option.Value);\n // Disambiguate within this enum if labels collide.\n let suffix = 2;\n while (usedKeys.has(key)) {\n key = `${toEnumKey(label, option.Value)}_${suffix}`;\n suffix += 1;\n }\n usedKeys.add(key);\n lines.push(` ${key} = ${option.Value},`);\n }\n lines.push('}');\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Build the single-line JSDoc that sits above each attribute constant.\n * Output shape:\n *\n * /** Type: Lookup, RequiredLevel: ApplicationRequired, Targets: account *​/\n *\n * Every interpolated value is sanitized to neutralize `*​/` and newlines.\n */\nfunction buildAttributeJsDoc(attr: AttributeMetadataInput): string {\n const parts: string[] = [];\n parts.push(`Type: ${sanitizeForJsDocLine(attr.AttributeType ?? 'Unknown')}`);\n parts.push(`RequiredLevel: ${sanitizeForJsDocLine(attr.RequiredLevel?.Value ?? 'None')}`);\n\n const category = categorizeAttributeType(attr.AttributeType);\n\n if (category === 'string') {\n if (typeof attr.MaxLength === 'number') parts.push(`MaxLength: ${attr.MaxLength}`);\n if (attr.Format) parts.push(`Format: ${sanitizeForJsDocLine(attr.Format)}`);\n }\n if (category === 'number') {\n if (typeof attr.MinValue === 'number') parts.push(`MinValue: ${attr.MinValue}`);\n if (typeof attr.MaxValue === 'number') parts.push(`MaxValue: ${attr.MaxValue}`);\n if (typeof attr.Precision === 'number') parts.push(`Precision: ${attr.Precision}`);\n }\n if (category === 'lookup') {\n if (attr.Targets && attr.Targets.length > 0) {\n parts.push(`Targets: ${sanitizeForJsDocLine(attr.Targets.join(', '))}`);\n }\n }\n if (category === 'optionset' || category === 'multi-optionset') {\n const displayLabel = getDisplayLabel(attr.DisplayName, '');\n if (displayLabel) parts.push(`DisplayName: ${sanitizeForJsDocLine(displayLabel)}`);\n if (typeof attr.DefaultFormValue === 'number') {\n parts.push(`DefaultFormValue: ${attr.DefaultFormValue}`);\n }\n }\n if (category === 'dateString') {\n if (attr.Format) parts.push(`Format: ${sanitizeForJsDocLine(attr.Format)}`);\n if (attr.DateTimeBehavior?.Value) {\n parts.push(`DateTimeBehavior: ${sanitizeForJsDocLine(attr.DateTimeBehavior.Value)}`);\n }\n }\n\n return `/** ${parts.join(', ')} */`;\n}\n","/**\n * `<Entity>.ts` template — interface + class for a single Dataverse entity.\n *\n * The generated class implements the matching interface so model\n * instances can be passed around with structural type safety. Static\n * methods cover the four CRUD operations plus `retrieveById` (built\n * on top of `retrieveMultipleRecords` because the in-monorepo\n * `IApiService` doesn't expose `retrieveRecord`).\n *\n * Constructor maps a raw Dataverse Web API payload into model\n * fields. Lookup attributes get two pieces:\n * - `<name>?: string` — the GUID from `_<logical>_value`\n * - `<name>Name?: string` — the formatted display from\n * `_<logical>_value@OData.Community.Display.V1.FormattedValue`\n *\n * Validation: `validate(): string[]` returns a list of human-readable\n * error messages — empty array means valid. Required-level\n * `ApplicationRequired` / `SystemRequired` attributes are checked.\n */\n\nimport type {\n EntityMetadataInput,\n AttributeMetadataInput,\n GenerateModelOptions,\n LinkEntitySpec,\n} from '../types';\nimport {\n deduplicateNames,\n detectPropertyNameCollisions,\n getDisplayLabel,\n toCamelCase,\n toConstantPropertyName,\n toEntityClassName,\n stripPublisherPrefix,\n} from '../utils/naming';\nimport { sanitizeForJsDocLine } from './sanitize';\nimport { buildHeaderComment } from './header';\nimport {\n categorizeAttributeType,\n tsTypeForCategory,\n type AttributeCategory,\n} from '../utils/typeMapping';\n\ninterface ResolvedAttribute {\n attr: AttributeMetadataInput;\n /** PascalCase name used in `<Entity>Constants.<name>` references. */\n constantName: string;\n /** camelCase model property name. */\n propName: string;\n category: AttributeCategory;\n}\n\n/** Lookup, option-set, and multi-select attributes carry a formatted display value. */\nfunction hasFormattedName(category: AttributeCategory): boolean {\n return category === 'lookup' || category === 'optionset' || category === 'multi-optionset';\n}\n\n/**\n * Expression for the raw key holding the OData formatted (display) value.\n * Lookups annotate the `_<logical>_value` navigation property; option-sets\n * (and multi-selects) annotate the attribute logical name directly.\n */\nfunction formattedValueKeyExpr(ref: string, category: AttributeCategory): string {\n return category === 'lookup'\n ? `\\`_\\${${ref}}_value@OData.Community.Display.V1.FormattedValue\\``\n : `\\`\\${${ref}}@OData.Community.Display.V1.FormattedValue\\``;\n}\n\nexport function generateModelFile(\n entity: EntityMetadataInput,\n apiServiceImportSource: string,\n generatorVersion: string | undefined,\n options: GenerateModelOptions = {}\n): string {\n const entityClass = toEntityClassName(entity.LogicalName);\n const constantsClass = `${entityClass}Constants`;\n const interfaceName = `I${entityClass}`;\n const primaryIdLogical = entity.PrimaryIdAttribute;\n const primaryNameLogical = entity.PrimaryNameAttribute;\n // Dataverse names the primary id attribute `<entity>id`; derive the\n // model property name from the entity class to get camelCase that\n // matches reference output (`orderId`, not `orderidId`).\n const primaryKeyProp = `${entityClass.charAt(0).toLowerCase()}${entityClass.slice(1)}Id`;\n\n const regularAttrs = entity.Attributes.filter(\n (a) => !a.IsPrimaryId && !a.IsPrimaryName\n );\n const constantNames = deduplicateNames(\n regularAttrs.map((a) =>\n toConstantPropertyName(getDisplayLabel(a.DisplayName, ''), a.LogicalName)\n )\n );\n\n const resolved: ResolvedAttribute[] = regularAttrs.map((attr, idx) => ({\n attr,\n constantName: constantNames[idx],\n propName: toCamelCase(\n getDisplayLabel(attr.DisplayName, '') || stripPublisherPrefix(attr.LogicalName)\n ),\n category: categorizeAttributeType(attr.AttributeType),\n }));\n\n // After camelCase, two display names could still collide. Dedupe.\n const propNames = deduplicateNames(resolved.map((r) => r.propName));\n resolved.forEach((r, i) => {\n r.propName = propNames[i];\n });\n const hasMultiOptionSet = resolved.some((r) => r.category === 'multi-optionset');\n\n // Build a collision-peer map so the interface JSDoc can flag each\n // affected attribute with the *other* logical names it conflicts\n // with. Keyed by LogicalName because that's the only stable identity\n // when DisplayName is missing (which is when collisions happen most).\n const collisionGroups = detectPropertyNameCollisions(regularAttrs);\n const collisionPeersByLogical = new Map<string, string[]>();\n for (const group of collisionGroups.values()) {\n for (const attr of group) {\n collisionPeersByLogical.set(\n attr.LogicalName,\n group\n .filter((a) => a.LogicalName !== attr.LogicalName)\n .map((a) => a.LogicalName)\n );\n }\n }\n\n const lines: string[] = [];\n lines.push(buildHeaderComment(`${entityClass} — generated model`, generatorVersion));\n lines.push('');\n lines.push(`import { ${constantsClass} } from '../constants/${entityClass}Constants';`);\n lines.push(`import type { IApiService } from ${JSON.stringify(apiServiceImportSource)};`);\n lines.push('');\n\n // ─── Interface ──────────────────────────────────────────────────────────\n lines.push(`export interface ${interfaceName} {`);\n // Primary key is required; everything else optional.\n lines.push(` /** Primary key (${sanitizeForJsDocLine(primaryIdLogical)}). */`);\n lines.push(` ${primaryKeyProp}: string;`);\n // Primary name as optional. Prefer the display name so \"Order Number\"\n // becomes `orderNumber` (matches reference); fall back to the\n // publisher-stripped logical name.\n // Prefer the declared PrimaryNameAttribute by logical name (the IsPrimaryName\n // flag isn't guaranteed unique per entity — see constants.ts note).\n const primaryNameAttr =\n entity.Attributes.find((a) => a.LogicalName === entity.PrimaryNameAttribute) ??\n entity.Attributes.find((a) => a.IsPrimaryName);\n const primaryNameLabel = primaryNameAttr ? getDisplayLabel(primaryNameAttr.DisplayName, '') : '';\n const primaryNameProp = toCamelCase(primaryNameLabel || stripPublisherPrefix(primaryNameLogical) || 'name');\n lines.push(` ${primaryNameProp}?: string;`);\n // Regular attributes.\n for (const r of resolved) {\n const tsType = tsTypeForCategory(r.category);\n const labelComment = getDisplayLabel(r.attr.DisplayName, '');\n const peers = collisionPeersByLogical.get(r.attr.LogicalName);\n if (peers) {\n // Collision JSDoc — multi-line, surfaces the other colliding\n // logical names so a consumer reading the generated property\n // can tell which Dataverse field actually maps here.\n lines.push(' /**');\n if (labelComment) {\n lines.push(` * ${sanitizeForJsDocLine(labelComment)}`);\n lines.push(' *');\n }\n lines.push(\n ` * WARNING: collides with ${peers.map((p) => `\\`${sanitizeForJsDocLine(p)}\\``).join(', ')} after stripping`,\n );\n lines.push(' * publisher prefix. Names differ by suffix; consider adding');\n lines.push(' * DisplayName to the source metadata to disambiguate.');\n lines.push(' *');\n lines.push(` * Logical name: ${sanitizeForJsDocLine(r.attr.LogicalName)}`);\n lines.push(' */');\n } else if (labelComment) {\n lines.push(` /** ${sanitizeForJsDocLine(labelComment)} */`);\n }\n if (r.category === 'unsupported') {\n lines.push(` // TODO: unsupported Dataverse type \\`${sanitizeForJsDocLine(r.attr.AttributeType)}\\` for \"${sanitizeForJsDocLine(r.attr.LogicalName)}\" — emitted as \\`unknown\\`.`);\n }\n lines.push(` ${r.propName}?: ${tsType};`);\n if (hasFormattedName(r.category)) {\n lines.push(` ${r.propName}Name?: string;`);\n }\n }\n lines.push('}');\n lines.push('');\n\n // ─── Class ──────────────────────────────────────────────────────────────\n lines.push(`export class ${entityClass} implements ${interfaceName} {`);\n lines.push(` ${primaryKeyProp}: string;`);\n lines.push(` ${primaryNameProp}?: string;`);\n for (const r of resolved) {\n const tsType = tsTypeForCategory(r.category);\n lines.push(` ${r.propName}?: ${tsType};`);\n if (hasFormattedName(r.category)) {\n lines.push(` ${r.propName}Name?: string;`);\n }\n }\n lines.push('');\n\n // Constructor.\n lines.push(` constructor(record: ${interfaceName}) {`);\n lines.push(` this.${primaryKeyProp} = record.${primaryKeyProp};`);\n lines.push(` this.${primaryNameProp} = record.${primaryNameProp};`);\n for (const r of resolved) {\n lines.push(` this.${r.propName} = record.${r.propName};`);\n if (hasFormattedName(r.category)) {\n lines.push(` this.${r.propName}Name = record.${r.propName}Name;`);\n }\n }\n lines.push(' }');\n lines.push('');\n\n // ─── fromRaw factory ────────────────────────────────────────────────────\n lines.push(' /**');\n lines.push(' * Map a raw Dataverse Web API record into a model instance.');\n lines.push(` * Handles \\`_<logical>_value\\` lookup unpacking and formatted-value annotations.`);\n lines.push(' */');\n lines.push(` public static fromRaw(raw: Record<string, unknown>): ${entityClass} {`);\n lines.push(` return new ${entityClass}({`);\n lines.push(` ${primaryKeyProp}: String(raw[${constantsClass}.PrimaryKey] ?? ''),`);\n lines.push(` ${primaryNameProp}: raw[${constantsClass}.PrimaryName] as string | undefined,`);\n for (const r of resolved) {\n const ref = `${constantsClass}.${r.constantName}`;\n const nameKey = formattedValueKeyExpr(ref, r.category);\n if (r.category === 'lookup') {\n lines.push(` ${r.propName}: raw[\\`_\\${${ref}}_value\\`] as string | undefined,`);\n lines.push(` ${r.propName}Name: raw[${nameKey}] as string | undefined,`);\n } else if (r.category === 'multi-optionset') {\n lines.push(` ${r.propName}: parseMultiOptionSet(raw[${ref}]),`);\n lines.push(` ${r.propName}Name: raw[${nameKey}] as string | undefined,`);\n } else if (r.category === 'boolean') {\n lines.push(` ${r.propName}: raw[${ref}] == null ? undefined : Boolean(raw[${ref}]),`);\n } else if (r.category === 'optionset') {\n lines.push(` ${r.propName}: raw[${ref}] == null ? undefined : Number(raw[${ref}]),`);\n lines.push(` ${r.propName}Name: raw[${nameKey}] as string | undefined,`);\n } else if (r.category === 'number') {\n lines.push(` ${r.propName}: raw[${ref}] == null ? undefined : Number(raw[${ref}]),`);\n } else if (r.category === 'unsupported') {\n lines.push(` ${r.propName}: raw[${ref}] as unknown,`);\n } else {\n lines.push(` ${r.propName}: raw[${ref}] as string | undefined,`);\n }\n }\n lines.push(` });`);\n lines.push(` }`);\n lines.push('');\n\n // ─── validate ───────────────────────────────────────────────────────────\n lines.push(' /** Returns a list of validation error messages — empty array means valid. */');\n lines.push(' public validate(): string[] {');\n lines.push(' const errors: string[] = [];');\n // primaryKeyProp is a sanitized identifier, but use JSON.stringify on\n // the user-facing message anyway — matches the parallel branch below\n // and keeps defense-in-depth if the identifier sanitizer ever loosens.\n lines.push(` if (!this.${primaryKeyProp}) errors.push(${JSON.stringify(`${primaryKeyProp} is required.`)});`);\n for (const r of resolved) {\n const req = r.attr.RequiredLevel?.Value;\n if (req === 'ApplicationRequired' || req === 'SystemRequired') {\n const label = getDisplayLabel(r.attr.DisplayName, r.attr.LogicalName);\n lines.push(` if (this.${r.propName} == null) errors.push(${JSON.stringify(`${label} is required.`)});`);\n }\n }\n lines.push(' return errors;');\n lines.push(' }');\n lines.push('');\n\n // ─── Static CRUD ────────────────────────────────────────────────────────\n generateStaticCrud(lines, entityClass, constantsClass);\n\n // ─── retrieveWithRelated scaffold (opt-in) ────────────────────────────────\n if (options.withRetrieve) {\n lines.push('');\n generateRetrieveWithRelated(lines, entityClass, constantsClass, options.links ?? []);\n }\n\n lines.push('}');\n lines.push('');\n\n // Helper for multi-optionset parsing — emitted only when the entity has a\n // multi-select attribute, as a free function to avoid clobbering the\n // instance namespace.\n if (hasMultiOptionSet) {\n lines.push('function parseMultiOptionSet(value: unknown): number[] | undefined {');\n lines.push(' if (value == null) return undefined;');\n lines.push(' if (Array.isArray(value)) return value.map(Number);');\n lines.push(' if (typeof value === \\'string\\') {');\n lines.push(' return value.split(\\',\\').map((v) => Number(v.trim())).filter((n) => !Number.isNaN(n));');\n lines.push(' }');\n lines.push(' return undefined;');\n lines.push('}');\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\nfunction generateStaticCrud(\n lines: string[],\n entityClass: string,\n constantsClass: string\n): void {\n lines.push(` /** Retrieve records via FetchXML. */`);\n lines.push(` public static async retrieve(apiService: IApiService, fetchXml: string): Promise<${entityClass}[]> {`);\n lines.push(` const result = await apiService.retrieveMultipleRecords(`);\n lines.push(` ${constantsClass}.EntityCollectionName,`);\n lines.push(' fetchXml,');\n lines.push(' );');\n lines.push(` return (result?.entities ?? []).map((row: Record<string, unknown>) => ${entityClass}.fromRaw(row));`);\n lines.push(` }`);\n lines.push('');\n\n lines.push(` /** Retrieve a single record by its primary id. */`);\n lines.push(` public static async retrieveById(apiService: IApiService, id: string): Promise<${entityClass} | null> {`);\n lines.push(' const fetchXml = `');\n lines.push(' <fetch top=\"1\">');\n lines.push(` <entity name=\"\\${${constantsClass}.EntityName}\">`);\n lines.push(' <all-attributes />');\n lines.push(' <filter type=\"and\">');\n lines.push(` <condition attribute=\"\\${${constantsClass}.PrimaryKey}\" operator=\"eq\" value=\"\\${id}\" />`);\n lines.push(' </filter>');\n lines.push(' </entity>');\n lines.push(' </fetch>`;');\n lines.push(` const list = await ${entityClass}.retrieve(apiService, fetchXml);`);\n lines.push(' return list[0] ?? null;');\n lines.push(' }');\n lines.push('');\n\n lines.push(` /** Create a new record. Returns the new GUID. */`);\n lines.push(` public static async create(apiService: IApiService, data: Partial<${entityClass}>): Promise<string> {`);\n lines.push(` const result = await apiService.createRecord(${constantsClass}.EntityCollectionName, data);`);\n lines.push(` if (result && typeof result === 'object') {`);\n lines.push(` const created = result as Record<string, unknown>;`);\n lines.push(` // Implementations return either { <primaryKey>: id } or { id }.`);\n lines.push(` const newId = created[${constantsClass}.PrimaryKey] ?? created.id;`);\n lines.push(` return newId == null ? '' : String(newId);`);\n lines.push(' }');\n lines.push(' return String(result ?? \\'\\');');\n lines.push(' }');\n lines.push('');\n\n lines.push(` /** Update an existing record. */`);\n lines.push(` public static async update(apiService: IApiService, id: string, data: Partial<${entityClass}>): Promise<void> {`);\n lines.push(` await apiService.updateRecord(${constantsClass}.EntityCollectionName, id, data);`);\n lines.push(' }');\n lines.push('');\n\n lines.push(` /** Delete a record by id. */`);\n lines.push(` public static async delete(apiService: IApiService, id: string): Promise<void> {`);\n lines.push(` await apiService.deleteRecord(${constantsClass}.EntityCollectionName, id);`);\n lines.push(' }');\n}\n\n/**\n * Emit `retrieveWithRelated()` — a FetchXML retrieve whose parent-lookup joins\n * are listed as COMMENTED `<link-entity>` scaffolds. The default query returns\n * just the entity (valid + light); the developer uncomments the joins they need.\n * Child (one-to-many) links are left as a TODO since they can't be inferred\n * generically.\n */\nfunction generateRetrieveWithRelated(\n lines: string[],\n entityClass: string,\n constantsClass: string,\n links: LinkEntitySpec[]\n): void {\n lines.push(' /**');\n lines.push(' * Retrieve records with related (link-entity) data via FetchXML.');\n lines.push(' *');\n lines.push(' * SCAFFOLD: parent-lookup joins are listed below as commented');\n lines.push(' * <link-entity> elements derived from this entity\\'s many-to-one');\n lines.push(' * relationships. Uncomment and adjust the ones you need (and their');\n lines.push(' * <attribute> selections), then add child (one-to-many) links manually.');\n lines.push(' */');\n lines.push(\n ` public static async retrieveWithRelated(apiService: IApiService, filter?: string): Promise<${entityClass}[]> {`,\n );\n lines.push(' const fetchXml = `');\n lines.push(' <fetch>');\n lines.push(` <entity name=\"\\${${constantsClass}.EntityName}\">`);\n lines.push(' <all-attributes />');\n // Literal `${filter ?? ''}` for the GENERATED code to interpolate at runtime\n // (plain string here → no generator-time interpolation).\n lines.push(\" ${filter ?? ''}\");\n if (links.length > 0) {\n lines.push(' <!-- parent-lookup joins (uncomment as needed): -->');\n for (const l of links) {\n const attrs = (l.attributes && l.attributes.length > 0 ? l.attributes : ['name'])\n .map((a) => `<attribute name=\"${sanitizeXmlAttr(a)}\" />`)\n .join('');\n lines.push(\n ` <!-- <link-entity name=\"${sanitizeXmlAttr(l.entity)}\" from=\"${sanitizeXmlAttr(l.from)}\" ` +\n `to=\"${sanitizeXmlAttr(l.to)}\" link-type=\"outer\" alias=\"${sanitizeXmlAttr(l.alias)}\">${attrs}</link-entity> -->`,\n );\n }\n } else {\n lines.push(' <!-- TODO: add <link-entity> joins for related records -->');\n }\n lines.push(' </entity>');\n lines.push(' </fetch>`;');\n lines.push(` return ${entityClass}.retrieve(apiService, fetchXml);`);\n lines.push(' }');\n}\n\n/** Defensive: keep link/attr names safe inside an XML attribute + JS template string. */\nfunction sanitizeXmlAttr(value: string): string {\n return String(value).replace(/[^A-Za-z0-9_]/g, '');\n}\n","/**\n * `use<Entity>.ts` template — optional React hooks emitted under\n * `--hooks` / `includeHooks: true`.\n *\n * One generic hook (`useDataverseQuery`) handles loading / error /\n * abort-on-unmount / refetch-on-deps for any entity-set + FetchXML\n * pair. Per-entity specializations (`useOrders()`) instantiate the\n * generic with the right mapping function.\n *\n * The generated file expects callers to supply the `IApiService`\n * instance via a React context, hook, or prop wiring of their\n * choice — we don't pick that for them. The placeholder\n * `useApiService` import is documented at the top of the emitted\n * file so the caller knows what to substitute.\n */\n\nimport type { EntityMetadataInput } from '../types';\nimport { toEntityClassName } from '../utils/naming';\nimport { sanitizeForJsDocLine } from './sanitize';\nimport { buildHeaderComment } from './header';\n\nexport function generateHooksFile(\n entity: EntityMetadataInput,\n generatorVersion: string | undefined\n): string {\n const entityClass = toEntityClassName(entity.LogicalName);\n const hookName = `use${pluralize(entityClass)}`;\n\n const lines: string[] = [];\n lines.push(buildHeaderComment(`${hookName} — generated React hooks`, generatorVersion));\n lines.push('');\n lines.push(`import { useEffect, useRef, useState } from 'react';`);\n lines.push(`import { ${entityClass} } from '../models/${entityClass}';`);\n lines.push(`import { ${entityClass}Constants } from '../constants/${entityClass}Constants';`);\n lines.push('');\n lines.push('/**');\n lines.push(' * Replace this stub with your application\\'s `IApiService` resolver.');\n lines.push(' * Common patterns: a React context provider, a Zustand store, or');\n lines.push(' * a Power Pages WebApi shim.');\n lines.push(' */');\n lines.push('declare function useApiService(): {');\n lines.push(' retrieveMultipleRecords: (entity: string, fetchXml: string) => Promise<{ entities: Record<string, unknown>[] }>;');\n lines.push('};');\n lines.push('');\n lines.push(`export interface ${hookName}Result {`);\n lines.push(` data: ${entityClass}[];`);\n lines.push(' loading: boolean;');\n lines.push(' error: Error | null;');\n lines.push(' refetch: () => void;');\n lines.push('}');\n lines.push('');\n lines.push('/**');\n lines.push(` * React hook that fetches ${sanitizeForJsDocLine(entity.LogicalName)} records via FetchXML.`);\n lines.push(' * Aborts in-flight requests on unmount and re-runs when `fetchXml` changes.');\n lines.push(' */');\n lines.push(`export function ${hookName}(fetchXml?: string): ${hookName}Result {`);\n lines.push(` const [data, setData] = useState<${entityClass}[]>([]);`);\n lines.push(' const [loading, setLoading] = useState(false);');\n lines.push(' const [error, setError] = useState<Error | null>(null);');\n lines.push(' const [tick, setTick] = useState(0);');\n lines.push(' const apiService = useApiService();');\n lines.push(' const aliveRef = useRef(true);');\n lines.push('');\n lines.push(' useEffect(() => {');\n lines.push(' aliveRef.current = true;');\n lines.push(` const effectiveFetch = fetchXml ?? defaultFetch();`);\n lines.push(' setLoading(true);');\n lines.push(' setError(null);');\n lines.push(' apiService');\n lines.push(` .retrieveMultipleRecords(${entityClass}Constants.EntityCollectionName, effectiveFetch)`);\n lines.push(' .then((result) => {');\n lines.push(' if (!aliveRef.current) return;');\n lines.push(` setData((result?.entities ?? []).map((row) => ${entityClass}.fromRaw(row)));`);\n lines.push(' })');\n lines.push(' .catch((err: unknown) => {');\n lines.push(' if (!aliveRef.current) return;');\n lines.push(' setError(err instanceof Error ? err : new Error(String(err)));');\n lines.push(' })');\n lines.push(' .finally(() => {');\n lines.push(' if (aliveRef.current) setLoading(false);');\n lines.push(' });');\n lines.push(' return () => {');\n lines.push(' aliveRef.current = false;');\n lines.push(' };');\n lines.push(' }, [apiService, fetchXml, tick]);');\n lines.push('');\n lines.push(' return { data, loading, error, refetch: () => setTick((t) => t + 1) };');\n lines.push('}');\n lines.push('');\n lines.push('function defaultFetch(): string {');\n lines.push(' return `');\n lines.push(` <fetch top=\"50\">`);\n lines.push(` <entity name=\"\\${${entityClass}Constants.EntityName}\">`);\n lines.push(` <all-attributes />`);\n lines.push(' </entity>');\n lines.push(' </fetch>`;');\n lines.push('}');\n lines.push('');\n\n return lines.join('\\n');\n}\n\n/**\n * Crude English pluralization — enough for entity-name suffixes. We\n * accept misses on the long tail (`Person` → `Persons`, not `People`)\n * because the user can rename the generated hook.\n */\nfunction pluralize(name: string): string {\n if (/[sxz]$/i.test(name) || /(?:ch|sh)$/i.test(name)) return `${name}es`;\n if (/[^aeiou]y$/i.test(name)) return `${name.slice(0, -1)}ies`;\n return `${name}s`;\n}\n","/**\n * `<entity>-sample.json` template — single sample record matching the\n * model interface shape. Useful for seeding `MockApiService` during\n * local development without a live Dataverse connection.\n *\n * Values are synthesized from attribute type defaults: strings get\n * the display name as placeholder text, numbers get 0, optionsets\n * get the first option value, booleans get false. Lookups get an\n * empty GUID + display \"(empty)\". Primary key gets a known stable\n * GUID so downstream tests can reference it.\n */\n\nimport type { EntityMetadataInput, AttributeMetadataInput } from '../types';\nimport {\n toCamelCase,\n stripPublisherPrefix,\n getDisplayLabel,\n deduplicateNames,\n toEntityClassName,\n} from '../utils/naming';\nimport { categorizeAttributeType, type AttributeCategory } from '../utils/typeMapping';\n\nconst SAMPLE_GUID = '00000000-0000-0000-0000-000000000001';\n\nexport function generateSampleDataFile(entity: EntityMetadataInput): string {\n const entityClass = toEntityClassName(entity.LogicalName);\n // Same primary-key convention as the model template: `<entityCamel>Id`.\n const primaryKeyProp = `${entityClass.charAt(0).toLowerCase()}${entityClass.slice(1)}Id`;\n // Primary name prop: same display-name-first rule as the model template.\n // Prefer the declared PrimaryNameAttribute by logical name (IsPrimaryName\n // isn't guaranteed unique per entity — see constants.ts note).\n const primaryNameAttr =\n entity.Attributes.find((a) => a.LogicalName === entity.PrimaryNameAttribute) ??\n entity.Attributes.find((a) => a.IsPrimaryName);\n const primaryNameLabel = primaryNameAttr ? getDisplayLabel(primaryNameAttr.DisplayName, '') : '';\n const primaryNameProp = toCamelCase(\n primaryNameLabel || stripPublisherPrefix(entity.PrimaryNameAttribute) || 'name'\n );\n\n const regularAttrs = entity.Attributes.filter(\n (a) => !a.IsPrimaryId && !a.IsPrimaryName\n );\n const propNames = deduplicateNames(\n regularAttrs.map((a) =>\n toCamelCase(\n getDisplayLabel(a.DisplayName, '') || stripPublisherPrefix(a.LogicalName)\n )\n )\n );\n\n const sample: Record<string, unknown> = {\n [primaryKeyProp]: SAMPLE_GUID,\n [primaryNameProp]: `Sample ${getDisplayLabel(entity.DisplayName, entity.LogicalName)}`,\n };\n\n regularAttrs.forEach((attr, idx) => {\n const propName = propNames[idx];\n const category = categorizeAttributeType(attr.AttributeType);\n sample[propName] = sampleValue(attr, category);\n if (category === 'lookup') {\n sample[`${propName}Name`] = '(empty)';\n }\n });\n\n return JSON.stringify(sample, null, 2) + '\\n';\n}\n\nfunction sampleValue(\n attr: AttributeMetadataInput,\n category: AttributeCategory\n): unknown {\n switch (category) {\n case 'string':\n return getDisplayLabel(attr.DisplayName, attr.LogicalName);\n case 'number':\n return 0;\n case 'boolean':\n return false;\n case 'dateString':\n return new Date(0).toISOString();\n case 'optionset': {\n const options = attr.OptionSet?.Options ?? attr.GlobalOptionSet?.Options;\n return options && options.length > 0 ? options[0].Value : 0;\n }\n case 'multi-optionset':\n return [];\n case 'lookup':\n return '';\n case 'unsupported':\n return null;\n }\n}\n","/**\n * Orchestrator — takes one or more `EntityMetadataInput` records and\n * returns the full `GeneratedFile[]` for them. Pure: no I/O, no\n * network, no filesystem. Suitable for in-process embedding (the\n * form-builder export pipeline calls this directly).\n *\n * File paths follow:\n *\n * constants/<Entity>Constants.ts\n * models/<Entity>.ts\n * hooks/use<Plural>.ts (only when includeHooks = true)\n * samples/<entity>-sample.json (only when includeSampleData = true)\n * index.ts (barrel re-exporting every constants + model)\n *\n * Optionally prefixed by `outputDir` from the options.\n */\n\nimport type {\n EntityMetadataInput,\n GenerateEntityFilesOptions,\n GeneratedFile,\n} from './types';\nimport { generateConstantsFile } from './templates/constants';\nimport { generateModelFile } from './templates/model';\nimport { generateHooksFile } from './templates/hooks';\nimport { generateSampleDataFile } from './templates/sampleData';\nimport { detectPropertyNameCollisions, toEntityClassName } from './utils/naming';\n\n// The default import target for generated entity files. Points at the\n// IApiService surface published by `@dynamics-ui-kit/api-service`. Override\n// via `GenerateEntityFilesOptions.apiServiceImportSource` if a downstream\n// project re-exports IApiService from a different module.\nconst DEFAULT_API_SERVICE_IMPORT = '@dynamics-ui-kit/api-service';\n\nexport function generateEntityFiles(\n input: EntityMetadataInput | EntityMetadataInput[],\n options: GenerateEntityFilesOptions = {}\n): GeneratedFile[] {\n const entities = Array.isArray(input) ? input : [input];\n if (entities.length === 0) return [];\n\n const {\n includeHooks = false,\n includeSampleData = false,\n apiServiceImportSource = DEFAULT_API_SERVICE_IMPORT,\n outputDir = '',\n generatorVersion,\n } = options;\n\n const files: GeneratedFile[] = [];\n const prefix = normalizePrefix(outputDir);\n\n for (const entity of entities) {\n validateEntity(entity);\n const className = toEntityClassName(entity.LogicalName);\n\n // Surface property-name collisions at generation time so they don't\n // hide inside a WARNING JSDoc no one reads. Fires once per group\n // per entity. The model template emits matching per-property JSDoc.\n const regularAttrs = entity.Attributes.filter(\n (a) => !a.IsPrimaryId && !a.IsPrimaryName\n );\n const collisions = detectPropertyNameCollisions(regularAttrs);\n for (const [propName, group] of collisions) {\n console.warn(\n `[entity-gen] ${entity.LogicalName}: ${group.length} attributes ` +\n `resolve to property \\`${propName}\\` after applying the ` +\n `display-name-then-publisher-prefix rule (` +\n `${group.map((a) => a.LogicalName).join(', ')}). ` +\n `See WARNING JSDoc on each affected property.`,\n );\n }\n\n files.push({\n path: `${prefix}constants/${className}Constants.ts`,\n content: generateConstantsFile(entity, generatorVersion),\n });\n files.push({\n path: `${prefix}models/${className}.ts`,\n content: generateModelFile(entity, apiServiceImportSource, generatorVersion),\n });\n if (includeHooks) {\n files.push({\n path: `${prefix}hooks/use${pluralize(className)}.ts`,\n content: generateHooksFile(entity, generatorVersion),\n });\n }\n if (includeSampleData) {\n files.push({\n path: `${prefix}samples/${entity.LogicalName}-sample.json`,\n content: generateSampleDataFile(entity),\n });\n }\n }\n\n // Barrel re-exports — only emit once.\n files.push({\n path: `${prefix}index.ts`,\n content: buildBarrel(entities, includeHooks, generatorVersion),\n });\n\n return files;\n}\n\n// Dataverse logical names: lowercase letter, then lowercase letters, digits,\n// underscores. This is the same shape Dataverse itself enforces. We re-validate\n// because LogicalName flows into filesystem paths in the CLI; hostile metadata\n// like `../../etc/cron.d/x` would otherwise escape `--output`.\nconst LOGICAL_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;\n\nfunction validateEntity(entity: EntityMetadataInput): void {\n if (!entity.LogicalName) {\n throw new Error('EntityMetadataInput.LogicalName is required.');\n }\n if (!LOGICAL_NAME_PATTERN.test(entity.LogicalName)) {\n throw new Error(\n `EntityMetadataInput.LogicalName \"${entity.LogicalName}\" is not a valid Dataverse logical name ` +\n '(expected lowercase letter, then [a-z0-9_]).'\n );\n }\n if (!entity.EntitySetName) {\n throw new Error(`EntityMetadataInput.EntitySetName is required (entity: ${entity.LogicalName}).`);\n }\n if (!entity.PrimaryIdAttribute) {\n throw new Error(`EntityMetadataInput.PrimaryIdAttribute is required (entity: ${entity.LogicalName}).`);\n }\n if (!entity.PrimaryNameAttribute) {\n throw new Error(`EntityMetadataInput.PrimaryNameAttribute is required (entity: ${entity.LogicalName}).`);\n }\n}\n\nfunction normalizePrefix(dir: string): string {\n if (!dir) return '';\n return dir.endsWith('/') ? dir : `${dir}/`;\n}\n\nfunction pluralize(name: string): string {\n if (/[sxz]$/i.test(name) || /(?:ch|sh)$/i.test(name)) return `${name}es`;\n if (/[^aeiou]y$/i.test(name)) return `${name.slice(0, -1)}ies`;\n return `${name}s`;\n}\n\nfunction buildBarrel(\n entities: EntityMetadataInput[],\n includeHooks: boolean,\n generatorVersion: string | undefined\n): string {\n const lines: string[] = [\n '/**',\n ' * Generated barrel index for entity-gen output.',\n ' *',\n ' * Auto-generated by @dynamics-ui-kit/entity-gen.',\n ];\n if (generatorVersion) lines.push(` * Generator version: ${generatorVersion}`);\n lines.push(' * Do not edit by hand.');\n lines.push(' */');\n lines.push('');\n for (const entity of entities) {\n const className = toEntityClassName(entity.LogicalName);\n lines.push(`export * from './constants/${className}Constants';`);\n lines.push(`export * from './models/${className}';`);\n if (includeHooks) {\n lines.push(`export * from './hooks/use${pluralize(className)}';`);\n }\n }\n lines.push('');\n return lines.join('\\n');\n}\n","/**\n * Connection resolution — build an IDataverseClient from CLI flags / env,\n * tolerant of the env-var prefixes client projects actually use\n * (VITE_/REACT_APP_/bare DYNAMICS_), with Azure CLI as the token fallback.\n *\n * Token precedence: --token > env (.env / process.env) > Azure CLI (az).\n * Use --token (or env) for cross-tenant client orgs where you don't have\n * `az login` to the client's tenant.\n */\n\nimport { createClient, type IDataverseClient } from '@dynamics-ui-kit/api-client';\nimport { loadEnv, getToken } from '@dynamics-ui-kit/dev-tools';\n\nexport interface ConnectionOptions {\n url?: string;\n token?: string;\n envFile?: string;\n}\n\nexport interface ResolvedConnection {\n client: IDataverseClient;\n url: string;\n /** The resolved bearer token — used for typed-cast metadata HTTP the client doesn't expose. */\n token: string;\n tokenSource: 'flag' | 'env' | 'azure-cli';\n}\n\nexport function resolveConnection(opts: ConnectionOptions): ResolvedConnection {\n const env = loadEnv({ path: opts.envFile, fallbackToProcessEnv: true });\n\n const url = opts.url ?? env.url;\n if (!url) {\n throw new Error(\n 'No Dataverse URL found. Pass --url <url>, or set one of ' +\n 'VITE_DYNAMICS_URL / REACT_APP_DYNAMICS_URL / DYNAMICS_URL (optionally via --env-file).',\n );\n }\n\n let token = opts.token;\n let tokenSource: ResolvedConnection['tokenSource'] = 'flag';\n if (!token) {\n // Token from the .env file (loadEnv exposes parsed pairs in `values`) or\n // process.env — tolerant of the VITE_/REACT_APP_/bare DYNAMICS_ prefixes.\n token =\n env.values.DYNAMICS_TOKEN ??\n env.values.VITE_DYNAMICS_TOKEN ??\n env.values.REACT_APP_DYNAMICS_TOKEN ??\n process.env.DYNAMICS_TOKEN ??\n process.env.VITE_DYNAMICS_TOKEN ??\n process.env.REACT_APP_DYNAMICS_TOKEN;\n if (token) tokenSource = 'env';\n }\n if (!token) {\n token = getToken({ resource: url }).token;\n tokenSource = 'azure-cli';\n }\n\n const client = createClient({ baseUrl: url, token });\n return { client, url, token, tokenSource };\n}\n","import { readFileSync, existsSync } from 'node:fs';\n\n/**\n * URL env var names in priority order. The first matching key in the .env file\n * (or process.env when no file is provided) wins. Matches the auto-detection\n * behavior of msft/04-dynamics/scripts/get-token.sh.\n */\nexport const URL_ENV_KEYS = [\n 'VITE_DYNAMICS_URL',\n 'REACT_APP_DYNAMICS_URL',\n 'DYNAMICS_URL',\n] as const;\n\nexport type UrlEnvKey = (typeof URL_ENV_KEYS)[number];\n\nexport interface LoadEnvResult {\n /** The matched URL, or undefined if no key matched. */\n url: string | undefined;\n /** The key that matched (priority winner), or undefined if no match. */\n matchedKey: UrlEnvKey | undefined;\n /** Parsed key/value pairs from the file (empty if no file was read). */\n values: Record<string, string>;\n}\n\nexport interface LoadEnvOptions {\n /** Path to a .env file. If omitted, reads from process.env only. */\n path?: string;\n /**\n * Also consider process.env if the file is missing the key. When `path` is\n * not provided, this defaults to true; when `path` IS provided, it defaults\n * to false so file contents are authoritative.\n */\n fallbackToProcessEnv?: boolean;\n}\n\n/** Parse a .env file body. Handles both \\n and \\r\\n line endings, and a leading UTF-8 BOM. */\nexport function parseEnvFile(content: string): Record<string, string> {\n const result: Record<string, string> = {};\n // Strip a UTF-8 BOM (U+FEFF) if present — otherwise the first key would\n // carry it as an invisible prefix and lookups for VITE_DYNAMICS_URL would miss.\n if (content.charCodeAt(0) === 0xfeff) {\n content = content.slice(1);\n }\n const lines = content.split(/\\r?\\n/);\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n const eq = trimmed.indexOf('=');\n if (eq === -1) continue;\n const key = trimmed.slice(0, eq).trim();\n let value = trimmed.slice(eq + 1).trim();\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n value = value.slice(1, -1);\n }\n result[key] = value;\n }\n return result;\n}\n\nexport function loadEnv(options: LoadEnvOptions = {}): LoadEnvResult {\n let values: Record<string, string> = {};\n\n if (options.path) {\n if (!existsSync(options.path)) {\n throw new Error(`Env file not found: ${options.path}`);\n }\n const content = readFileSync(options.path, 'utf-8');\n values = parseEnvFile(content);\n }\n\n const fallback = options.fallbackToProcessEnv ?? !options.path;\n\n const lookup = (key: string): string | undefined => {\n if (key in values && values[key] !== '') return values[key];\n if (fallback) {\n const v = process.env[key];\n if (v !== undefined && v !== '') return v;\n }\n return undefined;\n };\n\n for (const key of URL_ENV_KEYS) {\n const v = lookup(key);\n if (v !== undefined) {\n return { url: v, matchedKey: key, values };\n }\n }\n\n return { url: undefined, matchedKey: undefined, values };\n}\n","import { execFileSync } from 'node:child_process';\n\nexport interface TokenResult {\n token: string;\n expiresOn: Date;\n}\n\nexport interface GetTokenOptions {\n /** Dynamics URL — used as the OAuth resource. Required. */\n resource: string;\n /** Optional: explicit Azure CLI binary path. Defaults to `az` on PATH. */\n azCommand?: string;\n /**\n * Optional execFileSync replacement, primarily for tests. Should accept the\n * same shape as Node's execFileSync and return the stdout string.\n */\n exec?: (\n file: string,\n args: ReadonlyArray<string>,\n ) => string;\n}\n\ninterface AzCliTokenResponse {\n accessToken: string;\n expiresOn: string;\n}\n\nexport class AzCliError extends Error {\n public readonly cause?: unknown;\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'AzCliError';\n if (cause !== undefined) this.cause = cause;\n }\n}\n\n/**\n * Acquire a Dataverse bearer token via Azure CLI.\n *\n * Requires the user to have run `az login`. The resource MUST be the\n * Dataverse environment URL (e.g. https://myorg.crm.dynamics.com).\n */\nexport function getToken(options: GetTokenOptions): TokenResult {\n const { resource } = options;\n if (!resource) {\n throw new Error('getToken: resource is required (Dataverse URL)');\n }\n const az = options.azCommand ?? 'az';\n const args = [\n 'account',\n 'get-access-token',\n '--resource',\n resource,\n '--output',\n 'json',\n ];\n\n let stdout: string;\n try {\n if (options.exec) {\n stdout = options.exec(az, args);\n } else {\n stdout = execFileSync(az, args, {\n encoding: 'utf-8',\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n }\n } catch (err) {\n const errObj = err as { stderr?: Buffer | string; code?: string; message?: string };\n const stderr =\n typeof errObj.stderr === 'string'\n ? errObj.stderr\n : errObj.stderr?.toString('utf-8') ?? errObj.message ?? '';\n\n if (errObj.code === 'ENOENT') {\n throw new AzCliError(\n 'Azure CLI (`az`) is not installed or not on PATH. Install: https://learn.microsoft.com/cli/azure/install-azure-cli',\n err,\n );\n }\n if (/please run.*az login/i.test(stderr) || /not logged in/i.test(stderr)) {\n throw new AzCliError(\n 'Azure CLI is not authenticated. Run `az login` and retry.',\n err,\n );\n }\n throw new AzCliError(\n `Failed to acquire token via Azure CLI: ${stderr.trim() || 'unknown error'}`,\n err,\n );\n }\n\n let parsed: AzCliTokenResponse;\n try {\n parsed = JSON.parse(stdout) as AzCliTokenResponse;\n } catch (err) {\n throw new AzCliError(`Could not parse Azure CLI JSON output: ${stdout}`, err);\n }\n if (!parsed.accessToken) {\n throw new AzCliError(`Azure CLI returned no accessToken: ${stdout}`);\n }\n const expiresOn = new Date(parsed.expiresOn);\n if (Number.isNaN(expiresOn.getTime())) {\n throw new AzCliError(`Azure CLI returned unparseable expiresOn: ${parsed.expiresOn}`);\n }\n return { token: parsed.accessToken, expiresOn };\n}\n","export interface ViteProxyOptions {\n /** Dataverse base URL (no trailing slash). */\n target: string;\n /** Path prefix to proxy. Defaults to /api/data. */\n prefix?: string;\n /** Forward Authorization header. Defaults to true. */\n changeOrigin?: boolean;\n /** Secure: validate certs. Defaults to true. */\n secure?: boolean;\n}\n\nexport interface ViteProxyEntry {\n target: string;\n changeOrigin: boolean;\n secure: boolean;\n}\n\nexport type ViteProxyConfig = Record<string, ViteProxyEntry>;\n\n/**\n * Build a Vite `server.proxy` config object for Dataverse Web API requests.\n *\n * Usage:\n * import { defineConfig } from 'vite';\n * import { viteProxy } from '@dynamics-ui-kit/dev-tools';\n * export default defineConfig({\n * server: { proxy: viteProxy({ target: process.env.VITE_DYNAMICS_URL! }) },\n * });\n */\nexport function viteProxy(options: ViteProxyOptions): ViteProxyConfig {\n if (!options.target) {\n throw new Error('viteProxy: target is required (Dataverse URL)');\n }\n const target = options.target.replace(/\\/$/, '');\n const prefix = options.prefix ?? '/api/data';\n return {\n [prefix]: {\n target,\n changeOrigin: options.changeOrigin ?? true,\n secure: options.secure ?? true,\n },\n };\n}\n","export interface CraProxyOptions {\n /** Dataverse base URL (no trailing slash). */\n target: string;\n /** Path prefix to proxy. Defaults to /api/data. */\n prefix?: string;\n /** Whether the generated module uses CommonJS (default) or ESM. */\n module?: 'cjs' | 'esm';\n}\n\n/**\n * Generate a CRA `setupProxy.js` file as a string.\n *\n * Drop the returned content into `src/setupProxy.js` of a Create React App\n * project. CRA picks it up at dev-server startup.\n */\nexport function craProxy(options: CraProxyOptions): string {\n if (!options.target) {\n throw new Error('craProxy: target is required (Dataverse URL)');\n }\n const target = options.target.replace(/\\/$/, '');\n const prefix = options.prefix ?? '/api/data';\n const moduleFormat = options.module ?? 'cjs';\n\n const importLine =\n moduleFormat === 'esm'\n ? \"import { createProxyMiddleware } from 'http-proxy-middleware';\"\n : \"const { createProxyMiddleware } = require('http-proxy-middleware');\";\n\n const exportLine =\n moduleFormat === 'esm'\n ? 'export default function (app) {'\n : 'module.exports = function (app) {';\n\n // JSON.stringify guarantees the generated source is a valid JS string\n // literal even if `target` or `prefix` somehow contain `'`, `\"`, `\\`, or\n // a newline. Without this, a malicious .env value could inject code into\n // the user's generated setupProxy.js.\n return [\n '// Generated by @dynamics-ui-kit/dev-tools',\n importLine,\n '',\n exportLine,\n ` app.use(`,\n ` ${JSON.stringify(prefix)},`,\n ` createProxyMiddleware({`,\n ` target: ${JSON.stringify(target)},`,\n ` changeOrigin: true,`,\n ` secure: true,`,\n ` }),`,\n ` );`,\n `};`,\n '',\n ].join('\\n');\n}\n","/**\n * fetchEntityMetadata — compose a complete `EntityMetadataInput` for one\n * entity from a live org, fixing the gap entity-gen's own CLI has (it calls\n * a non-existent `client.getEntityMetadata`).\n *\n * = getEntityDefinitions(LogicalName eq '<e>')[0] + getAttributeMetadata('<e>')\n * → toEntityMetadataInput()\n * → (optional) typed-cast scalar augmentation (MaxLength/Precision/...)\n */\n\nimport type { IDataverseClient } from '@dynamics-ui-kit/api-client';\nimport type { EntityMetadataInput } from '@dynamics-ui-kit/entity-gen';\nimport { toEntityMetadataInput } from './adapter';\nimport { augmentScalarDetail } from './typedCast';\nimport type { MetadataHttp } from './http';\nimport { assertValidEntityName } from '../validate';\n\nexport interface FetchEntityMetadataOptions {\n /**\n * Optional extra OData filter ANDed onto the attribute query. The api-client\n * always restricts to readable attributes (`IsValidForRead eq true`), so\n * generated constants/models cover the readable attribute surface.\n */\n attributeFilter?: string;\n /**\n * When provided, fetch type-specific scalar detail (MaxLength, Precision,\n * Min/MaxValue, Format, DateTimeBehavior) via typed-cast queries and merge\n * it in. Best-effort — failures are logged and skipped.\n */\n augment?: MetadataHttp;\n}\n\nexport async function fetchEntityMetadata(\n client: IDataverseClient,\n logicalName: string,\n options: FetchEntityMetadataOptions = {},\n): Promise<EntityMetadataInput> {\n assertValidEntityName(logicalName);\n const defs = await client.getEntityDefinitions(`LogicalName eq '${logicalName}'`);\n const entity = defs[0];\n if (!entity) {\n throw new Error(\n `Entity '${logicalName}' was not found in this org (no EntityDefinitions match). ` +\n 'Check the logical name (singular, lowercase) and that your token targets the right org.',\n );\n }\n const attributes = await client.getAttributeMetadata(logicalName, options.attributeFilter);\n const input = toEntityMetadataInput(entity, attributes);\n\n if (options.augment) {\n try {\n await augmentScalarDetail(options.augment, logicalName, input.Attributes);\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n `[dvgen] scalar detail augmentation skipped for ${logicalName}: ${e instanceof Error ? e.message : String(e)}`,\n );\n }\n }\n\n return input;\n}\n","/**\n * Adapter: raw Dataverse metadata (from @dynamics-ui-kit/api-client) →\n * the `EntityMetadataInput` shape consumed by @dynamics-ui-kit/entity-gen.\n *\n * The two shapes are intentionally field-compatible (both PascalCase\n * Dataverse-style), so this is largely a structural passthrough. It exists\n * as an explicit seam so the codegen tools never depend on the api-client's\n * concrete types and so we can validate/normalize in one place.\n */\n\nimport type { EntityMetadata, AttributeMetadata } from '@dynamics-ui-kit/api-client';\nimport type { EntityMetadataInput, AttributeMetadataInput } from '@dynamics-ui-kit/entity-gen';\n\nexport function toAttributeMetadataInput(attr: AttributeMetadata): AttributeMetadataInput {\n return {\n LogicalName: attr.LogicalName,\n SchemaName: attr.SchemaName,\n DisplayName: attr.DisplayName,\n AttributeType: attr.AttributeType,\n RequiredLevel: attr.RequiredLevel,\n IsValidForRead: attr.IsValidForRead,\n IsValidForCreate: attr.IsValidForCreate,\n IsValidForUpdate: attr.IsValidForUpdate,\n IsPrimaryId: attr.IsPrimaryId,\n IsPrimaryName: attr.IsPrimaryName,\n MaxLength: attr.MaxLength,\n Precision: attr.Precision,\n MinValue: attr.MinValue,\n MaxValue: attr.MaxValue,\n Format: attr.Format,\n FormatName: attr.FormatName,\n OptionSet: attr.OptionSet,\n GlobalOptionSet: attr.GlobalOptionSet,\n DateTimeBehavior: attr.DateTimeBehavior,\n Targets: attr.Targets,\n };\n}\n\nexport function toEntityMetadataInput(\n entity: EntityMetadata,\n attributes: AttributeMetadata[],\n): EntityMetadataInput {\n if (!entity?.LogicalName) {\n throw new Error('toEntityMetadataInput: entity.LogicalName is required.');\n }\n if (!entity.EntitySetName) {\n throw new Error(`toEntityMetadataInput: ${entity.LogicalName} is missing EntitySetName.`);\n }\n if (!entity.PrimaryIdAttribute) {\n throw new Error(`toEntityMetadataInput: ${entity.LogicalName} is missing PrimaryIdAttribute.`);\n }\n // Some entities (e.g. many-to-many intersects) legitimately have no primary\n // name. entity-gen requires the field, so fall back to the primary id —\n // the generated PrimaryName constant then mirrors PrimaryKey, which is\n // harmless and keeps the output compiling.\n const primaryName = entity.PrimaryNameAttribute || entity.PrimaryIdAttribute;\n\n return {\n LogicalName: entity.LogicalName,\n EntitySetName: entity.EntitySetName,\n SchemaName: entity.SchemaName,\n DisplayName: entity.DisplayName,\n DisplayCollectionName: entity.DisplayCollectionName,\n PrimaryIdAttribute: entity.PrimaryIdAttribute,\n PrimaryNameAttribute: primaryName,\n IsCustomEntity: entity.IsCustomEntity,\n Attributes: attributes.map(toAttributeMetadataInput),\n };\n}\n","/**\n * Typed-cast attribute augmentation.\n *\n * The api-client's `getAttributeMetadata` returns the base attribute shape;\n * scalar detail (MaxLength, Precision, Min/MaxValue, Format, DateTimeBehavior)\n * lives on type-specific subtypes and is only returned via a typed cast on the\n * EntityDefinitions Attributes navigation, e.g.:\n *\n * EntityDefinitions(LogicalName='x')/Attributes/Microsoft.Dynamics.CRM.StringAttributeMetadata\n * ?$select=LogicalName,MaxLength,Format\n *\n * This fills those fields in so generated constants carry full JSDoc detail.\n * Best-effort: a failed cast query is skipped (codegen still succeeds, just\n * with thinner comments for that type).\n */\n\nimport type { AttributeMetadataInput } from '@dynamics-ui-kit/entity-gen';\nimport { metadataGetAll, type MetadataHttp } from './http';\n\ninterface ScalarDetail {\n LogicalName: string;\n MaxLength?: number;\n MinValue?: number;\n MaxValue?: number;\n Precision?: number;\n Format?: string;\n DateTimeBehavior?: { Value: string };\n}\n\ninterface CastSpec {\n /** Dataverse AttributeType values this cast covers. */\n types: string[];\n /** The *AttributeMetadata subtype name. */\n cast: string;\n /** Fields to $select (always includes LogicalName). */\n select: string[];\n}\n\nconst SPECS: CastSpec[] = [\n { types: ['String'], cast: 'StringAttributeMetadata', select: ['MaxLength', 'Format'] },\n { types: ['Memo'], cast: 'MemoAttributeMetadata', select: ['MaxLength', 'Format'] },\n { types: ['Integer'], cast: 'IntegerAttributeMetadata', select: ['MinValue', 'MaxValue', 'Format'] },\n { types: ['BigInt'], cast: 'BigIntAttributeMetadata', select: ['MinValue', 'MaxValue'] },\n { types: ['Decimal'], cast: 'DecimalAttributeMetadata', select: ['MinValue', 'MaxValue', 'Precision'] },\n { types: ['Double'], cast: 'DoubleAttributeMetadata', select: ['MinValue', 'MaxValue', 'Precision'] },\n { types: ['Money'], cast: 'MoneyAttributeMetadata', select: ['MinValue', 'MaxValue', 'Precision'] },\n { types: ['DateTime'], cast: 'DateTimeAttributeMetadata', select: ['Format', 'DateTimeBehavior'] },\n];\n\nexport type MetadataGetter = (http: MetadataHttp, path: string) => Promise<{ value: ScalarDetail[] }>;\n\n/**\n * Merge fetched scalar detail into the attribute list (in place). Only fills\n * fields that are currently unset, so an explicit value from the base fetch\n * always wins. Pure — exported for testing.\n */\nexport function mergeScalarDetail(\n attrs: AttributeMetadataInput[],\n details: ScalarDetail[],\n): void {\n const byName = new Map(details.map((d) => [d.LogicalName, d]));\n for (const a of attrs) {\n const d = byName.get(a.LogicalName);\n if (!d) continue;\n if (d.MaxLength != null && a.MaxLength == null) a.MaxLength = d.MaxLength;\n if (d.MinValue != null && a.MinValue == null) a.MinValue = d.MinValue;\n if (d.MaxValue != null && a.MaxValue == null) a.MaxValue = d.MaxValue;\n if (d.Precision != null && a.Precision == null) a.Precision = d.Precision;\n if (d.Format != null && a.Format == null) a.Format = d.Format;\n if (d.DateTimeBehavior != null && a.DateTimeBehavior == null) a.DateTimeBehavior = d.DateTimeBehavior;\n }\n}\n\nexport async function augmentScalarDetail(\n http: MetadataHttp,\n logicalName: string,\n attrs: AttributeMetadataInput[],\n get: MetadataGetter = async (h, p) => ({ value: await metadataGetAll<ScalarDetail>(h, p) }),\n): Promise<void> {\n const presentTypes = new Set(attrs.map((a) => a.AttributeType));\n for (const spec of SPECS) {\n if (!spec.types.some((t) => presentTypes.has(t))) continue;\n const select = ['LogicalName', ...spec.select].join(',');\n const path =\n `EntityDefinitions(LogicalName='${logicalName}')/Attributes/` +\n `Microsoft.Dynamics.CRM.${spec.cast}?$select=${select}`;\n try {\n const resp = await get(http, path);\n mergeScalarDetail(attrs, resp.value ?? []);\n } catch {\n // Best-effort: skip this type's detail, keep generating.\n }\n }\n}\n","/**\n * Minimal Dataverse metadata HTTP helper for the codegen tools.\n *\n * Used for typed-cast attribute queries the api-client doesn't expose\n * (scalar detail like MaxLength/Precision). Honors 429/503 throttling with\n * `Retry-After` backoff, and follows `@odata.nextLink` (metadataGetAll) so\n * wide results aren't truncated. Uses the global `fetch` (Node 18+).\n */\n\nexport interface MetadataHttp {\n /** Org base URL, e.g. https://org.crm.dynamics.com */\n baseUrl: string;\n token: string;\n /** Web API version. Default 9.2. */\n apiVersion?: string;\n}\n\n/** A single OData collection page. */\ninterface ODataPage<T> {\n value?: T[];\n '@odata.nextLink'?: string;\n}\n\nconst sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));\n\nfunction buildUrl(http: MetadataHttp, relativePath: string): string {\n const version = http.apiVersion ?? '9.2';\n const base = http.baseUrl.replace(/\\/+$/, '');\n return `${base}/api/data/v${version}/${relativePath}`;\n}\n\n/** GET an absolute URL with 429/503 Retry-After backoff. */\nasync function getWithRetry<T>(http: MetadataHttp, url: string, maxRetries: number): Promise<T> {\n for (let attempt = 0; ; attempt += 1) {\n const res = await fetch(url, {\n headers: {\n Authorization: `Bearer ${http.token}`,\n Accept: 'application/json',\n 'OData-MaxVersion': '4.0',\n 'OData-Version': '4.0',\n },\n });\n\n if (res.status === 429 || res.status === 503) {\n if (attempt >= maxRetries) {\n throw new Error(`Dataverse throttled (${res.status}) after ${attempt} retries: ${url}`);\n }\n const headerWait = Number(res.headers.get('Retry-After'));\n const waitSec = Number.isFinite(headerWait) && headerWait > 0 ? headerWait : Math.min(2 ** attempt, 30);\n await sleep(waitSec * 1000);\n continue;\n }\n\n if (!res.ok) {\n const body = await res.text().catch(() => '');\n throw new Error(\n `Dataverse metadata GET ${res.status} ${res.statusText}: ${url}\\n${body.slice(0, 300)}`,\n );\n }\n\n return (await res.json()) as T;\n }\n}\n\n/** GET a single metadata resource (relative path), with retry/backoff. */\nexport async function metadataGet<T = unknown>(\n http: MetadataHttp,\n relativePath: string,\n maxRetries = 4,\n): Promise<T> {\n return getWithRetry<T>(http, buildUrl(http, relativePath), maxRetries);\n}\n\n/**\n * GET a metadata collection (relative path), following `@odata.nextLink` and\n * concatenating every page's `value`. Use for queries that can exceed the\n * server page cap (e.g. typed-cast attribute lists on very wide entities).\n */\nexport async function metadataGetAll<T = unknown>(\n http: MetadataHttp,\n relativePath: string,\n maxRetries = 4,\n): Promise<T[]> {\n const out: T[] = [];\n let url: string | undefined = buildUrl(http, relativePath);\n while (url) {\n const page: ODataPage<T> = await getWithRetry<ODataPage<T>>(http, url, maxRetries);\n if (page.value) out.push(...page.value);\n url = page['@odata.nextLink'];\n }\n return out;\n}\n","/**\n * Dataverse logical-name allowlist.\n *\n * The same rule Dataverse itself enforces (lowercase letter, then\n * [a-z0-9_]). Applied to the user-supplied `--entity` value at every\n * metadata-access boundary so it cannot inject into the OData `$filter`\n * / resource-path queries it is interpolated into (e.g.\n * `LogicalName eq '<name>'` and `EntityDefinitions(LogicalName='<name>')`).\n */\nconst LOGICAL_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;\n\nexport function assertValidEntityName(name: string): string {\n if (!name || !LOGICAL_NAME_PATTERN.test(name)) {\n throw new Error(\n `Invalid entity logical name ${JSON.stringify(name)} — expected a lowercase letter ` +\n 'followed by [a-z0-9_] (Dataverse logical-name rule).',\n );\n }\n return name;\n}\n","/**\n * Parent-lookup (many-to-one) <link-entity> derivation for model retrieve\n * scaffolds. Shared by the `models` and `design` commands.\n */\nimport type { IDataverseClient } from '@dynamics-ui-kit/api-client';\nimport type { EntityMetadataInput } from '@dynamics-ui-kit/entity-gen';\n\nexport interface RetrieveLink {\n entity: string;\n from: string;\n to: string;\n alias: string;\n}\n\n/**\n * Derive parent-lookup joins from relationship metadata to pre-fill a model's\n * `retrieveWithRelated()` scaffold. Parent lookups are relationships where THIS\n * entity is the referencing (many) side — Dataverse reports both navigations as\n * `OneToManyRelationship`, so we identify by `ReferencingEntity`, not type.\n *\n * Best-effort: returns `[]` (with a console warning) when relationships can't\n * be fetched, so callers still emit a TODO scaffold.\n */\nexport async function deriveParentLookupLinks(\n client: IDataverseClient,\n entity: EntityMetadataInput,\n): Promise<RetrieveLink[]> {\n try {\n const lookupAttrs = new Set(\n entity.Attributes.filter((a) =>\n ['Lookup', 'Customer', 'Owner'].includes(a.AttributeType),\n ).map((a) => a.LogicalName),\n );\n const rels = await client.getRelationshipMetadata(entity.LogicalName);\n const seenAliases = new Set<string>();\n return rels\n .filter(\n (r) =>\n r.ReferencingEntity === entity.LogicalName &&\n lookupAttrs.has(r.ReferencingAttribute),\n )\n .map((r) => {\n let alias = r.ReferencingEntityNavigationPropertyName || r.ReferencedEntity;\n let n = 2;\n while (seenAliases.has(alias)) alias = `${r.ReferencedEntity}${n++}`;\n seenAliases.add(alias);\n return {\n entity: r.ReferencedEntity,\n from: r.ReferencedAttribute,\n to: r.ReferencingAttribute,\n alias,\n };\n });\n } catch (e) {\n // eslint-disable-next-line no-console\n console.warn(\n ` ⚠could not fetch relationships for ${entity.LogicalName}: ${e instanceof Error ? e.message : String(e)} (emitting TODO scaffold)`,\n );\n return [];\n }\n}\n","/**\n * Non-destructive file writing — the foundational safety guarantee.\n *\n * Client `src/models/*` etc. are frequently hand-customized. Commands MUST\n * NOT clobber existing files silently. `safeWrite`:\n * - refuses to overwrite an existing file unless `force`\n * - supports `dryRun` (report only) and `diff` (print a unified-ish diff)\n * - creates parent dirs as needed\n */\n\nimport { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';\nimport { dirname } from 'node:path';\n\nexport type WriteResult = 'created' | 'overwritten' | 'skipped-exists' | 'unchanged' | 'dry-run';\n\nexport interface SafeWriteOptions {\n force?: boolean;\n dryRun?: boolean;\n diff?: boolean;\n}\n\nexport function safeWrite(path: string, content: string, opts: SafeWriteOptions = {}): WriteResult {\n const exists = existsSync(path);\n const current = exists ? readFileSync(path, 'utf8') : undefined;\n\n if (exists && current === content) return 'unchanged';\n\n if (opts.diff && exists) printDiff(path, current ?? '', content);\n\n if (opts.dryRun) return 'dry-run';\n\n if (exists && !opts.force) {\n return 'skipped-exists';\n }\n\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, content, 'utf8');\n return exists ? 'overwritten' : 'created';\n}\n\n/** Minimal line-level diff (added/removed) — enough to eyeball changes in a terminal. */\nfunction printDiff(path: string, before: string, after: string): void {\n const a = before.split('\\n');\n const b = after.split('\\n');\n // eslint-disable-next-line no-console\n console.log(`\\n--- ${path} (existing)\\n+++ ${path} (generated)`);\n const max = Math.max(a.length, b.length);\n for (let i = 0; i < max; i += 1) {\n if (a[i] === b[i]) continue;\n if (a[i] !== undefined) console.log(`- ${a[i]}`); // eslint-disable-line no-console\n if (b[i] !== undefined) console.log(`+ ${b[i]}`); // eslint-disable-line no-console\n }\n}\n","/**\n * Self-contained services layer emitted by `dvgen api`.\n *\n * The generated entity models import `IApiService` (default\n * `../services/IApiService`) and call `retrieveMultipleRecords / createRecord /\n * updateRecord / deleteRecord`. These files provide that contract with ZERO\n * external dependencies (no `@khester/*`, no workspace packages) so they drop\n * straight into a bare client project:\n *\n * src/services/IApiService.ts — the strict interface (single contract)\n * src/services/FetchApiService.ts — fetch + bearer token (local dev / SWA)\n * src/services/XrmApiService.ts — model-driven host (window.Xrm)\n * src/services/MockApiService.ts — offline / tests\n * src/services/ServiceFactory.ts — environment-aware selection\n *\n * `entity` is always the entity SET (collection) name, e.g. \"accounts\" —\n * matching `<Entity>Constants.EntityCollectionName` used by the models.\n *\n * Emitted code avoids template literals so this module can wrap each file in\n * `String.raw` (preserving regex backslashes) without escaping headaches.\n */\n\nexport interface ScaffoldFile {\n path: string;\n content: string;\n}\n\nconst IAPI_SERVICE = String.raw`/**\n * IApiService — minimal Dataverse API surface consumed by generated models.\n * Auto-generated by @khester/dataverse-codegen. Safe to swap the\n * implementation as long as these signatures stay intact.\n *\n * NOTE: ` + '`entity`' + String.raw` is the entity SET (collection) name, e.g. \"accounts\".\n */\nexport interface IApiService {\n createRecord(entity: string, record: Record<string, unknown>): Promise<unknown>;\n updateRecord(entity: string, id: string, record: Record<string, unknown>): Promise<unknown>;\n deleteRecord(entity: string, id: string): Promise<void>;\n retrieveMultipleRecords(entity: string, fetchXml: string): Promise<{ entities: Record<string, unknown>[] }>;\n executeRequest(requestName: string, requestData: Record<string, unknown>): Promise<unknown>;\n uploadFile(file: File): Promise<string>;\n}\n`;\n\nconst FETCH_API_SERVICE = String.raw`import type { IApiService } from './IApiService';\n\n// Module-scoped so this file compiles without @types/node; the runtime guard\n// (typeof process) handles non-Node hosts.\ndeclare const process: { env?: Record<string, string | undefined> } | undefined;\n\n/**\n * Fetch-based IApiService for local dev / Static Web App hosting.\n * Reads org URL + bearer token from env (REACT_APP_/VITE_/bare DYNAMICS_*),\n * or pass them explicitly. With an empty baseUrl it targets a same-origin\n * proxy (e.g. a CRA/Vite dev proxy that injects the Authorization header).\n */\nconst API = 'v9.2';\n\nfunction envConn(): { url: string; token: string | undefined } {\n var p = (typeof process !== 'undefined' && process.env) ? process.env : ({} as Record<string, string | undefined>);\n var url = p.REACT_APP_DYNAMICS_URL || p.VITE_DYNAMICS_URL || p.DYNAMICS_URL || '';\n var token = p.REACT_APP_DYNAMICS_TOKEN || p.VITE_DYNAMICS_TOKEN || p.DYNAMICS_TOKEN;\n return { url: url, token: token };\n}\n\nexport interface FetchApiServiceOptions {\n baseUrl?: string;\n token?: string;\n}\n\nexport class FetchApiService implements IApiService {\n private baseUrl: string;\n private token: string | undefined;\n\n constructor(options: FetchApiServiceOptions = {}) {\n var env = envConn();\n var base = options.baseUrl !== undefined ? options.baseUrl : env.url;\n this.baseUrl = base.replace(/\\/+$/, '');\n this.token = options.token !== undefined ? options.token : env.token;\n }\n\n private headers(): Record<string, string> {\n var h: Record<string, string> = {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Accept': 'application/json',\n 'OData-Version': '4.0',\n 'OData-MaxVersion': '4.0',\n 'Prefer': 'odata.include-annotations=\"*\"',\n };\n if (this.token) { h['Authorization'] = 'Bearer ' + this.token; }\n return h;\n }\n\n private dataUrl(path: string): string {\n return this.baseUrl + '/api/data/' + API + '/' + path;\n }\n\n async retrieveMultipleRecords(entity: string, fetchXml: string): Promise<{ entities: Record<string, unknown>[] }> {\n var res = await fetch(this.dataUrl(entity + '?fetchXml=' + encodeURIComponent(fetchXml)), { method: 'GET', headers: this.headers() });\n if (!res.ok) { throw new Error('retrieveMultipleRecords ' + res.status + ': ' + (await res.text().catch(function () { return ''; }))); }\n var data = (await res.json()) as { value?: Record<string, unknown>[] };\n return { entities: data.value || [] };\n }\n\n async createRecord(entity: string, record: Record<string, unknown>): Promise<unknown> {\n var res = await fetch(this.dataUrl(entity), { method: 'POST', headers: this.headers(), body: JSON.stringify(record) });\n if (!res.ok) { throw new Error('createRecord ' + res.status + ': ' + (await res.text().catch(function () { return ''; }))); }\n var entityId = res.headers.get('OData-EntityId');\n var m = entityId ? /\\(([^)]+)\\)/.exec(entityId) : null;\n if (m) { return { id: m[1] }; }\n return res.json().catch(function () { return {}; });\n }\n\n async updateRecord(entity: string, id: string, record: Record<string, unknown>): Promise<unknown> {\n var res = await fetch(this.dataUrl(entity + '(' + id.replace(/[{}]/g, '') + ')'), { method: 'PATCH', headers: this.headers(), body: JSON.stringify(record) });\n if (!res.ok) { throw new Error('updateRecord ' + res.status + ': ' + (await res.text().catch(function () { return ''; }))); }\n return res.status === 204 ? {} : res.json().catch(function () { return {}; });\n }\n\n async deleteRecord(entity: string, id: string): Promise<void> {\n var res = await fetch(this.dataUrl(entity + '(' + id.replace(/[{}]/g, '') + ')'), { method: 'DELETE', headers: this.headers() });\n if (!res.ok) { throw new Error('deleteRecord ' + res.status + ': ' + (await res.text().catch(function () { return ''; }))); }\n }\n\n async executeRequest(requestName: string, requestData: Record<string, unknown>): Promise<unknown> {\n var res = await fetch(this.dataUrl(requestName), { method: 'POST', headers: this.headers(), body: JSON.stringify(requestData) });\n if (!res.ok) { throw new Error('executeRequest ' + res.status + ': ' + (await res.text().catch(function () { return ''; }))); }\n var text = await res.text();\n return text ? JSON.parse(text) : null;\n }\n\n async uploadFile(_file: File): Promise<string> {\n throw new Error('uploadFile is not implemented in FetchApiService.');\n }\n}\n`;\n\nconst XRM_API_SERVICE = String.raw`import type { IApiService } from './IApiService';\n\ninterface GlobalContext { getClientUrl(): string; }\ninterface XrmLike { Utility: { getGlobalContext(): GlobalContext }; }\n\n/**\n * IApiService backed by the model-driven host (window.Xrm). Uses the Web API\n * directly off the client URL so the contract (entity = collection name) stays\n * identical to FetchApiService.\n */\nexport class XrmApiService implements IApiService {\n private xrm: XrmLike;\n\n constructor(xrm: unknown) {\n if (!xrm) { throw new Error('Xrm object is required'); }\n this.xrm = xrm as XrmLike;\n }\n\n private dataUrl(path: string): string {\n return this.xrm.Utility.getGlobalContext().getClientUrl() + '/api/data/v9.2/' + path;\n }\n\n private headers(): Record<string, string> {\n return {\n 'Content-Type': 'application/json; charset=utf-8',\n 'Accept': 'application/json',\n 'OData-Version': '4.0',\n 'OData-MaxVersion': '4.0',\n 'Prefer': 'odata.include-annotations=\"*\"',\n };\n }\n\n async retrieveMultipleRecords(entity: string, fetchXml: string): Promise<{ entities: Record<string, unknown>[] }> {\n var res = await fetch(this.dataUrl(entity + '?fetchXml=' + encodeURIComponent(fetchXml)), { method: 'GET', headers: this.headers() });\n if (!res.ok) { throw new Error('retrieveMultipleRecords ' + res.status); }\n var data = (await res.json()) as { value?: Record<string, unknown>[] };\n return { entities: data.value || [] };\n }\n\n async createRecord(entity: string, record: Record<string, unknown>): Promise<unknown> {\n var res = await fetch(this.dataUrl(entity), { method: 'POST', headers: this.headers(), body: JSON.stringify(record) });\n if (!res.ok) { throw new Error('createRecord ' + res.status); }\n var entityId = res.headers.get('OData-EntityId');\n var m = entityId ? /\\(([^)]+)\\)/.exec(entityId) : null;\n return m ? { id: m[1] } : {};\n }\n\n async updateRecord(entity: string, id: string, record: Record<string, unknown>): Promise<unknown> {\n var res = await fetch(this.dataUrl(entity + '(' + id.replace(/[{}]/g, '') + ')'), { method: 'PATCH', headers: this.headers(), body: JSON.stringify(record) });\n if (!res.ok) { throw new Error('updateRecord ' + res.status); }\n return res.status === 204 ? {} : res.json().catch(function () { return {}; });\n }\n\n async deleteRecord(entity: string, id: string): Promise<void> {\n var res = await fetch(this.dataUrl(entity + '(' + id.replace(/[{}]/g, '') + ')'), { method: 'DELETE', headers: this.headers() });\n if (!res.ok) { throw new Error('deleteRecord ' + res.status); }\n }\n\n async executeRequest(requestName: string, requestData: Record<string, unknown>): Promise<unknown> {\n var res = await fetch(this.dataUrl(requestName), { method: 'POST', headers: this.headers(), body: JSON.stringify(requestData) });\n if (!res.ok) { throw new Error('executeRequest ' + res.status); }\n var text = await res.text();\n return text ? JSON.parse(text) : null;\n }\n\n async uploadFile(_file: File): Promise<string> {\n throw new Error('uploadFile is not implemented in XrmApiService.');\n }\n}\n`;\n\nconst MOCK_API_SERVICE = String.raw`import type { IApiService } from './IApiService';\n\n/** Offline IApiService for local dev / tests. Returns empty result sets. */\nexport class MockApiService implements IApiService {\n async retrieveMultipleRecords(_entity: string, _fetchXml: string): Promise<{ entities: Record<string, unknown>[] }> {\n return { entities: [] };\n }\n async createRecord(_entity: string, record: Record<string, unknown>): Promise<unknown> {\n return { id: '00000000-0000-0000-0000-000000000000', ...record };\n }\n async updateRecord(_entity: string, _id: string, record: Record<string, unknown>): Promise<unknown> {\n return record;\n }\n async deleteRecord(_entity: string, _id: string): Promise<void> {\n return;\n }\n async executeRequest(_requestName: string, _requestData: Record<string, unknown>): Promise<unknown> {\n return null;\n }\n async uploadFile(_file: File): Promise<string> {\n return 'mock://uploaded';\n }\n}\n`;\n\nconst SERVICE_FACTORY = String.raw`import type { IApiService } from './IApiService';\nimport { FetchApiService } from './FetchApiService';\nimport { XrmApiService } from './XrmApiService';\nimport { MockApiService } from './MockApiService';\n\n// Module-scoped so this file compiles without @types/node; the runtime guard\n// (typeof process) handles non-Node hosts.\ndeclare const process: { env?: Record<string, string | undefined> } | undefined;\n\n/**\n * Selects the right IApiService for the environment:\n * 1. Model-driven host (window.Xrm present) -> XrmApiService\n * 2. Org URL configured in env (REACT_APP_/VITE_/DYNAMICS_*) -> FetchApiService\n * 3. Otherwise -> MockApiService\n */\nexport class ServiceFactory {\n static createApiService(xrm?: unknown): IApiService {\n var w = (typeof window !== 'undefined') ? (window as unknown as Record<string, unknown>) : ({} as Record<string, unknown>);\n var x = xrm || w['Xrm'];\n if (x && (x as { Utility?: unknown }).Utility) { return new XrmApiService(x); }\n\n var p = (typeof process !== 'undefined' && process.env) ? process.env : ({} as Record<string, string | undefined>);\n var hasEnv = !!(p.REACT_APP_DYNAMICS_URL || p.VITE_DYNAMICS_URL || p.DYNAMICS_URL);\n if (hasEnv) { return new FetchApiService(); }\n\n return new MockApiService();\n }\n}\n`;\n\nexport const API_SERVICE_FILES: ScaffoldFile[] = [\n { path: 'services/IApiService.ts', content: IAPI_SERVICE },\n { path: 'services/FetchApiService.ts', content: FETCH_API_SERVICE },\n { path: 'services/XrmApiService.ts', content: XRM_API_SERVICE },\n { path: 'services/MockApiService.ts', content: MOCK_API_SERVICE },\n { path: 'services/ServiceFactory.ts', content: SERVICE_FACTORY },\n];\n","/**\n * Test-data helpers: pull live rows into OData fixtures, push fixtures back,\n * and a lightweight retrieve smoke test.\n *\n * `seed:pull` → src/sampleData/<entity>.json (OData `{ value: [...] }` shape)\n * `seed:push` → create records from a fixture (annotations / id / lookups stripped)\n * `test-retrieve` → confirm rows come back (live) or fixtures exist (default)\n */\n\nimport type { IDataverseClient } from '@dynamics-ui-kit/api-client';\nimport { assertValidEntityName } from './validate';\n\n/** Resolve the entity SET (collection) name + primary id from a logical name. */\nexport async function getEntityRefs(\n client: IDataverseClient,\n logicalName: string,\n): Promise<{ entitySetName: string; primaryIdAttribute: string }> {\n assertValidEntityName(logicalName);\n const defs = await client.getEntityDefinitions(`LogicalName eq '${logicalName}'`);\n const entity = defs[0];\n if (!entity) {\n throw new Error(`Entity '${logicalName}' was not found in this org.`);\n }\n return { entitySetName: entity.EntitySetName, primaryIdAttribute: entity.PrimaryIdAttribute };\n}\n\nexport interface PullOptions {\n top?: number;\n select?: string;\n filter?: string;\n}\n\nexport async function pullRows(\n client: IDataverseClient,\n setName: string,\n opts: PullOptions = {},\n): Promise<Record<string, unknown>[]> {\n const params: string[] = [];\n if (opts.top && opts.top > 0) params.push(`$top=${opts.top}`);\n if (opts.select) params.push(`$select=${opts.select}`);\n if (opts.filter) params.push(`$filter=${encodeURIComponent(opts.filter)}`);\n const res = await client.retrieveMultiple(setName, params.join('&'));\n return (res.value ?? []) as Record<string, unknown>[];\n}\n\n/** Serialize rows into the OData fixture shape the client projects use. */\nexport function toODataFixture(baseUrl: string, setName: string, rows: Record<string, unknown>[]): string {\n const context = `${baseUrl.replace(/\\/+$/, '')}/api/data/v9.2/$metadata#${setName}`;\n return `${JSON.stringify({ '@odata.context': context, value: rows }, null, 2)}\\n`;\n}\n\n/**\n * Strip a pulled row down to creatable fields: drop OData annotations\n * (`@`-keyed), the primary id (server-assigned), and `_<x>_value` lookups\n * (which would need `<nav>@odata.bind` to recreate — out of scope for a simple\n * seed). Returns the cleaned record plus the names of dropped lookup fields.\n */\nexport function stripForCreate(\n row: Record<string, unknown>,\n primaryIdAttribute: string,\n): { record: Record<string, unknown>; droppedLookups: string[] } {\n const record: Record<string, unknown> = {};\n const droppedLookups: string[] = [];\n for (const [key, value] of Object.entries(row)) {\n if (key.includes('@')) continue; // odata annotations / formatted values\n if (key === primaryIdAttribute) continue; // let the server assign\n if (/^_.*_value$/.test(key)) {\n droppedLookups.push(key);\n continue; // lookups need @odata.bind\n }\n record[key] = value;\n }\n return { record, droppedLookups };\n}\n\nexport interface PushResult {\n created: number;\n failed: Array<{ index: number; error: string }>;\n droppedLookupFields: string[];\n}\n\nexport async function pushRows(\n client: IDataverseClient,\n setName: string,\n primaryIdAttribute: string,\n rows: Record<string, unknown>[],\n): Promise<PushResult> {\n const result: PushResult = { created: 0, failed: [], droppedLookupFields: [] };\n const dropped = new Set<string>();\n for (let i = 0; i < rows.length; i += 1) {\n const { record, droppedLookups } = stripForCreate(rows[i], primaryIdAttribute);\n droppedLookups.forEach((d) => dropped.add(d));\n try {\n await client.create(setName, record);\n result.created += 1;\n } catch (e) {\n result.failed.push({ index: i, error: e instanceof Error ? e.message : String(e) });\n }\n }\n result.droppedLookupFields = [...dropped];\n return result;\n}\n","/**\n * Reader for the `*.design.json` contract exported by the design-only form\n * designer (`@dynamics-ui-kit/form-designer`). The `design` command uses this\n * to discover which Dataverse entities a set of forms targets, then scaffolds\n * the data layer for each.\n *\n * Parses untrusted JSON, so the shapes here are deliberately loose + defensive\n * rather than importing form-runtime's full `FormDefinition`.\n */\nimport { assertValidEntityName } from '../validate';\n\n/** Discriminator the form designer writes into every exported design file. */\nexport const FORM_DESIGN_KIND = 'dynamics-ui-kit.form-design';\n\ninterface DesignControl {\n type?: string;\n name?: string;\n properties?: { entityName?: unknown } & Record<string, unknown>;\n dataBinding?: { attributeLogicalName?: unknown; lookupTargets?: unknown };\n}\ninterface DesignCell {\n control?: DesignControl | null;\n}\ninterface DesignRow {\n cells?: DesignCell[];\n}\ninterface DesignSection {\n rows?: DesignRow[];\n}\ninterface DesignTab {\n sections?: DesignSection[];\n}\ninterface DesignForm {\n name?: string;\n type?: string;\n settings?: { dataSources?: Array<{ entityName?: unknown }> };\n sections?: DesignSection[];\n tabs?: DesignTab[];\n}\n\nexport interface FormDesignFile {\n kind?: string;\n schemaVersion?: number;\n name?: string;\n forms?: DesignForm[];\n}\n\n/** A Dataverse entity discovered in the design, with where it came from. */\nexport interface EntityRef {\n logicalName: string;\n /** Human-readable provenance, for reporting (e.g. `form \"Contact\" (target)`). */\n sources: string[];\n}\n\nexport interface CollectResult {\n entities: EntityRef[];\n /** Entity-name candidates rejected by the logical-name allowlist. */\n skipped: { name: string; reason: string }[];\n}\n\n/**\n * Parse + validate an exported design file. Throws on invalid JSON, an\n * unexpected `kind`, or a missing `forms` array.\n */\nexport function parseDesignFile(raw: string): FormDesignFile {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (e) {\n throw new Error(`Design file is not valid JSON: ${e instanceof Error ? e.message : String(e)}`);\n }\n if (!parsed || typeof parsed !== 'object') {\n throw new Error('Design file must be a JSON object.');\n }\n const file = parsed as FormDesignFile;\n if (file.kind && file.kind !== FORM_DESIGN_KIND) {\n throw new Error(\n `Unexpected design kind ${JSON.stringify(file.kind)} (expected ${JSON.stringify(FORM_DESIGN_KIND)}). ` +\n 'Is this a *.design.json exported from the form designer?',\n );\n }\n if (!Array.isArray(file.forms)) {\n throw new Error('Design file has no `forms` array — nothing to scan.');\n }\n return file;\n}\n\n/**\n * Walk every form and collect the Dataverse entities it references:\n * - each form's target entity (`settings.dataSources[0].entityName`),\n * - subgrid controls' `properties.entityName`,\n * - lookup controls' `dataBinding.lookupTargets`.\n *\n * Names are normalized to lowercase and validated against the Dataverse\n * logical-name rule; invalid candidates are reported in `skipped`, never\n * generated (they'd otherwise inject into metadata OData queries).\n */\nexport function collectEntities(design: FormDesignFile): CollectResult {\n const found = new Map<string, Set<string>>();\n const skipped: { name: string; reason: string }[] = [];\n\n const add = (raw: unknown, source: string): void => {\n if (typeof raw !== 'string') return;\n const name = raw.trim().toLowerCase();\n if (!name) return;\n try {\n assertValidEntityName(name);\n } catch {\n if (!skipped.some((s) => s.name === name)) {\n skipped.push({ name, reason: 'not a valid Dataverse logical name' });\n }\n return;\n }\n if (!found.has(name)) found.set(name, new Set());\n found.get(name)!.add(source);\n };\n\n const walkSections = (sections: DesignSection[] | undefined, formName: string): void => {\n for (const section of sections ?? []) {\n for (const row of section.rows ?? []) {\n for (const cell of row.cells ?? []) {\n const c = cell?.control;\n if (!c) continue;\n if (c.type === 'subgrid') {\n add(c.properties?.entityName, `subgrid in \"${formName}\"`);\n }\n if (c.type === 'lookup' && Array.isArray(c.dataBinding?.lookupTargets)) {\n for (const t of c.dataBinding!.lookupTargets as unknown[]) {\n add(t, `lookup in \"${formName}\"`);\n }\n }\n }\n }\n }\n };\n\n for (const form of design.forms ?? []) {\n const formName = form.name ?? '(unnamed form)';\n add(form.settings?.dataSources?.[0]?.entityName, `form \"${formName}\" (target)`);\n walkSections(form.sections, formName);\n for (const tab of form.tabs ?? []) walkSections(tab.sections, formName);\n }\n\n const entities: EntityRef[] = [...found.entries()]\n .map(([logicalName, sources]) => ({ logicalName, sources: [...sources] }))\n .sort((a, b) => a.logicalName.localeCompare(b.logicalName));\n\n return { entities, skipped };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAF9B;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAGA,QAAMA,kBAAN,cAA6B,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAOjC,YAAY,UAAU,MAA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aAAa,cAAc,IAAI,CAAC,EAAE;AAAA,IAChD,OAAO;AACL,YAAM,OAAO,KAAK,KAAK,KAAK,cAAc,GAAG,KAAK,MAAM,OAAO;AAC/D,YAAM,OAAO,gBAAgB,MAAM,KAAK,MAAM;AAE9C,cAAQ,IAAI,oBAAe,IAAI,KAAK,KAAK,MAAM,SAAS;AAExD,cAAQ,IAAI,aAAa,cAAc,IAAI,CAAC,EAAE;AAAA,IAChD;AAAA,EACF;AACF;AAEAA,SAAQ,WAAW,QAAQ,IAAI,EAAE,MAAM,CAAC,QAAiB;AAEvD,UAAQ,MAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,CAAC,EAAE;AAC1E,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["CommanderError","InvalidArgumentError","InvalidArgumentError","Argument","Help","cmd","InvalidArgumentError","Option","str","path","process","Argument","CommanderError","Help","Option","Command","option","Argument","Command","CommanderError","InvalidArgumentError","Help","Option","createClient","path","commander","existsSync","readFileSync","path","readFileSync","existsSync","path","program","readFileSync","path","existsSync"]}
|