@event-driven-io/emmett 0.43.0-beta.14 → 0.43.0-beta.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.cjs","names":["CliCommand","EmmettError","isPluginConfig","Command"],"sources":["../src/commandLine/config.ts","../src/commandLine/plugins.ts","../src/cli.ts"],"sourcesContent":["import { Command as CliCommand } from 'commander';\n// eslint-disable-next-line no-restricted-imports\nimport { writeFileSync } from 'node:fs';\nimport { exit } from 'process';\n\nexport const sampleConfig = (plugins: string[] = ['emmett-expressjs']) => {\n const pluginsNames =\n plugins.length > 0\n ? `[\\n${plugins.map((p) => `\"${p}\"`).join(',\\n')} \\n]`\n : '[]';\n\n return `\nexport default {\n plugins: ${pluginsNames},\n};\n`;\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const configCommand = new CliCommand('config').description(\n 'Manage Pongo configuration',\n);\n\ntype SampleConfigOptions =\n | {\n plugin: string[];\n print?: boolean;\n }\n | {\n plugin: string[];\n generate?: boolean;\n file?: string;\n };\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-plg, --plugins <name>',\n 'Specify the plugin name',\n (value: string, previous: string[]) => {\n // Accumulate plugins names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const plugins =\n options.plugin.length > 0\n ? options.plugin\n : ['@event-driven-io/emmett-expressjs'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(plugins)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n exit(1);\n }\n\n generateConfigFile(options.file, plugins);\n }\n });\n","import type { Command as CliCommand } from 'commander';\nimport path from 'path';\nimport {\n isPluginConfig,\n type EmmettCliCommand,\n type EmmettCliPlugin,\n type EmmettPlugin,\n type EmmettPluginConfig,\n type EmmettPluginsConfig,\n type EmmettPluginType,\n} from '../config';\nimport { EmmettError } from '../errors';\nimport { sampleConfig } from './config';\n\nconst PluginsConfigImportError = {\n missingDefaultExport: `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`,\n missingPluginsPropertyExport: `Error: Config should contain default export with plugins array, e.g.\\n\\n${sampleConfig()}`,\n wrongPluginStructure: `Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }`,\n};\nexport const importPluginsConfig = async (options?: {\n configPath?: string | undefined;\n}): Promise<EmmettPluginsConfig | EmmettError> => {\n const configPath = path.join(\n process.cwd(),\n options?.configPath ?? './dist/emmett.config.js',\n );\n\n console.log('IMPORTING' + configPath);\n\n try {\n const imported = (await import(configPath)) as {\n default: Partial<EmmettPluginsConfig>;\n };\n\n if (!imported.default) {\n return new EmmettError(PluginsConfigImportError.missingDefaultExport);\n }\n\n if (!imported.default.plugins || !Array.isArray(imported.default.plugins)) {\n return new EmmettError(\n PluginsConfigImportError.missingPluginsPropertyExport,\n );\n }\n\n if (!imported.default.plugins.every(isPluginConfig)) {\n return new EmmettError(PluginsConfigImportError.wrongPluginStructure);\n }\n\n return { plugins: imported.default.plugins };\n } catch (error) {\n if (!options?.configPath) {\n console.warn('Didn`t find config file: ' + configPath, error);\n return { plugins: [] };\n }\n return new EmmettError(\n `Error: Couldn't load file:` + (error as Error).toString(),\n );\n }\n};\n\nexport const loadPlugins = async (options?: {\n pluginType?: EmmettPluginType;\n configPath?: string;\n}): Promise<EmmettPlugin[]> => {\n try {\n const pluginsConfig = await importPluginsConfig({\n configPath: options?.configPath,\n });\n\n if (pluginsConfig instanceof EmmettError) throw pluginsConfig;\n\n if (pluginsConfig.plugins.length === 0) {\n console.log(`No extensions specified in config ${options?.configPath}.`);\n return [];\n }\n\n const pluginsToLoad = filterPluginsByType(\n pluginsConfig.plugins,\n options?.pluginType,\n );\n\n const pluginsPromises = pluginsToLoad.map(async (pluginConfig) => {\n const importPath = getImportPath(pluginConfig, options?.pluginType);\n try {\n const plugin = (await import(importPath)) as { default: EmmettPlugin };\n\n console.info(`Loaded plugin: ${importPath}`);\n\n if (!plugin.default) {\n throw new Error(`Plugin: ${importPath} is missing default export`);\n }\n\n return plugin.default;\n } catch (error) {\n console.error(`Failed to load extension \"${importPath}\":`, error);\n return undefined;\n }\n });\n\n return (await Promise.all(pluginsPromises)).filter(\n (plugin) => plugin !== undefined,\n );\n } catch (error) {\n console.error(`Failed to load config ${options?.configPath}:`, error);\n return [];\n }\n};\n\nexport const registerCliPlugins = async (\n program: CliCommand,\n plugins: EmmettCliPlugin[],\n): Promise<void> => {\n const result: EmmettCliPlugin[] = [];\n\n for (const plugin of plugins) {\n const pluginName = plugin.name;\n\n if (!('registerCommands' in plugin)) {\n console.warn(`No registerCommands function found in ${pluginName}`);\n }\n await plugin.registerCommands(program as EmmettCliCommand);\n console.log(`Loaded extension: ${plugin.name}`);\n result.push(plugin);\n }\n};\n\nconst filterPluginsByType = (\n plugins: EmmettPluginConfig[],\n pluginType?: EmmettPluginType,\n): EmmettPluginConfig[] =>\n plugins.filter(\n (p) =>\n typeof p === 'string' ||\n (pluginType &&\n (p.register === undefined ||\n p.register.some((r) => r.pluginType === pluginType))),\n );\n\nconst getImportPath = (\n pluginConfig: EmmettPluginConfig,\n pluginType: EmmettPluginType | undefined,\n) => {\n if (typeof pluginConfig === 'string') {\n return pluginType ? `${pluginConfig}/${pluginType}` : pluginConfig;\n }\n\n const pluginSubpath =\n pluginConfig.register.find((r) => pluginType && r.pluginType === pluginType)\n ?.path ?? pluginType;\n\n return pluginSubpath\n ? `${pluginConfig.name}/${pluginSubpath}`\n : pluginConfig.name;\n};\n","#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option('--config <path>', 'Path to the configuration file');\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const configIndex = process.argv.indexOf('--config');\n\n const configPath =\n configIndex !== -1 && process.argv.length > configIndex + 1\n ? process.argv[configIndex + 1]\n : undefined;\n\n try {\n const plugins = await loadPlugins({\n pluginType: 'cli',\n configPath: configPath,\n });\n await registerCliPlugins(program, plugins);\n\n // Parse the CLI arguments\n program.parse(process.argv);\n } catch (err) {\n console.error(`Failed to load config from ${configPath}:`, err);\n }\n};\n\n//Initialize CLI and handle errors\ninitCLI().catch((err) => {\n console.error(`CLI initialization failed:`);\n console.error(err);\n});\n\nexport default program;\nexport * from './commandLine';\n"],"mappings":";;;;;;;;;;AAKA,MAAa,gBAAgB,UAAoB,CAAC,mBAAmB,KAAK;AAMxE,QAAO;;aAJL,QAAQ,SAAS,IACb,MAAM,QAAQ,KAAK,MAAM,IAAI,EAAE,GAAG,CAAC,KAAK,MAAM,CAAC,SAC/C,KAIkB;;;;AAK1B,MAAa,sBACX,YACA,oBACS;AACT,KAAI;AACF,6BAAc,YAAY,aAAa,gBAAgB,EAAE,OAAO;AAChE,UAAQ,IAAI,iCAAiC,aAAa;UACnD,OAAO;AACd,UAAQ,MAAM,sCAAsC,WAAW,GAAG;AAClE,UAAQ,MAAM,MAAM;AACpB,UAAQ,KAAK,EAAE;;;AAInB,MAAa,gBAAgB,IAAIA,kBAAW,SAAS,CAAC,YACpD,6BACD;AAaD,cACG,QAAQ,SAAS,CACjB,YAAY,yCAAyC,CACrD,O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AM,MAAM,EAAE,eAAe,WAAW,EAC1D;AAEH,MAAM,iBACJ,cACA,eACG;AACH,KAAI,OAAO,iBAAiB,SAC1B,QAAO,aAAa,GAAG,aAAa,GAAG,eAAe;CAGxD,MAAM,gBACJ,aAAa,SAAS,MAAM,MAAM,cAAc,EAAE,eAAe,WAAW,EACxE,QAAQ;AAEd,QAAO,gBACH,GAAG,aAAa,KAAK,GAAG,kBACxB,aAAa;;;;;ACpJnB,MAAM,UAAU,IAAIE,mBAAS;AAE7B,QACG,KAAK,SAAS,CACd,YAAY,sBAAsB,CAClC,OAAO,mBAAmB,iCAAiC;AAG9D,MAAM,UAAU,YAAY;CAC1B,MAAM,cAAc,QAAQ,KAAK,QAAQ,WAAW;CAEpD,MAAM,aACJ,gBAAgB,MAAM,QAAQ,KAAK,SAAS,cAAc,IACtD,QAAQ,KAAK,cAAc,KAC3B;AAEN,KAAI;AAKF,QAAM,mBAAmB,SAJT,MAAM,YAAY;GAChC,YAAY;GACA;GACb,CAAC,CACwC;AAG1C,UAAQ,MAAM,QAAQ,KAAK;UACpB,KAAK;AACZ,UAAQ,MAAM,8BAA8B,WAAW,IAAI,IAAI;;;AAKnE,SAAS,CAAC,OAAO,QAAQ;AACvB,SAAQ,MAAM,6BAA6B;AAC3C,SAAQ,MAAM,IAAI;EAClB"}
1
+ {"version":3,"file":"cli.cjs","names":["CliCommand","EmmettError","isPluginConfig","Command"],"sources":["../src/commandLine/config.ts","../src/commandLine/plugins.ts","../src/cli.ts"],"sourcesContent":["import { Command as CliCommand } from 'commander';\n// eslint-disable-next-line no-restricted-imports\nimport { writeFileSync } from 'node:fs';\nimport { exit } from 'process';\n\nexport const sampleConfig = (plugins: string[] = ['emmett-expressjs']) => {\n const pluginsNames =\n plugins.length > 0\n ? `[\\n${plugins.map((p) => `\"${p}\"`).join(',\\n')} \\n]`\n : '[]';\n\n return `\nexport default {\n plugins: ${pluginsNames},\n};\n`;\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const configCommand = new CliCommand('config').description(\n 'Manage Pongo configuration',\n);\n\ntype SampleConfigOptions =\n | {\n plugin: string[];\n print?: boolean;\n }\n | {\n plugin: string[];\n generate?: boolean;\n file?: string;\n };\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-plg, --plugins <name>',\n 'Specify the plugin name',\n (value: string, previous: string[]) => {\n // Accumulate plugins names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const plugins =\n options.plugin.length > 0\n ? options.plugin\n : ['@event-driven-io/emmett-expressjs'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(plugins)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n exit(1);\n }\n\n generateConfigFile(options.file, plugins);\n }\n });\n","import type { Command as CliCommand } from 'commander';\nimport path from 'path';\nimport {\n isPluginConfig,\n type EmmettCliCommand,\n type EmmettCliPlugin,\n type EmmettPlugin,\n type EmmettPluginConfig,\n type EmmettPluginsConfig,\n type EmmettPluginType,\n} from '../config';\nimport { EmmettError } from '../errors';\nimport { sampleConfig } from './config';\n\nconst PluginsConfigImportError = {\n missingDefaultExport: `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`,\n missingPluginsPropertyExport: `Error: Config should contain default export with plugins array, e.g.\\n\\n${sampleConfig()}`,\n wrongPluginStructure: `Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }`,\n};\nexport const importPluginsConfig = async (options?: {\n configPath?: string | undefined;\n}): Promise<EmmettPluginsConfig | EmmettError> => {\n const configPath = path.join(\n process.cwd(),\n options?.configPath ?? './dist/emmett.config.js',\n );\n\n console.log('IMPORTING' + configPath);\n\n try {\n const imported = (await import(configPath)) as {\n default: Partial<EmmettPluginsConfig>;\n };\n\n if (!imported.default) {\n return new EmmettError(PluginsConfigImportError.missingDefaultExport);\n }\n\n if (!imported.default.plugins || !Array.isArray(imported.default.plugins)) {\n return new EmmettError(\n PluginsConfigImportError.missingPluginsPropertyExport,\n );\n }\n\n if (!imported.default.plugins.every(isPluginConfig)) {\n return new EmmettError(PluginsConfigImportError.wrongPluginStructure);\n }\n\n return { plugins: imported.default.plugins };\n } catch (error) {\n if (!options?.configPath) {\n console.warn('Didn`t find config file: ' + configPath, error);\n return { plugins: [] };\n }\n return new EmmettError(\n `Error: Couldn't load file:` + (error as Error).toString(),\n );\n }\n};\n\nexport const loadPlugins = async (options?: {\n pluginType?: EmmettPluginType;\n configPath?: string;\n}): Promise<EmmettPlugin[]> => {\n try {\n const pluginsConfig = await importPluginsConfig({\n configPath: options?.configPath,\n });\n\n if (pluginsConfig instanceof EmmettError) throw pluginsConfig;\n\n if (pluginsConfig.plugins.length === 0) {\n console.log(`No extensions specified in config ${options?.configPath}.`);\n return [];\n }\n\n const pluginsToLoad = filterPluginsByType(\n pluginsConfig.plugins,\n options?.pluginType,\n );\n\n const pluginsPromises = pluginsToLoad.map(async (pluginConfig) => {\n const importPath = getImportPath(pluginConfig, options?.pluginType);\n try {\n const plugin = (await import(importPath)) as { default: EmmettPlugin };\n\n console.info(`Loaded plugin: ${importPath}`);\n\n if (!plugin.default) {\n throw new Error(`Plugin: ${importPath} is missing default export`);\n }\n\n return plugin.default;\n } catch (error) {\n console.error(`Failed to load extension \"${importPath}\":`, error);\n return undefined;\n }\n });\n\n return (await Promise.all(pluginsPromises)).filter(\n (plugin) => plugin !== undefined,\n );\n } catch (error) {\n console.error(`Failed to load config ${options?.configPath}:`, error);\n return [];\n }\n};\n\nexport const registerCliPlugins = async (\n program: CliCommand,\n plugins: EmmettCliPlugin[],\n): Promise<void> => {\n const result: EmmettCliPlugin[] = [];\n\n for (const plugin of plugins) {\n const pluginName = plugin.name;\n\n if (!('registerCommands' in plugin)) {\n console.warn(`No registerCommands function found in ${pluginName}`);\n }\n await plugin.registerCommands(program as EmmettCliCommand);\n console.log(`Loaded extension: ${plugin.name}`);\n result.push(plugin);\n }\n};\n\nconst filterPluginsByType = (\n plugins: EmmettPluginConfig[],\n pluginType?: EmmettPluginType,\n): EmmettPluginConfig[] =>\n plugins.filter(\n (p) =>\n typeof p === 'string' ||\n (pluginType &&\n (p.register === undefined ||\n p.register.some((r) => r.pluginType === pluginType))),\n );\n\nconst getImportPath = (\n pluginConfig: EmmettPluginConfig,\n pluginType: EmmettPluginType | undefined,\n) => {\n if (typeof pluginConfig === 'string') {\n return pluginType ? `${pluginConfig}/${pluginType}` : pluginConfig;\n }\n\n const pluginSubpath =\n pluginConfig.register.find((r) => pluginType && r.pluginType === pluginType)\n ?.path ?? pluginType;\n\n return pluginSubpath\n ? `${pluginConfig.name}/${pluginSubpath}`\n : pluginConfig.name;\n};\n","#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option('--config <path>', 'Path to the configuration file');\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const configIndex = process.argv.indexOf('--config');\n\n const configPath =\n configIndex !== -1 && process.argv.length > configIndex + 1\n ? process.argv[configIndex + 1]\n : undefined;\n\n try {\n const plugins = await loadPlugins({\n pluginType: 'cli',\n configPath: configPath,\n });\n await registerCliPlugins(program, plugins);\n\n // Parse the CLI arguments\n program.parse(process.argv);\n } catch (err) {\n console.error(`Failed to load config from ${configPath}:`, err);\n }\n};\n\n//Initialize CLI and handle errors\ninitCLI().catch((err) => {\n console.error(`CLI initialization failed:`);\n console.error(err);\n});\n\nexport default program;\nexport * from './commandLine';\n"],"mappings":";;;;;;;;;;AAKA,MAAa,gBAAgB,UAAoB,CAAC,mBAAmB,KAAK;AAMxE,QAAO;;aAJL,QAAQ,SAAS,IACb,MAAM,QAAQ,KAAK,MAAM,IAAI,EAAE,GAAG,CAAC,KAAK,MAAM,CAAC,SAC/C,KAIkB;;;;AAK1B,MAAa,sBACX,YACA,oBACS;AACT,KAAI;AACF,6BAAc,YAAY,aAAa,gBAAgB,EAAE,OAAO;AAChE,UAAQ,IAAI,iCAAiC,aAAa;UACnD,OAAO;AACd,UAAQ,MAAM,sCAAsC,WAAW,GAAG;AAClE,UAAQ,MAAM,MAAM;AACpB,UAAQ,KAAK,EAAE;;;AAInB,MAAa,gBAAgB,IAAIA,kBAAW,SAAS,CAAC,YACpD,6BACD;AAaD,cACG,QAAQ,SAAS,CACjB,YAAY,yCAAyC,CACrD,OACC,0BACA,4BACC,OAAe,aAAuB;AAErC,QAAO,SAAS,OAAO,CAAC,MAAM,CAAC;GAEjC,EAAE,CACH,CACA,OACC,qBACA,kDACD,CACA,OAAO,kBAAkB,8BAA8B,CACvD,OAAO,eAAe,2BAA2B,CACjD,QAAQ,YAAiC;CACxC,MAAM,UACJ,QAAQ,OAAO,SAAS,IACpB,QAAQ,SACR,CAAC,oCAAoC;AAE3C,KAAI,EAAE,WAAW,YAAY,EAAE,cAAc,UAAU;AACrD,UAAQ,MACN,oHACD;AACD,sBAAK,EAAE;;AAGT,KAAI,WAAW,QACb,SAAQ,IAAI,GAAG,aAAa,QAAQ,GAAG;UAC9B,cAAc,SAAS;AAChC,MAAI,CAAC,QAAQ,MAAM;AACjB,WAAQ,MACN,4DACD;AACD,uBAAK,EAAE;;AAGT,qBAAmB,QAAQ,MAAM,QAAQ;;EAE3C;;;;AC5EJ,MAAM,2BAA2B;CAC/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SAAS,MAJZ,YAAY;GAChC,YAAY;GACA;GACb,CAAC,CACwC;AAG1C,UAAQ,MAAM,QAAQ,KAAK;UACpB,KAAK;AACZ,UAAQ,MAAM,8BAA8B,WAAW,IAAI,IAAI;;;AAKnE,SAAS,CAAC,OAAO,QAAQ;AACvB,SAAQ,MAAM,6BAA6B;AAC3C,SAAQ,MAAM,IAAI;EAClB"}
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":["CliCommand"],"sources":["../src/commandLine/config.ts","../src/commandLine/plugins.ts","../src/cli.ts"],"sourcesContent":["import { Command as CliCommand } from 'commander';\n// eslint-disable-next-line no-restricted-imports\nimport { writeFileSync } from 'node:fs';\nimport { exit } from 'process';\n\nexport const sampleConfig = (plugins: string[] = ['emmett-expressjs']) => {\n const pluginsNames =\n plugins.length > 0\n ? `[\\n${plugins.map((p) => `\"${p}\"`).join(',\\n')} \\n]`\n : '[]';\n\n return `\nexport default {\n plugins: ${pluginsNames},\n};\n`;\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const configCommand = new CliCommand('config').description(\n 'Manage Pongo configuration',\n);\n\ntype SampleConfigOptions =\n | {\n plugin: string[];\n print?: boolean;\n }\n | {\n plugin: string[];\n generate?: boolean;\n file?: string;\n };\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-plg, --plugins <name>',\n 'Specify the plugin name',\n (value: string, previous: string[]) => {\n // Accumulate plugins names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const plugins =\n options.plugin.length > 0\n ? options.plugin\n : ['@event-driven-io/emmett-expressjs'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(plugins)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n exit(1);\n }\n\n generateConfigFile(options.file, plugins);\n }\n });\n","import type { Command as CliCommand } from 'commander';\nimport path from 'path';\nimport {\n isPluginConfig,\n type EmmettCliCommand,\n type EmmettCliPlugin,\n type EmmettPlugin,\n type EmmettPluginConfig,\n type EmmettPluginsConfig,\n type EmmettPluginType,\n} from '../config';\nimport { EmmettError } from '../errors';\nimport { sampleConfig } from './config';\n\nconst PluginsConfigImportError = {\n missingDefaultExport: `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`,\n missingPluginsPropertyExport: `Error: Config should contain default export with plugins array, e.g.\\n\\n${sampleConfig()}`,\n wrongPluginStructure: `Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }`,\n};\nexport const importPluginsConfig = async (options?: {\n configPath?: string | undefined;\n}): Promise<EmmettPluginsConfig | EmmettError> => {\n const configPath = path.join(\n process.cwd(),\n options?.configPath ?? './dist/emmett.config.js',\n );\n\n console.log('IMPORTING' + configPath);\n\n try {\n const imported = (await import(configPath)) as {\n default: Partial<EmmettPluginsConfig>;\n };\n\n if (!imported.default) {\n return new EmmettError(PluginsConfigImportError.missingDefaultExport);\n }\n\n if (!imported.default.plugins || !Array.isArray(imported.default.plugins)) {\n return new EmmettError(\n PluginsConfigImportError.missingPluginsPropertyExport,\n );\n }\n\n if (!imported.default.plugins.every(isPluginConfig)) {\n return new EmmettError(PluginsConfigImportError.wrongPluginStructure);\n }\n\n return { plugins: imported.default.plugins };\n } catch (error) {\n if (!options?.configPath) {\n console.warn('Didn`t find config file: ' + configPath, error);\n return { plugins: [] };\n }\n return new EmmettError(\n `Error: Couldn't load file:` + (error as Error).toString(),\n );\n }\n};\n\nexport const loadPlugins = async (options?: {\n pluginType?: EmmettPluginType;\n configPath?: string;\n}): Promise<EmmettPlugin[]> => {\n try {\n const pluginsConfig = await importPluginsConfig({\n configPath: options?.configPath,\n });\n\n if (pluginsConfig instanceof EmmettError) throw pluginsConfig;\n\n if (pluginsConfig.plugins.length === 0) {\n console.log(`No extensions specified in config ${options?.configPath}.`);\n return [];\n }\n\n const pluginsToLoad = filterPluginsByType(\n pluginsConfig.plugins,\n options?.pluginType,\n );\n\n const pluginsPromises = pluginsToLoad.map(async (pluginConfig) => {\n const importPath = getImportPath(pluginConfig, options?.pluginType);\n try {\n const plugin = (await import(importPath)) as { default: EmmettPlugin };\n\n console.info(`Loaded plugin: ${importPath}`);\n\n if (!plugin.default) {\n throw new Error(`Plugin: ${importPath} is missing default export`);\n }\n\n return plugin.default;\n } catch (error) {\n console.error(`Failed to load extension \"${importPath}\":`, error);\n return undefined;\n }\n });\n\n return (await Promise.all(pluginsPromises)).filter(\n (plugin) => plugin !== undefined,\n );\n } catch (error) {\n console.error(`Failed to load config ${options?.configPath}:`, error);\n return [];\n }\n};\n\nexport const registerCliPlugins = async (\n program: CliCommand,\n plugins: EmmettCliPlugin[],\n): Promise<void> => {\n const result: EmmettCliPlugin[] = [];\n\n for (const plugin of plugins) {\n const pluginName = plugin.name;\n\n if (!('registerCommands' in plugin)) {\n console.warn(`No registerCommands function found in ${pluginName}`);\n }\n await plugin.registerCommands(program as EmmettCliCommand);\n console.log(`Loaded extension: ${plugin.name}`);\n result.push(plugin);\n }\n};\n\nconst filterPluginsByType = (\n plugins: EmmettPluginConfig[],\n pluginType?: EmmettPluginType,\n): EmmettPluginConfig[] =>\n plugins.filter(\n (p) =>\n typeof p === 'string' ||\n (pluginType &&\n (p.register === undefined ||\n p.register.some((r) => r.pluginType === pluginType))),\n );\n\nconst getImportPath = (\n pluginConfig: EmmettPluginConfig,\n pluginType: EmmettPluginType | undefined,\n) => {\n if (typeof pluginConfig === 'string') {\n return pluginType ? `${pluginConfig}/${pluginType}` : pluginConfig;\n }\n\n const pluginSubpath =\n pluginConfig.register.find((r) => pluginType && r.pluginType === pluginType)\n ?.path ?? pluginType;\n\n return pluginSubpath\n ? `${pluginConfig.name}/${pluginSubpath}`\n : pluginConfig.name;\n};\n","#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option('--config <path>', 'Path to the configuration file');\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const configIndex = process.argv.indexOf('--config');\n\n const configPath =\n configIndex !== -1 && process.argv.length > configIndex + 1\n ? process.argv[configIndex + 1]\n : undefined;\n\n try {\n const plugins = await loadPlugins({\n pluginType: 'cli',\n configPath: configPath,\n });\n await registerCliPlugins(program, plugins);\n\n // Parse the CLI arguments\n program.parse(process.argv);\n } catch (err) {\n console.error(`Failed to load config from ${configPath}:`, err);\n }\n};\n\n//Initialize CLI and handle errors\ninitCLI().catch((err) => {\n console.error(`CLI initialization failed:`);\n console.error(err);\n});\n\nexport default program;\nexport * from './commandLine';\n"],"mappings":";;;;;;;;AAKA,MAAa,gBAAgB,UAAoB,CAAC,mBAAmB,KAAK;AAMxE,QAAO;;aAJL,QAAQ,SAAS,IACb,MAAM,QAAQ,KAAK,MAAM,IAAI,EAAE,GAAG,CAAC,KAAK,MAAM,CAAC,SAC/C,KAIkB;;;;AAK1B,MAAa,sBACX,YACA,oBACS;AACT,KAAI;AACF,gBAAc,YAAY,aAAa,gBAAgB,EAAE,OAAO;AAChE,UAAQ,IAAI,iCAAiC,aAAa;UACnD,OAAO;AACd,UAAQ,MAAM,sCAAsC,WAAW,GAAG;AAClE,UAAQ,MAAM,MAAM;AACpB,UAAQ,KAAK,EAAE;;;AAInB,MAAa,gBAAgB,IA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QAAQ,QACL,MACC,OAAO,MAAM,YACZ,eACE,EAAE,aAAa,UACd,EAAE,SAAS,MAAM,MAAM,EAAE,eAAe,WAAW,EAC1D;AAEH,MAAM,iBACJ,cACA,eACG;AACH,KAAI,OAAO,iBAAiB,SAC1B,QAAO,aAAa,GAAG,aAAa,GAAG,eAAe;CAGxD,MAAM,gBACJ,aAAa,SAAS,MAAM,MAAM,cAAc,EAAE,eAAe,WAAW,EACxE,QAAQ;AAEd,QAAO,gBACH,GAAG,aAAa,KAAK,GAAG,kBACxB,aAAa;;;;;ACpJnB,MAAM,UAAU,IAAI,SAAS;AAE7B,QACG,KAAK,SAAS,CACd,YAAY,sBAAsB,CAClC,OAAO,mBAAmB,iCAAiC;AAG9D,MAAM,UAAU,YAAY;CAC1B,MAAM,cAAc,QAAQ,KAAK,QAAQ,WAAW;CAEpD,MAAM,aACJ,gBAAgB,MAAM,QAAQ,KAAK,SAAS,cAAc,IACtD,QAAQ,KAAK,cAAc,KAC3B;AAEN,KAAI;AAKF,QAAM,mBAAmB,SAJT,MAAM,YAAY;GAChC,YAAY;GACA;GACb,CAAC,CACwC;AAG1C,UAAQ,MAAM,QAAQ,KAAK;UACpB,KAAK;AACZ,UAAQ,MAAM,8BAA8B,WAAW,IAAI,IAAI;;;AAKnE,SAAS,CAAC,OAAO,QAAQ;AACvB,SAAQ,MAAM,6BAA6B;AAC3C,SAAQ,MAAM,IAAI;EAClB"}
1
+ {"version":3,"file":"cli.js","names":["CliCommand"],"sources":["../src/commandLine/config.ts","../src/commandLine/plugins.ts","../src/cli.ts"],"sourcesContent":["import { Command as CliCommand } from 'commander';\n// eslint-disable-next-line no-restricted-imports\nimport { writeFileSync } from 'node:fs';\nimport { exit } from 'process';\n\nexport const sampleConfig = (plugins: string[] = ['emmett-expressjs']) => {\n const pluginsNames =\n plugins.length > 0\n ? `[\\n${plugins.map((p) => `\"${p}\"`).join(',\\n')} \\n]`\n : '[]';\n\n return `\nexport default {\n plugins: ${pluginsNames},\n};\n`;\n};\n\nexport const generateConfigFile = (\n configPath: string,\n collectionNames: string[],\n): void => {\n try {\n writeFileSync(configPath, sampleConfig(collectionNames), 'utf8');\n console.log(`Configuration file stored at: ${configPath}`);\n } catch (error) {\n console.error(`Error: Couldn't store config file: ${configPath}!`);\n console.error(error);\n process.exit(1);\n }\n};\n\nexport const configCommand = new CliCommand('config').description(\n 'Manage Pongo configuration',\n);\n\ntype SampleConfigOptions =\n | {\n plugin: string[];\n print?: boolean;\n }\n | {\n plugin: string[];\n generate?: boolean;\n file?: string;\n };\n\nconfigCommand\n .command('sample')\n .description('Generate or print sample configuration')\n .option(\n '-plg, --plugins <name>',\n 'Specify the plugin name',\n (value: string, previous: string[]) => {\n // Accumulate plugins names into an array (explicitly typing `previous` as `string[]`)\n return previous.concat([value]);\n },\n [] as string[],\n )\n .option(\n '-f, --file <path>',\n 'Path to configuration file with collection list',\n )\n .option('-g, --generate', 'Generate sample config file')\n .option('-p, --print', 'Print sample config file')\n .action((options: SampleConfigOptions) => {\n const plugins =\n options.plugin.length > 0\n ? options.plugin\n : ['@event-driven-io/emmett-expressjs'];\n\n if (!('print' in options) && !('generate' in options)) {\n console.error(\n 'Error: Please provide either:\\n--print param to print sample config or\\n--generate to generate sample config file',\n );\n exit(1);\n }\n\n if ('print' in options) {\n console.log(`${sampleConfig(plugins)}`);\n } else if ('generate' in options) {\n if (!options.file) {\n console.error(\n 'Error: You need to provide a config file through a --file',\n );\n exit(1);\n }\n\n generateConfigFile(options.file, plugins);\n }\n });\n","import type { Command as CliCommand } from 'commander';\nimport path from 'path';\nimport {\n isPluginConfig,\n type EmmettCliCommand,\n type EmmettCliPlugin,\n type EmmettPlugin,\n type EmmettPluginConfig,\n type EmmettPluginsConfig,\n type EmmettPluginType,\n} from '../config';\nimport { EmmettError } from '../errors';\nimport { sampleConfig } from './config';\n\nconst PluginsConfigImportError = {\n missingDefaultExport: `Error: Config should contain default export, e.g.\\n\\n${sampleConfig()}`,\n missingPluginsPropertyExport: `Error: Config should contain default export with plugins array, e.g.\\n\\n${sampleConfig()}`,\n wrongPluginStructure: `Error: Plugin config should be either string with plugin name or object with plugin name, e.g. { name: 'emmett-expressjs' }`,\n};\nexport const importPluginsConfig = async (options?: {\n configPath?: string | undefined;\n}): Promise<EmmettPluginsConfig | EmmettError> => {\n const configPath = path.join(\n process.cwd(),\n options?.configPath ?? './dist/emmett.config.js',\n );\n\n console.log('IMPORTING' + configPath);\n\n try {\n const imported = (await import(configPath)) as {\n default: Partial<EmmettPluginsConfig>;\n };\n\n if (!imported.default) {\n return new EmmettError(PluginsConfigImportError.missingDefaultExport);\n }\n\n if (!imported.default.plugins || !Array.isArray(imported.default.plugins)) {\n return new EmmettError(\n PluginsConfigImportError.missingPluginsPropertyExport,\n );\n }\n\n if (!imported.default.plugins.every(isPluginConfig)) {\n return new EmmettError(PluginsConfigImportError.wrongPluginStructure);\n }\n\n return { plugins: imported.default.plugins };\n } catch (error) {\n if (!options?.configPath) {\n console.warn('Didn`t find config file: ' + configPath, error);\n return { plugins: [] };\n }\n return new EmmettError(\n `Error: Couldn't load file:` + (error as Error).toString(),\n );\n }\n};\n\nexport const loadPlugins = async (options?: {\n pluginType?: EmmettPluginType;\n configPath?: string;\n}): Promise<EmmettPlugin[]> => {\n try {\n const pluginsConfig = await importPluginsConfig({\n configPath: options?.configPath,\n });\n\n if (pluginsConfig instanceof EmmettError) throw pluginsConfig;\n\n if (pluginsConfig.plugins.length === 0) {\n console.log(`No extensions specified in config ${options?.configPath}.`);\n return [];\n }\n\n const pluginsToLoad = filterPluginsByType(\n pluginsConfig.plugins,\n options?.pluginType,\n );\n\n const pluginsPromises = pluginsToLoad.map(async (pluginConfig) => {\n const importPath = getImportPath(pluginConfig, options?.pluginType);\n try {\n const plugin = (await import(importPath)) as { default: EmmettPlugin };\n\n console.info(`Loaded plugin: ${importPath}`);\n\n if (!plugin.default) {\n throw new Error(`Plugin: ${importPath} is missing default export`);\n }\n\n return plugin.default;\n } catch (error) {\n console.error(`Failed to load extension \"${importPath}\":`, error);\n return undefined;\n }\n });\n\n return (await Promise.all(pluginsPromises)).filter(\n (plugin) => plugin !== undefined,\n );\n } catch (error) {\n console.error(`Failed to load config ${options?.configPath}:`, error);\n return [];\n }\n};\n\nexport const registerCliPlugins = async (\n program: CliCommand,\n plugins: EmmettCliPlugin[],\n): Promise<void> => {\n const result: EmmettCliPlugin[] = [];\n\n for (const plugin of plugins) {\n const pluginName = plugin.name;\n\n if (!('registerCommands' in plugin)) {\n console.warn(`No registerCommands function found in ${pluginName}`);\n }\n await plugin.registerCommands(program as EmmettCliCommand);\n console.log(`Loaded extension: ${plugin.name}`);\n result.push(plugin);\n }\n};\n\nconst filterPluginsByType = (\n plugins: EmmettPluginConfig[],\n pluginType?: EmmettPluginType,\n): EmmettPluginConfig[] =>\n plugins.filter(\n (p) =>\n typeof p === 'string' ||\n (pluginType &&\n (p.register === undefined ||\n p.register.some((r) => r.pluginType === pluginType))),\n );\n\nconst getImportPath = (\n pluginConfig: EmmettPluginConfig,\n pluginType: EmmettPluginType | undefined,\n) => {\n if (typeof pluginConfig === 'string') {\n return pluginType ? `${pluginConfig}/${pluginType}` : pluginConfig;\n }\n\n const pluginSubpath =\n pluginConfig.register.find((r) => pluginType && r.pluginType === pluginType)\n ?.path ?? pluginType;\n\n return pluginSubpath\n ? `${pluginConfig.name}/${pluginSubpath}`\n : pluginConfig.name;\n};\n","#!/usr/bin/env node\nimport { Command } from 'commander';\nimport { loadPlugins, registerCliPlugins } from './commandLine';\n\nconst program = new Command();\n\nprogram\n .name('emmett')\n .description('CLI tool for Emmett')\n .option('--config <path>', 'Path to the configuration file');\n\n// Load extensions and parse CLI arguments\nconst initCLI = async () => {\n const configIndex = process.argv.indexOf('--config');\n\n const configPath =\n configIndex !== -1 && process.argv.length > configIndex + 1\n ? process.argv[configIndex + 1]\n : undefined;\n\n try {\n const plugins = await loadPlugins({\n pluginType: 'cli',\n configPath: configPath,\n });\n await registerCliPlugins(program, plugins);\n\n // Parse the CLI arguments\n program.parse(process.argv);\n } catch (err) {\n console.error(`Failed to load config from ${configPath}:`, err);\n }\n};\n\n//Initialize CLI and handle errors\ninitCLI().catch((err) => {\n console.error(`CLI initialization failed:`);\n console.error(err);\n});\n\nexport default program;\nexport * from './commandLine';\n"],"mappings":";;;;;;;;AAKA,MAAa,gBAAgB,UAAoB,CAAC,mBAAmB,KAAK;AAMxE,QAAO;;aAJL,QAAQ,SAAS,IACb,MAAM,QAAQ,KAAK,MAAM,IAAI,EAAE,GAAG,CAAC,KAAK,MAAM,CAAC,SAC/C,KAIkB;;;;AAK1B,MAAa,sBACX,YACA,oBACS;AACT,KAAI;AACF,gBAAc,YAAY,aAAa,gBAAgB,EAAE,OAAO;AAChE,UAAQ,IAAI,iCAAiC,aAAa;UACnD,OAAO;AACd,UAAQ,MAAM,sCAAsC,WAAW,GAAG;AAClE,UAAQ,MAAM,MAAM;AACpB,UAAQ,KAAK,EAAE;;;AAInB,MAAa,gBAAgB,IAAIA,QAAW,SAAS,CAAC,YACpD,6BACD;AAaD,cACG,QAAQ,SAAS,CACjB,YAAY,yCAAyC,CACrD,OACC,0BACA,4BACC,OAAe,aAAuB;AAErC,QAAO,SAAS,OAAO,CAAC,MAAM,CAAC;GAEjC,EAAE,CACH,CACA,OACC,qBACA,kDACD,CACA,OAAO,kBAAkB,8BAA8B,CACvD,OAAO,eAAe,2BAA2B,CACjD,QAAQ,YAAiC;CACxC,MAAM,UACJ,QAAQ,OAAO,SAAS,IACpB,QAAQ,SACR,CAAC,oCAAoC;AAE3C,KAAI,EAAE,WAAW,YAAY,EAAE,cAAc,UAAU;AACrD,UAAQ,MACN,oHACD;AACD,OAAK,EAAE;;AAGT,KAAI,WAAW,QACb,SAAQ,IAAI,GAAG,aAAa,QAAQ,GAAG;UAC9B,cAAc,SAAS;AAChC,MAAI,CAAC,QAAQ,MAAM;AACjB,WAAQ,MACN,4DACD;AACD,QAAK,EAAE;;AAGT,qBAAmB,QAAQ,MAAM,QAAQ;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AI;AAKF,QAAM,mBAAmB,SAAS,MAJZ,YAAY;GAChC,YAAY;GACA;GACb,CAAC,CACwC;AAG1C,UAAQ,MAAM,QAAQ,KAAK;UACpB,KAAK;AACZ,UAAQ,MAAM,8BAA8B,WAAW,IAAI,IAAI;;;AAKnE,SAAS,CAAC,OAAO,QAAQ;AACvB,SAAQ,MAAM,6BAA6B;AAC3C,SAAQ,MAAM,IAAI;EAClB"}
package/dist/index.cjs CHANGED
@@ -3,6 +3,7 @@ const require_plugins = require('./plugins-DB9xe8AV.cjs');
3
3
  let uuid = require("uuid");
