@utilarium/cardigantime 0.0.24-dev.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 (89) hide show
  1. package/LICENSE +65 -0
  2. package/README.md +398 -0
  3. package/dist/cardigantime.cjs +2169 -0
  4. package/dist/cardigantime.cjs.map +1 -0
  5. package/dist/cardigantime.d.ts +92 -0
  6. package/dist/cardigantime.js +198 -0
  7. package/dist/cardigantime.js.map +1 -0
  8. package/dist/config/executable-security.d.ts +32 -0
  9. package/dist/config/format-detector.d.ts +59 -0
  10. package/dist/configure.d.ts +55 -0
  11. package/dist/configure.js +125 -0
  12. package/dist/configure.js.map +1 -0
  13. package/dist/constants.d.ts +25 -0
  14. package/dist/constants.js +38 -0
  15. package/dist/constants.js.map +1 -0
  16. package/dist/discovery/discoverer.d.ts +62 -0
  17. package/dist/discovery/hierarchical-modes.d.ts +64 -0
  18. package/dist/discovery/index.d.ts +15 -0
  19. package/dist/discovery/patterns.d.ts +77 -0
  20. package/dist/discovery/root-detection.d.ts +100 -0
  21. package/dist/discovery/traversal-security.d.ts +106 -0
  22. package/dist/env/errors.d.ts +18 -0
  23. package/dist/env/index.d.ts +7 -0
  24. package/dist/env/naming.d.ts +38 -0
  25. package/dist/env/parser.d.ts +61 -0
  26. package/dist/env/reader.d.ts +45 -0
  27. package/dist/env/resolver.d.ts +25 -0
  28. package/dist/env/schema-utils.d.ts +33 -0
  29. package/dist/env/types.d.ts +43 -0
  30. package/dist/error/ArgumentError.d.ts +31 -0
  31. package/dist/error/ArgumentError.js +48 -0
  32. package/dist/error/ArgumentError.js.map +1 -0
  33. package/dist/error/ConfigParseError.d.ts +26 -0
  34. package/dist/error/ConfigurationError.d.ts +21 -0
  35. package/dist/error/ConfigurationError.js +46 -0
  36. package/dist/error/ConfigurationError.js.map +1 -0
  37. package/dist/error/FileSystemError.d.ts +30 -0
  38. package/dist/error/FileSystemError.js +58 -0
  39. package/dist/error/FileSystemError.js.map +1 -0
  40. package/dist/error/index.d.ts +4 -0
  41. package/dist/mcp/discovery.d.ts +105 -0
  42. package/dist/mcp/errors.d.ts +75 -0
  43. package/dist/mcp/index.d.ts +22 -0
  44. package/dist/mcp/integration.d.ts +184 -0
  45. package/dist/mcp/parser.d.ts +141 -0
  46. package/dist/mcp/resolver.d.ts +165 -0
  47. package/dist/mcp/tools/check-config-types.d.ts +208 -0
  48. package/dist/mcp/tools/check-config.d.ts +85 -0
  49. package/dist/mcp/tools/index.d.ts +12 -0
  50. package/dist/mcp/types.d.ts +210 -0
  51. package/dist/parsers/index.d.ts +25 -0
  52. package/dist/parsers/javascript-parser.d.ts +12 -0
  53. package/dist/parsers/json-parser.d.ts +6 -0
  54. package/dist/parsers/typescript-parser.d.ts +15 -0
  55. package/dist/parsers/yaml-parser.d.ts +6 -0
  56. package/dist/read.d.ts +56 -0
  57. package/dist/read.js +653 -0
  58. package/dist/read.js.map +1 -0
  59. package/dist/security/audit-logger.d.ts +135 -0
  60. package/dist/security/cli-validator.d.ts +73 -0
  61. package/dist/security/config-validator.d.ts +95 -0
  62. package/dist/security/defaults.d.ts +17 -0
  63. package/dist/security/index.d.ts +14 -0
  64. package/dist/security/numeric-guard.d.ts +111 -0
  65. package/dist/security/path-guard.d.ts +53 -0
  66. package/dist/security/profiles.d.ts +127 -0
  67. package/dist/security/security-validator.d.ts +109 -0
  68. package/dist/security/string-guard.d.ts +92 -0
  69. package/dist/security/types.d.ts +126 -0
  70. package/dist/security/zod-secure-enum.d.ts +20 -0
  71. package/dist/security/zod-secure-number.d.ts +39 -0
  72. package/dist/security/zod-secure-path.d.ts +24 -0
  73. package/dist/security/zod-secure-string.d.ts +38 -0
  74. package/dist/types.d.ts +584 -0
  75. package/dist/types.js +56 -0
  76. package/dist/types.js.map +1 -0
  77. package/dist/util/hierarchical.d.ts +136 -0
  78. package/dist/util/hierarchical.js +436 -0
  79. package/dist/util/hierarchical.js.map +1 -0
  80. package/dist/util/schema-defaults.d.ts +80 -0
  81. package/dist/util/schema-defaults.js +118 -0
  82. package/dist/util/schema-defaults.js.map +1 -0
  83. package/dist/util/storage.d.ts +31 -0
  84. package/dist/util/storage.js +154 -0
  85. package/dist/util/storage.js.map +1 -0
  86. package/dist/validate.d.ts +113 -0
  87. package/dist/validate.js +260 -0
  88. package/dist/validate.js.map +1 -0
  89. package/package.json +84 -0
