@jaypie/fabric 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +677 -0
  2. package/dist/cjs/commander/FabricCommander.d.ts +94 -0
  3. package/dist/cjs/commander/createCommanderOptions.d.ts +25 -0
  4. package/dist/cjs/commander/fabricCommand.d.ts +43 -0
  5. package/dist/cjs/commander/index.cjs +1487 -0
  6. package/dist/cjs/commander/index.cjs.map +1 -0
  7. package/dist/cjs/commander/index.d.ts +6 -0
  8. package/dist/cjs/commander/parseCommanderOptions.d.ts +32 -0
  9. package/dist/cjs/commander/registerServiceCommand.d.ts +43 -0
  10. package/dist/cjs/commander/types.d.ts +107 -0
  11. package/dist/cjs/constants.d.ts +12 -0
  12. package/dist/cjs/convert-date.d.ts +47 -0
  13. package/dist/cjs/convert.d.ts +69 -0
  14. package/dist/cjs/data/FabricData.d.ts +42 -0
  15. package/dist/cjs/data/index.cjs +1575 -0
  16. package/dist/cjs/data/index.cjs.map +1 -0
  17. package/dist/cjs/data/index.d.ts +5 -0
  18. package/dist/cjs/data/services/archive.d.ts +8 -0
  19. package/dist/cjs/data/services/create.d.ts +8 -0
  20. package/dist/cjs/data/services/delete.d.ts +8 -0
  21. package/dist/cjs/data/services/execute.d.ts +8 -0
  22. package/dist/cjs/data/services/index.d.ts +7 -0
  23. package/dist/cjs/data/services/list.d.ts +8 -0
  24. package/dist/cjs/data/services/read.d.ts +8 -0
  25. package/dist/cjs/data/services/update.d.ts +8 -0
  26. package/dist/cjs/data/transforms.d.ts +80 -0
  27. package/dist/cjs/data/types.d.ts +190 -0
  28. package/dist/cjs/express/FabricRouter.d.ts +29 -0
  29. package/dist/cjs/express/fabricExpress.d.ts +16 -0
  30. package/dist/cjs/express/index.cjs +505 -0
  31. package/dist/cjs/express/index.cjs.map +1 -0
  32. package/dist/cjs/express/index.d.ts +3 -0
  33. package/dist/cjs/express/types.d.ts +51 -0
  34. package/dist/cjs/helpers/fallback.d.ts +21 -0
  35. package/dist/cjs/helpers/index.d.ts +3 -0
  36. package/dist/cjs/helpers/resolvedName.d.ts +24 -0
  37. package/dist/cjs/http/FabricHttpServer.d.ts +31 -0
  38. package/dist/cjs/http/authorization.d.ts +30 -0
  39. package/dist/cjs/http/cors.d.ts +40 -0
  40. package/dist/cjs/http/fabricHttp.d.ts +28 -0
  41. package/dist/cjs/http/httpTransform.d.ts +36 -0
  42. package/dist/cjs/http/index.cjs +1820 -0
  43. package/dist/cjs/http/index.cjs.map +1 -0
  44. package/dist/cjs/http/index.d.ts +10 -0
  45. package/dist/cjs/http/stream.d.ts +185 -0
  46. package/dist/cjs/http/types.d.ts +343 -0
  47. package/dist/cjs/index/index.d.ts +8 -0
  48. package/dist/cjs/index/keyBuilder.d.ts +81 -0
  49. package/dist/cjs/index/registry.d.ts +56 -0
  50. package/dist/cjs/index/types.d.ts +54 -0
  51. package/dist/cjs/index.cjs +1674 -0
  52. package/dist/cjs/index.cjs.map +1 -0
  53. package/dist/cjs/index.d.ts +18 -0
  54. package/dist/cjs/lambda/createLambdaService.d.ts +33 -0
  55. package/dist/cjs/lambda/fabricLambda.d.ts +36 -0
  56. package/dist/cjs/lambda/index.cjs +967 -0
  57. package/dist/cjs/lambda/index.cjs.map +1 -0
  58. package/dist/cjs/lambda/index.d.ts +2 -0
  59. package/dist/cjs/lambda/types.d.ts +68 -0
  60. package/dist/cjs/llm/createLlmTool.d.ts +40 -0
  61. package/dist/cjs/llm/fabricTool.d.ts +40 -0
  62. package/dist/cjs/llm/index.cjs +1107 -0
  63. package/dist/cjs/llm/index.cjs.map +1 -0
  64. package/dist/cjs/llm/index.d.ts +3 -0
  65. package/dist/cjs/llm/inputToJsonSchema.d.ts +32 -0
  66. package/dist/cjs/llm/types.d.ts +61 -0
  67. package/dist/cjs/mcp/fabricMcp.d.ts +38 -0
  68. package/dist/cjs/mcp/index.cjs +938 -0
  69. package/dist/cjs/mcp/index.cjs.map +1 -0
  70. package/dist/cjs/mcp/index.d.ts +2 -0
  71. package/dist/cjs/mcp/registerMcpTool.d.ts +38 -0
  72. package/dist/cjs/mcp/types.d.ts +60 -0
  73. package/dist/cjs/models/base.d.ts +209 -0
  74. package/dist/cjs/resolve-date.d.ts +47 -0
  75. package/dist/cjs/resolve.d.ts +69 -0
  76. package/dist/cjs/resolveService.d.ts +49 -0
  77. package/dist/cjs/service.d.ts +13 -0
  78. package/dist/cjs/status.d.ts +30 -0
  79. package/dist/cjs/types/elementaryTypes.d.ts +84 -0
  80. package/dist/cjs/types/fieldCategory.d.ts +20 -0
  81. package/dist/cjs/types/fieldDefinition.d.ts +46 -0
  82. package/dist/cjs/types/index.d.ts +4 -0
  83. package/dist/cjs/types.d.ts +56 -0
  84. package/dist/esm/commander/FabricCommander.d.ts +94 -0
  85. package/dist/esm/commander/createCommanderOptions.d.ts +25 -0
  86. package/dist/esm/commander/fabricCommand.d.ts +43 -0
  87. package/dist/esm/commander/index.d.ts +6 -0
  88. package/dist/esm/commander/index.js +1482 -0
  89. package/dist/esm/commander/index.js.map +1 -0
  90. package/dist/esm/commander/parseCommanderOptions.d.ts +32 -0
  91. package/dist/esm/commander/registerServiceCommand.d.ts +43 -0
  92. package/dist/esm/commander/types.d.ts +107 -0
  93. package/dist/esm/constants.d.ts +12 -0
  94. package/dist/esm/convert-date.d.ts +47 -0
  95. package/dist/esm/convert.d.ts +69 -0
  96. package/dist/esm/data/FabricData.d.ts +42 -0
  97. package/dist/esm/data/index.d.ts +5 -0
  98. package/dist/esm/data/index.js +1548 -0
  99. package/dist/esm/data/index.js.map +1 -0
  100. package/dist/esm/data/services/archive.d.ts +8 -0
  101. package/dist/esm/data/services/create.d.ts +8 -0
  102. package/dist/esm/data/services/delete.d.ts +8 -0
  103. package/dist/esm/data/services/execute.d.ts +8 -0
  104. package/dist/esm/data/services/index.d.ts +7 -0
  105. package/dist/esm/data/services/list.d.ts +8 -0
  106. package/dist/esm/data/services/read.d.ts +8 -0
  107. package/dist/esm/data/services/update.d.ts +8 -0
  108. package/dist/esm/data/transforms.d.ts +80 -0
  109. package/dist/esm/data/types.d.ts +190 -0
  110. package/dist/esm/express/FabricRouter.d.ts +29 -0
  111. package/dist/esm/express/fabricExpress.d.ts +16 -0
  112. package/dist/esm/express/index.d.ts +3 -0
  113. package/dist/esm/express/index.js +500 -0
  114. package/dist/esm/express/index.js.map +1 -0
  115. package/dist/esm/express/types.d.ts +51 -0
  116. package/dist/esm/helpers/fallback.d.ts +21 -0
  117. package/dist/esm/helpers/index.d.ts +3 -0
  118. package/dist/esm/helpers/resolvedName.d.ts +24 -0
  119. package/dist/esm/http/FabricHttpServer.d.ts +31 -0
  120. package/dist/esm/http/authorization.d.ts +30 -0
  121. package/dist/esm/http/cors.d.ts +40 -0
  122. package/dist/esm/http/fabricHttp.d.ts +28 -0
  123. package/dist/esm/http/httpTransform.d.ts +36 -0
  124. package/dist/esm/http/index.d.ts +10 -0
  125. package/dist/esm/http/index.js +1775 -0
  126. package/dist/esm/http/index.js.map +1 -0
  127. package/dist/esm/http/stream.d.ts +185 -0
  128. package/dist/esm/http/types.d.ts +343 -0
  129. package/dist/esm/index/index.d.ts +8 -0
  130. package/dist/esm/index/keyBuilder.d.ts +81 -0
  131. package/dist/esm/index/registry.d.ts +56 -0
  132. package/dist/esm/index/types.d.ts +54 -0
  133. package/dist/esm/index.d.ts +18 -0
  134. package/dist/esm/index.js +1606 -0
  135. package/dist/esm/index.js.map +1 -0
  136. package/dist/esm/lambda/createLambdaService.d.ts +33 -0
  137. package/dist/esm/lambda/fabricLambda.d.ts +36 -0
  138. package/dist/esm/lambda/index.d.ts +2 -0
  139. package/dist/esm/lambda/index.js +965 -0
  140. package/dist/esm/lambda/index.js.map +1 -0
  141. package/dist/esm/lambda/types.d.ts +68 -0
  142. package/dist/esm/llm/createLlmTool.d.ts +40 -0
  143. package/dist/esm/llm/fabricTool.d.ts +40 -0
  144. package/dist/esm/llm/index.d.ts +3 -0
  145. package/dist/esm/llm/index.js +1104 -0
  146. package/dist/esm/llm/index.js.map +1 -0
  147. package/dist/esm/llm/inputToJsonSchema.d.ts +32 -0
  148. package/dist/esm/llm/types.d.ts +61 -0
  149. package/dist/esm/mcp/fabricMcp.d.ts +38 -0
  150. package/dist/esm/mcp/index.d.ts +2 -0
  151. package/dist/esm/mcp/index.js +936 -0
  152. package/dist/esm/mcp/index.js.map +1 -0
  153. package/dist/esm/mcp/registerMcpTool.d.ts +38 -0
  154. package/dist/esm/mcp/types.d.ts +60 -0
  155. package/dist/esm/models/base.d.ts +209 -0
  156. package/dist/esm/resolve-date.d.ts +47 -0
  157. package/dist/esm/resolve.d.ts +69 -0
  158. package/dist/esm/resolveService.d.ts +49 -0
  159. package/dist/esm/service.d.ts +13 -0
  160. package/dist/esm/status.d.ts +30 -0
  161. package/dist/esm/types/elementaryTypes.d.ts +84 -0
  162. package/dist/esm/types/fieldCategory.d.ts +20 -0
  163. package/dist/esm/types/fieldDefinition.d.ts +46 -0
  164. package/dist/esm/types/index.d.ts +4 -0
  165. package/dist/esm/types.d.ts +56 -0
  166. package/package.json +122 -0