4
4
  let async_retry = require("async-retry");
5
5
  async_retry = require_plugins.__toESM(async_retry, 1);
6
+ let _event_driven_io_almanac = require("@event-driven-io/almanac");
6
7
 
7
8
  //#region src/eventStore/afterCommit/afterEventStoreCommitHandler.ts
8
9
  async function tryPublishMessagesAfterCommit(messages, options, context) {
@@ -1374,9 +1375,12 @@ const assertNotDeepEqual = (actual, expected, message) => {
1374
1375
  const assertThat = (item) => {
1375
1376
  return { isEqualTo: (other) => assertTrue(deepEquals(item, other)) };
1376
1377
  };
1377
- const assertDefined = (value, message) => {
1378
- assertOk(value, message instanceof Error ? message.message : message);
1379
- };
1378
+ function assertDefined(value, message) {
1379
+ if (value === void 0 || value === null) throw new AssertionError((message instanceof Error ? message.message : message) ?? "Value is not defined");
1380
+ }
1381
+ function assertUndefined(value, message) {
1382
+ if (value !== void 0 && value !== null) throw new AssertionError((message instanceof Error ? message.message : message) ?? "Value is defined");
1383
+ }
1380
1384
  function assertFalse(condition, message) {
1381
1385
  if (condition !== false) throw new AssertionError(message ?? `Condition is true`);
1382
1386
  }
@@ -1855,6 +1859,247 @@ const getInMemoryEventStore = (eventStoreOptions) => {
1855
1859
  return eventStore;
1856
1860
  };
1857
1861
 
1862
+ //#endregion
1863
+ //#region src/observability/attributes.ts
1864
+ const EmmettAttributes = {
1865
+ scope: { type: "emmett.scope.type" },
1866
+ command: {
1867
+ type: "emmett.command.type",
1868
+ status: "emmett.command.status",
1869
+ eventCount: "emmett.command.event_count",
1870
+ eventTypes: "emmett.command.event_types"
1871
+ },
1872
+ stream: {
1873
+ name: "emmett.stream.name",
1874
+ versionBefore: "emmett.stream.version.before",
1875
+ versionAfter: "emmett.stream.version.after"
1876
+ },
1877
+ eventStore: {
1878
+ operation: "emmett.eventstore.operation",
1879
+ read: {
1880
+ eventCount: "emmett.eventstore.read.event_count",
1881
+ eventTypes: "emmett.eventstore.read.event_types",
1882
+ status: "emmett.eventstore.read.status"
1883
+ },
1884
+ append: {
1885
+ batchSize: "emmett.eventstore.append.batch_size",
1886
+ status: "emmett.eventstore.append.status"
1887
+ }
1888
+ },
1889
+ event: { type: "emmett.event.type" },
1890
+ processor: {
1891
+ id: "emmett.processor.id",
1892
+ type: "emmett.processor.type",
1893
+ status: "emmett.processor.status",
1894
+ batchSize: "emmett.processor.batch_size",
1895
+ eventTypes: "emmett.processor.event_types",
1896
+ checkpointBefore: "emmett.processor.checkpoint.before",
1897
+ checkpointAfter: "emmett.processor.checkpoint.after",
1898
+ lagEvents: "emmett.processor.lag_events"
1899
+ },
1900
+ workflow: {
1901
+ id: "emmett.workflow.id",
1902
+ type: "emmett.workflow.type",
1903
+ inputType: "emmett.workflow.input.type",
1904
+ outputs: "emmett.workflow.outputs",
1905
+ outputsCount: "emmett.workflow.outputs.count",
1906
+ streamPosition: "emmett.workflow.stream_position",
1907
+ stateRebuildEventCount: "emmett.workflow.state_rebuild.event_count"
1908
+ },
1909
+ consumer: {
1910
+ batchSize: "emmett.consumer.batch_size",
1911
+ processorCount: "emmett.consumer.processor_count",
1912
+ delivery: { processorId: "emmett.consumer.delivery.processor_id" }
1913
+ }
1914
+ };
1915
+ const EmmettMetrics = {
1916
+ command: { handlingDuration: "emmett.command.handling.duration" },
1917
+ event: {
1918
+ appendingCount: "emmett.event.appending.count",
1919
+ readingCount: "emmett.event.reading.count"
1920
+ },
1921
+ stream: {
1922
+ readingDuration: "emmett.stream.reading.duration",
1923
+ readingSize: "emmett.stream.reading.size",
1924
+ appendingDuration: "emmett.stream.appending.duration",
1925
+ appendingSize: "emmett.stream.appending.size"
1926
+ },
1927
+ processor: {
1928
+ processingDuration: "emmett.processor.processing.duration",
1929
+ lagEvents: "emmett.processor.lag_events"
1930
+ },
1931
+ workflow: { processingDuration: "emmett.workflow.processing.duration" },
1932
+ consumer: {
1933
+ pollDuration: "emmett.consumer.poll.duration",
1934
+ deliveryDuration: "emmett.consumer.delivery.duration"
1935
+ }
1936
+ };
1937
+ const ScopeTypes = {
1938
+ command: "command",
1939
+ processor: "processor",
1940
+ reactor: "reactor",
1941
+ projector: "projector",
1942
+ workflow: "workflow",
1943
+ consumer: "consumer"
1944
+ };
1945
+ const MessagingSystemName = "emmett";
1946
+
1947
+ //#endregion
1948
+ //#region src/observability/options.ts
1949
+ const resolveCommandObservability = (options, parent) => ({
1950
+ tracer: options?.observability?.tracer ?? parent?.observability?.tracer ?? (0, _event_driven_io_almanac.noopTracer)(),
1951
+ meter: options?.observability?.meter ?? parent?.observability?.meter ?? (0, _event_driven_io_almanac.noopMeter)(),
1952
+ attributeTarget: options?.observability?.attributeTarget ?? parent?.observability?.attributeTarget ?? "both",
1953
+ includeMessagePayloads: options?.observability?.includeMessagePayloads ?? parent?.observability?.includeMessagePayloads ?? false
1954
+ });
1955
+
1956
+ //#endregion
1957
+ //#region src/observability/tracer.ts
1958
+ const tracer = () => {};
1959
+ const LogLevel = {
1960
+ DISABLED: "DISABLED",
1961
+ INFO: "INFO",
1962
+ LOG: "LOG",
1963
+ WARN: "WARN",
1964
+ ERROR: "ERROR"
1965
+ };
1966
+ const getEnvVariable = (name) => {
1967
+ try {
1968
+ if (typeof process !== "undefined" && process.env) return process.env[name];
1969
+ return;
1970
+ } catch {
1971
+ return;
1972
+ }
1973
+ };
1974
+ const shouldLog = (logLevel) => {
1975
+ const definedLogLevel = getEnvVariable("DUMBO_LOG_LEVEL") ?? LogLevel.ERROR;
1976
+ if (definedLogLevel === LogLevel.ERROR && logLevel === LogLevel.ERROR) return true;
1977
+ if (definedLogLevel === LogLevel.WARN && [LogLevel.ERROR, LogLevel.WARN].includes(logLevel)) return true;
1978
+ if (definedLogLevel === LogLevel.LOG && [
1979
+ LogLevel.ERROR,
1980
+ LogLevel.WARN,
1981
+ LogLevel.LOG
1982
+ ].includes(logLevel)) return true;
1983
+ if (definedLogLevel === LogLevel.INFO && [
1984
+ LogLevel.ERROR,
1985
+ LogLevel.WARN,
1986
+ LogLevel.LOG,
1987
+ LogLevel.INFO
1988
+ ].includes(logLevel)) return true;
1989
+ return false;
1990
+ };
1991
+ const nulloTraceEventRecorder = () => {};
1992
+ const getTraceEventFormatter = (logStyle, serializer) => (event) => {
1993
+ serializer = serializer ?? JSONSerializer.from();
1994
+ switch (logStyle) {
1995
+ case "RAW": return serializer.serialize(event);
1996
+ case "PRETTY": return serializer.serialize(event);
1997
+ }
1998
+ };
1999
+ const getTraceEventRecorder = (logLevel, logStyle) => {
2000
+ const format = getTraceEventFormatter(logStyle);
2001
+ switch (logLevel) {
2002
+ case "DISABLED": return nulloTraceEventRecorder;
2003
+ case "INFO": return (event) => console.info(format(event));
2004
+ case "LOG": return (event) => console.log(format(event));
2005
+ case "WARN": return (event) => console.warn(format(event));
2006
+ case "ERROR": return (event) => console.error(format(event));
2007
+ }
2008
+ };
2009
+ const recordTraceEvent = (logLevel, eventName, attributes) => {
2010
+ if (!shouldLog(LogLevel.LOG)) return;
2011
+ const event = {
2012
+ name: eventName,
2013
+ timestamp: (/* @__PURE__ */ new Date()).getTime(),
2014
+ ...attributes
2015
+ };
2016
+ getTraceEventRecorder(logLevel, getEnvVariable("DUMBO_LOG_STYLE") ?? "RAW")(event);
2017
+ };
2018
+ tracer.info = (eventName, attributes) => recordTraceEvent(LogLevel.INFO, eventName, attributes);
2019
+ tracer.warn = (eventName, attributes) => recordTraceEvent(LogLevel.WARN, eventName, attributes);
2020
+ tracer.log = (eventName, attributes) => recordTraceEvent(LogLevel.LOG, eventName, attributes);
2021
+ tracer.error = (eventName, attributes) => recordTraceEvent(LogLevel.ERROR, eventName, attributes);
2022
+
2023
+ //#endregion
2024
+ //#region src/commandHandling/observability/commandHandlerCollector.ts
2025
+ const commandHandlerCollector = (observability) => {
2026
+ const { startScope } = (0, _event_driven_io_almanac.ObservabilityScope)({
2027
+ ...observability,
2028
+ attributePrefix: "emmett"
2029
+ });
2030
+ const A = EmmettAttributes;
2031
+ const M = _event_driven_io_almanac.MessagingAttributes;
2032
+ const commandHandlingDuration = observability.meter.histogram(EmmettMetrics.command.handlingDuration);
2033
+ const eventAppendingCount = observability.meter.counter(EmmettMetrics.event.appendingCount);
2034
+ return {
2035
+ startScope: (context, fn) => {
2036
+ const start = Date.now();
2037
+ return startScope("command.handle", async (scope) => {
2038
+ scope.setAttributes({
2039
+ [A.scope.type]: ScopeTypes.command,
2040
+ [M.system]: MessagingSystemName,
2041
+ [M.destination.name]: context.streamName,
2042
+ ...context.commandType ? { [A.command.type]: context.commandType } : {},
2043
+ ...context.correlationId ? { [M.message.correlationId]: context.correlationId } : {},
2044
+ ...context.causationId ? { [M.message.causationId]: context.causationId } : {}
2045
+ });
2046
+ let status = "success";
2047
+ try {
2048
+ const result = await fn(scope);
2049
+ status = "success";
2050
+ scope.setAttributes({
2051
+ [A.command.status]: "success",
2052
+ error: false
2053
+ });
2054
+ return result;
2055
+ } catch (err) {
2056
+ status = "failure";
2057
+ scope.setAttributes({
2058
+ [A.command.status]: "failure",
2059
+ error: true,
2060
+ "exception.message": err instanceof Error ? err.message : String(err),
2061
+ "exception.type": err instanceof Error ? err.constructor.name : "unknown"
2062
+ });
2063
+ scope.recordException(err instanceof Error ? err : new Error(String(err)));
2064
+ throw err;
2065
+ } finally {
2066
+ commandHandlingDuration.record(Date.now() - start, {
2067
+ [A.command.status]: status,
2068
+ ...typeof context.commandType === "string" ? { [A.command.type]: context.commandType } : {}
2069
+ });
2070
+ }
2071
+ }, {
2072
+ parent: context.traceId && context.spanId ? {
2073
+ traceId: context.traceId,
2074
+ spanId: context.spanId
2075
+ } : void 0,
2076
+ attributes: {
2077
+ [A.scope.type]: ScopeTypes.command,
2078
+ [A.stream.name]: context.streamName,
2079
+ ...context.commandType ? { [A.command.type]: context.commandType } : {},
2080
+ ...context.correlationId ? { [M.message.correlationId]: context.correlationId } : {},
2081
+ ...context.causationId ? { [M.message.causationId]: context.causationId } : {}
2082
+ }
2083
+ });
2084
+ },
2085
+ recordEvents: (scope, events, status) => {
2086
+ scope.setAttributes({
2087
+ [A.command.eventCount]: events.length,
2088
+ [A.command.eventTypes]: events.map((e) => e.type),
2089
+ [M.batch.messageCount]: events.length,
2090
+ [A.command.status]: status
2091
+ });
2092
+ for (const event of events) eventAppendingCount.add(1, { [A.event.type]: event.type });
2093
+ },
2094
+ recordVersions: (scope, before, after) => {
2095
+ scope.setAttributes({
2096
+ [A.stream.versionBefore]: Number(before),
2097
+ [A.stream.versionAfter]: Number(after)
2098
+ });
2099
+ }
2100
+ };
2101
+ };
2102
+
1858
2103
  //#endregion
1859
2104
  //#region src/commandHandling/handleCommand.ts
1860
2105
  const CommandHandlerStreamVersionConflictRetryOptions = {
@@ -1863,6 +2108,76 @@ const CommandHandlerStreamVersionConflictRetryOptions = {
1863
2108
  factor: 1.5,
1864
2109
  shouldRetryError: isExpectedVersionConflictError
1865
2110
  };
2111
+ const CommandHandler = (options) => async (store, id, handle, handleOptions) => {
2112
+ const collector = commandHandlerCollector(resolveCommandObservability(options));
2113
+ const streamName = (options.mapToStreamId ?? ((id) => id))(id);
2114
+ const commandType = handleOptions?.commandType ?? options.commandType ?? options.name ?? handlerNames(handle);
2115
+ const correlationId = handleOptions?.observability?.correlationId ?? (0, uuid.v7)();
2116
+ const causationId = handleOptions?.observability?.causationId;
2117
+ return asyncRetry(() => collector.startScope({
2118
+ streamName,
2119
+ commandType,
2120
+ correlationId,
2121
+ causationId,
2122
+ traceId: handleOptions?.observability?.traceId,
2123
+ spanId: handleOptions?.observability?.spanId
2124
+ }, async (scope) => {
2125
+ return await withSession$1(store, async ({ eventStore }) => {
2126
+ const { evolve, initialState } = options;
2127
+ const aggregationResult = await eventStore.aggregateStream(streamName, {
2128
+ evolve,
2129
+ initialState,
2130
+ read: {
2131
+ schema: options.schema,
2132
+ ...handleOptions,
2133
+ serialization: options.serialization,
2134
+ expectedStreamVersion: handleOptions?.expectedStreamVersion ?? "NO_CONCURRENCY_CHECK"
2135
+ }
2136
+ });
2137
+ const { currentStreamVersion, streamExists: _streamExists, ...restOfAggregationResult } = aggregationResult;
2138
+ let state = aggregationResult.state;
2139
+ const handlers = Array.isArray(handle) ? handle : [handle];
2140
+ let eventsToAppend = [];
2141
+ for (const handler of handlers) {
2142
+ const result = await handler(state);
2143
+ const newEvents = Array.isArray(result) ? result : [result];
2144
+ if (newEvents.length > 0) state = newEvents.reduce(evolve, state);
2145
+ eventsToAppend = [...eventsToAppend, ...newEvents];
2146
+ }
2147
+ if (eventsToAppend.length === 0) {
2148
+ collector.recordVersions(scope, currentStreamVersion, currentStreamVersion);
2149
+ return {
2150
+ ...restOfAggregationResult,
2151
+ newEvents: [],
2152
+ newState: state,
2153
+ nextExpectedStreamVersion: currentStreamVersion,
2154
+ createdNewStream: false
2155
+ };
2156
+ }
2157
+ const expectedStreamVersion = handleOptions?.expectedStreamVersion ?? (aggregationResult.streamExists ? currentStreamVersion : "STREAM_DOES_NOT_EXIST");
2158
+ const { traceId, spanId } = scope.spanContext();
2159
+ const { observability: _appendObservability, ...handleOptionsForAppend } = handleOptions ?? {};
2160
+ const appendResult = await eventStore.appendToStream(streamName, eventsToAppend, {
2161
+ ...handleOptionsForAppend,
2162
+ expectedStreamVersion,
2163
+ correlationId,
2164
+ ...causationId ? { causationId } : {},
2165
+ traceId,
2166
+ spanId
2167
+ });
2168
+ collector.recordEvents(scope, eventsToAppend, "success");
2169
+ collector.recordVersions(scope, currentStreamVersion, appendResult.nextExpectedStreamVersion);
2170
+ return {
2171
+ ...appendResult,
2172
+ newEvents: eventsToAppend,
2173
+ newState: state
2174
+ };
2175
+ });
2176
+ }), fromCommandHandlerRetryOptions(handleOptions && "retry" in handleOptions ? handleOptions.retry : options.retry));
2177
+ };
2178
+ const withSession$1 = (eventStore, callback) => {
2179
+ return (canCreateEventStoreSession(eventStore) ? eventStore : nulloSessionFactory(eventStore)).withSession(callback);
2180
+ };
1866
2181
  const fromCommandHandlerRetryOptions = (retryOptions) => {
1867
2182
  if (retryOptions === void 0) return NoRetries;
1868
2183
  if ("onVersionConflict" in retryOptions) if (typeof retryOptions.onVersionConflict === "boolean") return CommandHandlerStreamVersionConflictRetryOptions;
@@ -1873,58 +2188,24 @@ const fromCommandHandlerRetryOptions = (retryOptions) => {
1873
2188
  else return retryOptions.onVersionConflict;
1874
2189
  return retryOptions;
1875
2190
  };
1876
- const CommandHandler = (options) => async (store, id, handle, handleOptions) => asyncRetry(async () => {
1877
- return await withSession$1(store, async ({ eventStore }) => {
1878
- const { evolve, initialState } = options;
1879
- const streamName = (options.mapToStreamId ?? ((id) => id))(id);
1880
- const aggregationResult = await eventStore.aggregateStream(streamName, {
1881
- evolve,
1882
- initialState,
1883
- read: {
1884
- schema: options.schema,
1885
- ...handleOptions,
1886
- serialization: options.serialization,
1887
- expectedStreamVersion: handleOptions?.expectedStreamVersion ?? "NO_CONCURRENCY_CHECK"
1888
- }
1889
- });
1890
- const { currentStreamVersion, streamExists: _streamExists, ...restOfAggregationResult } = aggregationResult;
1891
- let state = aggregationResult.state;
1892
- const handlers = Array.isArray(handle) ? handle : [handle];
1893
- let eventsToAppend = [];
1894
- for (const handler of handlers) {
1895
- const result = await handler(state);
1896
- const newEvents = Array.isArray(result) ? result : [result];
1897
- if (newEvents.length > 0) state = newEvents.reduce(evolve, state);
1898
- eventsToAppend = [...eventsToAppend, ...newEvents];
1899
- }
1900
- if (eventsToAppend.length === 0) return {
1901
- ...restOfAggregationResult,
1902
- newEvents: [],
1903
- newState: state,
1904
- nextExpectedStreamVersion: currentStreamVersion,
1905
- createdNewStream: false
1906
- };
1907
- const expectedStreamVersion = handleOptions?.expectedStreamVersion ?? (aggregationResult.streamExists ? currentStreamVersion : "STREAM_DOES_NOT_EXIST");
1908
- return {
1909
- ...await eventStore.appendToStream(streamName, eventsToAppend, {
1910
- ...handleOptions,
1911
- expectedStreamVersion
1912
- }),
1913
- newEvents: eventsToAppend,
1914
- newState: state
1915
- };
1916
- });
1917
- }, fromCommandHandlerRetryOptions(handleOptions && "retry" in handleOptions ? handleOptions.retry : options.retry));
1918
- const withSession$1 = (eventStore, callback) => {
1919
- return (canCreateEventStoreSession(eventStore) ? eventStore : nulloSessionFactory(eventStore)).withSession(callback);
2191
+ const handlerNames = (handle) => {
2192
+ if (Array.isArray(handle)) {
2193
+ const names = handle.map((h) => h.name).filter((n) => !!n);
2194
+ return names.length > 0 ? names : void 0;
2195
+ }
2196
+ return handle.name || void 0;
1920
2197
  };
1921
2198
 
1922
2199
  //#endregion
1923
2200
  //#region src/commandHandling/handleCommandWithDecider.ts
2201
+ const commandTypesOf = (commands) => Array.isArray(commands) ? commands.map((c) => c.type) : commands.type;
1924
2202
  const DeciderCommandHandler = (options) => async (eventStore, id, commands, handleOptions) => {
1925
2203
  const { decide, ...rest } = options;
1926
2204
  const deciders = (Array.isArray(commands) ? commands : [commands]).map((command) => (state) => decide(command, state));
1927
- return CommandHandler(rest)(eventStore, id, deciders, handleOptions);
2205
+ return CommandHandler(rest)(eventStore, id, deciders, {
2206
+ commandType: commandTypesOf(commands),
2207
+ ...handleOptions
2208
+ });
1928
2209
  };
1929
2210
 
1930
2211
  //#endregion
@@ -2263,6 +2544,7 @@ exports.assertThatArray = assertThatArray;
2263
2544
  exports.assertThrows = assertThrows;
2264
2545
  exports.assertThrowsAsync = assertThrowsAsync;
2265
2546
  exports.assertTrue = assertTrue;
2547
+ exports.assertUndefined = assertUndefined;
2266
2548
  exports.assertUnsignedBigInt = require_plugins.assertUnsignedBigInt;
2267
2549
  exports.asyncAwaiter = asyncAwaiter;
2268
2550
  exports.asyncProjections = asyncProjections;