@kidd-cli/core 0.1.2 → 0.3.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.
Files changed (54) hide show
  1. package/dist/{config-BvGapuFJ.js → config-D8e5qxLp.js} +63 -80
  2. package/dist/config-D8e5qxLp.js.map +1 -0
  3. package/dist/{create-store-BQUX0tAn.js → create-store-OHdkm_Yt.js} +33 -6
  4. package/dist/create-store-OHdkm_Yt.js.map +1 -0
  5. package/dist/index.d.ts +50 -6
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +90 -54
  8. package/dist/index.js.map +1 -1
  9. package/dist/lib/config.js +3 -4
  10. package/dist/lib/logger.d.ts +1 -1
  11. package/dist/lib/logger.js +1 -2
  12. package/dist/lib/logger.js.map +1 -1
  13. package/dist/lib/project.d.ts +1 -1
  14. package/dist/lib/project.d.ts.map +1 -1
  15. package/dist/lib/project.js +2 -3
  16. package/dist/lib/store.d.ts +2 -1
  17. package/dist/lib/store.d.ts.map +1 -1
  18. package/dist/lib/store.js +3 -4
  19. package/dist/{logger-BkQQej8h.d.ts → logger-9j49T5da.d.ts} +1 -1
  20. package/dist/{logger-BkQQej8h.d.ts.map → logger-9j49T5da.d.ts.map} +1 -1
  21. package/dist/middleware/auth.d.ts +250 -13
  22. package/dist/middleware/auth.d.ts.map +1 -1
  23. package/dist/middleware/auth.js +1008 -428
  24. package/dist/middleware/auth.js.map +1 -1
  25. package/dist/middleware/http.d.ts +10 -16
  26. package/dist/middleware/http.d.ts.map +1 -1
  27. package/dist/middleware/http.js +53 -94
  28. package/dist/middleware/http.js.map +1 -1
  29. package/dist/{middleware-D3psyhYo.js → middleware-BWnPSRWR.js} +14 -5
  30. package/dist/{middleware-D3psyhYo.js.map → middleware-BWnPSRWR.js.map} +1 -1
  31. package/dist/{project-NPtYX2ZX.js → project-D0g84bZY.js} +22 -23
  32. package/dist/project-D0g84bZY.js.map +1 -0
  33. package/dist/{types-kjpRau0U.d.ts → types-CTvrsrnD.d.ts} +79 -14
  34. package/dist/types-CTvrsrnD.d.ts.map +1 -0
  35. package/dist/{types-Cz9h927W.d.ts → types-D-BxshYM.d.ts} +1 -1
  36. package/dist/{types-Cz9h927W.d.ts.map → types-D-BxshYM.d.ts.map} +1 -1
  37. package/package.json +9 -16
  38. package/dist/config-BvGapuFJ.js.map +0 -1
  39. package/dist/create-store-BQUX0tAn.js.map +0 -1
  40. package/dist/lib/output.d.ts +0 -62
  41. package/dist/lib/output.d.ts.map +0 -1
  42. package/dist/lib/output.js +0 -276
  43. package/dist/lib/output.js.map +0 -1
  44. package/dist/lib/prompts.d.ts +0 -24
  45. package/dist/lib/prompts.d.ts.map +0 -1
  46. package/dist/lib/prompts.js +0 -3
  47. package/dist/project-NPtYX2ZX.js.map +0 -1
  48. package/dist/prompts-lLfUSgd6.js +0 -63
  49. package/dist/prompts-lLfUSgd6.js.map +0 -1
  50. package/dist/types-CqKJhsYk.d.ts +0 -135
  51. package/dist/types-CqKJhsYk.d.ts.map +0 -1
  52. package/dist/types-DFtYg5uZ.d.ts +0 -26
  53. package/dist/types-DFtYg5uZ.d.ts.map +0 -1
  54. package/dist/types-kjpRau0U.d.ts.map +0 -1
@@ -1,27 +1,18 @@
1
- import { i as findProjectRoot } from "./project-NPtYX2ZX.js";
1
+ import { i as findProjectRoot } from "./project-D0g84bZY.js";
2
2
  import { dirname, extname, join } from "node:path";
3
3
  import { attempt, attemptAsync, err, match } from "@kidd-cli/utils/fp";
4
4
  import { jsonParse, jsonStringify } from "@kidd-cli/utils/json";
5
- import { access, mkdir, readFile, writeFile } from "node:fs/promises";
5
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
6
6
  import { formatZodIssues } from "@kidd-cli/utils/validate";
7
+ import { fileExists } from "@kidd-cli/utils/fs";
7
8
  import { parse, printParseErrorCode } from "jsonc-parser";
8
9
  import { parse as parse$1, stringify } from "yaml";
9
-
10
- //#region src/utils/constants.ts
11
- /**
12
- * Default process exit code for error conditions.
13
- */
14
- const DEFAULT_EXIT_CODE = 1;
15
-
16
- //#endregion
17
10
  //#region src/lib/config/constants.ts
18
- const EMPTY_LENGTH = 0;
19
11
  const CONFIG_EXTENSIONS = [
20
12
  ".jsonc",
21
13
  ".json",
22
14
  ".yaml"
23
15
  ];
24
-
25
16
  //#endregion
26
17
  //#region src/lib/config/find.ts