@@ -0,0 +1,260 @@
1
+ import { z } from 'zod';
2
+ import { ConfigurationError } from './error/ConfigurationError.js';
3
+ import { FileSystemError } from './error/FileSystemError.js';
4
+ import { ConfigSchema } from './types.js';
5
+ import { create } from './util/storage.js';
6
+
7
+ /**
8
+ * Recursively extracts all keys from a Zod schema in dot notation.
9
+ *
10
+ * This function traverses a Zod schema structure and builds a flat list
11
+ * of all possible keys, using dot notation for nested objects. It handles
12
+ * optional/nullable types by unwrapping them and supports arrays by
13
+ * introspecting their element type.
14
+ *
15
+ * Special handling for:
16
+ * - ZodOptional/ZodNullable: Unwraps to get the underlying type
17
+ * - ZodAny/ZodRecord: Accepts any keys, returns the prefix or empty array
18
+ * - ZodArray: Introspects the element type
19
+ * - ZodObject: Recursively processes all shape properties
20
+ *
21
+ * @param schema - The Zod schema to introspect
22
+ * @param prefix - Internal parameter for building nested key paths
23
+ * @returns Array of strings representing all possible keys in dot notation
24
+ *
25
+ * @example
26
+ * ```typescript
27
+ * const schema = z.object({
28
+ * user: z.object({
29
+ * name: z.string(),
30
+ * settings: z.object({ theme: z.string() })
31
+ * }),
32
+ * debug: z.boolean()
33
+ * });
34
+ *
35
+ * const keys = listZodKeys(schema);
36
+ * // Returns: ['user.name', 'user.settings.theme', 'debug']
37
+ * ```
38
+ */ const listZodKeys = (schema, prefix = '')=>{
39
+ // Handle ZodOptional and ZodNullable - unwrap to get the underlying type
40
+ if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {
41
+ return listZodKeys(schema.unwrap(), prefix);
42
+ }
43
+ // Handle ZodAny and ZodRecord - these accept any keys, so don't introspect
44
+ if (schema instanceof z.ZodAny || schema instanceof z.ZodRecord) {
45
+ return prefix ? [
46
+ prefix
47
+ ] : [];
48
+ }
49
+ if (schema instanceof z.ZodArray) {
50
+ return listZodKeys(schema.element, prefix);
51
+ }
52
+ if (schema instanceof z.ZodObject) {
53
+ return Object.entries(schema.shape).flatMap(([key, subschema])=>{
54
+ const fullKey = prefix ? `${prefix}.${key}` : key;
55
+ const nested = listZodKeys(subschema, fullKey);
56
+ return nested.length ? nested : fullKey;
57
+ });
58
+ }
59
+ return [];
60
+ };
61
+ /**
62
+ * Type guard to check if a value is a plain object (not array, null, or other types).
63
+ *
64
+ * @param value - The value to check
65
+ * @returns True if the value is a plain object
66
+ */ const isPlainObject = (value)=>{
67
+ // Check if it's an object, not null, and not an array.
68
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
69
+ };
70
+ /**
71
+ * Generates a list of all keys within a JavaScript object, using dot notation for nested keys.
72
+ * Mimics the behavior of listZodKeys but operates on plain objects.
73
+ * For arrays, it inspects the first element that is a plain object to determine nested keys.
74
+ * If an array contains no plain objects, or is empty, the key for the array itself is listed.
75
+ *
76
+ * @param obj The object to introspect.
77
+ * @param prefix Internal use for recursion: the prefix for the current nesting level.
78
+ * @returns An array of strings representing all keys in dot notation.
79
+ */ const listObjectKeys = (obj, prefix = '')=>{
80
+ const keys = new Set(); // Use Set to automatically handle duplicates from array recursion
81
+ for(const key in obj){
82
+ // Ensure it's an own property, not from the prototype chain
83
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
84
+ const value = obj[key];
85
+ const fullKey = prefix ? `${prefix}.${key}` : key;
86
+ if (Array.isArray(value)) {
87
+ // Find the first element that is a plain object to determine structure
88
+ const firstObjectElement = value.find(isPlainObject);
89
+ if (firstObjectElement) {
90
+ // Recurse into the structure of the first object element found
91
+ const nestedKeys = listObjectKeys(firstObjectElement, fullKey);
92
+ nestedKeys.forEach((k)=>keys.add(k));
93
+ } else {
94
+ // Array is empty or contains no plain objects, list the array key itself
95
+ keys.add(fullKey);
96
+ }
97
+ } else if (isPlainObject(value)) {
98
+ // Recurse into nested plain objects
99
+ const nestedKeys = listObjectKeys(value, fullKey);
100
+ nestedKeys.forEach((k)=>keys.add(k));
101
+ } else {
102
+ // It's a primitive, null, or other non-plain object/array type
103
+ keys.add(fullKey);
104
+ }
105
+ }
106
+ }
107
+ return Array.from(keys); // Convert Set back to Array
108
+ };
109
+ /**
110
+ * Validates that the configuration object contains only keys allowed by the schema.
111
+ *
112
+ * This function prevents configuration errors by detecting typos or extra keys
113
+ * that aren't defined in the Zod schema. It intelligently handles:
114
+ * - ZodRecord types that accept arbitrary keys
115
+ * - Nested objects and their key structures
116
+ * - Arrays and their element key structures
117
+ *
118
+ * The function throws a ConfigurationError if extra keys are found, providing
119
+ * helpful information about what keys are allowed vs. what was found.
120
+ *
121
+ * @param mergedSources - The merged configuration object to validate
122
+ * @param fullSchema - The complete Zod schema including base and user schemas
123
+ * @param logger - Logger for error reporting
124
+ * @throws {ConfigurationError} When extra keys are found that aren't in the schema
125
+ *
126
+ * @example
127
+ * ```typescript
128
+ * const schema = z.object({ name: z.string(), age: z.number() });
129
+ * const config = { name: 'John', age: 30, typo: 'invalid' };
130
+ *
131
+ * checkForExtraKeys(config, schema, console);
132
+ * // Throws: ConfigurationError with details about 'typo' being an extra key
133
+ * ```
134
+ */ const checkForExtraKeys = (mergedSources, fullSchema, logger)=>{
135
+ const allowedKeys = new Set(listZodKeys(fullSchema));
136
+ const actualKeys = listObjectKeys(mergedSources);
137
+ // Filter out keys that are under a record type (ZodRecord accepts any keys)
138
+ const recordPrefixes = new Set();
139
+ // Find all prefixes that are ZodRecord types
140
+ const findRecordPrefixes = (schema, prefix = '')=>{
141
+ if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {
142
+ findRecordPrefixes(schema.unwrap(), prefix);
143
+ return;
144
+ }
145
+ if (schema instanceof z.ZodAny || schema instanceof z.ZodRecord) {
146
+ if (prefix) recordPrefixes.add(prefix);
147
+ return;
148
+ }
149
+ if (schema instanceof z.ZodObject) {
150
+ Object.entries(schema.shape).forEach(([key, subschema])=>{
151
+ const fullKey = prefix ? `${prefix}.${key}` : key;
152
+ findRecordPrefixes(subschema, fullKey);
153
+ });
154
+ }
155
+ };
156
+ findRecordPrefixes(fullSchema);
157
+ // Filter out keys that are under record prefixes
158
+ const extraKeys = actualKeys.filter((key)=>{
159
+ if (allowedKeys.has(key)) return false;
160
+ // Check if this key is under a record prefix
161
+ for (const recordPrefix of recordPrefixes){
162
+ if (key.startsWith(recordPrefix + '.')) {
163
+ return false; // This key is allowed under a record
164
+ }
165
+ }
166
+ return true; // This is an extra key
167
+ });
168
+ if (extraKeys.length > 0) {
169
+ const allowedKeysArray = Array.from(allowedKeys);
170
+ const error = ConfigurationError.extraKeys(extraKeys, allowedKeysArray);
171
+ logger.error(error.message);
172
+ throw error;
173
+ }
174
+ };
175
+ /**
176
+ * Validates that a configuration directory exists and is accessible.
177
+ *
178
+ * This function performs file system checks to ensure the configuration
179
+ * directory can be used. It handles the isRequired flag to determine
180
+ * whether a missing directory should cause an error or be silently ignored.
181
+ *
182
+ * @param configDirectory - Path to the configuration directory
183
+ * @param isRequired - Whether the directory must exist
184
+ * @param logger - Optional logger for debug information
185
+ * @throws {FileSystemError} When the directory is required but missing or unreadable
186
+ */ const validateConfigDirectory = async (configDirectory, isRequired, logger)=>{
187
+ const storage = create({
188
+ log: (logger === null || logger === void 0 ? void 0 : logger.debug) || (()=>{})
189
+ });
190
+ const exists = await storage.exists(configDirectory);
191
+ if (!exists) {
192
+ if (isRequired) {
193
+ throw FileSystemError.directoryNotFound(configDirectory, true);
194
+ }
195
+ } else if (exists) {
196
+ const isReadable = await storage.isDirectoryReadable(configDirectory);
197
+ if (!isReadable) {
198
+ throw FileSystemError.directoryNotReadable(configDirectory);
199
+ }
200
+ }
201
+ };
202
+ /**
203
+ * Validates a configuration object against the combined Zod schema.
204
+ *
205
+ * This is the main validation function that:
206
+ * 1. Validates the configuration directory (if config feature enabled)
207
+ * 2. Combines the base ConfigSchema with user-provided schema shape
208
+ * 3. Checks for extra keys not defined in the schema
209
+ * 4. Validates all values against their schema definitions
210
+ * 5. Provides detailed error reporting for validation failures
211
+ *
212
+ * The validation is comprehensive and catches common configuration errors
213
+ * including typos, missing required fields, wrong types, and invalid values.
214
+ *
215
+ * @template T - The Zod schema shape type for configuration validation
216
+ * @param config - The merged configuration object to validate
217
+ * @param options - Cardigantime options containing schema, defaults, and logger
218
+ * @throws {ConfigurationError} When configuration validation fails
219
+ * @throws {FileSystemError} When configuration directory validation fails
220
+ *
221
+ * @example
222
+ * ```typescript
223
+ * const schema = z.object({
224
+ * apiKey: z.string().min(1),
225
+ * timeout: z.number().positive(),
226
+ * });
227
+ *
228
+ * await validate(config, {
229
+ * configShape: schema.shape,
230
+ * defaults: { configDirectory: './config', isRequired: true },
231
+ * logger: console,
232
+ * features: ['config']
233
+ * });
234
+ * // Throws detailed errors if validation fails
235
+ * ```
236
+ */ const validate = async (config, options)=>{
237
+ const logger = options.logger;
238
+ if (options.features.includes('config') && config.configDirectory) {
239
+ await validateConfigDirectory(config.configDirectory, options.defaults.isRequired, logger);
240
+ }
241
+ // Combine the base schema with the user-provided shape
242
+ const fullSchema = z.object({
243
+ ...ConfigSchema.shape,
244
+ ...options.configShape
245
+ });
246
+ // Validate the merged sources against the full schema
247
+ const validationResult = fullSchema.safeParse(config);
248
+ // Check for extraneous keys
249
+ checkForExtraKeys(config, fullSchema, logger);
250
+ if (!validationResult.success) {
251
+ const formattedError = JSON.stringify(validationResult.error.format(), null, 2);
252
+ logger.error('Configuration validation failed. Check logs for details.');
253
+ logger.silly('Configuration validation failed: %s', formattedError);
254
+ throw ConfigurationError.validation('Configuration validation failed. Check logs for details.', validationResult.error);
255
+ }
256
+ return;
257
+ };
258
+
259
+ export { ConfigurationError, FileSystemError, checkForExtraKeys, listObjectKeys, listZodKeys, validate };
260
+ //# sourceMappingURL=validate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validate.js","sources":["../src/validate.ts"],"sourcesContent":["import { z, ZodObject } from \"zod\";\nimport { ArgumentError } from \"./error/ArgumentError\";\nimport { ConfigurationError } from \"./error/ConfigurationError\";\nimport { FileSystemError } from \"./error/FileSystemError\";\nimport { ConfigSchema, Logger, Options } from \"./types\";\nimport * as Storage from \"./util/storage\";\nexport { ArgumentError, ConfigurationError, FileSystemError };\n\n/**\n * Recursively extracts all keys from a Zod schema in dot notation.\n *\n * This function traverses a Zod schema structure and builds a flat list\n * of all possible keys, using dot notation for nested objects. It handles\n * optional/nullable types by unwrapping them and supports arrays by\n * introspecting their element type.\n *\n * Special handling for:\n * - ZodOptional/ZodNullable: Unwraps to get the underlying type\n * - ZodAny/ZodRecord: Accepts any keys, returns the prefix or empty array\n * - ZodArray: Introspects the element type\n * - ZodObject: Recursively processes all shape properties\n *\n * @param schema - The Zod schema to introspect\n * @param prefix - Internal parameter for building nested key paths\n * @returns Array of strings representing all possible keys in dot notation\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * user: z.object({\n * name: z.string(),\n * settings: z.object({ theme: z.string() })\n * }),\n * debug: z.boolean()\n * });\n *\n * const keys = listZodKeys(schema);\n * // Returns: ['user.name', 'user.settings.theme', 'debug']\n * ```\n */\nexport const listZodKeys = (schema: z.ZodTypeAny, prefix = ''): string[] => {\n // Handle ZodOptional and ZodNullable - unwrap to get the underlying type\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n return listZodKeys(schema.unwrap() as z.ZodTypeAny, prefix);\n }\n\n // Handle ZodAny and ZodRecord - these accept any keys, so don't introspect\n if (schema instanceof z.ZodAny || schema instanceof z.ZodRecord) {\n return prefix ? [prefix] : [];\n }\n\n if (schema instanceof z.ZodArray) {\n return listZodKeys(schema.element as z.ZodTypeAny, prefix);\n }\n\n if (schema instanceof z.ZodObject) {\n return Object.entries(schema.shape).flatMap(([key, subschema]) => {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n const nested = listZodKeys(subschema as z.ZodTypeAny, fullKey);\n return nested.length ? nested : fullKey;\n });\n }\n return [];\n}\n\n/**\n * Type guard to check if a value is a plain object (not array, null, or other types).\n *\n * @param value - The value to check\n * @returns True if the value is a plain object\n */\nconst isPlainObject = (value: unknown): value is Record<string, unknown> => {\n // Check if it's an object, not null, and not an array.\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n};\n\n/**\n * Generates a list of all keys within a JavaScript object, using dot notation for nested keys.\n * Mimics the behavior of listZodKeys but operates on plain objects.\n * For arrays, it inspects the first element that is a plain object to determine nested keys.\n * If an array contains no plain objects, or is empty, the key for the array itself is listed.\n *\n * @param obj The object to introspect.\n * @param prefix Internal use for recursion: the prefix for the current nesting level.\n * @returns An array of strings representing all keys in dot notation.\n */\nexport const listObjectKeys = (obj: Record<string, unknown>, prefix = ''): string[] => {\n const keys = new Set<string>(); // Use Set to automatically handle duplicates from array recursion\n\n for (const key in obj) {\n // Ensure it's an own property, not from the prototype chain\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n const value = obj[key];\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (Array.isArray(value)) {\n // Find the first element that is a plain object to determine structure\n const firstObjectElement = value.find(isPlainObject);\n if (firstObjectElement) {\n // Recurse into the structure of the first object element found\n const nestedKeys = listObjectKeys(firstObjectElement, fullKey);\n nestedKeys.forEach(k => keys.add(k));\n } else {\n // Array is empty or contains no plain objects, list the array key itself\n keys.add(fullKey);\n }\n } else if (isPlainObject(value)) {\n // Recurse into nested plain objects\n const nestedKeys = listObjectKeys(value, fullKey);\n nestedKeys.forEach(k => keys.add(k));\n } else {\n // It's a primitive, null, or other non-plain object/array type\n keys.add(fullKey);\n }\n }\n }\n return Array.from(keys); // Convert Set back to Array\n};\n\n/**\n * Validates that the configuration object contains only keys allowed by the schema.\n *\n * This function prevents configuration errors by detecting typos or extra keys\n * that aren't defined in the Zod schema. It intelligently handles:\n * - ZodRecord types that accept arbitrary keys\n * - Nested objects and their key structures\n * - Arrays and their element key structures\n *\n * The function throws a ConfigurationError if extra keys are found, providing\n * helpful information about what keys are allowed vs. what was found.\n *\n * @param mergedSources - The merged configuration object to validate\n * @param fullSchema - The complete Zod schema including base and user schemas\n * @param logger - Logger for error reporting\n * @throws {ConfigurationError} When extra keys are found that aren't in the schema\n *\n * @example\n * ```typescript\n * const schema = z.object({ name: z.string(), age: z.number() });\n * const config = { name: 'John', age: 30, typo: 'invalid' };\n *\n * checkForExtraKeys(config, schema, console);\n * // Throws: ConfigurationError with details about 'typo' being an extra key\n * ```\n */\nexport const checkForExtraKeys = (mergedSources: object, fullSchema: ZodObject<any>, logger: Logger | typeof console): void => {\n const allowedKeys = new Set(listZodKeys(fullSchema));\n const actualKeys = listObjectKeys(mergedSources as Record<string, unknown>);\n\n // Filter out keys that are under a record type (ZodRecord accepts any keys)\n const recordPrefixes = new Set<string>();\n\n // Find all prefixes that are ZodRecord types\n const findRecordPrefixes = (schema: z.ZodTypeAny, prefix = ''): void => {\n if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) {\n findRecordPrefixes(schema.unwrap() as z.ZodTypeAny, prefix);\n return;\n }\n\n if (schema instanceof z.ZodAny || schema instanceof z.ZodRecord) {\n if (prefix) recordPrefixes.add(prefix);\n return;\n }\n\n if (schema instanceof z.ZodObject) {\n Object.entries(schema.shape).forEach(([key, subschema]) => {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n findRecordPrefixes(subschema as z.ZodTypeAny, fullKey);\n });\n }\n };\n\n findRecordPrefixes(fullSchema);\n\n // Filter out keys that are under record prefixes\n const extraKeys = actualKeys.filter(key => {\n if (allowedKeys.has(key)) return false;\n\n // Check if this key is under a record prefix\n for (const recordPrefix of recordPrefixes) {\n if (key.startsWith(recordPrefix + '.')) {\n return false; // This key is allowed under a record\n }\n }\n\n return true; // This is an extra key\n });\n\n if (extraKeys.length > 0) {\n const allowedKeysArray = Array.from(allowedKeys);\n const error = ConfigurationError.extraKeys(extraKeys, allowedKeysArray);\n logger.error(error.message);\n throw error;\n }\n}\n\n/**\n * Validates that a configuration directory exists and is accessible.\n *\n * This function performs file system checks to ensure the configuration\n * directory can be used. It handles the isRequired flag to determine\n * whether a missing directory should cause an error or be silently ignored.\n *\n * @param configDirectory - Path to the configuration directory\n * @param isRequired - Whether the directory must exist\n * @param logger - Optional logger for debug information\n * @throws {FileSystemError} When the directory is required but missing or unreadable\n */\nconst validateConfigDirectory = async (configDirectory: string, isRequired: boolean, logger?: Logger): Promise<void> => {\n const storage = Storage.create({ log: logger?.debug || (() => { }) });\n const exists = await storage.exists(configDirectory);\n if (!exists) {\n if (isRequired) {\n throw FileSystemError.directoryNotFound(configDirectory, true);\n }\n } else if (exists) {\n const isReadable = await storage.isDirectoryReadable(configDirectory);\n if (!isReadable) {\n throw FileSystemError.directoryNotReadable(configDirectory);\n }\n }\n}\n\n/**\n * Validates a configuration object against the combined Zod schema.\n *\n * This is the main validation function that:\n * 1. Validates the configuration directory (if config feature enabled)\n * 2. Combines the base ConfigSchema with user-provided schema shape\n * 3. Checks for extra keys not defined in the schema\n * 4. Validates all values against their schema definitions\n * 5. Provides detailed error reporting for validation failures\n *\n * The validation is comprehensive and catches common configuration errors\n * including typos, missing required fields, wrong types, and invalid values.\n *\n * @template T - The Zod schema shape type for configuration validation\n * @param config - The merged configuration object to validate\n * @param options - Cardigantime options containing schema, defaults, and logger\n * @throws {ConfigurationError} When configuration validation fails\n * @throws {FileSystemError} When configuration directory validation fails\n *\n * @example\n * ```typescript\n * const schema = z.object({\n * apiKey: z.string().min(1),\n * timeout: z.number().positive(),\n * });\n *\n * await validate(config, {\n * configShape: schema.shape,\n * defaults: { configDirectory: './config', isRequired: true },\n * logger: console,\n * features: ['config']\n * });\n * // Throws detailed errors if validation fails\n * ```\n */\nexport const validate = async <T extends z.ZodRawShape>(config: z.infer<ZodObject<T & typeof ConfigSchema.shape>>, options: Options<T>): Promise<void> => {\n const logger = options.logger;\n\n if (options.features.includes('config') && (config as any).configDirectory) {\n await validateConfigDirectory((config as any).configDirectory, options.defaults.isRequired, logger);\n }\n\n // Combine the base schema with the user-provided shape\n const fullSchema = z.object({\n ...ConfigSchema.shape,\n ...options.configShape,\n });\n\n // Validate the merged sources against the full schema\n const validationResult = fullSchema.safeParse(config);\n\n // Check for extraneous keys\n checkForExtraKeys(config, fullSchema, logger);\n\n if (!validationResult.success) {\n const formattedError = JSON.stringify(validationResult.error.format(), null, 2);\n logger.error('Configuration validation failed. Check logs for details.');\n logger.silly('Configuration validation failed: %s', formattedError);\n throw ConfigurationError.validation('Configuration validation failed. Check logs for details.', validationResult.error);\n }\n\n return;\n}\n\n"],"names":["listZodKeys","schema","prefix","z","ZodOptional","ZodNullable","unwrap","ZodAny","ZodRecord","ZodArray","element","ZodObject","Object","entries","shape","flatMap","key","subschema","fullKey","nested","length","isPlainObject","value","Array","isArray","listObjectKeys","obj","keys","Set","prototype","hasOwnProperty","call","firstObjectElement","find","nestedKeys","forEach","k","add","from","checkForExtraKeys","mergedSources","fullSchema","logger","allowedKeys","actualKeys","recordPrefixes","findRecordPrefixes","extraKeys","filter","has","recordPrefix","startsWith","allowedKeysArray","error","ConfigurationError","message","validateConfigDirectory","configDirectory","isRequired","storage","Storage","log","debug","exists","FileSystemError","directoryNotFound","isReadable","isDirectoryReadable","directoryNotReadable","validate","config","options","features","includes","defaults","object","ConfigSchema","configShape","validationResult","safeParse","success","formattedError","JSON","stringify","format","silly","validation"],"mappings":";;;;;;AAQA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BC,IACM,MAAMA,WAAAA,GAAc,CAACC,MAAAA,EAAsBC,SAAS,EAAE,GAAA;;AAEzD,IAAA,IAAID,kBAAkBE,CAAAA,CAAEC,WAAW,IAAIH,MAAAA,YAAkBE,CAAAA,CAAEE,WAAW,EAAE;QACpE,OAAOL,WAAAA,CAAYC,MAAAA,CAAOK,MAAM,EAAA,EAAoBJ,MAAAA,CAAAA;AACxD,IAAA;;AAGA,IAAA,IAAID,kBAAkBE,CAAAA,CAAEI,MAAM,IAAI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;;;;;;;;;;;;;;;;;;;;;;;;AAkCC,IACM,MAAMY,QAAAA,GAAW,OAAgCC,MAAAA,EAA2DC,OAAAA,GAAAA;IAC/G,MAAM7B,MAAAA,GAAS6B,QAAQ7B,MAAM;IAE7B,IAAI6B,OAAAA,CAAQC,QAAQ,CAACC,QAAQ,CAAC,QAAA,CAAA,IAAcH,MAAAA,CAAeb,eAAe,EAAE;QACxE,MAAMD,uBAAAA,CAAwB,MAACc,CAAeb,eAAe,EAAEc,OAAAA,CAAQG,QAAQ,CAAChB,UAAU,EAAEhB,MAAAA,CAAAA;AAChG,IAAA;;IAGA,MAAMD,UAAAA,GAAatC,CAAAA,CAAEwE,MAAM,CAAC;AACxB,QAAA,GAAGC,aAAa9D,KAAK;AACrB,QAAA,GAAGyD,QAAQM;AACf,KAAA,CAAA;;IAGA,MAAMC,gBAAAA,GAAmBrC,UAAAA,CAAWsC,SAAS,CAACT,MAAAA,CAAAA;;AAG9C/B,IAAAA,iBAAAA,CAAkB+B,QAAQ7B,UAAAA,EAAYC,MAAAA,CAAAA;IAEtC,IAAI,CAACoC,gBAAAA,CAAiBE,OAAO,EAAE;QAC3B,MAAMC,cAAAA,GAAiBC,KAAKC,SAAS,CAACL,iBAAiBzB,KAAK,CAAC+B,MAAM,EAAA,EAAI,IAAA,EAAM,CAAA,CAAA;AAC7E1C,QAAAA,MAAAA,CAAOW,KAAK,CAAC,0DAAA,CAAA;QACbX,MAAAA,CAAO2C,KAAK,CAAC,qCAAA,EAAuCJ,cAAAA,CAAAA;AACpD,QAAA,MAAM3B,kBAAAA,CAAmBgC,UAAU,CAAC,0DAAA,EAA4DR,iBAAiBzB,KAAK,CAAA;AAC1H,IAAA;AAEA,IAAA;AACJ;;;;"}
package/package.json ADDED
@@ -0,0 +1,84 @@
1
+ {
2
+ "name": "@utilarium/cardigantime",
3
+ "version": "0.0.24-dev.0",
4
+ "description": "cardigantime is a tool to help you time your cardigans.",
5
+ "type": "module",
6
+ "main": "./dist/cardigantime.cjs",
7
+ "module": "./dist/cardigantime.js",
8
+ "types": "./dist/cardigantime.d.ts",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/utilarium/cardigantime.git"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/cardigantime.d.ts",
16
+ "import": "./dist/cardigantime.js",
17
+ "require": "./dist/cardigantime.cjs"
18
+ },
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md",
24
+ "LICENSE"
25
+ ],
26
+ "scripts": {
27
+ "build": "npm run lint && tsc --noEmit && vite build",
28
+ "start": "dist/main.js",
29
+ "dev": "vite build --watch",
30
+ "watch": "vite build --watch",
31
+ "test": "vitest run --coverage",
32
+ "precommit": "npm run lint && npm run build && npm run test",
33
+ "lint": "eslint . --ext .ts",
34
+ "lint:fix": "eslint . --ext .ts --fix",
35
+ "clean": "rm -rf dist",
36
+ "prepublishOnly": "npm run clean && npm run build",
37
+ "docs:dev": "cd docs && cp ../README.md public/ && npm install && npm run dev",
38
+ "docs:build": "cd docs && cp ../README.md public/ && npm install && npm run build",
39
+ "docs:preview": "cd docs && npm run preview",
40
+ "docs:test": "cd docs && npm install && npm run test",
41
+ "docs:coverage": "cd docs && npm install && npm run coverage"
42
+ },
43
+ "keywords": [
44
+ "config",
45
+ "productivity",
46
+ "notes",
47
+ "genai"
48
+ ],
49
+ "author": "Tim O'Brien <tobrien@discursive.com>",
50
+ "license": "Apache-2.0",
51
+ "homepage": "https://utilarium.github.io/cardigantime/",
52
+ "engines": {
53
+ "node": ">=24.0.0"
54
+ },
55
+ "dependencies": {
56
+ "commander": "^14.0.0",
57
+ "glob": "^13.0.0",
58
+ "js-yaml": "^4.1.0",
59
+ "yn": "^5.1.0",
60
+ "zod": "^4.3.6"
61
+ },
62
+ "devDependencies": {
63
+ "@eslint/eslintrc": "^3.3.1",
64
+ "@eslint/js": "^9.30.1",
65
+ "@rollup/plugin-replace": "^6.0.2",
66
+ "@swc/core": "^1.15.11",
67
+ "@types/js-yaml": "^4.0.9",
68
+ "@types/node": "^25.1.0",
69
+ "@typescript-eslint/eslint-plugin": "^8.54.0",
70
+ "@typescript-eslint/parser": "^8.54.0",
71
+ "@vitest/coverage-v8": "^4.0.18",
72
+ "eslint": "^9.30.1",
73
+ "eslint-plugin-import": "^2.32.0",
74
+ "globals": "^17.2.0",
75
+ "typescript": "^5.8.3",
76
+ "vite": "^7.0.4",
77
+ "vite-plugin-dts": "^4.5.4",
78
+ "vite-plugin-node": "^7.0.0",
79
+ "vitest": "^4.0.18"
80
+ },
81
+ "overrides": {
82
+ "wrap-ansi": "7.0.0"
83
+ }
84
+ }