@@ -0,0 +1,1482 @@
1
+ import { Option, Command } from 'commander';
2
+ import { BadRequestError } from '@jaypie/errors';
3
+
4
+ // Create Commander.js options from service config
5
+ /**
6
+ * Convert camelCase to kebab-case
7
+ */
8
+ function toKebabCase$1(str) {
9
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
10
+ }
11
+ /**
12
+ * Check if a type is a typed array (e.g., [String], [Number])
13
+ */
14
+ function isTypedArrayType$2(type) {
15
+ if (!Array.isArray(type)) {
16
+ return false;
17
+ }
18
+ if (type.length === 0) {
19
+ return true; // [] is untyped array
20
+ }
21
+ if (type.length !== 1) {
22
+ return false;
23
+ }
24
+ const element = type[0];
25
+ return (element === Boolean ||
26
+ element === Number ||
27
+ element === String ||
28
+ element === Object ||
29
+ element === "boolean" ||
30
+ element === "number" ||
31
+ element === "string" ||
32
+ element === "object" ||
33
+ element === "" ||
34
+ (typeof element === "object" &&
35
+ element !== null &&
36
+ !(element instanceof RegExp) &&
37
+ Object.keys(element).length === 0));
38
+ }
39
+ /**
40
+ * Check if a type represents a boolean
41
+ */
42
+ function isBooleanType$1(type) {
43
+ return type === Boolean || type === "boolean";
44
+ }
45
+ /**
46
+ * Check if a type is variadic (array-like)
47
+ */
48
+ function isVariadicType(type) {
49
+ if (type === Array || type === "array") {
50
+ return true;
51
+ }
52
+ return isTypedArrayType$2(type);
53
+ }
54
+ /**
55
+ * Get default description for a field
56
+ */
57
+ function getDescription(fieldName, definition, override) {
58
+ if (override?.description) {
59
+ return override.description;
60
+ }
61
+ if (definition.description) {
62
+ return definition.description;
63
+ }
64
+ return fieldName;
65
+ }
66
+ /**
67
+ * Build the flags string for an option
68
+ */
69
+ function buildFlags(fieldName, definition, override) {
70
+ if (override?.flags) {
71
+ return override.flags;
72
+ }
73
+ // Priority: override.long > definition.flag > toKebabCase(fieldName)
74
+ const long = override?.long ?? definition.flag ?? toKebabCase$1(fieldName);
75
+ // Priority: override.short > definition.letter
76
+ const short = override?.short ?? definition.letter;
77
+ const isBoolean = isBooleanType$1(definition.type);
78
+ const isVariadic = isVariadicType(definition.type);
79
+ const isRequired = definition.required !== false && definition.default === undefined;
80
+ let flags = "";
81
+ if (short) {
82
+ flags += `-${short}, `;
83
+ }
84
+ flags += `--${long}`;
85
+ if (!isBoolean) {
86
+ if (isVariadic) {
87
+ // Variadic: can take multiple values
88
+ if (isRequired) {
89
+ flags += ` <${fieldName}...>`;
90
+ }
91
+ else {
92
+ flags += ` [${fieldName}...]`;
93
+ }
94
+ }
95
+ else {
96
+ // Scalar value
97
+ if (isRequired) {
98
+ flags += ` <${fieldName}>`;
99
+ }
100
+ else {
101
+ flags += ` [${fieldName}]`;
102
+ }
103
+ }
104
+ }
105
+ return flags;
106
+ }
107
+ /**
108
+ * Create a Commander Option from a field definition
109
+ */
110
+ function createOption(fieldName, definition, override) {
111
+ const flags = buildFlags(fieldName, definition, override);
112
+ const description = getDescription(fieldName, definition, override);
113
+ const option = new Option(flags, description);
114
+ // Set default value if provided
115
+ if (definition.default !== undefined) {
116
+ option.default(definition.default);
117
+ }
118
+ // Hide from help if specified
119
+ if (override?.hidden) {
120
+ option.hideHelp();
121
+ }
122
+ return option;
123
+ }
124
+ /**
125
+ * Create Commander.js Option objects from a service config
126
+ *
127
+ * @param input - The input field definitions from a service config
128
+ * @param config - Optional configuration for excluding fields or overriding options
129
+ * @returns An object containing an array of Commander Option objects
130
+ *
131
+ * @example
132
+ * ```typescript
133
+ * const handler = createService({
134
+ * input: {
135
+ * name: { type: String, description: "User name" },
136
+ * age: { type: Number, default: 25 },
137
+ * verbose: { type: Boolean },
138
+ * },
139
+ * service: (input) => input,
140
+ * });
141
+ *
142
+ * const { options } = createCommanderOptions(handler.input);
143
+ * options.forEach(opt => command.addOption(opt));
144
+ * ```
145
+ */
146
+ function createCommanderOptions(input, config = {}) {
147
+ if (!input) {
148
+ return { options: [] };
149
+ }
150
+ const { exclude = [], overrides = {} } = config;
151
+ const options = [];
152
+ for (const [fieldName, definition] of Object.entries(input)) {
153
+ // Skip excluded fields
154
+ if (exclude.includes(fieldName)) {
155
+ continue;
156
+ }
157
+ const override = overrides[fieldName];
158
+ const option = createOption(fieldName, definition, override);
159
+ options.push(option);
160
+ // For boolean fields, also create a --no-<flag> option for negation
161
+ // Commander.js requires separate options for --flag and --no-flag
162
+ if (isBooleanType$1(definition.type) && !override?.flags) {
163
+ const long = override?.long ?? definition.flag ?? toKebabCase$1(fieldName);
164
+ const negateOption = new Option(`--no-${long}`, `Disable ${fieldName}`);
165
+ // Hide the negatable option from help to avoid clutter
166
+ negateOption.hideHelp();
167
+ options.push(negateOption);
168
+ }
169
+ }
170
+ return { options };
171
+ }
172
+
173
+ /**
174
+ * Meta-modeling Constants
175
+ */
176
+ // =============================================================================
177
+ // Constants
178
+ // =============================================================================
179
+ /** Root organizational unit */
180
+ /** Fabric version - used to identify pre-instantiated Services */
181
+ const FABRIC_VERSION = "0.1.0";
182
+
183
+ /**
184
+ * Date Type Conversion for @jaypie/fabric
185
+ *
186
+ * Adds Date as a supported type in the fabric type system.
187
+ * Follows the same conversion patterns as String, Number, Boolean.
188
+ */
189
+ /**
190
+ * Convert a value to a Date
191
+ *
192
+ * Supported inputs:
193
+ * - Date: returned as-is (validated)
194
+ * - Number: treated as Unix timestamp (milliseconds)
195
+ * - String: parsed via Date constructor (ISO 8601, etc.)
196
+ * - Object with value property: unwrapped and converted
197
+ *
198
+ * @throws BadRequestError if value cannot be converted to valid Date
199
+ */
200
+ function fabricDate(value) {
201
+ // Already a Date
202
+ if (value instanceof Date) {
203
+ if (Number.isNaN(value.getTime())) {
204
+ throw new BadRequestError("Invalid Date value");
205
+ }
206
+ return value;
207
+ }
208
+ // Null/undefined
209
+ if (value === null || value === undefined) {
210
+ throw new BadRequestError("Cannot convert null or undefined to Date");
211
+ }
212
+ // Object with value property (fabric pattern)
213
+ if (typeof value === "object" && value !== null && "value" in value) {
214
+ return fabricDate(value.value);
215
+ }
216
+ // Number (timestamp in milliseconds)
217
+ if (typeof value === "number") {
218
+ if (Number.isNaN(value)) {
219
+ throw new BadRequestError("Cannot convert NaN to Date");
220
+ }
221
+ const date = new Date(value);
222
+ if (Number.isNaN(date.getTime())) {
223
+ throw new BadRequestError(`Cannot convert ${value} to Date`);
224
+ }
225
+ return date;
226
+ }
227
+ // String (ISO 8601 or parseable format)
228
+ if (typeof value === "string") {
229
+ // Empty string is invalid
230
+ if (value.trim() === "") {
231
+ throw new BadRequestError("Cannot convert empty string to Date");
232
+ }
233
+ const date = new Date(value);
234
+ if (Number.isNaN(date.getTime())) {
235
+ throw new BadRequestError(`Cannot convert "${value}" to Date`);
236
+ }
237
+ return date;
238
+ }
239
+ // Boolean cannot be converted to Date
240
+ if (typeof value === "boolean") {
241
+ throw new BadRequestError("Cannot convert boolean to Date");
242
+ }
243
+ // Arrays - attempt single element extraction
244
+ if (Array.isArray(value)) {
245
+ if (value.length === 1) {
246
+ return fabricDate(value[0]);
247
+ }
248
+ throw new BadRequestError(`Cannot convert array with ${value.length} elements to Date`);
249
+ }
250
+ throw new BadRequestError(`Cannot convert ${typeof value} to Date`);
251
+ }
252
+ /**
253
+ * Type guard for Date type in schema definitions
254
+ */
255
+ function isDateType(type) {
256
+ return type === Date;
257
+ }
258
+
259
+ // Fabric functions for @jaypie/fabric
260
+ /**
261
+ * Try to parse a string as JSON if it looks like JSON
262
+ * Returns the parsed value or the original string if not JSON
263
+ */
264
+ function tryParseJson(value) {
265
+ const trimmed = value.trim();
266
+ if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
267
+ (trimmed.startsWith("[") && trimmed.endsWith("]"))) {
268
+ try {
269
+ return JSON.parse(trimmed);
270
+ }
271
+ catch {
272
+ // Not valid JSON, return original
273
+ return value;
274
+ }
275
+ }
276
+ return value;
277
+ }
278
+ /**
279
+ * Unwrap arrays and objects to get to the scalar value
280
+ * - Single-element arrays unwrap to their element
281
+ * - Objects with value property unwrap to that value
282
+ * - Recursively unwraps nested structures
283
+ */
284
+ function unwrapToScalar(value) {
285
+ if (value === undefined || value === null) {
286
+ return value;
287
+ }
288
+ // Unwrap single-element arrays
289
+ if (Array.isArray(value)) {
290
+ if (value.length === 0) {
291
+ return undefined;
292
+ }
293
+ if (value.length === 1) {
294
+ return unwrapToScalar(value[0]);
295
+ }
296
+ throw new BadRequestError("Cannot convert multi-value array to scalar");
297
+ }
298
+ // Unwrap objects with value property
299
+ if (typeof value === "object") {
300
+ const obj = value;
301
+ if ("value" in obj) {
302
+ return unwrapToScalar(obj.value);
303
+ }
304
+ throw new BadRequestError("Object must have a value attribute");
305
+ }
306
+ return value;
307
+ }
308
+ /**
309
+ * Prepare a value for scalar conversion by parsing JSON strings and unwrapping
310
+ */
311
+ function prepareForScalarConversion(value) {
312
+ if (value === undefined || value === null) {
313
+ return value;
314
+ }
315
+ // Try to parse JSON strings
316
+ if (typeof value === "string") {
317
+ const parsed = tryParseJson(value);
318
+ if (parsed !== value) {
319
+ // Successfully parsed, unwrap the result
320
+ return unwrapToScalar(parsed);
321
+ }
322
+ return value;
323
+ }
324
+ // Unwrap arrays and objects
325
+ if (Array.isArray(value) || typeof value === "object") {
326
+ return unwrapToScalar(value);
327
+ }
328
+ return value;
329
+ }
330
+ /**
331
+ * Convert a value to a boolean
332
+ * - Arrays, objects, and JSON strings are unwrapped first
333
+ * - String "true" becomes true
334
+ * - String "false" becomes false
335
+ * - Strings that parse to numbers: positive = true, zero or negative = false
336
+ * - Numbers: positive = true, zero or negative = false
337
+ * - Boolean passes through
338
+ */
339
+ function fabricBoolean(value) {
340
+ // Prepare value by parsing JSON and unwrapping arrays/objects
341
+ const prepared = prepareForScalarConversion(value);
342
+ if (prepared === undefined || prepared === null) {
343
+ return undefined;
344
+ }
345
+ if (typeof prepared === "boolean") {
346
+ return prepared;
347
+ }
348
+ if (typeof prepared === "string") {
349
+ if (prepared === "") {
350
+ return undefined;
351
+ }
352
+ const lower = prepared.toLowerCase();
353
+ if (lower === "true") {
354
+ return true;
355
+ }
356
+ if (lower === "false") {
357
+ return false;
358
+ }
359
+ // Try to parse as number
360
+ const num = parseFloat(prepared);
361
+ if (isNaN(num)) {
362
+ throw new BadRequestError(`Cannot convert "${prepared}" to Boolean`);
363
+ }
364
+ return num > 0;
365
+ }
366
+ if (typeof prepared === "number") {
367
+ if (isNaN(prepared)) {
368
+ throw new BadRequestError("Cannot convert NaN to Boolean");
369
+ }
370
+ return prepared > 0;
371
+ }
372
+ throw new BadRequestError(`Cannot convert ${typeof prepared} to Boolean`);
373
+ }
374
+ /**
375
+ * Convert a value to a number
376
+ * - Arrays, objects, and JSON strings are unwrapped first
377
+ * - String "" becomes undefined
378
+ * - String "true" becomes 1
379
+ * - String "false" becomes 0
380
+ * - Strings that parse to numbers use those values
381
+ * - Strings that parse to NaN throw BadRequestError
382
+ * - Boolean true becomes 1, false becomes 0
383
+ * - Number passes through
384
+ */
385
+ function fabricNumber(value) {
386
+ // Prepare value by parsing JSON and unwrapping arrays/objects
387
+ const prepared = prepareForScalarConversion(value);
388
+ if (prepared === undefined || prepared === null) {
389
+ return undefined;
390
+ }
391
+ if (typeof prepared === "number") {
392
+ if (isNaN(prepared)) {
393
+ throw new BadRequestError("Cannot convert NaN to Number");
394
+ }
395
+ return prepared;
396
+ }
397
+ if (typeof prepared === "boolean") {
398
+ return prepared ? 1 : 0;
399
+ }
400
+ if (typeof prepared === "string") {
401
+ if (prepared === "") {
402
+ return undefined;
403
+ }
404
+ const lower = prepared.toLowerCase();
405
+ if (lower === "true") {
406
+ return 1;
407
+ }
408
+ if (lower === "false") {
409
+ return 0;
410
+ }
411
+ const num = parseFloat(prepared);
412
+ if (isNaN(num)) {
413
+ throw new BadRequestError(`Cannot convert "${prepared}" to Number`);
414
+ }
415
+ return num;
416
+ }
417
+ throw new BadRequestError(`Cannot convert ${typeof prepared} to Number`);
418
+ }
419
+ /**
420
+ * Convert a value to a string
421
+ * - Arrays, objects, and JSON strings are unwrapped first
422
+ * - String "" becomes undefined
423
+ * - Boolean true becomes "true", false becomes "false"
424
+ * - Number converts to string representation
425
+ * - String passes through
426
+ */
427
+ function fabricString(value) {
428
+ // Prepare value by parsing JSON and unwrapping arrays/objects
429
+ const prepared = prepareForScalarConversion(value);
430
+ if (prepared === undefined || prepared === null) {
431
+ return undefined;
432
+ }
433
+ if (typeof prepared === "string") {
434
+ if (prepared === "") {
435
+ return undefined;
436
+ }
437
+ return prepared;
438
+ }
439
+ if (typeof prepared === "boolean") {
440
+ return prepared ? "true" : "false";
441
+ }
442
+ if (typeof prepared === "number") {
443
+ if (isNaN(prepared)) {
444
+ throw new BadRequestError("Cannot convert NaN to String");
445
+ }
446
+ return String(prepared);
447
+ }
448
+ throw new BadRequestError(`Cannot convert ${typeof prepared} to String`);
449
+ }
450
+ /**
451
+ * Convert a value to an array
452
+ * - Non-arrays become arrays containing that value
453
+ * - Arrays of a single value become that value (unwrapped)
454
+ * - Multi-value arrays throw BadRequestError
455
+ * - undefined/null become undefined
456
+ */
457
+ function fabricArray(value) {
458
+ if (value === undefined || value === null) {
459
+ return undefined;
460
+ }
461
+ if (Array.isArray(value)) {
462
+ // Arrays pass through (single-element unwrapping happens when converting FROM array)
463
+ return value;
464
+ }
465
+ // Non-arrays become single-element arrays
466
+ return [value];
467
+ }
468
+ /**
469
+ * Convert a value to an object with a value property
470
+ * - Scalars become { value: scalar }
471
+ * - Arrays become { value: array }
472
+ * - Objects with a value attribute pass through
473
+ * - Objects without a value attribute throw BadRequestError
474
+ * - undefined/null become undefined
475
+ */
476
+ function fabricObject(value) {
477
+ if (value === undefined || value === null) {
478
+ return undefined;
479
+ }
480
+ // Check if already an object (but not an array)
481
+ if (typeof value === "object" && !Array.isArray(value)) {
482
+ const obj = value;
483
+ if ("value" in obj) {
484
+ return obj;
485
+ }
486
+ throw new BadRequestError("Object must have a value attribute");
487
+ }
488
+ // Scalars and arrays become { value: ... }
489
+ return { value };
490
+ }
491
+ /**
492
+ * Check if a type is a typed array (e.g., [String], [Number], [], etc.)
493
+ */
494
+ function isTypedArrayType$1(type) {
495
+ return Array.isArray(type);
496
+ }
497
+ /**
498
+ * Split a string on comma or tab delimiters for typed array conversion.
499
+ * Only splits if the string contains commas or tabs.
500
+ * Returns the original value if not a string or no delimiters found.
501
+ */
502
+ function splitStringForArray(value) {
503
+ if (typeof value !== "string") {
504
+ return value;
505
+ }
506
+ // Check for comma or tab delimiters
507
+ if (value.includes(",")) {
508
+ return value.split(",").map((s) => s.trim());
509
+ }
510
+ if (value.includes("\t")) {
511
+ return value.split("\t").map((s) => s.trim());
512
+ }
513
+ return value;
514
+ }
515
+ /**
516
+ * Try to parse a string as JSON for array context.
517
+ * Returns parsed value if it's an array, otherwise returns original.
518
+ */
519
+ function tryParseJsonArray(value) {
520
+ if (typeof value !== "string") {
521
+ return value;
522
+ }
523
+ const trimmed = value.trim();
524
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
525
+ try {
526
+ const parsed = JSON.parse(trimmed);
527
+ if (Array.isArray(parsed)) {
528
+ return parsed;
529
+ }
530
+ }
531
+ catch {
532
+ // Not valid JSON, fall through
533
+ }
534
+ }
535
+ return value;
536
+ }
537
+ /**
538
+ * Get the element type from a typed array type
539
+ * Returns undefined for untyped arrays ([])
540
+ */
541
+ function getArrayElementType(type) {
542
+ if (type.length === 0) {
543
+ return undefined; // Untyped array
544
+ }
545
+ const elementType = type[0];
546
+ // Handle constructor types
547
+ if (elementType === Boolean)
548
+ return "boolean";
549
+ if (elementType === Number)
550
+ return "number";
551
+ if (elementType === String)
552
+ return "string";
553
+ if (elementType === Object)
554
+ return "object";
555
+ // Handle string types
556
+ if (elementType === "boolean")
557
+ return "boolean";
558
+ if (elementType === "number")
559
+ return "number";
560
+ if (elementType === "string")
561
+ return "string";
562
+ if (elementType === "object")
563
+ return "object";
564
+ // Handle shorthand types
565
+ if (elementType === "")
566
+ return "string"; // "" shorthand for String
567
+ if (typeof elementType === "object" &&
568
+ elementType !== null &&
569
+ Object.keys(elementType).length === 0) {
570
+ return "object"; // {} shorthand for Object
571
+ }
572
+ throw new BadRequestError(`Unknown array element type: ${String(elementType)}`);
573
+ }
574
+ /**
575
+ * Convert a value to a typed array
576
+ * - Tries to parse JSON arrays first
577
+ * - Splits strings on comma/tab if present
578
+ * - Wraps non-arrays in an array
579
+ * - Converts each element to the specified element type
580
+ */
581
+ function fabricTypedArray(value, elementType) {
582
+ // Try to parse JSON array first
583
+ let processed = tryParseJsonArray(value);
584
+ // If still a string, try to split on comma/tab
585
+ processed = splitStringForArray(processed);
586
+ // Convert to array (wraps non-arrays)
587
+ const array = fabricArray(processed);
588
+ if (array === undefined) {
589
+ return undefined;
590
+ }
591
+ // If no element type specified, return as-is
592
+ if (elementType === undefined) {
593
+ return array;
594
+ }
595
+ // Convert each element to the element type
596
+ return array.map((element, index) => {
597
+ try {
598
+ switch (elementType) {
599
+ case "boolean":
600
+ return fabricBoolean(element);
601
+ case "number":
602
+ return fabricNumber(element);
603
+ case "object":
604
+ return fabricObject(element);
605
+ case "string":
606
+ return fabricString(element);
607
+ default:
608
+ throw new BadRequestError(`Unknown element type: ${elementType}`);
609
+ }
610
+ }
611
+ catch (error) {
612
+ if (error instanceof BadRequestError) {
613
+ throw new BadRequestError(`Cannot convert array element at index ${index}: ${error.message}`);
614
+ }
615
+ throw error;
616
+ }
617
+ });
618
+ }
619
+ /**
620
+ * Fabric a value to the specified type
621
+ */
622
+ function fabric(value, type) {
623
+ // Check for Date type first
624
+ if (isDateType(type)) {
625
+ return fabricDate(value);
626
+ }
627
+ // Check for typed array types
628
+ if (isTypedArrayType$1(type)) {
629
+ const elementType = getArrayElementType(type);
630
+ return fabricTypedArray(value, elementType);
631
+ }
632
+ const normalizedType = normalizeType(type);
633
+ switch (normalizedType) {
634
+ case "array":
635
+ return fabricArray(value);
636
+ case "boolean":
637
+ return fabricBoolean(value);
638
+ case "number":
639
+ return fabricNumber(value);
640
+ case "object":
641
+ return fabricObject(value);
642
+ case "string":
643
+ return fabricString(value);
644
+ default:
645
+ throw new BadRequestError(`Unknown type: ${String(type)}`);
646
+ }
647
+ }
648
+ /**
649
+ * Normalize type to string representation
650
+ */
651
+ function normalizeType(type) {
652
+ if (type === Array || type === "array") {
653
+ return "array";
654
+ }
655
+ if (type === Boolean || type === "boolean") {
656
+ return "boolean";
657
+ }
658
+ if (type === Number || type === "number") {
659
+ return "number";
660
+ }
661
+ if (type === Object || type === "object") {
662
+ return "object";
663
+ }
664
+ if (type === String || type === "string") {
665
+ return "string";
666
+ }
667
+ throw new BadRequestError(`Unknown type: ${String(type)}`);
668
+ }
669
+
670
+ // Service for @jaypie/fabric
671
+ /**
672
+ * Check if a single-element array is a typed array type constructor.
673
+ */
674
+ function isTypedArrayConstructor(element) {
675
+ return (element === Boolean ||
676
+ element === Number ||
677
+ element === String ||
678
+ element === Object ||
679
+ element === "boolean" ||
680
+ element === "number" ||
681
+ element === "string" ||
682
+ element === "object" ||
683
+ element === "" ||
684
+ (typeof element === "object" &&
685
+ element !== null &&
686
+ !(element instanceof RegExp) &&
687
+ Object.keys(element).length === 0));
688
+ }
689
+ /**
690
+ * Check if a type is a validated string type (array of string literals and/or RegExp).
691
+ * Distinguishes from typed arrays like [String], [Number], etc.
692
+ */
693
+ function isValidatedStringType(type) {
694
+ if (!Array.isArray(type)) {
695
+ return false;
696
+ }
697
+ // Empty array is untyped array, not validated string
698
+ if (type.length === 0) {
699
+ return false;
700
+ }
701
+ // Single-element arrays with type constructors are typed arrays
702
+ if (type.length === 1 && isTypedArrayConstructor(type[0])) {
703
+ return false;
704
+ }
705
+ // Check that all elements are strings or RegExp
706
+ return type.every((item) => typeof item === "string" || item instanceof RegExp);
707
+ }
708
+ /**
709
+ * Check if a type is a validated number type (array of number literals).
710
+ * Distinguishes from typed arrays like [Number], etc.
711
+ */
712
+ function isValidatedNumberType(type) {
713
+ if (!Array.isArray(type)) {
714
+ return false;
715
+ }
716
+ // Empty array is untyped array, not validated number
717
+ if (type.length === 0) {
718
+ return false;
719
+ }
720
+ // Single-element arrays with type constructors are typed arrays
721
+ if (type.length === 1 && isTypedArrayConstructor(type[0])) {
722
+ return false;
723
+ }
724
+ // Check that all elements are numbers
725
+ return type.every((item) => typeof item === "number");
726
+ }
727
+ /**
728
+ * Parse input string as JSON if it's a string
729
+ */
730
+ function parseInput(input) {
731
+ if (input === undefined || input === null) {
732
+ return {};
733
+ }
734
+ if (typeof input === "string") {
735
+ if (input === "") {
736
+ return {};
737
+ }
738
+ try {
739
+ const parsed = JSON.parse(input);
740
+ if (typeof parsed !== "object" ||
741
+ parsed === null ||
742
+ Array.isArray(parsed)) {
743
+ throw new BadRequestError("Input must be an object");
744
+ }
745
+ return parsed;
746
+ }
747
+ catch (error) {
748
+ if (error instanceof BadRequestError) {
749
+ throw error;
750
+ }
751
+ throw new BadRequestError("Invalid JSON input");
752
+ }
753
+ }
754
+ if (typeof input === "object" && !Array.isArray(input)) {
755
+ return input;
756
+ }
757
+ throw new BadRequestError("Input must be an object or JSON string");
758
+ }
759
+ /**
760
+ * Run validation on a value (supports async validators)
761
+ */
762
+ async function runValidation(value, validate, fieldName) {
763
+ if (typeof validate === "function") {
764
+ const result = await validate(value);
765
+ if (result === false) {
766
+ throw new BadRequestError(`Validation failed for field "${fieldName}"`);
767
+ }
768
+ }
769
+ else if (validate instanceof RegExp) {
770
+ if (typeof value !== "string" || !validate.test(value)) {
771
+ throw new BadRequestError(`Validation failed for field "${fieldName}"`);
772
+ }
773
+ }
774
+ else if (Array.isArray(validate)) {
775
+ // Check if value matches any item in the array
776
+ for (const item of validate) {
777
+ if (item instanceof RegExp) {
778
+ if (typeof value === "string" && item.test(value)) {
779
+ return; // Match found
780
+ }
781
+ }
782
+ else if (typeof item === "function") {
783
+ try {
784
+ const result = await item(value);
785
+ if (result !== false) {
786
+ return; // Match found
787
+ }
788
+ }
789
+ catch {
790
+ // Continue to next item
791
+ }
792
+ }
793
+ else if (value === item) {
794
+ return; // Scalar match found
795
+ }
796
+ }
797
+ throw new BadRequestError(`Validation failed for field "${fieldName}"`);
798
+ }
799
+ }
800
+ /**
801
+ * Check if a field is required
802
+ * A field is required unless it has a default OR required is explicitly false
803
+ */
804
+ function isFieldRequired(definition) {
805
+ if (definition.required === false) {
806
+ return false;
807
+ }
808
+ if (definition.default !== undefined) {
809
+ return false;
810
+ }
811
+ return true;
812
+ }
813
+ /**
814
+ * Process a single field through conversion and validation
815
+ */
816
+ async function processField(fieldName, value, definition) {
817
+ // Apply default if value is undefined
818
+ let processedValue = value;
819
+ if (processedValue === undefined && definition.default !== undefined) {
820
+ processedValue = definition.default;
821
+ }
822
+ // Determine actual type and validation
823
+ let actualType = definition.type;
824
+ let validation = definition.validate;
825
+ // Handle bare RegExp shorthand: /regex/
826
+ if (definition.type instanceof RegExp) {
827
+ actualType = String;
828
+ validation = definition.type; // The RegExp becomes the validation
829
+ }
830
+ // Handle validated string shorthand: ["value1", "value2"] or [/regex/]
831
+ else if (isValidatedStringType(definition.type)) {
832
+ actualType = String;
833
+ validation = definition.type; // The array becomes the validation
834
+ }
835
+ // Handle validated number shorthand: [1, 2, 3]
836
+ else if (isValidatedNumberType(definition.type)) {
837
+ actualType = Number;
838
+ validation = definition.type; // The array becomes the validation
839
+ }
840
+ // Fabric to target type
841
+ const convertedValue = fabric(processedValue, actualType);
842
+ // Check if required field is missing
843
+ if (convertedValue === undefined && isFieldRequired(definition)) {
844
+ throw new BadRequestError(`Missing required field "${fieldName}"`);
845
+ }
846
+ // Run validation if provided
847
+ if (validation !== undefined && convertedValue !== undefined) {
848
+ await runValidation(convertedValue, validation, fieldName);
849
+ }
850
+ return convertedValue;
851
+ }
852
+ /**
853
+ * Fabric a service function
854
+ *
855
+ * Service builds a function that initiates a "controller" step that:
856
+ * - Parses the input if it is a string to object
857
+ * - Fabrics each input field to its type
858
+ * - Calls the validation function or regular expression or checks the array
859
+ * - Calls the service function and returns the response
860
+ *
861
+ * The returned function has config properties for introspection.
862
+ */
863
+ function fabricService(config) {
864
+ const { input: inputDefinitions, service } = config;
865
+ const handler = async (rawInput, context) => {
866
+ // Parse input (handles string JSON)
867
+ const parsedInput = parseInput(rawInput);
868
+ // If no input definitions, pass through to service or return parsed input
869
+ if (!inputDefinitions) {
870
+ if (service) {
871
+ return service(parsedInput, context);
872
+ }
873
+ return parsedInput;
874
+ }
875
+ // Process all fields in parallel
876
+ const entries = Object.entries(inputDefinitions);
877
+ const processedValues = await Promise.all(entries.map(([fieldName, definition]) => processField(fieldName, parsedInput[fieldName], definition)));
878
+ // Build processed input object
879
+ const processedInput = {};
880
+ entries.forEach(([fieldName], index) => {
881
+ processedInput[fieldName] = processedValues[index];
882
+ });
883
+ // Return processed input if no service, otherwise call service
884
+ if (service) {
885
+ return service(processedInput, context);
886
+ }
887
+ return processedInput;
888
+ };
889
+ // Attach config properties directly to handler for flat access
890
+ const typedHandler = handler;
891
+ typedHandler.$fabric = FABRIC_VERSION;
892
+ if (config.alias !== undefined)
893
+ typedHandler.alias = config.alias;
894
+ if (config.description !== undefined)
895
+ typedHandler.description = config.description;
896
+ if (config.input !== undefined)
897
+ typedHandler.input = config.input;
898
+ if (config.service !== undefined)
899
+ typedHandler.service = config.service;
900
+ return typedHandler;
901
+ }
902
+
903
+ // Resolve inline service definitions to full Service objects
904
+ /**
905
+ * Type guard to check if a value is a pre-instantiated Service
906
+ * A Service is a function with the `$fabric` property set by fabricService
907
+ */
908
+ function isService(value) {
909
+ return typeof value === "function" && "$fabric" in value;
910
+ }
911
+ /**
912
+ * Resolve a service configuration to a full Service object
913
+ *
914
+ * Supports two patterns:
915
+ * 1. Inline service definition - pass a plain function as `service` along with
916
+ * `alias`, `description`, and `input` in the config
917
+ * 2. Pre-instantiated Service - pass a Service object as `service`
918
+ *
919
+ * When a pre-instantiated Service is passed, config fields act as overrides:
920
+ * - `alias` overrides service.alias
921
+ * - `description` overrides service.description
922
+ * - `input` overrides service.input
923
+ *
924
+ * The original Service is never mutated - a new Service is created when overrides
925
+ * are applied.
926
+ *
927
+ * @example
928
+ * ```typescript
929
+ * // Inline service definition
930
+ * const service = resolveService({
931
+ * alias: "greet",
932
+ * description: "Greet a user",
933
+ * input: { name: { type: String } },
934
+ * service: ({ name }) => `Hello, ${name}!`,
935
+ * });
936
+ *
937
+ * // Pre-instantiated with override
938
+ * const baseService = fabricService({ alias: "foo", service: (x) => x });
939
+ * const overridden = resolveService({
940
+ * alias: "bar", // Override alias
941
+ * service: baseService,
942
+ * });
943
+ * ```
944
+ */
945
+ function resolveService(config) {
946
+ const { alias, description, input, service } = config;
947
+ if (isService(service)) {
948
+ // Service is pre-instantiated - config fields act as overrides
949
+ // Create new Service with merged properties (config overrides service)
950
+ return fabricService({
951
+ alias: alias ?? service.alias,
952
+ description: description ?? service.description,
953
+ input: input ?? service.input,
954
+ service: service.service,
955
+ });
956
+ }
957
+ // Service is an inline function - create Service from config
958
+ return fabricService({
959
+ alias,
960
+ description,
961
+ input,
962
+ service,
963
+ });
964
+ }
965
+
966
+ // Parse Commander.js options back to handler input format
967
+ /**
968
+ * Convert kebab-case to camelCase
969
+ */
970
+ function toCamelCase(str) {
971
+ return str.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
972
+ }
973
+ /**
974
+ * Convert camelCase to kebab-case
975
+ */
976
+ function toKebabCase(str) {
977
+ return str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
978
+ }
979
+ /**
980
+ * Check if a type is a typed array (e.g., [String], [Number])
981
+ */
982
+ function isTypedArrayType(type) {
983
+ if (!Array.isArray(type)) {
984
+ return false;
985
+ }
986
+ if (type.length === 0) {
987
+ return true; // [] is untyped array
988
+ }
989
+ if (type.length !== 1) {
990
+ return false;
991
+ }
992
+ const element = type[0];
993
+ return (element === Boolean ||
994
+ element === Number ||
995
+ element === String ||
996
+ element === Object ||
997
+ element === "boolean" ||
998
+ element === "number" ||
999
+ element === "string" ||
1000
+ element === "object" ||
1001
+ element === "" ||
1002
+ (typeof element === "object" &&
1003
+ element !== null &&
1004
+ !(element instanceof RegExp) &&
1005
+ Object.keys(element).length === 0));
1006
+ }
1007
+ /**
1008
+ * Check if a type represents a number (scalar or validated)
1009
+ */
1010
+ function isNumberType(type) {
1011
+ if (type === Number || type === "number") {
1012
+ return true;
1013
+ }
1014
+ // Check for validated number type [1, 2, 3]
1015
+ if (Array.isArray(type) && type.length > 0) {
1016
+ // If it's not a typed array and all elements are numbers, it's a validated number
1017
+ if (!isTypedArrayType(type) &&
1018
+ type.every((item) => typeof item === "number")) {
1019
+ return true;
1020
+ }
1021
+ }
1022
+ return false;
1023
+ }
1024
+ /**
1025
+ * Check if a type represents a boolean
1026
+ */
1027
+ function isBooleanType(type) {
1028
+ return type === Boolean || type === "boolean";
1029
+ }
1030
+ /**
1031
+ * Check if a type is an array type (Array, "array", or typed array)
1032
+ */
1033
+ function isArrayType(type) {
1034
+ if (type === Array || type === "array") {
1035
+ return true;
1036
+ }
1037
+ return isTypedArrayType(type);
1038
+ }
1039
+ /**
1040
+ * Check if a type is an object type
1041
+ */
1042
+ function isObjectType(type) {
1043
+ return type === Object || type === "object";
1044
+ }
1045
+ /**
1046
+ * Convert a single value based on its target type
1047
+ */
1048
+ function convertValue(value, type) {
1049
+ if (value === undefined || value === null) {
1050
+ return undefined;
1051
+ }
1052
+ // Boolean type - Commander handles this automatically
1053
+ if (isBooleanType(type)) {
1054
+ if (typeof value === "boolean") {
1055
+ return value;
1056
+ }
1057
+ if (typeof value === "string") {
1058
+ const lower = value.toLowerCase();
1059
+ if (lower === "true" || lower === "1" || lower === "yes") {
1060
+ return true;
1061
+ }
1062
+ if (lower === "false" || lower === "0" || lower === "no") {
1063
+ return false;
1064
+ }
1065
+ }
1066
+ return Boolean(value);
1067
+ }
1068
+ // Number type
1069
+ if (isNumberType(type)) {
1070
+ if (typeof value === "number") {
1071
+ return value;
1072
+ }
1073
+ if (typeof value === "string") {
1074
+ const num = Number(value);
1075
+ if (!isNaN(num)) {
1076
+ return num;
1077
+ }
1078
+ }
1079
+ return value;
1080
+ }
1081
+ // Date type
1082
+ if (isDateType(type)) {
1083
+ if (value instanceof Date) {
1084
+ return value;
1085
+ }
1086
+ try {
1087
+ return fabricDate(value);
1088
+ }
1089
+ catch {
1090
+ // If conversion fails, return as-is and let createService handle it
1091
+ return value;
1092
+ }
1093
+ }
1094
+ // Array types - handle variadic options
1095
+ if (isArrayType(type)) {
1096
+ if (Array.isArray(value)) {
1097
+ return value;
1098
+ }
1099
+ if (typeof value === "string") {
1100
+ // Try to parse as JSON first
1101
+ try {
1102
+ const parsed = JSON.parse(value);
1103
+ if (Array.isArray(parsed)) {
1104
+ return parsed;
1105
+ }
1106
+ }
1107
+ catch {
1108
+ // Not JSON, check for comma or tab separated
1109
+ if (value.includes(",")) {
1110
+ return value.split(",").map((s) => s.trim());
1111
+ }
1112
+ if (value.includes("\t")) {
1113
+ return value.split("\t").map((s) => s.trim());
1114
+ }
1115
+ }
1116
+ // Single value becomes array
1117
+ return [value];
1118
+ }
1119
+ return [value];
1120
+ }
1121
+ // Object type - try to parse JSON
1122
+ if (isObjectType(type)) {
1123
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
1124
+ return value;
1125
+ }
1126
+ if (typeof value === "string") {
1127
+ try {
1128
+ const parsed = JSON.parse(value);
1129
+ if (typeof parsed === "object" &&
1130
+ parsed !== null &&
1131
+ !Array.isArray(parsed)) {
1132
+ return parsed;
1133
+ }
1134
+ }
1135
+ catch {
1136
+ // Not valid JSON
1137
+ }
1138
+ }
1139
+ return value;
1140
+ }
1141
+ // String type (default) - just return as-is
1142
+ return value;
1143
+ }
1144
+ /**
1145
+ * Parse Commander.js options back to handler input format
1146
+ *
1147
+ * This function converts the options object from Commander.js (which uses
1148
+ * kebab-case converted to camelCase) back to the expected handler input
1149
+ * format with proper type conversion based on the input definitions.
1150
+ *
1151
+ * @param options - The options object from Commander.js (program.opts())
1152
+ * @param config - Configuration including input field definitions
1153
+ * @returns An object suitable for passing to a service
1154
+ *
1155
+ * @example
1156
+ * ```typescript
1157
+ * const handler = createService({
1158
+ * input: {
1159
+ * userName: { type: String },
1160
+ * age: { type: Number },
1161
+ * tags: { type: [String] },
1162
+ * },
1163
+ * service: (input) => input,
1164
+ * });
1165
+ *
1166
+ * program.action((options) => {
1167
+ * const input = parseCommanderOptions(options, {
1168
+ * input: handler.input,
1169
+ * });
1170
+ * await handler(input);
1171
+ * });
1172
+ * ```
1173
+ */
1174
+ function parseCommanderOptions(options, config = {}) {
1175
+ const { exclude = [], input: inputDefinitions } = config;
1176
+ const result = {};
1177
+ // Build reverse mapping from flag name (camelCase) to field name
1178
+ // This handles cases where input.flag overrides the default flag name
1179
+ const flagToFieldMap = new Map();
1180
+ if (inputDefinitions) {
1181
+ for (const [fieldName, definition] of Object.entries(inputDefinitions)) {
1182
+ if (definition.flag) {
1183
+ // Custom flag: map flag (as camelCase) -> fieldName
1184
+ const flagCamelCase = toCamelCase(definition.flag);
1185
+ flagToFieldMap.set(flagCamelCase, fieldName);
1186
+ }
1187
+ else {
1188
+ // Default: kebab-case of fieldName -> fieldName
1189
+ const defaultFlag = toKebabCase(fieldName);
1190
+ const defaultFlagCamelCase = toCamelCase(defaultFlag);
1191
+ flagToFieldMap.set(defaultFlagCamelCase, fieldName);
1192
+ }
1193
+ }
1194
+ }
1195
+ for (const [key, value] of Object.entries(options)) {
1196
+ // Skip excluded fields
1197
+ if (exclude.includes(key)) {
1198
+ continue;
1199
+ }
1200
+ // Convert kebab-case Commander option to camelCase
1201
+ const keyCamelCase = toCamelCase(key);
1202
+ // Look up the actual field name from our mapping
1203
+ const fieldName = flagToFieldMap.get(keyCamelCase) ?? keyCamelCase;
1204
+ // Skip if excluded after resolution
1205
+ if (exclude.includes(fieldName)) {
1206
+ continue;
1207
+ }
1208
+ // Get field definition for type conversion
1209
+ const definition = inputDefinitions?.[fieldName];
1210
+ if (definition) {
1211
+ // Convert based on type definition
1212
+ result[fieldName] = convertValue(value, definition.type);
1213
+ }
1214
+ else {
1215
+ // No definition, pass through as-is
1216
+ result[fieldName] = value;
1217
+ }
1218
+ }
1219
+ return result;
1220
+ }
1221
+
1222
+ // Fabric a service as a Commander command
1223
+ /**
1224
+ * Fabric a service as a Commander.js command
1225
+ *
1226
+ * This function creates a command from a service, automatically:
1227
+ * - Creating the command with the service's alias (or custom name)
1228
+ * - Adding a description from the service's description (or custom)
1229
+ * - Converting input definitions to Commander options
1230
+ * - Wiring up the action to call the service with parsed input
1231
+ *
1232
+ * Error handling:
1233
+ * - Services can call context.onError() for recoverable errors
1234
+ * - Services can call context.onFatal() for fatal errors
1235
+ * - Any error that throws out of the service is treated as fatal
1236
+ *
1237
+ * @param config - Configuration including service, program, and optional overrides
1238
+ * @returns An object containing the created command
1239
+ *
1240
+ * @example
1241
+ * ```typescript
1242
+ * import { Command } from "commander";
1243
+ * import { fabricService } from "@jaypie/fabric";
1244
+ * import { fabricCommand } from "@jaypie/fabric/commander";
1245
+ *
1246
+ * const myService = fabricService({
1247
+ * alias: "greet",
1248
+ * description: "Greet a user",
1249
+ * input: {
1250
+ * userName: { type: String, description: "User name" },
1251
+ * loud: { type: Boolean, description: "Shout greeting" },
1252
+ * },
1253
+ * service: ({ userName, loud }) => {
1254
+ * const greeting = `Hello, ${userName}!`;
1255
+ * return loud ? greeting.toUpperCase() : greeting;
1256
+ * },
1257
+ * });
1258
+ *
1259
+ * const program = new Command();
1260
+ * fabricCommand({ program, service: myService });
1261
+ * program.parse();
1262
+ * ```
1263
+ */
1264
+ function fabricCommand({ alias, description, exclude, input, name, onComplete, onError, onFatal, onMessage, overrides, program, service: serviceOrFunction, }) {
1265
+ // Resolve inline service or apply overrides to pre-instantiated service
1266
+ const service = resolveService({
1267
+ alias,
1268
+ description,
1269
+ input,
1270
+ service: serviceOrFunction,
1271
+ });
1272
+ // Determine command name (priority: name > service.alias > "command")
1273
+ const commandName = name ?? service.alias ?? "command";
1274
+ // Determine command description
1275
+ const commandDescription = service.description;
1276
+ // Create the command
1277
+ const command = program.command(commandName);
1278
+ // Add description if available
1279
+ if (commandDescription) {
1280
+ command.description(commandDescription);
1281
+ }
1282
+ // Create and add options from service input
1283
+ if (service.input) {
1284
+ const { options } = createCommanderOptions(service.input, {
1285
+ exclude,
1286
+ overrides,
1287
+ });
1288
+ options.forEach((opt) => command.addOption(opt));
1289
+ }
1290
+ // Wire up the action
1291
+ command.action(async (options) => {
1292
+ // Parse Commander options to service input format
1293
+ const input = parseCommanderOptions(options, {
1294
+ exclude,
1295
+ input: service.input,
1296
+ });
1297
+ // Create context callbacks that wrap the registration callbacks with error swallowing
1298
+ // Callback failures should never halt service execution
1299
+ const sendMessage = onMessage
1300
+ ? async (message) => {
1301
+ try {
1302
+ await onMessage(message);
1303
+ }
1304
+ catch {
1305
+ // Swallow errors - messaging failures should not halt execution
1306
+ }
1307
+ }
1308
+ : undefined;
1309
+ const contextOnError = onError
1310
+ ? async (error) => {
1311
+ try {
1312
+ await onError(error);
1313
+ }
1314
+ catch {
1315
+ // Swallow errors - callback failures should not halt execution
1316
+ }
1317
+ }
1318
+ : undefined;
1319
+ const contextOnFatal = onFatal
1320
+ ? async (error) => {
1321
+ try {
1322
+ await onFatal(error);
1323
+ }
1324
+ catch {
1325
+ // Swallow errors - callback failures should not halt execution
1326
+ }
1327
+ }
1328
+ : undefined;
1329
+ // Create context for the service
1330
+ const context = {
1331
+ onError: contextOnError,
1332
+ onFatal: contextOnFatal,
1333
+ sendMessage,
1334
+ };
1335
+ try {
1336
+ // Call the service with context
1337
+ const response = await service(input, context);
1338
+ // Call onComplete callback if provided
1339
+ if (onComplete) {
1340
+ await onComplete(response);
1341
+ }
1342
+ }
1343
+ catch (error) {
1344
+ // Any error that escapes the service is treated as fatal
1345
+ // Services should catch recoverable errors and call context.onError() explicitly
1346
+ if (onFatal) {
1347
+ await onFatal(error);
1348
+ }
1349
+ else if (onError) {
1350
+ // Fall back to onError if onFatal not provided
1351
+ await onError(error);
1352
+ }
1353
+ else {
1354
+ // No error callbacks provided, re-throw
1355
+ throw error;
1356
+ }
1357
+ }
1358
+ });
1359
+ return { command, onMessage };
1360
+ }
1361
+
1362
+ // FabricCommander - Convenient wrapper for multi-command CLIs
1363
+ /**
1364
+ * Type guard to check if config is an array of services
1365
+ */
1366
+ function isServicesArray(config) {
1367
+ return Array.isArray(config);
1368
+ }
1369
+ /**
1370
+ * Type guard to check if a service entry is an inline definition
1371
+ */
1372
+ function isInlineDefinition(entry) {
1373
+ return (typeof entry === "object" &&
1374
+ entry !== null &&
1375
+ "alias" in entry &&
1376
+ "service" in entry &&
1377
+ !("$fabric" in entry));
1378
+ }
1379
+ /**
1380
+ * FabricCommander - Convenient wrapper for creating multi-command CLIs
1381
+ *
1382
+ * Creates a Commander program with multiple service commands in a single call.
1383
+ *
1384
+ * @example
1385
+ * ```typescript
1386
+ * // Array form - simple list of services
1387
+ * const cli = new FabricCommander([greetService, farewellService]);
1388
+ * cli.parse();
1389
+ *
1390
+ * // Config form - with description and version
1391
+ * const cli = new FabricCommander({
1392
+ * name: "my-cli",
1393
+ * description: "My CLI application",
1394
+ * version: "1.0.0",
1395
+ * services: [greetService, farewellService],
1396
+ * });
1397
+ * cli.parse();
1398
+ *
1399
+ * // With inline service definitions
1400
+ * const cli = new FabricCommander({
1401
+ * description: "My CLI",
1402
+ * version: "1.0.0",
1403
+ * services: [
1404
+ * existingService,
1405
+ * {
1406
+ * alias: "greet",
1407
+ * description: "Greet a user",
1408
+ * input: { name: { type: String } },
1409
+ * service: ({ name }) => `Hello, ${name}!`,
1410
+ * },
1411
+ * ],
1412
+ * });
1413
+ * cli.parse();
1414
+ * ```
1415
+ */
1416
+ class FabricCommander {
1417
+ constructor(config) {
1418
+ this.command = new Command();
1419
+ // Normalize config
1420
+ const normalizedConfig = isServicesArray(config)
1421
+ ? { services: config }
1422
+ : config;
1423
+ const { description, name, onComplete, onError, onFatal, onMessage, services, version, } = normalizedConfig;
1424
+ // Set program metadata
1425
+ if (name) {
1426
+ this.command.name(name);
1427
+ }
1428
+ if (version) {
1429
+ this.command.version(version);
1430
+ }
1431
+ if (description) {
1432
+ this.command.description(description);
1433
+ }
1434
+ // Register each service as a command
1435
+ for (const entry of services) {
1436
+ if (isInlineDefinition(entry)) {
1437
+ // Inline service definition
1438
+ fabricCommand({
1439
+ alias: entry.alias,
1440
+ description: entry.description,
1441
+ input: entry.input,
1442
+ onComplete,
1443
+ onError,
1444
+ onFatal,
1445
+ onMessage,
1446
+ program: this.command,
1447
+ service: entry.service,
1448
+ });
1449
+ }
1450
+ else {
1451
+ // Pre-instantiated Service
1452
+ fabricCommand({
1453
+ onComplete,
1454
+ onError,
1455
+ onFatal,
1456
+ onMessage,
1457
+ program: this.command,
1458
+ service: entry,
1459
+ });
1460
+ }
1461
+ }
1462
+ }
1463
+ /**
1464
+ * Parse command-line arguments
1465
+ * Delegates to Commander's parse method
1466
+ */
1467
+ parse(argv) {
1468
+ this.command.parse(argv);
1469
+ return this;
1470
+ }
1471
+ /**
1472
+ * Parse command-line arguments asynchronously
1473
+ * Delegates to Commander's parseAsync method
1474
+ */
1475
+ async parseAsync(argv) {
1476
+ await this.command.parseAsync(argv);
1477
+ return this;
1478
+ }
1479
+ }
1480
+
1481
+ export { FabricCommander, createCommanderOptions, fabricCommand, parseCommanderOptions };
1482
+ //# sourceMappingURL=index.js.map