27
18
  /**
@@ -37,33 +28,6 @@ function getConfigFileNames(name) {
37
28
  return CONFIG_EXTENSIONS.map((ext) => `.${name}${ext}`);
38
29
  }
39
30
  /**
40
- * Check whether a file exists at the given path.
41
- *
42
- * @param filePath - The absolute file path to check.
43
- * @returns True when the file exists and is accessible.
44
- */
45
- async function fileExists(filePath) {
46
- const [error] = await attemptAsync(() => access(filePath));
47
- return !error;
48
- }
49
- /**
50
- * Search a single directory for the first matching config file name.
51
- *
52
- * Checks each candidate file name in order and returns the path of the first
53
- * one that exists on disk.
54
- *
55
- * @param dir - The directory to search in.
56
- * @param fileNames - Candidate config file names to look for.
57
- * @returns The full path to the first matching config file, or null if none found.
58
- */
59
- async function findConfigFile(dir, fileNames) {
60
- return (await Promise.all(fileNames.map(async (fileName) => {
61
- const filePath = join(dir, fileName);
62
- if (await fileExists(filePath)) return filePath;
63
- return null;
64
- }))).find((result) => result !== null) ?? null;
65
- }
66
- /**
67
31
  * Search for a config file across multiple directories.
68
32
  *
69
33
  * Searches in order: explicit search paths, the current working directory,
@@ -88,7 +52,24 @@ async function findConfig(options) {
88
52
  }
89
53
  return null;
90
54
  }
91
-
55
+ /**
56
+ * Search a single directory for the first matching config file name.
57
+ *
58
+ * Checks each candidate file name in order and returns the path of the first
59
+ * one that exists on disk.
60
+ *
61
+ * @param dir - The directory to search in.
62
+ * @param fileNames - Candidate config file names to look for.
63
+ * @returns The full path to the first matching config file, or null if none found.
64
+ * @private
65
+ */
66
+ async function findConfigFile(dir, fileNames) {
67
+ return (await Promise.all(fileNames.map(async (fileName) => {
68
+ const filePath = join(dir, fileName);
69
+ if (await fileExists(filePath)) return filePath;
70
+ return null;
71
+ }))).find((result) => result !== null) ?? null;
72
+ }
92
73
  //#endregion
93
74
  //#region src/lib/config/parse.ts
94
75
  /**
@@ -101,11 +82,47 @@ function getFormat(filePath) {
101
82
  return match(extname(filePath)).with(".jsonc", () => "jsonc").with(".yaml", () => "yaml").otherwise(() => "json");
102
83
  }
103
84
  /**
85
+ * Parse config file content using the appropriate parser for the given format.
86
+ *
87
+ * @param options - Parse content options.
88
+ * @returns A ConfigOperationResult with the parsed data or an error.
89
+ */
90
+ function parseContent(options) {
91
+ const { content, filePath, format } = options;
92
+ return match(format).with("json", () => parseJson(content, filePath)).with("jsonc", () => parseJsoncContent(content, filePath)).with("yaml", () => parseYamlContent(content, filePath)).exhaustive();
93
+ }
94
+ /**
95
+ * Serialize data to a string in the specified config format.
96
+ *
97
+ * @param data - The data to serialize.
98
+ * @param format - The target config format.
99
+ * @returns The serialized string representation.
100
+ */
101
+ function serializeContent(data, format) {
102
+ return match(format).with("json", () => {
103
+ const [, json] = jsonStringify(data, { pretty: true });
104
+ return `${json}\n`;
105
+ }).with("jsonc", () => {
106
+ const [, json] = jsonStringify(data, { pretty: true });
107
+ return `${json}\n`;
108
+ }).with("yaml", () => stringify(data)).exhaustive();
109
+ }
110
+ /**
111
+ * Get the file extension string for a given config format.
112
+ *
113
+ * @param format - The config format.
114
+ * @returns The file extension including the leading dot (e.g. '.json').
115
+ */
116
+ function getExtension(format) {
117
+ return match(format).with("json", () => ".json").with("jsonc", () => ".jsonc").with("yaml", () => ".yaml").exhaustive();
118
+ }
119
+ /**
104
120
  * Parse a JSON string and return the result as a ConfigOperationResult.
105
121
  *
106
122
  * @param content - The raw JSON string to parse.
107
123
  * @param filePath - The file path used in error messages.
108
124
  * @returns A ConfigOperationResult with the parsed data or a parse error.
125
+ * @private
109
126
  */
110
127
  function parseJson(content, filePath) {
111
128
  const [error, result] = jsonParse(content);
@@ -118,6 +135,7 @@ function parseJson(content, filePath) {
118
135
  * @param content - The raw JSONC string to parse.
119
136
  * @param filePath - The file path used in error messages.
120
137
  * @returns A ConfigOperationResult with the parsed data or a parse error.
138
+ * @private
121
139
  */
122
140
  function parseJsoncContent(content, filePath) {
123
141
  const errors = [];
@@ -125,7 +143,7 @@ function parseJsoncContent(content, filePath) {
125
143
  allowEmptyContent: false,
126
144
  allowTrailingComma: true
127
145
  });
128
- if (errors.length > EMPTY_LENGTH) return err(`Failed to parse JSONC in ${filePath}:\n${errors.map((parseError) => ` - ${printParseErrorCode(parseError.error)} at offset ${parseError.offset}`).join("\n")}`);
146
+ if (errors.length > 0) return err(`Failed to parse JSONC in ${filePath}:\n${errors.map((parseError) => ` - ${printParseErrorCode(parseError.error)} at offset ${parseError.offset}`).join("\n")}`);
129
147
  return [null, result];
130
148
  }
131
149
  /**
@@ -134,48 +152,13 @@ function parseJsoncContent(content, filePath) {
134
152
  * @param content - The raw YAML string to parse.
135
153
  * @param filePath - The file path used in error messages.
136
154
  * @returns A ConfigOperationResult with the parsed data or a parse error.
155
+ * @private
137
156
  */
138
157
  function parseYamlContent(content, filePath) {
139
158
  const [error, result] = attempt(() => parse$1(content));
140
159
  if (error) return err(`Failed to parse YAML in ${filePath}: ${String(error)}`);
141
160
  return [null, result];
142
161
  }
143
- /**
144
- * Parse config file content using the appropriate parser for the given format.
145
- *
146
- * @param options - Parse content options.
147
- * @returns A ConfigOperationResult with the parsed data or an error.
148
- */
149
- function parseContent(options) {
150
- const { content, filePath, format } = options;
151
- return match(format).with("json", () => parseJson(content, filePath)).with("jsonc", () => parseJsoncContent(content, filePath)).with("yaml", () => parseYamlContent(content, filePath)).exhaustive();
152
- }
153
- /**
154
- * Serialize data to a string in the specified config format.
155
- *
156
- * @param data - The data to serialize.
157
- * @param format - The target config format.
158
- * @returns The serialized string representation.
159
- */
160
- function serializeContent(data, format) {
161
- return match(format).with("json", () => {
162
- const [, json] = jsonStringify(data, { pretty: true });
163
- return `${json}\n`;
164
- }).with("jsonc", () => {
165
- const [, json] = jsonStringify(data, { pretty: true });
166
- return `${json}\n`;
167
- }).with("yaml", () => stringify(data)).exhaustive();
168
- }
169
- /**
170
- * Get the file extension string for a given config format.
171
- *
172
- * @param format - The config format.
173
- * @returns The file extension including the leading dot (e.g. '.json').
174
- */
175
- function getExtension(format) {
176
- return match(format).with("json", () => ".json").with("jsonc", () => ".jsonc").with("yaml", () => ".yaml").exhaustive();
177
- }
178
-
179
162
  //#endregion
180
163
  //#region src/lib/config/create-config.ts
181
164
  /**
@@ -276,7 +259,7 @@ function resolveReadErrorDetail(readError) {
276
259
  if (readError) return String(readError);
277
260
  return "empty file";
278
261
  }
279
-
280
262
  //#endregion
281
- export { DEFAULT_EXIT_CODE as n, createConfigClient as t };
282
- //# sourceMappingURL=config-BvGapuFJ.js.map
263
+ export { createConfigClient as t };
264
+
265
+ //# sourceMappingURL=config-D8e5qxLp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config-D8e5qxLp.js","names":["stringifyYaml","parseJsonc","parseYaml"],"sources":["../src/lib/config/constants.ts","../src/lib/config/find.ts","../src/lib/config/parse.ts","../src/lib/config/create-config.ts"],"sourcesContent":["/**\n * Supported configuration file formats.\n */\nexport type ConfigFormat = 'json' | 'jsonc' | 'yaml'\n\nexport { JSON_INDENT } from '@/utils/constants.js'\nexport const EMPTY_LENGTH = 0\nexport const CONFIG_EXTENSIONS = ['.jsonc', '.json', '.yaml'] as const\n","import { join } from 'node:path'\n\nimport { fileExists } from '@kidd-cli/utils/fs'\n\nimport { findProjectRoot } from '@/lib/project/index.js'\n\nimport { CONFIG_EXTENSIONS } from './constants.js'\n\n/**\n * Generate the list of config file names to search for based on the CLI name.\n *\n * Produces names like `.myapp.jsonc`, `.myapp.json`, `.myapp.yaml` from the\n * supported extension list.\n *\n * @param name - The CLI name used to derive config file names.\n * @returns An array of config file names to search for.\n */\nexport function getConfigFileNames(name: string): string[] {\n return CONFIG_EXTENSIONS.map((ext) => `.${name}${ext}`)\n}\n\n/**\n * Search for a config file across multiple directories.\n *\n * Searches in order: explicit search paths, the current working directory,\n * and the project root (if different from cwd). Returns the path of the\n * first matching file found.\n *\n * @param options - Search options including cwd, file names, and optional search paths.\n * @returns The full path to the config file, or null if not found.\n */\nexport async function findConfig(options: {\n cwd: string\n fileNames: string[]\n searchPaths?: string[]\n}): Promise<string | null> {\n const { fileNames, cwd, searchPaths } = options\n\n if (searchPaths) {\n const searchResults = await Promise.all(\n searchPaths.map((dir) => findConfigFile(dir, fileNames))\n )\n const found = searchResults.find((result): result is string => result !== null)\n if (found) {\n return found\n }\n }\n\n const fromCwd = await findConfigFile(cwd, fileNames)\n if (fromCwd) {\n return fromCwd\n }\n\n const projectRoot = findProjectRoot(cwd)\n if (projectRoot && projectRoot.path !== cwd) {\n const fromRoot = await findConfigFile(projectRoot.path, fileNames)\n if (fromRoot) {\n return fromRoot\n }\n }\n\n return null\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Search a single directory for the first matching config file name.\n *\n * Checks each candidate file name in order and returns the path of the first\n * one that exists on disk.\n *\n * @param dir - The directory to search in.\n * @param fileNames - Candidate config file names to look for.\n * @returns The full path to the first matching config file, or null if none found.\n * @private\n */\nasync function findConfigFile(dir: string, fileNames: readonly string[]): Promise<string | null> {\n const results = await Promise.all(\n fileNames.map(async (fileName) => {\n const filePath = join(dir, fileName)\n const exists = await fileExists(filePath)\n if (exists) {\n return filePath\n }\n return null\n })\n )\n const found = results.find((result): result is string => result !== null)\n return found ?? null\n}\n","import { extname } from 'node:path'\n\nimport { attempt, err, match } from '@kidd-cli/utils/fp'\nimport { jsonParse, jsonStringify } from '@kidd-cli/utils/json'\nimport type { ParseError } from 'jsonc-parser'\nimport { parse as parseJsonc, printParseErrorCode } from 'jsonc-parser'\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml'\n\nimport type { ConfigFormat } from './constants.js'\nimport { EMPTY_LENGTH } from './constants.js'\nimport type { ConfigOperationResult } from './types.js'\n\n/**\n * Determine the config format from a file path's extension.\n *\n * @param filePath - The file path to inspect.\n * @returns The detected config format ('json', 'jsonc', or 'yaml').\n */\nexport function getFormat(filePath: string): ConfigFormat {\n const ext = extname(filePath)\n return match(ext)\n .with('.jsonc', () => 'jsonc' as const)\n .with('.yaml', () => 'yaml' as const)\n .otherwise(() => 'json' as const)\n}\n\n/**\n * Options for parsing config file content.\n */\nexport interface ParseContentOptions {\n readonly content: string\n readonly filePath: string\n readonly format: ConfigFormat\n}\n\n/**\n * Parse config file content using the appropriate parser for the given format.\n *\n * @param options - Parse content options.\n * @returns A ConfigOperationResult with the parsed data or an error.\n */\nexport function parseContent(options: ParseContentOptions): ConfigOperationResult<unknown> {\n const { content, filePath, format } = options\n return match(format)\n .with('json', () => parseJson(content, filePath))\n .with('jsonc', () => parseJsoncContent(content, filePath))\n .with('yaml', () => parseYamlContent(content, filePath))\n .exhaustive()\n}\n\n/**\n * Serialize data to a string in the specified config format.\n *\n * @param data - The data to serialize.\n * @param format - The target config format.\n * @returns The serialized string representation.\n */\nexport function serializeContent(data: unknown, format: ConfigFormat): string {\n return match(format)\n .with('json', () => {\n const [, json] = jsonStringify(data, { pretty: true })\n return `${json}\\n`\n })\n .with('jsonc', () => {\n const [, json] = jsonStringify(data, { pretty: true })\n return `${json}\\n`\n })\n .with('yaml', () => stringifyYaml(data))\n .exhaustive()\n}\n\n/**\n * Get the file extension string for a given config format.\n *\n * @param format - The config format.\n * @returns The file extension including the leading dot (e.g. '.json').\n */\nexport function getExtension(format: ConfigFormat): string {\n return match(format)\n .with('json', () => '.json')\n .with('jsonc', () => '.jsonc')\n .with('yaml', () => '.yaml')\n .exhaustive()\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Parse a JSON string and return the result as a ConfigOperationResult.\n *\n * @param content - The raw JSON string to parse.\n * @param filePath - The file path used in error messages.\n * @returns A ConfigOperationResult with the parsed data or a parse error.\n * @private\n */\nfunction parseJson(content: string, filePath: string): ConfigOperationResult<unknown> {\n const [error, result] = jsonParse(content)\n if (error) {\n return err(`Failed to parse JSON in ${filePath}: ${error.message}`)\n }\n return [null, result]\n}\n\n/**\n * Parse a JSONC (JSON with comments) string and return the result as a ConfigOperationResult.\n *\n * @param content - The raw JSONC string to parse.\n * @param filePath - The file path used in error messages.\n * @returns A ConfigOperationResult with the parsed data or a parse error.\n * @private\n */\nfunction parseJsoncContent(content: string, filePath: string): ConfigOperationResult<unknown> {\n // Intentional mutation: jsonc-parser API requires a mutable errors array.\n // There is no immutable alternative — the parser populates it during parsing.\n const errors: ParseError[] = []\n const result = parseJsonc(content, errors, {\n allowEmptyContent: false,\n allowTrailingComma: true,\n })\n if (errors.length > EMPTY_LENGTH) {\n const errorMessages = errors\n .map(\n (parseError) =>\n ` - ${printParseErrorCode(parseError.error)} at offset ${parseError.offset}`\n )\n .join('\\n')\n return err(`Failed to parse JSONC in ${filePath}:\\n${errorMessages}`)\n }\n return [null, result]\n}\n\n/**\n * Parse a YAML string and return the result as a ConfigOperationResult.\n *\n * @param content - The raw YAML string to parse.\n * @param filePath - The file path used in error messages.\n * @returns A ConfigOperationResult with the parsed data or a parse error.\n * @private\n */\nfunction parseYamlContent(content: string, filePath: string): ConfigOperationResult<unknown> {\n const [error, result] = attempt(() => parseYaml(content))\n if (error) {\n return err(`Failed to parse YAML in ${filePath}: ${String(error)}`)\n }\n return [null, result]\n}\n","import { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\n\nimport { attemptAsync, err, match } from '@kidd-cli/utils/fp'\nimport { formatZodIssues } from '@kidd-cli/utils/validate'\nimport type { ZodTypeAny, output } from 'zod'\n\nimport { findConfig, getConfigFileNames } from './find.js'\nimport { getExtension, getFormat, parseContent, serializeContent } from './parse.js'\nimport type {\n Config,\n ConfigOperationResult,\n ConfigOptions,\n ConfigResult,\n ConfigWriteOptions,\n ConfigWriteResult,\n} from './types.js'\n\n/**\n * Create a typed config client that loads, validates, and writes config files.\n *\n * @param options - Config client options including name and Zod schema.\n * @returns A {@link Config} client instance.\n */\nexport function createConfigClient<TSchema extends ZodTypeAny>(\n options: ConfigOptions<TSchema>\n): Config<output<TSchema>> {\n const { name, schema, searchPaths } = options\n const fileNames = getConfigFileNames(name)\n\n /**\n * Find a config file in the given directory.\n *\n * @private\n * @param cwd - Working directory to search from.\n * @returns The path to the config file, or null if not found.\n */\n async function find(cwd?: string): Promise<string | null> {\n return findConfig({\n cwd: cwd ?? process.cwd(),\n fileNames,\n searchPaths,\n })\n }\n\n /**\n * Load and validate a config file.\n *\n * @private\n * @param cwd - Working directory to search from.\n * @returns A ConfigOperationResult with the loaded config, or [null, null] if not found.\n */\n async function load(\n cwd?: string\n ): Promise<ConfigOperationResult<ConfigResult<output<TSchema>>> | readonly [null, null]> {\n const filePath = await find(cwd)\n if (!filePath) {\n return [null, null]\n }\n\n const [readError, content] = await attemptAsync(() => readFile(filePath, 'utf8'))\n if (readError || content === null) {\n const errorDetail = resolveReadErrorDetail(readError)\n return err(`Failed to read config at ${filePath}: ${errorDetail}`)\n }\n\n const format = getFormat(filePath)\n const parsedResult = parseContent({ content, filePath, format })\n\n if (parsedResult[0]) {\n return [parsedResult[0], null]\n }\n\n const result = schema.safeParse(parsedResult[1])\n if (!result.success) {\n const { message } = formatZodIssues(result.error.issues, '\\n')\n return err(`Invalid config in ${filePath}:\\n${message}`)\n }\n\n return [\n null,\n {\n config: result.data,\n filePath,\n format,\n },\n ]\n }\n\n /**\n * Validate and write config data to a file.\n *\n * @private\n * @param data - The config data to write.\n * @param writeOptions - Write options including path and format.\n * @returns A ConfigOperationResult with the write result.\n */\n async function write(\n data: output<TSchema>,\n writeOptions: ConfigWriteOptions = {}\n ): Promise<ConfigOperationResult<ConfigWriteResult>> {\n const result = schema.safeParse(data)\n if (!result.success) {\n const { message } = formatZodIssues(result.error.issues, '\\n')\n return err(`Invalid config data:\\n${message}`)\n }\n\n const resolvedFormat = match(writeOptions)\n .when(\n (opts) => opts.format !== null && opts.format !== undefined,\n (opts) => opts.format ?? ('jsonc' as const)\n )\n .when(\n (opts) => opts.filePath !== null && opts.filePath !== undefined,\n (opts) => getFormat(opts.filePath ?? '')\n )\n .otherwise(() => 'jsonc' as const)\n\n const resolvedFilePath = match(writeOptions.filePath)\n .when(\n (fp) => fp !== null && fp !== undefined,\n (fp) => fp ?? ''\n )\n .otherwise(() => {\n const dir = writeOptions.dir ?? process.cwd()\n const ext = getExtension(resolvedFormat)\n return join(dir, `.${name}${ext}`)\n })\n\n const serialized = serializeContent(result.data, resolvedFormat)\n\n const [mkdirError] = await attemptAsync(() =>\n mkdir(dirname(resolvedFilePath), { recursive: true })\n )\n if (mkdirError) {\n return err(`Failed to create directory for ${resolvedFilePath}: ${String(mkdirError)}`)\n }\n\n const [writeError] = await attemptAsync(() => writeFile(resolvedFilePath, serialized, 'utf8'))\n if (writeError) {\n return err(`Failed to write config to ${resolvedFilePath}: ${String(writeError)}`)\n }\n\n return [null, { filePath: resolvedFilePath, format: resolvedFormat }]\n }\n\n return { find, load, write }\n}\n\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the error detail string from a read error.\n *\n * @private\n * @param readError - The error from the read operation, or null.\n * @returns A descriptive error string.\n */\nfunction resolveReadErrorDetail(readError: unknown): string {\n if (readError) {\n return String(readError)\n }\n return 'empty file'\n}\n"],"mappings":";;;;;;;;;;AAOA,MAAa,oBAAoB;CAAC;CAAU;CAAS;CAAQ;;;;;;;;;;;;ACU7D,SAAgB,mBAAmB,MAAwB;AACzD,QAAO,kBAAkB,KAAK,QAAQ,IAAI,OAAO,MAAM;;;;;;;;;;;;AAazD,eAAsB,WAAW,SAIN;CACzB,MAAM,EAAE,WAAW,KAAK,gBAAgB;AAExC,KAAI,aAAa;EAIf,MAAM,SAHgB,MAAM,QAAQ,IAClC,YAAY,KAAK,QAAQ,eAAe,KAAK,UAAU,CAAC,CACzD,EAC2B,MAAM,WAA6B,WAAW,KAAK;AAC/E,MAAI,MACF,QAAO;;CAIX,MA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ACtD;AACD,MAAI,WACF,QAAO,IAAI,kCAAkC,iBAAiB,IAAI,OAAO,WAAW,GAAG;EAGzF,MAAM,CAAC,cAAc,MAAM,mBAAmB,UAAU,kBAAkB,YAAY,OAAO,CAAC;AAC9F,MAAI,WACF,QAAO,IAAI,6BAA6B,iBAAiB,IAAI,OAAO,WAAW,GAAG;AAGpF,SAAO,CAAC,MAAM;GAAE,UAAU;GAAkB,QAAQ;GAAgB,CAAC;;AAGvE,QAAO;EAAE;EAAM;EAAM;EAAO;;;;;;;;;AAY9B,SAAS,uBAAuB,WAA4B;AAC1D,KAAI,UACF,QAAO,OAAO,UAAU;AAE1B,QAAO"}
@@ -1,9 +1,8 @@
1
- import { n as resolveLocalPath, t as resolveGlobalPath } from "./project-NPtYX2ZX.js";
1
+ import { n as resolveLocalPath, t as resolveGlobalPath } from "./project-D0g84bZY.js";
2
2
  import { join } from "node:path";
3
3
  import { attempt, err, match, ok } from "@kidd-cli/utils/fp";
4
4
  import { jsonParse, jsonStringify } from "@kidd-cli/utils/json";
5
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
-
5
+ import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
7
6
  //#region src/lib/store/create-store.ts
8
7
  /**
9
8
  * Create a file-backed {@link FileStore} that resolves JSON files from project-local
@@ -44,7 +43,6 @@ function createStore(options) {
44
43
  * @returns The file content, or null if the file does not exist or cannot be read.
45
44
  */
46
45
  function loadFromPath(filePath) {
47
- if (!existsSync(filePath)) return null;
48
46
  const [error, content] = attempt(() => readFileSync(filePath, "utf8"));
49
47
  if (error) return null;
50
48
  return content;
@@ -172,12 +170,41 @@ function createStore(options) {
172
170
  if (writeError) return err(writeError);
173
171
  return ok(filePath);
174
172
  }
173
+ /**
174
+ * Remove a file from the store.
175
+ *
176
+ * Returns `ok(filePath)` when the file was deleted or did not exist
177
+ * (idempotent). Returns an error when the target directory cannot be
178
+ * resolved or the unlink fails.
179
+ *
180
+ * @private
181
+ * @param filename - The filename to remove.
182
+ * @param removeOptions - Options controlling the removal target.
183
+ * @returns A Result with the file path on success.
184
+ */
185
+ function remove(filename, removeOptions = {}) {
186
+ const { source: removeSource = "global", startDir } = removeOptions;
187
+ const dir = resolveSaveDir({
188
+ globalDir: getGlobalDir(),
189
+ localDir: getLocalDir(startDir),
190
+ source: removeSource
191
+ });
192
+ if (dir === null) return err(/* @__PURE__ */ new Error(`Cannot remove from "${removeSource}" — no local project directory found`));
193
+ const filePath = join(dir, filename);
194
+ if (!existsSync(filePath)) return ok(filePath);
195
+ const [removeError] = attempt(() => {
196
+ unlinkSync(filePath);
197
+ });
198
+ if (removeError) return err(removeError);
199
+ return ok(filePath);
200
+ }
175
201
  return {
176
202
  getFilePath,
177
203
  getGlobalDir,
178
204
  getLocalDir,
179
205
  load,
180
206
  loadRaw,
207
+ remove,
181
208
  save
182
209
  };
183
210
  }
@@ -191,7 +218,7 @@ function createStore(options) {
191
218
  function resolveSaveDir(options) {
192
219
  return match(options.source).with("local", () => options.localDir).with("global", () => options.globalDir).exhaustive();
193
220
  }
194
-
195
221
  //#endregion
196
222
  export { createStore as t };
197
- //# sourceMappingURL=create-store-BQUX0tAn.js.map
223
+
224
+ //# sourceMappingURL=create-store-OHdkm_Yt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"create-store-OHdkm_Yt.js","names":[],"sources":["../src/lib/store/create-store.ts"],"sourcesContent":["import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nimport { attempt, err, match, ok } from '@kidd-cli/utils/fp'\nimport type { Result } from '@kidd-cli/utils/fp'\nimport { jsonParse, jsonStringify } from '@kidd-cli/utils/json'\n\nimport { resolveGlobalPath, resolveLocalPath } from '@/lib/project/index.js'\nimport type { PathSource } from '@/lib/project/types.js'\n\nimport type { FileStore, LoadOptions, SaveOptions, StoreOptions } from './types.js'\n\n/**\n * Create a file-backed {@link FileStore} that resolves JSON files from project-local\n * or global home directories.\n *\n * @param options - Store configuration.\n * @returns A FileStore instance.\n */\nexport function createStore<TData = unknown>(options: StoreOptions<TData>): FileStore<TData> {\n const { dirName, defaults } = options\n\n /**\n * Resolve the local project directory for the store.\n *\n * @private\n * @param startDir - Optional directory to start searching from.\n * @returns The local directory path, or null if no project root is found.\n */\n function getLocalDir(startDir?: string): string | null {\n return resolveLocalPath({ dirName, startDir })\n }\n\n /**\n * Resolve the global home directory for the store.\n *\n * @private\n * @returns The global directory path.\n */\n function getGlobalDir(): string {\n return resolveGlobalPath({ dirName })\n }\n\n /**\n * Read the raw string content from a file path.\n *\n * @private\n * @param filePath - The file path to read.\n * @returns The file content, or null if the file does not exist or cannot be read.\n */\n function loadFromPath(filePath: string): string | null {\n const [error, content] = attempt(() => readFileSync(filePath, 'utf8'))\n\n if (error) {\n return null\n }\n\n return content\n }\n\n /**\n * Resolve a file from local or global directories based on the source strategy.\n *\n * @private\n * @param resolveOptions - Resolution options.\n * @returns The resolved result, or null if not found.\n */\n function resolveFromSource<T>(resolveOptions: {\n source: PathSource\n localDir: string | null\n globalDir: string\n filename: string\n handler: (filePath: string) => T | null\n }): T | null {\n return match(resolveOptions.source)\n .with('local', (): T | null => {\n if (!resolveOptions.localDir) {\n return null\n }\n return resolveOptions.handler(join(resolveOptions.localDir, resolveOptions.filename))\n })\n .with('global', () =>\n resolveOptions.handler(join(resolveOptions.globalDir, resolveOptions.filename))\n )\n .with('resolve', (): T | null => {\n if (resolveOptions.localDir) {\n const localResult = resolveOptions.handler(\n join(resolveOptions.localDir, resolveOptions.filename)\n )\n if (localResult !== null) {\n return localResult\n }\n }\n return resolveOptions.handler(join(resolveOptions.globalDir, resolveOptions.filename))\n })\n .exhaustive()\n }\n\n /**\n * Load the raw string content of a store file.\n *\n * @private\n * @param filename - The filename to load.\n * @param loadOptions - Options controlling source resolution.\n * @returns The raw file content, or null if not found.\n */\n function loadRaw(filename: string, loadOptions: LoadOptions = {}): string | null {\n const { source: loadSource = 'resolve', startDir } = loadOptions\n const localDir = getLocalDir(startDir)\n const globalDir = getGlobalDir()\n\n return resolveFromSource<string>({\n filename,\n globalDir,\n handler: loadFromPath,\n localDir,\n source: loadSource,\n })\n }\n\n /**\n * Load and parse a store file as JSON, merging with defaults if available.\n *\n * @private\n * @param filename - The filename to load.\n * @param loadOptions - Options controlling source resolution.\n * @returns The parsed data, defaults, or null.\n */\n function load(filename: string, loadOptions: LoadOptions = {}): TData | null {\n const raw = loadRaw(filename, loadOptions)\n\n if (raw === null) {\n return defaults ?? null\n }\n\n const [parseError, parsed] = jsonParse(raw)\n if (parseError) {\n return defaults ?? null\n }\n\n if (defaults) {\n return { ...defaults, ...(parsed as Partial<TData>) }\n }\n return parsed as TData\n }\n\n /**\n * Check if a file exists at the given path and return the path if so.\n *\n * @private\n * @param filePath - The file path to check.\n * @returns The file path if it exists, or null.\n */\n function checkFileExists(filePath: string): string | null {\n if (existsSync(filePath)) {\n return filePath\n }\n return null\n }\n\n /**\n * Resolve the file path for a store file without reading its content.\n *\n * @private\n * @param filename - The filename to resolve.\n * @param loadOptions - Options controlling source resolution.\n * @returns The resolved file path, or null if not found.\n */\n function getFilePath(filename: string, loadOptions: LoadOptions = {}): string | null {\n const { source: fileSource = 'resolve', startDir } = loadOptions\n const localDir = getLocalDir(startDir)\n const globalDir = getGlobalDir()\n\n return resolveFromSource<string>({\n filename,\n globalDir,\n handler: checkFileExists,\n localDir,\n source: fileSource,\n })\n }\n\n /**\n * Serialize data to JSON and write it to a store file.\n *\n * Creates the target directory if it does not exist. Defaults to\n * the global home directory when no source is specified.\n *\n * @private\n * @param filename - The filename to write.\n * @param data - The data to serialize.\n * @param saveOptions - Options controlling the write target.\n * @returns A Result with the written file path on success.\n */\n function save(filename: string, data: unknown, saveOptions: SaveOptions = {}): Result<string> {\n const { source: saveSource = 'global', startDir } = saveOptions\n\n const dir = resolveSaveDir({\n globalDir: getGlobalDir(),\n localDir: getLocalDir(startDir),\n source: saveSource,\n })\n\n if (dir === null) {\n return err(new Error(`Cannot save to \"${saveSource}\" — no local project directory found`))\n }\n\n const [stringifyError, json] = jsonStringify(data, { pretty: true })\n\n if (stringifyError) {\n return err(stringifyError)\n }\n\n const filePath = join(dir, filename)\n\n const [writeError] = attempt(() => {\n mkdirSync(dir, { mode: 0o700, recursive: true })\n writeFileSync(filePath, json, { encoding: 'utf8', mode: 0o600 })\n })\n\n if (writeError) {\n return err(writeError)\n }\n\n return ok(filePath)\n }\n\n /**\n * Remove a file from the store.\n *\n * Returns `ok(filePath)` when the file was deleted or did not exist\n * (idempotent). Returns an error when the target directory cannot be\n * resolved or the unlink fails.\n *\n * @private\n * @param filename - The filename to remove.\n * @param removeOptions - Options controlling the removal target.\n * @returns A Result with the file path on success.\n */\n function remove(filename: string, removeOptions: SaveOptions = {}): Result<string> {\n const { source: removeSource = 'global', startDir } = removeOptions\n\n const dir = resolveSaveDir({\n globalDir: getGlobalDir(),\n localDir: getLocalDir(startDir),\n source: removeSource,\n })\n\n if (dir === null) {\n return err(\n new Error(`Cannot remove from \"${removeSource}\" — no local project directory found`)\n )\n }\n\n const filePath = join(dir, filename)\n\n if (!existsSync(filePath)) {\n return ok(filePath)\n }\n\n const [removeError] = attempt(() => {\n unlinkSync(filePath)\n })\n\n if (removeError) {\n return err(removeError)\n }\n\n return ok(filePath)\n }\n\n return {\n getFilePath,\n getGlobalDir,\n getLocalDir,\n load,\n loadRaw,\n remove,\n save,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve the target directory for a save operation.\n *\n * @private\n * @param options - Resolution options.\n * @returns The directory path, or null when `local` is requested but unavailable.\n */\nfunction resolveSaveDir(options: {\n readonly localDir: string | null\n readonly globalDir: string\n readonly source: 'local' | 'global'\n}): string | null {\n return match(options.source)\n .with('local', (): string | null => options.localDir)\n .with('global', () => options.globalDir)\n .exhaustive()\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,SAAgB,YAA6B,SAAgD;CA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,oBACL,IAAI,MAAM,uBAAuB,aAAa,sCAAsC,CACrF;EAGH,MAAM,WAAW,KAAK,KAAK,SAAS;AAEpC,MAAI,CAAC,WAAW,SAAS,CACvB,QAAO,GAAG,SAAS;EAGrB,MAAM,CAAC,eAAe,cAAc;AAClC,cAAW,SAAS;IACpB;AAEF,MAAI,YACF,QAAO,IAAI,YAAY;AAGzB,SAAO,GAAG,SAAS;;AAGrB,QAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACD;;;;;;;;;AAcH,SAAS,eAAe,SAIN;AAChB,QAAO,MAAM,QAAQ,OAAO,CACzB,KAAK,eAA8B,QAAQ,SAAS,CACpD,KAAK,gBAAgB,QAAQ,UAAU,CACvC,YAAY"}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as CommandDef, c as MiddlewareFn, i as Command, l as Context, n as AutoloadOptions, o as CommandMap, r as CliOptions, s as Middleware, t as ArgsDef } from "./types-kjpRau0U.js";
1
+ import { a as CommandDef, c as Middleware, d as Context, i as Command, l as MiddlewareEnv, n as AutoloadOptions, o as CommandMap, r as CliOptions, s as InferVariables, t as ArgsDef, u as MiddlewareFn } from "./types-CTvrsrnD.js";
2
2
  import { defineConfig } from "@kidd-cli/config";
3
3
  import { z } from "zod";
4
4
 
@@ -17,10 +17,43 @@ declare function cli<TSchema extends z.ZodType = z.ZodType>(options: CliOptions<
17
17
  /**
18
18
  * Define a CLI command with typed args, config, and handler.
19
19
  *
20
- * @param def - Command definition including description, args schema, and handler.
20
+ * The `const TMiddleware` generic preserves the middleware tuple as a literal type,
21
+ * enabling TypeScript to extract and intersect `Variables` from each middleware
22
+ * element onto the handler's `ctx` type.
23
+ *
24
+ * @param def - Command definition including description, args schema, middleware, and handler.
21
25
  * @returns A resolved Command object for registration in the command map.
22
26
  */
23
- declare function command<TArgsDef extends ArgsDef = ArgsDef, TConfig extends Record<string, unknown> = Record<string, unknown>>(def: CommandDef<TArgsDef, TConfig>): Command;
27
+ declare function command<TArgsDef extends ArgsDef = ArgsDef, TConfig extends Record<string, unknown> = Record<string, unknown>, const TMiddleware extends readonly Middleware<MiddlewareEnv>[] = readonly Middleware<MiddlewareEnv>[]>(def: CommandDef<TArgsDef, TConfig, TMiddleware>): Command;
28
+ //#endregion
29
+ //#region src/compose.d.ts
30
+ /**
31
+ * The composed return environment. Uses a conditional type to normalize
32
+ * `unknown` (produced by empty tuples) into `Record<string, unknown>`,
33
+ * satisfying the `MiddlewareEnv` constraint.
34
+ */
35
+ interface ComposedEnv<TMiddleware extends readonly Middleware<MiddlewareEnv>[]> {
36
+ readonly Variables: InferVariables<TMiddleware> extends infer V ? unknown extends V ? Record<string, unknown> : V : never;
37
+ }
38
+ /**
39
+ * Compose multiple middleware into a single middleware.
40
+ *
41
+ * Executes each middleware in order, threading `next()` through the chain.
42
+ * The final `next()` call from the last composed middleware continues to
43
+ * the downstream middleware or command handler.
44
+ *
45
+ * The returned middleware's type merges all `Variables` from the input tuple,
46
+ * so downstream handlers see the combined context.
47
+ *
48
+ * @param middlewares - An ordered tuple of middleware to compose.
49
+ * @returns A single Middleware whose Variables is the intersection of all input Variables.
50
+ *
51
+ * @example
52
+ * ```ts
53
+ * const combined = compose([auth({ strategies: [auth.env()] }), auth.require()])
54
+ * ```
55
+ */
56
+ declare function compose<const TMiddleware extends readonly Middleware<MiddlewareEnv>[]>(middlewares: TMiddleware): Middleware<ComposedEnv<TMiddleware>>;
24
57
  //#endregion
25
58
  //#region src/autoloader.d.ts
26
59
  /**
@@ -64,10 +97,21 @@ declare function decorateContext<TKey extends string, TValue>(ctx: Context, key:
64
97
  /**
65
98
  * Create a typed middleware that runs before command handlers.
66
99
  *
100
+ * Use the generic parameter to declare context variables the middleware provides.
101
+ * The handler's `ctx` type in downstream commands will include these variables.
102
+ *
67
103
  * @param handler - The middleware function receiving ctx and next.
68
- * @returns A Middleware object for use in the cli() middleware stack.
104
+ * @returns A Middleware object for use in the cli() or command() middleware stack.
105
+ *
106
+ * @example
107
+ * ```ts
108
+ * const loadUser = middleware<{ Variables: { user: User } }>(async (ctx, next) => {
109
+ * decorateContext(ctx, 'user', await fetchUser())
110
+ * await next()
111
+ * })
112
+ * ```
69
113
  */
70
- declare function middleware<TConfig extends Record<string, unknown> = Record<string, unknown>>(handler: MiddlewareFn<TConfig>): Middleware<TConfig>;
114
+ declare function middleware<TEnv extends MiddlewareEnv = MiddlewareEnv>(handler: MiddlewareFn<TEnv>): Middleware<TEnv>;
71
115
  //#endregion
72
- export { type Command, type Context, autoload, cli, command, decorateContext, defineConfig, middleware };
116
+ export { type Command, type Context, type MiddlewareEnv, autoload, cli, command, compose, decorateContext, defineConfig, middleware };
73
117
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/cli.ts","../src/command.ts","../src/autoloader.ts","../src/context/decorate.ts","../src/middleware.ts"],"mappings":";;;;;;;;;AAyBA;;;;iBAAsB,GAAA,iBAAoB,CAAA,CAAE,OAAA,GAAU,CAAA,CAAE,OAAA,CAAA,CACtD,OAAA,EAAS,UAAA,CAAW,OAAA,IACnB,OAAA;;;;;;;;AAFH;iBCfgB,OAAA,kBACG,OAAA,GAAU,OAAA,kBACX,MAAA,oBAA0B,MAAA,kBAAA,CAC1C,GAAA,EAAK,UAAA,CAAW,QAAA,EAAU,OAAA,IAAW,OAAA;;;;;;;;ADYvC;iBEPsB,QAAA,CAAS,OAAA,GAAU,eAAA,GAAkB,OAAA,CAAQ,UAAA;;;;;;;;AFOnE;;;;;;;;;;;;;;;;;;;;;iBGGgB,eAAA,6BAAA,CACd,GAAA,EAAK,OAAA,EACL,GAAA,EAAK,IAAA,EACL,KAAA,EAAO,MAAA,GACN,OAAA;;;;;;;;AHPH;iBIfgB,UAAA,iBAA2B,MAAA,oBAA0B,MAAA,kBAAA,CACnE,OAAA,EAAS,YAAA,CAAa,OAAA,IACrB,UAAA,CAAW,OAAA"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/cli.ts","../src/command.ts","../src/compose.ts","../src/autoloader.ts","../src/context/decorate.ts","../src/middleware.ts"],"mappings":";;;;;;;;AAyBA;;;;;iBAAsB,GAAA,iBAAoB,CAAA,CAAE,OAAA,GAAU,CAAA,CAAE,OAAA,CAAA,CACtD,OAAA,EAAS,UAAA,CAAW,OAAA,IACnB,OAAA;;;;;;;AAFH;;;;;;iBCLgB,OAAA,kBACG,OAAA,GAAU,OAAA,kBACX,MAAA,oBAA0B,MAAA,sDACP,UAAA,CAAW,aAAA,eACnC,UAAA,CAAW,aAAA,IAAA,CACtB,GAAA,EAAK,UAAA,CAAW,QAAA,EAAU,OAAA,EAAS,WAAA,IAAe,OAAA;;;;;;;ADApD;UEXU,WAAA,8BAAyC,UAAA,CAAW,aAAA;EAAA,SACnD,SAAA,EAAW,cAAA,CAAe,WAAA,oCACf,CAAA,GACd,MAAA,oBACA,CAAA;AAAA;;;;;;;;;;;;;;;;;;;iBAsBQ,OAAA,oCAA2C,UAAA,CAAW,aAAA,IAAA,CACpE,WAAA,EAAa,WAAA,GACZ,UAAA,CAAW,WAAA,CAAY,WAAA;;;;;;;AFjB1B;;iBGPsB,QAAA,CAAS,OAAA,GAAU,eAAA,GAAkB,OAAA,CAAQ,UAAA;;;;;;;AHOnE;;;;;;;;;;;;;;;;;;;;;;iBIGgB,eAAA,6BAAA,CACd,GAAA,EAAK,OAAA,EACL,GAAA,EAAK,IAAA,EACL,KAAA,EAAO,MAAA,GACN,OAAA;;;;;;;AJPH;;;;;;;;;;;;;iBKJgB,UAAA,cAAwB,aAAA,GAAgB,aAAA,CAAA,CACtD,OAAA,EAAS,YAAA,CAAa,IAAA,IACrB,UAAA,CAAW,IAAA"}