@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.
- package/README.md +677 -0
- package/dist/cjs/commander/FabricCommander.d.ts +94 -0
- package/dist/cjs/commander/createCommanderOptions.d.ts +25 -0
- package/dist/cjs/commander/fabricCommand.d.ts +43 -0
- package/dist/cjs/commander/index.cjs +1487 -0
- package/dist/cjs/commander/index.cjs.map +1 -0
- package/dist/cjs/commander/index.d.ts +6 -0
- package/dist/cjs/commander/parseCommanderOptions.d.ts +32 -0
- package/dist/cjs/commander/registerServiceCommand.d.ts +43 -0
- package/dist/cjs/commander/types.d.ts +107 -0
- package/dist/cjs/constants.d.ts +12 -0
- package/dist/cjs/convert-date.d.ts +47 -0
- package/dist/cjs/convert.d.ts +69 -0
- package/dist/cjs/data/FabricData.d.ts +42 -0
- package/dist/cjs/data/index.cjs +1575 -0
- package/dist/cjs/data/index.cjs.map +1 -0
- package/dist/cjs/data/index.d.ts +5 -0
- package/dist/cjs/data/services/archive.d.ts +8 -0
- package/dist/cjs/data/services/create.d.ts +8 -0
- package/dist/cjs/data/services/delete.d.ts +8 -0
- package/dist/cjs/data/services/execute.d.ts +8 -0
- package/dist/cjs/data/services/index.d.ts +7 -0
- package/dist/cjs/data/services/list.d.ts +8 -0
- package/dist/cjs/data/services/read.d.ts +8 -0
- package/dist/cjs/data/services/update.d.ts +8 -0
- package/dist/cjs/data/transforms.d.ts +80 -0
- package/dist/cjs/data/types.d.ts +190 -0
- package/dist/cjs/express/FabricRouter.d.ts +29 -0
- package/dist/cjs/express/fabricExpress.d.ts +16 -0
- package/dist/cjs/express/index.cjs +505 -0
- package/dist/cjs/express/index.cjs.map +1 -0
- package/dist/cjs/express/index.d.ts +3 -0
- package/dist/cjs/express/types.d.ts +51 -0
- package/dist/cjs/helpers/fallback.d.ts +21 -0
- package/dist/cjs/helpers/index.d.ts +3 -0
- package/dist/cjs/helpers/resolvedName.d.ts +24 -0
- package/dist/cjs/http/FabricHttpServer.d.ts +31 -0
- package/dist/cjs/http/authorization.d.ts +30 -0
- package/dist/cjs/http/cors.d.ts +40 -0
- package/dist/cjs/http/fabricHttp.d.ts +28 -0
- package/dist/cjs/http/httpTransform.d.ts +36 -0
- package/dist/cjs/http/index.cjs +1820 -0
- package/dist/cjs/http/index.cjs.map +1 -0
- package/dist/cjs/http/index.d.ts +10 -0
- package/dist/cjs/http/stream.d.ts +185 -0
- package/dist/cjs/http/types.d.ts +343 -0
- package/dist/cjs/index/index.d.ts +8 -0
- package/dist/cjs/index/keyBuilder.d.ts +81 -0
- package/dist/cjs/index/registry.d.ts +56 -0
- package/dist/cjs/index/types.d.ts +54 -0
- package/dist/cjs/index.cjs +1674 -0
- package/dist/cjs/index.cjs.map +1 -0
- package/dist/cjs/index.d.ts +18 -0
- package/dist/cjs/lambda/createLambdaService.d.ts +33 -0
- package/dist/cjs/lambda/fabricLambda.d.ts +36 -0
- package/dist/cjs/lambda/index.cjs +967 -0
- package/dist/cjs/lambda/index.cjs.map +1 -0
- package/dist/cjs/lambda/index.d.ts +2 -0
- package/dist/cjs/lambda/types.d.ts +68 -0
- package/dist/cjs/llm/createLlmTool.d.ts +40 -0
- package/dist/cjs/llm/fabricTool.d.ts +40 -0
- package/dist/cjs/llm/index.cjs +1107 -0
- package/dist/cjs/llm/index.cjs.map +1 -0
- package/dist/cjs/llm/index.d.ts +3 -0
- package/dist/cjs/llm/inputToJsonSchema.d.ts +32 -0
- package/dist/cjs/llm/types.d.ts +61 -0
- package/dist/cjs/mcp/fabricMcp.d.ts +38 -0
- package/dist/cjs/mcp/index.cjs +938 -0
- package/dist/cjs/mcp/index.cjs.map +1 -0
- package/dist/cjs/mcp/index.d.ts +2 -0
- package/dist/cjs/mcp/registerMcpTool.d.ts +38 -0
- package/dist/cjs/mcp/types.d.ts +60 -0
- package/dist/cjs/models/base.d.ts +209 -0
- package/dist/cjs/resolve-date.d.ts +47 -0
- package/dist/cjs/resolve.d.ts +69 -0
- package/dist/cjs/resolveService.d.ts +49 -0
- package/dist/cjs/service.d.ts +13 -0
- package/dist/cjs/status.d.ts +30 -0
- package/dist/cjs/types/elementaryTypes.d.ts +84 -0
- package/dist/cjs/types/fieldCategory.d.ts +20 -0
- package/dist/cjs/types/fieldDefinition.d.ts +46 -0
- package/dist/cjs/types/index.d.ts +4 -0
- package/dist/cjs/types.d.ts +56 -0
- package/dist/esm/commander/FabricCommander.d.ts +94 -0
- package/dist/esm/commander/createCommanderOptions.d.ts +25 -0
- package/dist/esm/commander/fabricCommand.d.ts +43 -0
- package/dist/esm/commander/index.d.ts +6 -0
- package/dist/esm/commander/index.js +1482 -0
- package/dist/esm/commander/index.js.map +1 -0
- package/dist/esm/commander/parseCommanderOptions.d.ts +32 -0
- package/dist/esm/commander/registerServiceCommand.d.ts +43 -0
- package/dist/esm/commander/types.d.ts +107 -0
- package/dist/esm/constants.d.ts +12 -0
- package/dist/esm/convert-date.d.ts +47 -0
- package/dist/esm/convert.d.ts +69 -0
- package/dist/esm/data/FabricData.d.ts +42 -0
- package/dist/esm/data/index.d.ts +5 -0
- package/dist/esm/data/index.js +1548 -0
- package/dist/esm/data/index.js.map +1 -0
- package/dist/esm/data/services/archive.d.ts +8 -0
- package/dist/esm/data/services/create.d.ts +8 -0
- package/dist/esm/data/services/delete.d.ts +8 -0
- package/dist/esm/data/services/execute.d.ts +8 -0
- package/dist/esm/data/services/index.d.ts +7 -0
- package/dist/esm/data/services/list.d.ts +8 -0
- package/dist/esm/data/services/read.d.ts +8 -0
- package/dist/esm/data/services/update.d.ts +8 -0
- package/dist/esm/data/transforms.d.ts +80 -0
- package/dist/esm/data/types.d.ts +190 -0
- package/dist/esm/express/FabricRouter.d.ts +29 -0
- package/dist/esm/express/fabricExpress.d.ts +16 -0
- package/dist/esm/express/index.d.ts +3 -0
- package/dist/esm/express/index.js +500 -0
- package/dist/esm/express/index.js.map +1 -0
- package/dist/esm/express/types.d.ts +51 -0
- package/dist/esm/helpers/fallback.d.ts +21 -0
- package/dist/esm/helpers/index.d.ts +3 -0
- package/dist/esm/helpers/resolvedName.d.ts +24 -0
- package/dist/esm/http/FabricHttpServer.d.ts +31 -0
- package/dist/esm/http/authorization.d.ts +30 -0
- package/dist/esm/http/cors.d.ts +40 -0
- package/dist/esm/http/fabricHttp.d.ts +28 -0
- package/dist/esm/http/httpTransform.d.ts +36 -0
- package/dist/esm/http/index.d.ts +10 -0
- package/dist/esm/http/index.js +1775 -0
- package/dist/esm/http/index.js.map +1 -0
- package/dist/esm/http/stream.d.ts +185 -0
- package/dist/esm/http/types.d.ts +343 -0
- package/dist/esm/index/index.d.ts +8 -0
- package/dist/esm/index/keyBuilder.d.ts +81 -0
- package/dist/esm/index/registry.d.ts +56 -0
- package/dist/esm/index/types.d.ts +54 -0
- package/dist/esm/index.d.ts +18 -0
- package/dist/esm/index.js +1606 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/lambda/createLambdaService.d.ts +33 -0
- package/dist/esm/lambda/fabricLambda.d.ts +36 -0
- package/dist/esm/lambda/index.d.ts +2 -0
- package/dist/esm/lambda/index.js +965 -0
- package/dist/esm/lambda/index.js.map +1 -0
- package/dist/esm/lambda/types.d.ts +68 -0
- package/dist/esm/llm/createLlmTool.d.ts +40 -0
- package/dist/esm/llm/fabricTool.d.ts +40 -0
- package/dist/esm/llm/index.d.ts +3 -0
- package/dist/esm/llm/index.js +1104 -0
- package/dist/esm/llm/index.js.map +1 -0
- package/dist/esm/llm/inputToJsonSchema.d.ts +32 -0
- package/dist/esm/llm/types.d.ts +61 -0
- package/dist/esm/mcp/fabricMcp.d.ts +38 -0
- package/dist/esm/mcp/index.d.ts +2 -0
- package/dist/esm/mcp/index.js +936 -0
- package/dist/esm/mcp/index.js.map +1 -0
- package/dist/esm/mcp/registerMcpTool.d.ts +38 -0
- package/dist/esm/mcp/types.d.ts +60 -0
- package/dist/esm/models/base.d.ts +209 -0
- package/dist/esm/resolve-date.d.ts +47 -0
- package/dist/esm/resolve.d.ts +69 -0
- package/dist/esm/resolveService.d.ts +49 -0
- package/dist/esm/service.d.ts +13 -0
- package/dist/esm/status.d.ts +30 -0
- package/dist/esm/types/elementaryTypes.d.ts +84 -0
- package/dist/esm/types/fieldCategory.d.ts +20 -0
- package/dist/esm/types/fieldDefinition.d.ts +46 -0
- package/dist/esm/types/index.d.ts +4 -0
- package/dist/esm/types.d.ts +56 -0
- package/package.json +122 -0
|
@@ -0,0 +1,1674 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var errors = require('@jaypie/errors');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* FabricModel - Core model vocabulary for @jaypie/fabric
|
|
7
|
+
*
|
|
8
|
+
* Defines the standard fields and structure for all fabric models.
|
|
9
|
+
* Provides a consistent, reusable vocabulary across applications.
|
|
10
|
+
*/
|
|
11
|
+
// =============================================================================
|
|
12
|
+
// Field Name Constants
|
|
13
|
+
// =============================================================================
|
|
14
|
+
/**
|
|
15
|
+
* FabricModel field names as constants
|
|
16
|
+
* Useful for building queries, validation, and serialization
|
|
17
|
+
*/
|
|
18
|
+
const FABRIC_MODEL_FIELDS = {
|
|
19
|
+
// Content
|
|
20
|
+
CONTENT: "content",
|
|
21
|
+
METADATA: "metadata",
|
|
22
|
+
// Display
|
|
23
|
+
EMOJI: "emoji",
|
|
24
|
+
ICON: "icon",
|
|
25
|
+
// History
|
|
26
|
+
HISTORY: "history",
|
|
27
|
+
// Identity (optional)
|
|
28
|
+
ABBREVIATION: "abbreviation",
|
|
29
|
+
ALIAS: "alias",
|
|
30
|
+
DESCRIPTION: "description",
|
|
31
|
+
LABEL: "label",
|
|
32
|
+
NAME: "name",
|
|
33
|
+
XID: "xid",
|
|
34
|
+
// Identity (required)
|
|
35
|
+
ID: "id",
|
|
36
|
+
// Schema
|
|
37
|
+
CLASS: "class",
|
|
38
|
+
MODEL: "model",
|
|
39
|
+
TYPE: "type",
|
|
40
|
+
// Storage
|
|
41
|
+
SCOPE: "scope",
|
|
42
|
+
SEQUENCE: "sequence",
|
|
43
|
+
// Time
|
|
44
|
+
ARCHIVED_AT: "archivedAt",
|
|
45
|
+
CREATED_AT: "createdAt",
|
|
46
|
+
DELETED_AT: "deletedAt",
|
|
47
|
+
UPDATED_AT: "updatedAt",
|
|
48
|
+
};
|
|
49
|
+
/**
|
|
50
|
+
* Required fields for FabricModel
|
|
51
|
+
*/
|
|
52
|
+
const FABRIC_MODEL_REQUIRED_FIELDS = [
|
|
53
|
+
FABRIC_MODEL_FIELDS.CREATED_AT,
|
|
54
|
+
FABRIC_MODEL_FIELDS.ID,
|
|
55
|
+
FABRIC_MODEL_FIELDS.MODEL,
|
|
56
|
+
FABRIC_MODEL_FIELDS.UPDATED_AT,
|
|
57
|
+
];
|
|
58
|
+
/**
|
|
59
|
+
* Auto-generated fields (set by store, not by user)
|
|
60
|
+
*/
|
|
61
|
+
const FABRIC_MODEL_AUTO_FIELDS = [
|
|
62
|
+
FABRIC_MODEL_FIELDS.CREATED_AT,
|
|
63
|
+
FABRIC_MODEL_FIELDS.HISTORY,
|
|
64
|
+
FABRIC_MODEL_FIELDS.ID,
|
|
65
|
+
FABRIC_MODEL_FIELDS.UPDATED_AT,
|
|
66
|
+
];
|
|
67
|
+
/**
|
|
68
|
+
* Timestamp fields
|
|
69
|
+
*/
|
|
70
|
+
const FABRIC_MODEL_TIMESTAMP_FIELDS = [
|
|
71
|
+
FABRIC_MODEL_FIELDS.ARCHIVED_AT,
|
|
72
|
+
FABRIC_MODEL_FIELDS.CREATED_AT,
|
|
73
|
+
FABRIC_MODEL_FIELDS.DELETED_AT,
|
|
74
|
+
FABRIC_MODEL_FIELDS.UPDATED_AT,
|
|
75
|
+
];
|
|
76
|
+
// =============================================================================
|
|
77
|
+
// Type Guards
|
|
78
|
+
// =============================================================================
|
|
79
|
+
/**
|
|
80
|
+
* Check if a value is a FabricModel
|
|
81
|
+
*/
|
|
82
|
+
function isFabricModel(value) {
|
|
83
|
+
if (typeof value !== "object" || value === null) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
const obj = value;
|
|
87
|
+
return (obj.createdAt instanceof Date &&
|
|
88
|
+
typeof obj.id === "string" &&
|
|
89
|
+
typeof obj.model === "string" &&
|
|
90
|
+
obj.updatedAt instanceof Date);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Check if a value has the minimum FabricModel shape (for partial objects)
|
|
94
|
+
*/
|
|
95
|
+
function hasFabricModelShape(value) {
|
|
96
|
+
if (typeof value !== "object" || value === null) {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
const obj = value;
|
|
100
|
+
return typeof obj.id === "string" && typeof obj.model === "string";
|
|
101
|
+
}
|
|
102
|
+
// =============================================================================
|
|
103
|
+
// Utility Functions
|
|
104
|
+
// =============================================================================
|
|
105
|
+
/**
|
|
106
|
+
* Create a minimal FabricModelInput with required fields
|
|
107
|
+
*/
|
|
108
|
+
function createFabricModelInput(overrides) {
|
|
109
|
+
return {
|
|
110
|
+
...overrides,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* Extract only FabricModel fields from an object
|
|
115
|
+
* Useful for sanitizing input or preparing for storage
|
|
116
|
+
*/
|
|
117
|
+
function pickFabricModelFields(obj) {
|
|
118
|
+
const fields = Object.values(FABRIC_MODEL_FIELDS);
|
|
119
|
+
const result = {};
|
|
120
|
+
for (const field of fields) {
|
|
121
|
+
if (field in obj) {
|
|
122
|
+
result[field] = obj[field];
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return result;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Check if a field name is a timestamp field
|
|
129
|
+
*/
|
|
130
|
+
function isTimestampField(field) {
|
|
131
|
+
return FABRIC_MODEL_TIMESTAMP_FIELDS.includes(field);
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Check if a field name is auto-generated
|
|
135
|
+
*/
|
|
136
|
+
function isAutoField(field) {
|
|
137
|
+
return FABRIC_MODEL_AUTO_FIELDS.includes(field);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Meta-modeling Constants
|
|
142
|
+
*/
|
|
143
|
+
// =============================================================================
|
|
144
|
+
// Constants
|
|
145
|
+
// =============================================================================
|
|
146
|
+
/** Root organizational unit */
|
|
147
|
+
const APEX = "@";
|
|
148
|
+
/** Fabric version - used to identify pre-instantiated Services */
|
|
149
|
+
const FABRIC_VERSION = "0.1.0";
|
|
150
|
+
/** Composite key separator */
|
|
151
|
+
const SEPARATOR = "#";
|
|
152
|
+
/** System-level models that describe other models */
|
|
153
|
+
const SYSTEM_MODELS = ["context", "field", "model"];
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Date Type Conversion for @jaypie/fabric
|
|
157
|
+
*
|
|
158
|
+
* Adds Date as a supported type in the fabric type system.
|
|
159
|
+
* Follows the same conversion patterns as String, Number, Boolean.
|
|
160
|
+
*/
|
|
161
|
+
/**
|
|
162
|
+
* Check if a value is a valid Date
|
|
163
|
+
*/
|
|
164
|
+
function isValidDate(value) {
|
|
165
|
+
return value instanceof Date && !Number.isNaN(value.getTime());
|
|
166
|
+
}
|
|
167
|
+
/**
|
|
168
|
+
* Convert a value to a Date
|
|
169
|
+
*
|
|
170
|
+
* Supported inputs:
|
|
171
|
+
* - Date: returned as-is (validated)
|
|
172
|
+
* - Number: treated as Unix timestamp (milliseconds)
|
|
173
|
+
* - String: parsed via Date constructor (ISO 8601, etc.)
|
|
174
|
+
* - Object with value property: unwrapped and converted
|
|
175
|
+
*
|
|
176
|
+
* @throws BadRequestError if value cannot be converted to valid Date
|
|
177
|
+
*/
|
|
178
|
+
function fabricDate(value) {
|
|
179
|
+
// Already a Date
|
|
180
|
+
if (value instanceof Date) {
|
|
181
|
+
if (Number.isNaN(value.getTime())) {
|
|
182
|
+
throw new errors.BadRequestError("Invalid Date value");
|
|
183
|
+
}
|
|
184
|
+
return value;
|
|
185
|
+
}
|
|
186
|
+
// Null/undefined
|
|
187
|
+
if (value === null || value === undefined) {
|
|
188
|
+
throw new errors.BadRequestError("Cannot convert null or undefined to Date");
|
|
189
|
+
}
|
|
190
|
+
// Object with value property (fabric pattern)
|
|
191
|
+
if (typeof value === "object" && value !== null && "value" in value) {
|
|
192
|
+
return fabricDate(value.value);
|
|
193
|
+
}
|
|
194
|
+
// Number (timestamp in milliseconds)
|
|
195
|
+
if (typeof value === "number") {
|
|
196
|
+
if (Number.isNaN(value)) {
|
|
197
|
+
throw new errors.BadRequestError("Cannot convert NaN to Date");
|
|
198
|
+
}
|
|
199
|
+
const date = new Date(value);
|
|
200
|
+
if (Number.isNaN(date.getTime())) {
|
|
201
|
+
throw new errors.BadRequestError(`Cannot convert ${value} to Date`);
|
|
202
|
+
}
|
|
203
|
+
return date;
|
|
204
|
+
}
|
|
205
|
+
// String (ISO 8601 or parseable format)
|
|
206
|
+
if (typeof value === "string") {
|
|
207
|
+
// Empty string is invalid
|
|
208
|
+
if (value.trim() === "") {
|
|
209
|
+
throw new errors.BadRequestError("Cannot convert empty string to Date");
|
|
210
|
+
}
|
|
211
|
+
const date = new Date(value);
|
|
212
|
+
if (Number.isNaN(date.getTime())) {
|
|
213
|
+
throw new errors.BadRequestError(`Cannot convert "${value}" to Date`);
|
|
214
|
+
}
|
|
215
|
+
return date;
|
|
216
|
+
}
|
|
217
|
+
// Boolean cannot be converted to Date
|
|
218
|
+
if (typeof value === "boolean") {
|
|
219
|
+
throw new errors.BadRequestError("Cannot convert boolean to Date");
|
|
220
|
+
}
|
|
221
|
+
// Arrays - attempt single element extraction
|
|
222
|
+
if (Array.isArray(value)) {
|
|
223
|
+
if (value.length === 1) {
|
|
224
|
+
return fabricDate(value[0]);
|
|
225
|
+
}
|
|
226
|
+
throw new errors.BadRequestError(`Cannot convert array with ${value.length} elements to Date`);
|
|
227
|
+
}
|
|
228
|
+
throw new errors.BadRequestError(`Cannot convert ${typeof value} to Date`);
|
|
229
|
+
}
|
|
230
|
+
/**
|
|
231
|
+
* Resolve a value from a Date to another type
|
|
232
|
+
*
|
|
233
|
+
* @param value - Date to convert
|
|
234
|
+
* @param targetType - Target type (String, Number)
|
|
235
|
+
*/
|
|
236
|
+
function resolveFromDate(value, targetType) {
|
|
237
|
+
if (!isValidDate(value)) {
|
|
238
|
+
throw new errors.BadRequestError("Invalid Date value");
|
|
239
|
+
}
|
|
240
|
+
if (targetType === String) {
|
|
241
|
+
return value.toISOString();
|
|
242
|
+
}
|
|
243
|
+
if (targetType === Number) {
|
|
244
|
+
return value.getTime();
|
|
245
|
+
}
|
|
246
|
+
throw new errors.BadRequestError(`Cannot convert Date to ${targetType}`);
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Date type constant for use in fabricService input definitions
|
|
250
|
+
*
|
|
251
|
+
* Usage:
|
|
252
|
+
* ```typescript
|
|
253
|
+
* const handler = fabricService({
|
|
254
|
+
* input: {
|
|
255
|
+
* startDate: { type: Date },
|
|
256
|
+
* endDate: { type: Date, default: undefined }
|
|
257
|
+
* }
|
|
258
|
+
* });
|
|
259
|
+
* ```
|
|
260
|
+
*/
|
|
261
|
+
const DateType = Date;
|
|
262
|
+
/**
|
|
263
|
+
* Type guard for Date type in schema definitions
|
|
264
|
+
*/
|
|
265
|
+
function isDateType(type) {
|
|
266
|
+
return type === Date;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// Fabric functions for @jaypie/fabric
|
|
270
|
+
/**
|
|
271
|
+
* Try to parse a string as JSON if it looks like JSON
|
|
272
|
+
* Returns the parsed value or the original string if not JSON
|
|
273
|
+
*/
|
|
274
|
+
function tryParseJson(value) {
|
|
275
|
+
const trimmed = value.trim();
|
|
276
|
+
if ((trimmed.startsWith("{") && trimmed.endsWith("}")) ||
|
|
277
|
+
(trimmed.startsWith("[") && trimmed.endsWith("]"))) {
|
|
278
|
+
try {
|
|
279
|
+
return JSON.parse(trimmed);
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
// Not valid JSON, return original
|
|
283
|
+
return value;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return value;
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Unwrap arrays and objects to get to the scalar value
|
|
290
|
+
* - Single-element arrays unwrap to their element
|
|
291
|
+
* - Objects with value property unwrap to that value
|
|
292
|
+
* - Recursively unwraps nested structures
|
|
293
|
+
*/
|
|
294
|
+
function unwrapToScalar(value) {
|
|
295
|
+
if (value === undefined || value === null) {
|
|
296
|
+
return value;
|
|
297
|
+
}
|
|
298
|
+
// Unwrap single-element arrays
|
|
299
|
+
if (Array.isArray(value)) {
|
|
300
|
+
if (value.length === 0) {
|
|
301
|
+
return undefined;
|
|
302
|
+
}
|
|
303
|
+
if (value.length === 1) {
|
|
304
|
+
return unwrapToScalar(value[0]);
|
|
305
|
+
}
|
|
306
|
+
throw new errors.BadRequestError("Cannot convert multi-value array to scalar");
|
|
307
|
+
}
|
|
308
|
+
// Unwrap objects with value property
|
|
309
|
+
if (typeof value === "object") {
|
|
310
|
+
const obj = value;
|
|
311
|
+
if ("value" in obj) {
|
|
312
|
+
return unwrapToScalar(obj.value);
|
|
313
|
+
}
|
|
314
|
+
throw new errors.BadRequestError("Object must have a value attribute");
|
|
315
|
+
}
|
|
316
|
+
return value;
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* Prepare a value for scalar conversion by parsing JSON strings and unwrapping
|
|
320
|
+
*/
|
|
321
|
+
function prepareForScalarConversion(value) {
|
|
322
|
+
if (value === undefined || value === null) {
|
|
323
|
+
return value;
|
|
324
|
+
}
|
|
325
|
+
// Try to parse JSON strings
|
|
326
|
+
if (typeof value === "string") {
|
|
327
|
+
const parsed = tryParseJson(value);
|
|
328
|
+
if (parsed !== value) {
|
|
329
|
+
// Successfully parsed, unwrap the result
|
|
330
|
+
return unwrapToScalar(parsed);
|
|
331
|
+
}
|
|
332
|
+
return value;
|
|
333
|
+
}
|
|
334
|
+
// Unwrap arrays and objects
|
|
335
|
+
if (Array.isArray(value) || typeof value === "object") {
|
|
336
|
+
return unwrapToScalar(value);
|
|
337
|
+
}
|
|
338
|
+
return value;
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* Convert a value to a boolean
|
|
342
|
+
* - Arrays, objects, and JSON strings are unwrapped first
|
|
343
|
+
* - String "true" becomes true
|
|
344
|
+
* - String "false" becomes false
|
|
345
|
+
* - Strings that parse to numbers: positive = true, zero or negative = false
|
|
346
|
+
* - Numbers: positive = true, zero or negative = false
|
|
347
|
+
* - Boolean passes through
|
|
348
|
+
*/
|
|
349
|
+
function fabricBoolean(value) {
|
|
350
|
+
// Prepare value by parsing JSON and unwrapping arrays/objects
|
|
351
|
+
const prepared = prepareForScalarConversion(value);
|
|
352
|
+
if (prepared === undefined || prepared === null) {
|
|
353
|
+
return undefined;
|
|
354
|
+
}
|
|
355
|
+
if (typeof prepared === "boolean") {
|
|
356
|
+
return prepared;
|
|
357
|
+
}
|
|
358
|
+
if (typeof prepared === "string") {
|
|
359
|
+
if (prepared === "") {
|
|
360
|
+
return undefined;
|
|
361
|
+
}
|
|
362
|
+
const lower = prepared.toLowerCase();
|
|
363
|
+
if (lower === "true") {
|
|
364
|
+
return true;
|
|
365
|
+
}
|
|
366
|
+
if (lower === "false") {
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
// Try to parse as number
|
|
370
|
+
const num = parseFloat(prepared);
|
|
371
|
+
if (isNaN(num)) {
|
|
372
|
+
throw new errors.BadRequestError(`Cannot convert "${prepared}" to Boolean`);
|
|
373
|
+
}
|
|
374
|
+
return num > 0;
|
|
375
|
+
}
|
|
376
|
+
if (typeof prepared === "number") {
|
|
377
|
+
if (isNaN(prepared)) {
|
|
378
|
+
throw new errors.BadRequestError("Cannot convert NaN to Boolean");
|
|
379
|
+
}
|
|
380
|
+
return prepared > 0;
|
|
381
|
+
}
|
|
382
|
+
throw new errors.BadRequestError(`Cannot convert ${typeof prepared} to Boolean`);
|
|
383
|
+
}
|
|
384
|
+
/**
|
|
385
|
+
* Convert a value to a number
|
|
386
|
+
* - Arrays, objects, and JSON strings are unwrapped first
|
|
387
|
+
* - String "" becomes undefined
|
|
388
|
+
* - String "true" becomes 1
|
|
389
|
+
* - String "false" becomes 0
|
|
390
|
+
* - Strings that parse to numbers use those values
|
|
391
|
+
* - Strings that parse to NaN throw BadRequestError
|
|
392
|
+
* - Boolean true becomes 1, false becomes 0
|
|
393
|
+
* - Number passes through
|
|
394
|
+
*/
|
|
395
|
+
function fabricNumber(value) {
|
|
396
|
+
// Prepare value by parsing JSON and unwrapping arrays/objects
|
|
397
|
+
const prepared = prepareForScalarConversion(value);
|
|
398
|
+
if (prepared === undefined || prepared === null) {
|
|
399
|
+
return undefined;
|
|
400
|
+
}
|
|
401
|
+
if (typeof prepared === "number") {
|
|
402
|
+
if (isNaN(prepared)) {
|
|
403
|
+
throw new errors.BadRequestError("Cannot convert NaN to Number");
|
|
404
|
+
}
|
|
405
|
+
return prepared;
|
|
406
|
+
}
|
|
407
|
+
if (typeof prepared === "boolean") {
|
|
408
|
+
return prepared ? 1 : 0;
|
|
409
|
+
}
|
|
410
|
+
if (typeof prepared === "string") {
|
|
411
|
+
if (prepared === "") {
|
|
412
|
+
return undefined;
|
|
413
|
+
}
|
|
414
|
+
const lower = prepared.toLowerCase();
|
|
415
|
+
if (lower === "true") {
|
|
416
|
+
return 1;
|
|
417
|
+
}
|
|
418
|
+
if (lower === "false") {
|
|
419
|
+
return 0;
|
|
420
|
+
}
|
|
421
|
+
const num = parseFloat(prepared);
|
|
422
|
+
if (isNaN(num)) {
|
|
423
|
+
throw new errors.BadRequestError(`Cannot convert "${prepared}" to Number`);
|
|
424
|
+
}
|
|
425
|
+
return num;
|
|
426
|
+
}
|
|
427
|
+
throw new errors.BadRequestError(`Cannot convert ${typeof prepared} to Number`);
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Convert a value to a string
|
|
431
|
+
* - Arrays, objects, and JSON strings are unwrapped first
|
|
432
|
+
* - String "" becomes undefined
|
|
433
|
+
* - Boolean true becomes "true", false becomes "false"
|
|
434
|
+
* - Number converts to string representation
|
|
435
|
+
* - String passes through
|
|
436
|
+
*/
|
|
437
|
+
function fabricString(value) {
|
|
438
|
+
// Prepare value by parsing JSON and unwrapping arrays/objects
|
|
439
|
+
const prepared = prepareForScalarConversion(value);
|
|
440
|
+
if (prepared === undefined || prepared === null) {
|
|
441
|
+
return undefined;
|
|
442
|
+
}
|
|
443
|
+
if (typeof prepared === "string") {
|
|
444
|
+
if (prepared === "") {
|
|
445
|
+
return undefined;
|
|
446
|
+
}
|
|
447
|
+
return prepared;
|
|
448
|
+
}
|
|
449
|
+
if (typeof prepared === "boolean") {
|
|
450
|
+
return prepared ? "true" : "false";
|
|
451
|
+
}
|
|
452
|
+
if (typeof prepared === "number") {
|
|
453
|
+
if (isNaN(prepared)) {
|
|
454
|
+
throw new errors.BadRequestError("Cannot convert NaN to String");
|
|
455
|
+
}
|
|
456
|
+
return String(prepared);
|
|
457
|
+
}
|
|
458
|
+
throw new errors.BadRequestError(`Cannot convert ${typeof prepared} to String`);
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* Convert a value to an array
|
|
462
|
+
* - Non-arrays become arrays containing that value
|
|
463
|
+
* - Arrays of a single value become that value (unwrapped)
|
|
464
|
+
* - Multi-value arrays throw BadRequestError
|
|
465
|
+
* - undefined/null become undefined
|
|
466
|
+
*/
|
|
467
|
+
function fabricArray(value) {
|
|
468
|
+
if (value === undefined || value === null) {
|
|
469
|
+
return undefined;
|
|
470
|
+
}
|
|
471
|
+
if (Array.isArray(value)) {
|
|
472
|
+
// Arrays pass through (single-element unwrapping happens when converting FROM array)
|
|
473
|
+
return value;
|
|
474
|
+
}
|
|
475
|
+
// Non-arrays become single-element arrays
|
|
476
|
+
return [value];
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Resolve a value from an array to a scalar
|
|
480
|
+
* - Single-element arrays become that element
|
|
481
|
+
* - Multi-element arrays throw BadRequestError
|
|
482
|
+
* - Non-arrays pass through
|
|
483
|
+
*/
|
|
484
|
+
function resolveFromArray(value) {
|
|
485
|
+
if (value === undefined || value === null) {
|
|
486
|
+
return undefined;
|
|
487
|
+
}
|
|
488
|
+
if (Array.isArray(value)) {
|
|
489
|
+
if (value.length === 0) {
|
|
490
|
+
return undefined;
|
|
491
|
+
}
|
|
492
|
+
if (value.length === 1) {
|
|
493
|
+
return value[0];
|
|
494
|
+
}
|
|
495
|
+
throw new errors.BadRequestError("Cannot convert multi-value array to scalar");
|
|
496
|
+
}
|
|
497
|
+
return value;
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* Convert a value to an object with a value property
|
|
501
|
+
* - Scalars become { value: scalar }
|
|
502
|
+
* - Arrays become { value: array }
|
|
503
|
+
* - Objects with a value attribute pass through
|
|
504
|
+
* - Objects without a value attribute throw BadRequestError
|
|
505
|
+
* - undefined/null become undefined
|
|
506
|
+
*/
|
|
507
|
+
function fabricObject(value) {
|
|
508
|
+
if (value === undefined || value === null) {
|
|
509
|
+
return undefined;
|
|
510
|
+
}
|
|
511
|
+
// Check if already an object (but not an array)
|
|
512
|
+
if (typeof value === "object" && !Array.isArray(value)) {
|
|
513
|
+
const obj = value;
|
|
514
|
+
if ("value" in obj) {
|
|
515
|
+
return obj;
|
|
516
|
+
}
|
|
517
|
+
throw new errors.BadRequestError("Object must have a value attribute");
|
|
518
|
+
}
|
|
519
|
+
// Scalars and arrays become { value: ... }
|
|
520
|
+
return { value };
|
|
521
|
+
}
|
|
522
|
+
/**
|
|
523
|
+
* Resolve a value from an object to its value property
|
|
524
|
+
* - Objects with a value property return that value
|
|
525
|
+
* - Objects without a value throw BadRequestError
|
|
526
|
+
* - Scalars pass through
|
|
527
|
+
*/
|
|
528
|
+
function resolveFromObject(value) {
|
|
529
|
+
if (value === undefined || value === null) {
|
|
530
|
+
return undefined;
|
|
531
|
+
}
|
|
532
|
+
if (typeof value === "object" && !Array.isArray(value)) {
|
|
533
|
+
const obj = value;
|
|
534
|
+
if ("value" in obj) {
|
|
535
|
+
return obj.value;
|
|
536
|
+
}
|
|
537
|
+
throw new errors.BadRequestError("Object must have a value attribute");
|
|
538
|
+
}
|
|
539
|
+
return value;
|
|
540
|
+
}
|
|
541
|
+
/**
|
|
542
|
+
* Check if a type is a typed array (e.g., [String], [Number], [], etc.)
|
|
543
|
+
*/
|
|
544
|
+
function isTypedArrayType(type) {
|
|
545
|
+
return Array.isArray(type);
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Split a string on comma or tab delimiters for typed array conversion.
|
|
549
|
+
* Only splits if the string contains commas or tabs.
|
|
550
|
+
* Returns the original value if not a string or no delimiters found.
|
|
551
|
+
*/
|
|
552
|
+
function splitStringForArray(value) {
|
|
553
|
+
if (typeof value !== "string") {
|
|
554
|
+
return value;
|
|
555
|
+
}
|
|
556
|
+
// Check for comma or tab delimiters
|
|
557
|
+
if (value.includes(",")) {
|
|
558
|
+
return value.split(",").map((s) => s.trim());
|
|
559
|
+
}
|
|
560
|
+
if (value.includes("\t")) {
|
|
561
|
+
return value.split("\t").map((s) => s.trim());
|
|
562
|
+
}
|
|
563
|
+
return value;
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Try to parse a string as JSON for array context.
|
|
567
|
+
* Returns parsed value if it's an array, otherwise returns original.
|
|
568
|
+
*/
|
|
569
|
+
function tryParseJsonArray(value) {
|
|
570
|
+
if (typeof value !== "string") {
|
|
571
|
+
return value;
|
|
572
|
+
}
|
|
573
|
+
const trimmed = value.trim();
|
|
574
|
+
if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
|
|
575
|
+
try {
|
|
576
|
+
const parsed = JSON.parse(trimmed);
|
|
577
|
+
if (Array.isArray(parsed)) {
|
|
578
|
+
return parsed;
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
catch {
|
|
582
|
+
// Not valid JSON, fall through
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
return value;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Get the element type from a typed array type
|
|
589
|
+
* Returns undefined for untyped arrays ([])
|
|
590
|
+
*/
|
|
591
|
+
function getArrayElementType(type) {
|
|
592
|
+
if (type.length === 0) {
|
|
593
|
+
return undefined; // Untyped array
|
|
594
|
+
}
|
|
595
|
+
const elementType = type[0];
|
|
596
|
+
// Handle constructor types
|
|
597
|
+
if (elementType === Boolean)
|
|
598
|
+
return "boolean";
|
|
599
|
+
if (elementType === Number)
|
|
600
|
+
return "number";
|
|
601
|
+
if (elementType === String)
|
|
602
|
+
return "string";
|
|
603
|
+
if (elementType === Object)
|
|
604
|
+
return "object";
|
|
605
|
+
// Handle string types
|
|
606
|
+
if (elementType === "boolean")
|
|
607
|
+
return "boolean";
|
|
608
|
+
if (elementType === "number")
|
|
609
|
+
return "number";
|
|
610
|
+
if (elementType === "string")
|
|
611
|
+
return "string";
|
|
612
|
+
if (elementType === "object")
|
|
613
|
+
return "object";
|
|
614
|
+
// Handle shorthand types
|
|
615
|
+
if (elementType === "")
|
|
616
|
+
return "string"; // "" shorthand for String
|
|
617
|
+
if (typeof elementType === "object" &&
|
|
618
|
+
elementType !== null &&
|
|
619
|
+
Object.keys(elementType).length === 0) {
|
|
620
|
+
return "object"; // {} shorthand for Object
|
|
621
|
+
}
|
|
622
|
+
throw new errors.BadRequestError(`Unknown array element type: ${String(elementType)}`);
|
|
623
|
+
}
|
|
624
|
+
/**
|
|
625
|
+
* Convert a value to a typed array
|
|
626
|
+
* - Tries to parse JSON arrays first
|
|
627
|
+
* - Splits strings on comma/tab if present
|
|
628
|
+
* - Wraps non-arrays in an array
|
|
629
|
+
* - Converts each element to the specified element type
|
|
630
|
+
*/
|
|
631
|
+
function fabricTypedArray(value, elementType) {
|
|
632
|
+
// Try to parse JSON array first
|
|
633
|
+
let processed = tryParseJsonArray(value);
|
|
634
|
+
// If still a string, try to split on comma/tab
|
|
635
|
+
processed = splitStringForArray(processed);
|
|
636
|
+
// Convert to array (wraps non-arrays)
|
|
637
|
+
const array = fabricArray(processed);
|
|
638
|
+
if (array === undefined) {
|
|
639
|
+
return undefined;
|
|
640
|
+
}
|
|
641
|
+
// If no element type specified, return as-is
|
|
642
|
+
if (elementType === undefined) {
|
|
643
|
+
return array;
|
|
644
|
+
}
|
|
645
|
+
// Convert each element to the element type
|
|
646
|
+
return array.map((element, index) => {
|
|
647
|
+
try {
|
|
648
|
+
switch (elementType) {
|
|
649
|
+
case "boolean":
|
|
650
|
+
return fabricBoolean(element);
|
|
651
|
+
case "number":
|
|
652
|
+
return fabricNumber(element);
|
|
653
|
+
case "object":
|
|
654
|
+
return fabricObject(element);
|
|
655
|
+
case "string":
|
|
656
|
+
return fabricString(element);
|
|
657
|
+
default:
|
|
658
|
+
throw new errors.BadRequestError(`Unknown element type: ${elementType}`);
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
catch (error) {
|
|
662
|
+
if (error instanceof errors.BadRequestError) {
|
|
663
|
+
throw new errors.BadRequestError(`Cannot convert array element at index ${index}: ${error.message}`);
|
|
664
|
+
}
|
|
665
|
+
throw error;
|
|
666
|
+
}
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
/**
|
|
670
|
+
* Fabric a value to the specified type
|
|
671
|
+
*/
|
|
672
|
+
function fabric(value, type) {
|
|
673
|
+
// Check for Date type first
|
|
674
|
+
if (isDateType(type)) {
|
|
675
|
+
return fabricDate(value);
|
|
676
|
+
}
|
|
677
|
+
// Check for typed array types
|
|
678
|
+
if (isTypedArrayType(type)) {
|
|
679
|
+
const elementType = getArrayElementType(type);
|
|
680
|
+
return fabricTypedArray(value, elementType);
|
|
681
|
+
}
|
|
682
|
+
const normalizedType = normalizeType(type);
|
|
683
|
+
switch (normalizedType) {
|
|
684
|
+
case "array":
|
|
685
|
+
return fabricArray(value);
|
|
686
|
+
case "boolean":
|
|
687
|
+
return fabricBoolean(value);
|
|
688
|
+
case "number":
|
|
689
|
+
return fabricNumber(value);
|
|
690
|
+
case "object":
|
|
691
|
+
return fabricObject(value);
|
|
692
|
+
case "string":
|
|
693
|
+
return fabricString(value);
|
|
694
|
+
default:
|
|
695
|
+
throw new errors.BadRequestError(`Unknown type: ${String(type)}`);
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
/**
|
|
699
|
+
* Normalize type to string representation
|
|
700
|
+
*/
|
|
701
|
+
function normalizeType(type) {
|
|
702
|
+
if (type === Array || type === "array") {
|
|
703
|
+
return "array";
|
|
704
|
+
}
|
|
705
|
+
if (type === Boolean || type === "boolean") {
|
|
706
|
+
return "boolean";
|
|
707
|
+
}
|
|
708
|
+
if (type === Number || type === "number") {
|
|
709
|
+
return "number";
|
|
710
|
+
}
|
|
711
|
+
if (type === Object || type === "object") {
|
|
712
|
+
return "object";
|
|
713
|
+
}
|
|
714
|
+
if (type === String || type === "string") {
|
|
715
|
+
return "string";
|
|
716
|
+
}
|
|
717
|
+
throw new errors.BadRequestError(`Unknown type: ${String(type)}`);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
/**
|
|
721
|
+
* Fallback Resolution Helper
|
|
722
|
+
*
|
|
723
|
+
* Resolves a field value with a fallback chain.
|
|
724
|
+
*/
|
|
725
|
+
// =============================================================================
|
|
726
|
+
// Helper Functions
|
|
727
|
+
// =============================================================================
|
|
728
|
+
/**
|
|
729
|
+
* Resolve a field value with fallbacks
|
|
730
|
+
*
|
|
731
|
+
* @param entity - The entity to read from
|
|
732
|
+
* @param field - The primary field name
|
|
733
|
+
* @param fallbacks - Fallback field names in priority order
|
|
734
|
+
* @returns First defined value, or undefined
|
|
735
|
+
*
|
|
736
|
+
* @example
|
|
737
|
+
* ```typescript
|
|
738
|
+
* const model = { title: undefined, name: "My Model", description: "A description" };
|
|
739
|
+
* resolveWithFallback(model, "title", ["name", "description"]);
|
|
740
|
+
* // Returns "My Model"
|
|
741
|
+
* ```
|
|
742
|
+
*/
|
|
743
|
+
function resolveWithFallback(entity, field, fallbacks = []) {
|
|
744
|
+
// Check primary field
|
|
745
|
+
if (entity[field] !== undefined) {
|
|
746
|
+
return entity[field];
|
|
747
|
+
}
|
|
748
|
+
// Check fallbacks in order
|
|
749
|
+
for (const fallback of fallbacks) {
|
|
750
|
+
if (entity[fallback] !== undefined) {
|
|
751
|
+
return entity[fallback];
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
return undefined;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Resolved Name Helper
|
|
759
|
+
*
|
|
760
|
+
* Computes a resolved name from model fields using a priority chain.
|
|
761
|
+
*/
|
|
762
|
+
// =============================================================================
|
|
763
|
+
// Helper Functions
|
|
764
|
+
// =============================================================================
|
|
765
|
+
/**
|
|
766
|
+
* Compute resolved name from model fields
|
|
767
|
+
*
|
|
768
|
+
* Priority: name > alias > abbreviation > description
|
|
769
|
+
* Result is lowercase for consistent sorting/indexing
|
|
770
|
+
*
|
|
771
|
+
* @param model - The model to compute the resolved name from
|
|
772
|
+
* @returns The resolved name (lowercase) or undefined if no name fields exist
|
|
773
|
+
*/
|
|
774
|
+
function computeResolvedName(model) {
|
|
775
|
+
const value = model.name || model.alias || model.abbreviation || model.description;
|
|
776
|
+
return value?.toLowerCase();
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
/**
|
|
780
|
+
* Index Types for @jaypie/fabric
|
|
781
|
+
*
|
|
782
|
+
* Declarative index definitions for DynamoDB single-table design.
|
|
783
|
+
* Models can specify their own indexes, and dynamodb will create
|
|
784
|
+
* GSIs and auto-detect which index to use for queries.
|
|
785
|
+
*/
|
|
786
|
+
// =============================================================================
|
|
787
|
+
// Default Indexes
|
|
788
|
+
// =============================================================================
|
|
789
|
+
/**
|
|
790
|
+
* Default indexes for the DynamoDB GSI pattern.
|
|
791
|
+
* These are used when a model does not specify custom indexes.
|
|
792
|
+
*/
|
|
793
|
+
const DEFAULT_INDEXES = [
|
|
794
|
+
{ name: "indexScope", pk: ["scope", "model"], sk: ["sequence"] },
|
|
795
|
+
{
|
|
796
|
+
name: "indexAlias",
|
|
797
|
+
pk: ["scope", "model", "alias"],
|
|
798
|
+
sk: ["sequence"],
|
|
799
|
+
sparse: true,
|
|
800
|
+
},
|
|
801
|
+
{
|
|
802
|
+
name: "indexClass",
|
|
803
|
+
pk: ["scope", "model", "class"],
|
|
804
|
+
sk: ["sequence"],
|
|
805
|
+
sparse: true,
|
|
806
|
+
},
|
|
807
|
+
{
|
|
808
|
+
name: "indexType",
|
|
809
|
+
pk: ["scope", "model", "type"],
|
|
810
|
+
sk: ["sequence"],
|
|
811
|
+
sparse: true,
|
|
812
|
+
},
|
|
813
|
+
{
|
|
814
|
+
name: "indexXid",
|
|
815
|
+
pk: ["scope", "model", "xid"],
|
|
816
|
+
sk: ["sequence"],
|
|
817
|
+
sparse: true,
|
|
818
|
+
},
|
|
819
|
+
];
|
|
820
|
+
// =============================================================================
|
|
821
|
+
// Constants
|
|
822
|
+
// =============================================================================
|
|
823
|
+
/**
|
|
824
|
+
* Default sort key fields when sk is not specified
|
|
825
|
+
*/
|
|
826
|
+
const DEFAULT_SORT_KEY = ["sequence"];
|
|
827
|
+
/**
|
|
828
|
+
* Suffix appended to index keys when model is archived
|
|
829
|
+
*/
|
|
830
|
+
const ARCHIVED_SUFFIX = "#archived";
|
|
831
|
+
/**
|
|
832
|
+
* Suffix appended to index keys when model is deleted
|
|
833
|
+
*/
|
|
834
|
+
const DELETED_SUFFIX = "#deleted";
|
|
835
|
+
|
|
836
|
+
/**
|
|
837
|
+
* Key Builder for @jaypie/fabric
|
|
838
|
+
*
|
|
839
|
+
* Builds composite keys from model fields and index definitions.
|
|
840
|
+
*/
|
|
841
|
+
// =============================================================================
|
|
842
|
+
// Key Builders
|
|
843
|
+
// =============================================================================
|
|
844
|
+
/**
|
|
845
|
+
* Build a composite key from model fields
|
|
846
|
+
*
|
|
847
|
+
* @param model - Model with fields to extract
|
|
848
|
+
* @param fields - Field names to combine
|
|
849
|
+
* @param suffix - Optional suffix to append (e.g., "#deleted")
|
|
850
|
+
* @returns Composite key string (e.g., "@#record#my-alias")
|
|
851
|
+
* @throws ConfigurationError if a required field is missing
|
|
852
|
+
*/
|
|
853
|
+
function buildCompositeKey(model, fields, suffix) {
|
|
854
|
+
const parts = fields.map((field) => {
|
|
855
|
+
const value = model[field];
|
|
856
|
+
if (value === undefined || value === null) {
|
|
857
|
+
throw new errors.ConfigurationError(`Missing field for index key: ${field}`);
|
|
858
|
+
}
|
|
859
|
+
return String(value);
|
|
860
|
+
});
|
|
861
|
+
const key = parts.join(SEPARATOR);
|
|
862
|
+
return suffix ? key + suffix : key;
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Try to build a composite key, returning undefined if fields are missing
|
|
866
|
+
*
|
|
867
|
+
* @param model - Model with fields to extract
|
|
868
|
+
* @param fields - Field names to combine
|
|
869
|
+
* @param suffix - Optional suffix to append
|
|
870
|
+
* @returns Composite key string or undefined if fields missing
|
|
871
|
+
*/
|
|
872
|
+
function tryBuildCompositeKey(model, fields, suffix) {
|
|
873
|
+
for (const field of fields) {
|
|
874
|
+
const value = model[field];
|
|
875
|
+
if (value === undefined || value === null) {
|
|
876
|
+
return undefined;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
return buildCompositeKey(model, fields, suffix);
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* Generate an index name from partition key fields
|
|
883
|
+
*
|
|
884
|
+
* @param pk - Partition key field names
|
|
885
|
+
* @returns Generated index name (e.g., "indexOuModelAlias")
|
|
886
|
+
*/
|
|
887
|
+
function generateIndexName(pk) {
|
|
888
|
+
const suffix = pk
|
|
889
|
+
.map((field) => {
|
|
890
|
+
const str = String(field);
|
|
891
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
892
|
+
})
|
|
893
|
+
.join("");
|
|
894
|
+
return `index${suffix}`;
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Calculate the suffix for index keys based on model state
|
|
898
|
+
*
|
|
899
|
+
* @param model - Model to check for archived/deleted state
|
|
900
|
+
* @returns Suffix string (e.g., "", "#archived", "#deleted", "#archived#deleted")
|
|
901
|
+
*/
|
|
902
|
+
function calculateIndexSuffix(model) {
|
|
903
|
+
let suffix = "";
|
|
904
|
+
if (model.archivedAt !== undefined && model.archivedAt !== null) {
|
|
905
|
+
suffix += ARCHIVED_SUFFIX;
|
|
906
|
+
}
|
|
907
|
+
if (model.deletedAt !== undefined && model.deletedAt !== null) {
|
|
908
|
+
suffix += DELETED_SUFFIX;
|
|
909
|
+
}
|
|
910
|
+
return suffix;
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Populate index keys on a model based on index definitions
|
|
914
|
+
*
|
|
915
|
+
* Only the partition key composite is stored on the model (e.g., indexOu).
|
|
916
|
+
* The sort key (e.g., sequence) is a regular field that the GSI references directly.
|
|
917
|
+
*
|
|
918
|
+
* @param model - Model to populate index keys on
|
|
919
|
+
* @param indexes - Index definitions to use
|
|
920
|
+
* @param suffix - Optional suffix to append to all index keys
|
|
921
|
+
* @returns Model with index keys populated
|
|
922
|
+
*/
|
|
923
|
+
function populateIndexKeys(model, indexes, suffix) {
|
|
924
|
+
const result = { ...model };
|
|
925
|
+
const appliedSuffix = suffix ?? calculateIndexSuffix(model);
|
|
926
|
+
for (const index of indexes) {
|
|
927
|
+
const indexName = index.name ?? generateIndexName(index.pk);
|
|
928
|
+
const pkKey = indexName;
|
|
929
|
+
// For sparse indexes, only populate if all pk fields are present
|
|
930
|
+
if (index.sparse) {
|
|
931
|
+
const pkValue = tryBuildCompositeKey(model, index.pk, appliedSuffix);
|
|
932
|
+
if (pkValue !== undefined) {
|
|
933
|
+
result[pkKey] = pkValue;
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
else {
|
|
937
|
+
// For non-sparse indexes, always try to populate (will throw if fields missing)
|
|
938
|
+
const pkValue = tryBuildCompositeKey(model, index.pk, appliedSuffix);
|
|
939
|
+
if (pkValue !== undefined) {
|
|
940
|
+
result[pkKey] = pkValue;
|
|
941
|
+
}
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
return result;
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Calculate scope from parent reference
|
|
948
|
+
*
|
|
949
|
+
* @param parent - Parent model with model and id
|
|
950
|
+
* @returns Scope string ("{parent.model}#{parent.id}") or APEX ("@") if no parent
|
|
951
|
+
*/
|
|
952
|
+
function calculateScope(parent) {
|
|
953
|
+
if (!parent) {
|
|
954
|
+
return "@"; // APEX
|
|
955
|
+
}
|
|
956
|
+
return `${parent.model}${SEPARATOR}${parent.id}`;
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/**
|
|
960
|
+
* Model Registry for @jaypie/fabric
|
|
961
|
+
*
|
|
962
|
+
* Stores model schemas with their index definitions.
|
|
963
|
+
* DynamoDB reads from this registry to create GSIs and select indexes for queries.
|
|
964
|
+
*/
|
|
965
|
+
// =============================================================================
|
|
966
|
+
// Registry
|
|
967
|
+
// =============================================================================
|
|
968
|
+
/**
|
|
969
|
+
* Global model registry - maps model names to their schemas
|
|
970
|
+
*/
|
|
971
|
+
const MODEL_REGISTRY = new Map();
|
|
972
|
+
// =============================================================================
|
|
973
|
+
// Functions
|
|
974
|
+
// =============================================================================
|
|
975
|
+
/**
|
|
976
|
+
* Register a model schema with its index definitions
|
|
977
|
+
*
|
|
978
|
+
* @param schema - Model schema with model name and optional indexes
|
|
979
|
+
*/
|
|
980
|
+
function registerModel(schema) {
|
|
981
|
+
MODEL_REGISTRY.set(schema.model, schema);
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* Get a model schema by name
|
|
985
|
+
*
|
|
986
|
+
* @param model - Model name to look up
|
|
987
|
+
* @returns Model schema or undefined if not registered
|
|
988
|
+
*/
|
|
989
|
+
function getModelSchema(model) {
|
|
990
|
+
return MODEL_REGISTRY.get(model);
|
|
991
|
+
}
|
|
992
|
+
/**
|
|
993
|
+
* Get index definitions for a model
|
|
994
|
+
*
|
|
995
|
+
* Returns the model's custom indexes if registered,
|
|
996
|
+
* otherwise returns DEFAULT_INDEXES.
|
|
997
|
+
*
|
|
998
|
+
* @param model - Model name to get indexes for
|
|
999
|
+
* @returns Array of index definitions
|
|
1000
|
+
*/
|
|
1001
|
+
function getModelIndexes(model) {
|
|
1002
|
+
const schema = MODEL_REGISTRY.get(model);
|
|
1003
|
+
return schema?.indexes ?? DEFAULT_INDEXES;
|
|
1004
|
+
}
|
|
1005
|
+
/**
|
|
1006
|
+
* Get all registered models
|
|
1007
|
+
*
|
|
1008
|
+
* @returns Array of model names
|
|
1009
|
+
*/
|
|
1010
|
+
function getRegisteredModels() {
|
|
1011
|
+
return Array.from(MODEL_REGISTRY.keys());
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Get all unique indexes across all registered models
|
|
1015
|
+
*
|
|
1016
|
+
* Used by createTable to collect all GSIs that need to be created.
|
|
1017
|
+
* Deduplicates by index name.
|
|
1018
|
+
*
|
|
1019
|
+
* @returns Array of unique index definitions
|
|
1020
|
+
*/
|
|
1021
|
+
function getAllRegisteredIndexes() {
|
|
1022
|
+
const indexMap = new Map();
|
|
1023
|
+
// Collect indexes from all registered models
|
|
1024
|
+
for (const schema of MODEL_REGISTRY.values()) {
|
|
1025
|
+
const indexes = schema.indexes ?? [];
|
|
1026
|
+
for (const index of indexes) {
|
|
1027
|
+
const name = index.name ?? generateIndexNameFromPk(index.pk);
|
|
1028
|
+
if (!indexMap.has(name)) {
|
|
1029
|
+
indexMap.set(name, { ...index, name });
|
|
1030
|
+
}
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
return Array.from(indexMap.values());
|
|
1034
|
+
}
|
|
1035
|
+
/**
|
|
1036
|
+
* Check if a model is registered
|
|
1037
|
+
*
|
|
1038
|
+
* @param model - Model name to check
|
|
1039
|
+
* @returns true if model is registered
|
|
1040
|
+
*/
|
|
1041
|
+
function isModelRegistered(model) {
|
|
1042
|
+
return MODEL_REGISTRY.has(model);
|
|
1043
|
+
}
|
|
1044
|
+
/**
|
|
1045
|
+
* Clear the model registry (for testing)
|
|
1046
|
+
*/
|
|
1047
|
+
function clearRegistry() {
|
|
1048
|
+
MODEL_REGISTRY.clear();
|
|
1049
|
+
}
|
|
1050
|
+
// =============================================================================
|
|
1051
|
+
// Helpers
|
|
1052
|
+
// =============================================================================
|
|
1053
|
+
/**
|
|
1054
|
+
* Generate an index name from pk fields (used when index.name is not set)
|
|
1055
|
+
*/
|
|
1056
|
+
function generateIndexNameFromPk(pk) {
|
|
1057
|
+
const suffix = pk
|
|
1058
|
+
.map((field) => {
|
|
1059
|
+
const str = String(field);
|
|
1060
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
1061
|
+
})
|
|
1062
|
+
.join("");
|
|
1063
|
+
return `index${suffix}`;
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
/**
|
|
1067
|
+
* Elementary Field Types
|
|
1068
|
+
*
|
|
1069
|
+
* Defines the 10 elementary field types for the Fabric vocabulary.
|
|
1070
|
+
* Each type has: alias, name, icon, and optional validation/format rules.
|
|
1071
|
+
*/
|
|
1072
|
+
// =============================================================================
|
|
1073
|
+
// Constants
|
|
1074
|
+
// =============================================================================
|
|
1075
|
+
/** Elementary type aliases */
|
|
1076
|
+
const ELEMENTARY_TYPES = [
|
|
1077
|
+
"boolean",
|
|
1078
|
+
"date",
|
|
1079
|
+
"datetime",
|
|
1080
|
+
"dollars",
|
|
1081
|
+
"multiselect",
|
|
1082
|
+
"number",
|
|
1083
|
+
"reference",
|
|
1084
|
+
"select",
|
|
1085
|
+
"text",
|
|
1086
|
+
"textarea",
|
|
1087
|
+
];
|
|
1088
|
+
// =============================================================================
|
|
1089
|
+
// Type Guards
|
|
1090
|
+
// =============================================================================
|
|
1091
|
+
/**
|
|
1092
|
+
* Check if a string is an elementary type
|
|
1093
|
+
*/
|
|
1094
|
+
function isElementaryType(value) {
|
|
1095
|
+
return (typeof value === "string" &&
|
|
1096
|
+
ELEMENTARY_TYPES.includes(value));
|
|
1097
|
+
}
|
|
1098
|
+
// =============================================================================
|
|
1099
|
+
// Elementary Type Definitions
|
|
1100
|
+
// =============================================================================
|
|
1101
|
+
/**
|
|
1102
|
+
* Boolean - True/false toggle
|
|
1103
|
+
*/
|
|
1104
|
+
const BOOLEAN_TYPE = {
|
|
1105
|
+
alias: "boolean",
|
|
1106
|
+
defaultValue: false,
|
|
1107
|
+
description: "True/false toggle",
|
|
1108
|
+
icon: "lucide#toggle-left",
|
|
1109
|
+
inputComponent: "checkbox",
|
|
1110
|
+
name: "Boolean",
|
|
1111
|
+
type: "boolean",
|
|
1112
|
+
};
|
|
1113
|
+
/**
|
|
1114
|
+
* Date - Date picker (ISO format)
|
|
1115
|
+
*/
|
|
1116
|
+
const DATE_TYPE = {
|
|
1117
|
+
alias: "date",
|
|
1118
|
+
description: "Date value (YYYY-MM-DD)",
|
|
1119
|
+
formatPattern: "YYYY-MM-DD",
|
|
1120
|
+
icon: "lucide#calendar",
|
|
1121
|
+
inputComponent: "date-picker",
|
|
1122
|
+
name: "Date",
|
|
1123
|
+
type: "date",
|
|
1124
|
+
};
|
|
1125
|
+
/**
|
|
1126
|
+
* Datetime - Date + time picker
|
|
1127
|
+
*/
|
|
1128
|
+
const DATETIME_TYPE = {
|
|
1129
|
+
alias: "datetime",
|
|
1130
|
+
description: "Date and time value (ISO 8601)",
|
|
1131
|
+
formatPattern: "YYYY-MM-DDTHH:mm:ssZ",
|
|
1132
|
+
icon: "lucide#calendar-clock",
|
|
1133
|
+
inputComponent: "datetime-picker",
|
|
1134
|
+
name: "Date & Time",
|
|
1135
|
+
type: "datetime",
|
|
1136
|
+
};
|
|
1137
|
+
/**
|
|
1138
|
+
* Dollars - Currency with formatting
|
|
1139
|
+
*/
|
|
1140
|
+
const DOLLARS_TYPE = {
|
|
1141
|
+
alias: "dollars",
|
|
1142
|
+
description: "Currency value formatted as $X.XX",
|
|
1143
|
+
formatPattern: "$0,0.00",
|
|
1144
|
+
icon: "lucide#dollar-sign",
|
|
1145
|
+
inputComponent: "currency-input",
|
|
1146
|
+
name: "Dollars",
|
|
1147
|
+
type: "dollars",
|
|
1148
|
+
validation: [
|
|
1149
|
+
{ message: "Must be a valid number", type: "numeric" },
|
|
1150
|
+
{ message: "Cannot be negative", type: "min", value: 0 },
|
|
1151
|
+
],
|
|
1152
|
+
};
|
|
1153
|
+
/**
|
|
1154
|
+
* Multiselect - Multiple selections from options
|
|
1155
|
+
*/
|
|
1156
|
+
const MULTISELECT_TYPE = {
|
|
1157
|
+
alias: "multiselect",
|
|
1158
|
+
description: "Multiple selections from predefined options",
|
|
1159
|
+
icon: "lucide#list-checks",
|
|
1160
|
+
inputComponent: "multiselect",
|
|
1161
|
+
name: "Multi-Select",
|
|
1162
|
+
options: [], // Populated per-field
|
|
1163
|
+
type: "multiselect",
|
|
1164
|
+
};
|
|
1165
|
+
/**
|
|
1166
|
+
* Number - Numeric input (integer or float)
|
|
1167
|
+
*/
|
|
1168
|
+
const NUMBER_TYPE = {
|
|
1169
|
+
alias: "number",
|
|
1170
|
+
description: "Numeric value (integer or decimal)",
|
|
1171
|
+
icon: "lucide#hash",
|
|
1172
|
+
inputComponent: "input[type=number]",
|
|
1173
|
+
name: "Number",
|
|
1174
|
+
type: "number",
|
|
1175
|
+
validation: [{ message: "Must be a valid number", type: "numeric" }],
|
|
1176
|
+
};
|
|
1177
|
+
/**
|
|
1178
|
+
* Reference - Link to another model
|
|
1179
|
+
*/
|
|
1180
|
+
const REFERENCE_TYPE = {
|
|
1181
|
+
alias: "reference",
|
|
1182
|
+
description: "Link to another model by id or alias",
|
|
1183
|
+
icon: "lucide#link",
|
|
1184
|
+
inputComponent: "entity-picker",
|
|
1185
|
+
name: "Reference",
|
|
1186
|
+
referenceModel: undefined, // Set per-field
|
|
1187
|
+
type: "reference",
|
|
1188
|
+
};
|
|
1189
|
+
/**
|
|
1190
|
+
* Select - Single selection from options
|
|
1191
|
+
*/
|
|
1192
|
+
const SELECT_TYPE = {
|
|
1193
|
+
alias: "select",
|
|
1194
|
+
description: "Single selection from predefined options",
|
|
1195
|
+
icon: "lucide#list",
|
|
1196
|
+
inputComponent: "select",
|
|
1197
|
+
name: "Select",
|
|
1198
|
+
options: [], // Populated per-field
|
|
1199
|
+
type: "select",
|
|
1200
|
+
};
|
|
1201
|
+
/**
|
|
1202
|
+
* Text - Single-line string input
|
|
1203
|
+
*/
|
|
1204
|
+
const TEXT_TYPE = {
|
|
1205
|
+
alias: "text",
|
|
1206
|
+
description: "Single-line text input",
|
|
1207
|
+
icon: "lucide#type",
|
|
1208
|
+
inputComponent: "input",
|
|
1209
|
+
name: "Text",
|
|
1210
|
+
type: "text",
|
|
1211
|
+
};
|
|
1212
|
+
/**
|
|
1213
|
+
* Textarea - Multi-line string input
|
|
1214
|
+
*/
|
|
1215
|
+
const TEXTAREA_TYPE = {
|
|
1216
|
+
alias: "textarea",
|
|
1217
|
+
description: "Multi-line text input",
|
|
1218
|
+
icon: "lucide#align-left",
|
|
1219
|
+
inputComponent: "textarea",
|
|
1220
|
+
name: "Text Area",
|
|
1221
|
+
type: "textarea",
|
|
1222
|
+
};
|
|
1223
|
+
// =============================================================================
|
|
1224
|
+
// Type Registry
|
|
1225
|
+
// =============================================================================
|
|
1226
|
+
/**
|
|
1227
|
+
* Registry of all elementary types
|
|
1228
|
+
*/
|
|
1229
|
+
const ELEMENTARY_TYPE_REGISTRY = {
|
|
1230
|
+
boolean: BOOLEAN_TYPE,
|
|
1231
|
+
date: DATE_TYPE,
|
|
1232
|
+
datetime: DATETIME_TYPE,
|
|
1233
|
+
dollars: DOLLARS_TYPE,
|
|
1234
|
+
multiselect: MULTISELECT_TYPE,
|
|
1235
|
+
number: NUMBER_TYPE,
|
|
1236
|
+
reference: REFERENCE_TYPE,
|
|
1237
|
+
select: SELECT_TYPE,
|
|
1238
|
+
text: TEXT_TYPE,
|
|
1239
|
+
textarea: TEXTAREA_TYPE,
|
|
1240
|
+
};
|
|
1241
|
+
// =============================================================================
|
|
1242
|
+
// Helper Functions
|
|
1243
|
+
// =============================================================================
|
|
1244
|
+
/**
|
|
1245
|
+
* Get an elementary type definition by alias
|
|
1246
|
+
*/
|
|
1247
|
+
function getElementaryType(alias) {
|
|
1248
|
+
return ELEMENTARY_TYPE_REGISTRY[alias];
|
|
1249
|
+
}
|
|
1250
|
+
/**
|
|
1251
|
+
* Get all elementary type definitions
|
|
1252
|
+
*/
|
|
1253
|
+
function getAllElementaryTypes() {
|
|
1254
|
+
return Object.values(ELEMENTARY_TYPE_REGISTRY);
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
/**
|
|
1258
|
+
* Field Definition - Describes a field's structure and behavior
|
|
1259
|
+
*
|
|
1260
|
+
* Field definitions are the building blocks of model definitions,
|
|
1261
|
+
* specifying type, validation, and metadata for each field.
|
|
1262
|
+
*/
|
|
1263
|
+
// =============================================================================
|
|
1264
|
+
// Type Guards
|
|
1265
|
+
// =============================================================================
|
|
1266
|
+
/**
|
|
1267
|
+
* Check if a field ref is an inline definition
|
|
1268
|
+
*/
|
|
1269
|
+
function isFieldDefinition(ref) {
|
|
1270
|
+
return typeof ref === "object" && "alias" in ref && "type" in ref;
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
// Service for @jaypie/fabric
|
|
1274
|
+
/**
|
|
1275
|
+
* Check if a single-element array is a typed array type constructor.
|
|
1276
|
+
*/
|
|
1277
|
+
function isTypedArrayConstructor(element) {
|
|
1278
|
+
return (element === Boolean ||
|
|
1279
|
+
element === Number ||
|
|
1280
|
+
element === String ||
|
|
1281
|
+
element === Object ||
|
|
1282
|
+
element === "boolean" ||
|
|
1283
|
+
element === "number" ||
|
|
1284
|
+
element === "string" ||
|
|
1285
|
+
element === "object" ||
|
|
1286
|
+
element === "" ||
|
|
1287
|
+
(typeof element === "object" &&
|
|
1288
|
+
element !== null &&
|
|
1289
|
+
!(element instanceof RegExp) &&
|
|
1290
|
+
Object.keys(element).length === 0));
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Check if a type is a validated string type (array of string literals and/or RegExp).
|
|
1294
|
+
* Distinguishes from typed arrays like [String], [Number], etc.
|
|
1295
|
+
*/
|
|
1296
|
+
function isValidatedStringType(type) {
|
|
1297
|
+
if (!Array.isArray(type)) {
|
|
1298
|
+
return false;
|
|
1299
|
+
}
|
|
1300
|
+
// Empty array is untyped array, not validated string
|
|
1301
|
+
if (type.length === 0) {
|
|
1302
|
+
return false;
|
|
1303
|
+
}
|
|
1304
|
+
// Single-element arrays with type constructors are typed arrays
|
|
1305
|
+
if (type.length === 1 && isTypedArrayConstructor(type[0])) {
|
|
1306
|
+
return false;
|
|
1307
|
+
}
|
|
1308
|
+
// Check that all elements are strings or RegExp
|
|
1309
|
+
return type.every((item) => typeof item === "string" || item instanceof RegExp);
|
|
1310
|
+
}
|
|
1311
|
+
/**
|
|
1312
|
+
* Check if a type is a validated number type (array of number literals).
|
|
1313
|
+
* Distinguishes from typed arrays like [Number], etc.
|
|
1314
|
+
*/
|
|
1315
|
+
function isValidatedNumberType(type) {
|
|
1316
|
+
if (!Array.isArray(type)) {
|
|
1317
|
+
return false;
|
|
1318
|
+
}
|
|
1319
|
+
// Empty array is untyped array, not validated number
|
|
1320
|
+
if (type.length === 0) {
|
|
1321
|
+
return false;
|
|
1322
|
+
}
|
|
1323
|
+
// Single-element arrays with type constructors are typed arrays
|
|
1324
|
+
if (type.length === 1 && isTypedArrayConstructor(type[0])) {
|
|
1325
|
+
return false;
|
|
1326
|
+
}
|
|
1327
|
+
// Check that all elements are numbers
|
|
1328
|
+
return type.every((item) => typeof item === "number");
|
|
1329
|
+
}
|
|
1330
|
+
/**
|
|
1331
|
+
* Parse input string as JSON if it's a string
|
|
1332
|
+
*/
|
|
1333
|
+
function parseInput(input) {
|
|
1334
|
+
if (input === undefined || input === null) {
|
|
1335
|
+
return {};
|
|
1336
|
+
}
|
|
1337
|
+
if (typeof input === "string") {
|
|
1338
|
+
if (input === "") {
|
|
1339
|
+
return {};
|
|
1340
|
+
}
|
|
1341
|
+
try {
|
|
1342
|
+
const parsed = JSON.parse(input);
|
|
1343
|
+
if (typeof parsed !== "object" ||
|
|
1344
|
+
parsed === null ||
|
|
1345
|
+
Array.isArray(parsed)) {
|
|
1346
|
+
throw new errors.BadRequestError("Input must be an object");
|
|
1347
|
+
}
|
|
1348
|
+
return parsed;
|
|
1349
|
+
}
|
|
1350
|
+
catch (error) {
|
|
1351
|
+
if (error instanceof errors.BadRequestError) {
|
|
1352
|
+
throw error;
|
|
1353
|
+
}
|
|
1354
|
+
throw new errors.BadRequestError("Invalid JSON input");
|
|
1355
|
+
}
|
|
1356
|
+
}
|
|
1357
|
+
if (typeof input === "object" && !Array.isArray(input)) {
|
|
1358
|
+
return input;
|
|
1359
|
+
}
|
|
1360
|
+
throw new errors.BadRequestError("Input must be an object or JSON string");
|
|
1361
|
+
}
|
|
1362
|
+
/**
|
|
1363
|
+
* Run validation on a value (supports async validators)
|
|
1364
|
+
*/
|
|
1365
|
+
async function runValidation(value, validate, fieldName) {
|
|
1366
|
+
if (typeof validate === "function") {
|
|
1367
|
+
const result = await validate(value);
|
|
1368
|
+
if (result === false) {
|
|
1369
|
+
throw new errors.BadRequestError(`Validation failed for field "${fieldName}"`);
|
|
1370
|
+
}
|
|
1371
|
+
}
|
|
1372
|
+
else if (validate instanceof RegExp) {
|
|
1373
|
+
if (typeof value !== "string" || !validate.test(value)) {
|
|
1374
|
+
throw new errors.BadRequestError(`Validation failed for field "${fieldName}"`);
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
else if (Array.isArray(validate)) {
|
|
1378
|
+
// Check if value matches any item in the array
|
|
1379
|
+
for (const item of validate) {
|
|
1380
|
+
if (item instanceof RegExp) {
|
|
1381
|
+
if (typeof value === "string" && item.test(value)) {
|
|
1382
|
+
return; // Match found
|
|
1383
|
+
}
|
|
1384
|
+
}
|
|
1385
|
+
else if (typeof item === "function") {
|
|
1386
|
+
try {
|
|
1387
|
+
const result = await item(value);
|
|
1388
|
+
if (result !== false) {
|
|
1389
|
+
return; // Match found
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
catch {
|
|
1393
|
+
// Continue to next item
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
else if (value === item) {
|
|
1397
|
+
return; // Scalar match found
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
throw new errors.BadRequestError(`Validation failed for field "${fieldName}"`);
|
|
1401
|
+
}
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* Check if a field is required
|
|
1405
|
+
* A field is required unless it has a default OR required is explicitly false
|
|
1406
|
+
*/
|
|
1407
|
+
function isFieldRequired(definition) {
|
|
1408
|
+
if (definition.required === false) {
|
|
1409
|
+
return false;
|
|
1410
|
+
}
|
|
1411
|
+
if (definition.default !== undefined) {
|
|
1412
|
+
return false;
|
|
1413
|
+
}
|
|
1414
|
+
return true;
|
|
1415
|
+
}
|
|
1416
|
+
/**
|
|
1417
|
+
* Process a single field through conversion and validation
|
|
1418
|
+
*/
|
|
1419
|
+
async function processField(fieldName, value, definition) {
|
|
1420
|
+
// Apply default if value is undefined
|
|
1421
|
+
let processedValue = value;
|
|
1422
|
+
if (processedValue === undefined && definition.default !== undefined) {
|
|
1423
|
+
processedValue = definition.default;
|
|
1424
|
+
}
|
|
1425
|
+
// Determine actual type and validation
|
|
1426
|
+
let actualType = definition.type;
|
|
1427
|
+
let validation = definition.validate;
|
|
1428
|
+
// Handle bare RegExp shorthand: /regex/
|
|
1429
|
+
if (definition.type instanceof RegExp) {
|
|
1430
|
+
actualType = String;
|
|
1431
|
+
validation = definition.type; // The RegExp becomes the validation
|
|
1432
|
+
}
|
|
1433
|
+
// Handle validated string shorthand: ["value1", "value2"] or [/regex/]
|
|
1434
|
+
else if (isValidatedStringType(definition.type)) {
|
|
1435
|
+
actualType = String;
|
|
1436
|
+
validation = definition.type; // The array becomes the validation
|
|
1437
|
+
}
|
|
1438
|
+
// Handle validated number shorthand: [1, 2, 3]
|
|
1439
|
+
else if (isValidatedNumberType(definition.type)) {
|
|
1440
|
+
actualType = Number;
|
|
1441
|
+
validation = definition.type; // The array becomes the validation
|
|
1442
|
+
}
|
|
1443
|
+
// Fabric to target type
|
|
1444
|
+
const convertedValue = fabric(processedValue, actualType);
|
|
1445
|
+
// Check if required field is missing
|
|
1446
|
+
if (convertedValue === undefined && isFieldRequired(definition)) {
|
|
1447
|
+
throw new errors.BadRequestError(`Missing required field "${fieldName}"`);
|
|
1448
|
+
}
|
|
1449
|
+
// Run validation if provided
|
|
1450
|
+
if (validation !== undefined && convertedValue !== undefined) {
|
|
1451
|
+
await runValidation(convertedValue, validation, fieldName);
|
|
1452
|
+
}
|
|
1453
|
+
return convertedValue;
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* Fabric a service function
|
|
1457
|
+
*
|
|
1458
|
+
* Service builds a function that initiates a "controller" step that:
|
|
1459
|
+
* - Parses the input if it is a string to object
|
|
1460
|
+
* - Fabrics each input field to its type
|
|
1461
|
+
* - Calls the validation function or regular expression or checks the array
|
|
1462
|
+
* - Calls the service function and returns the response
|
|
1463
|
+
*
|
|
1464
|
+
* The returned function has config properties for introspection.
|
|
1465
|
+
*/
|
|
1466
|
+
function fabricService(config) {
|
|
1467
|
+
const { input: inputDefinitions, service } = config;
|
|
1468
|
+
const handler = async (rawInput, context) => {
|
|
1469
|
+
// Parse input (handles string JSON)
|
|
1470
|
+
const parsedInput = parseInput(rawInput);
|
|
1471
|
+
// If no input definitions, pass through to service or return parsed input
|
|
1472
|
+
if (!inputDefinitions) {
|
|
1473
|
+
if (service) {
|
|
1474
|
+
return service(parsedInput, context);
|
|
1475
|
+
}
|
|
1476
|
+
return parsedInput;
|
|
1477
|
+
}
|
|
1478
|
+
// Process all fields in parallel
|
|
1479
|
+
const entries = Object.entries(inputDefinitions);
|
|
1480
|
+
const processedValues = await Promise.all(entries.map(([fieldName, definition]) => processField(fieldName, parsedInput[fieldName], definition)));
|
|
1481
|
+
// Build processed input object
|
|
1482
|
+
const processedInput = {};
|
|
1483
|
+
entries.forEach(([fieldName], index) => {
|
|
1484
|
+
processedInput[fieldName] = processedValues[index];
|
|
1485
|
+
});
|
|
1486
|
+
// Return processed input if no service, otherwise call service
|
|
1487
|
+
if (service) {
|
|
1488
|
+
return service(processedInput, context);
|
|
1489
|
+
}
|
|
1490
|
+
return processedInput;
|
|
1491
|
+
};
|
|
1492
|
+
// Attach config properties directly to handler for flat access
|
|
1493
|
+
const typedHandler = handler;
|
|
1494
|
+
typedHandler.$fabric = FABRIC_VERSION;
|
|
1495
|
+
if (config.alias !== undefined)
|
|
1496
|
+
typedHandler.alias = config.alias;
|
|
1497
|
+
if (config.description !== undefined)
|
|
1498
|
+
typedHandler.description = config.description;
|
|
1499
|
+
if (config.input !== undefined)
|
|
1500
|
+
typedHandler.input = config.input;
|
|
1501
|
+
if (config.service !== undefined)
|
|
1502
|
+
typedHandler.service = config.service;
|
|
1503
|
+
return typedHandler;
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
// Resolve inline service definitions to full Service objects
|
|
1507
|
+
/**
|
|
1508
|
+
* Type guard to check if a value is a pre-instantiated Service
|
|
1509
|
+
* A Service is a function with the `$fabric` property set by fabricService
|
|
1510
|
+
*/
|
|
1511
|
+
function isService(value) {
|
|
1512
|
+
return typeof value === "function" && "$fabric" in value;
|
|
1513
|
+
}
|
|
1514
|
+
/**
|
|
1515
|
+
* Resolve a service configuration to a full Service object
|
|
1516
|
+
*
|
|
1517
|
+
* Supports two patterns:
|
|
1518
|
+
* 1. Inline service definition - pass a plain function as `service` along with
|
|
1519
|
+
* `alias`, `description`, and `input` in the config
|
|
1520
|
+
* 2. Pre-instantiated Service - pass a Service object as `service`
|
|
1521
|
+
*
|
|
1522
|
+
* When a pre-instantiated Service is passed, config fields act as overrides:
|
|
1523
|
+
* - `alias` overrides service.alias
|
|
1524
|
+
* - `description` overrides service.description
|
|
1525
|
+
* - `input` overrides service.input
|
|
1526
|
+
*
|
|
1527
|
+
* The original Service is never mutated - a new Service is created when overrides
|
|
1528
|
+
* are applied.
|
|
1529
|
+
*
|
|
1530
|
+
* @example
|
|
1531
|
+
* ```typescript
|
|
1532
|
+
* // Inline service definition
|
|
1533
|
+
* const service = resolveService({
|
|
1534
|
+
* alias: "greet",
|
|
1535
|
+
* description: "Greet a user",
|
|
1536
|
+
* input: { name: { type: String } },
|
|
1537
|
+
* service: ({ name }) => `Hello, ${name}!`,
|
|
1538
|
+
* });
|
|
1539
|
+
*
|
|
1540
|
+
* // Pre-instantiated with override
|
|
1541
|
+
* const baseService = fabricService({ alias: "foo", service: (x) => x });
|
|
1542
|
+
* const overridden = resolveService({
|
|
1543
|
+
* alias: "bar", // Override alias
|
|
1544
|
+
* service: baseService,
|
|
1545
|
+
* });
|
|
1546
|
+
* ```
|
|
1547
|
+
*/
|
|
1548
|
+
function resolveService(config) {
|
|
1549
|
+
const { alias, description, input, service } = config;
|
|
1550
|
+
if (isService(service)) {
|
|
1551
|
+
// Service is pre-instantiated - config fields act as overrides
|
|
1552
|
+
// Create new Service with merged properties (config overrides service)
|
|
1553
|
+
return fabricService({
|
|
1554
|
+
alias: alias ?? service.alias,
|
|
1555
|
+
description: description ?? service.description,
|
|
1556
|
+
input: input ?? service.input,
|
|
1557
|
+
service: service.service,
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
// Service is an inline function - create Service from config
|
|
1561
|
+
return fabricService({
|
|
1562
|
+
alias,
|
|
1563
|
+
description,
|
|
1564
|
+
input,
|
|
1565
|
+
service,
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
/**
|
|
1570
|
+
* Status Type for @jaypie/fabric
|
|
1571
|
+
*
|
|
1572
|
+
* Standard status values for fields that track processing state.
|
|
1573
|
+
*/
|
|
1574
|
+
/**
|
|
1575
|
+
* Valid status values for status fields
|
|
1576
|
+
*/
|
|
1577
|
+
const STATUS_VALUES = [
|
|
1578
|
+
"canceled",
|
|
1579
|
+
"complete",
|
|
1580
|
+
"error",
|
|
1581
|
+
"pending",
|
|
1582
|
+
"processing",
|
|
1583
|
+
"queued",
|
|
1584
|
+
"sending",
|
|
1585
|
+
];
|
|
1586
|
+
/**
|
|
1587
|
+
* Status type for use in createService input definitions
|
|
1588
|
+
*
|
|
1589
|
+
* Usage:
|
|
1590
|
+
* ```typescript
|
|
1591
|
+
* const handler = createService({
|
|
1592
|
+
* input: {
|
|
1593
|
+
* status: { type: StatusType, description: "Current status" },
|
|
1594
|
+
* },
|
|
1595
|
+
* });
|
|
1596
|
+
* ```
|
|
1597
|
+
*/
|
|
1598
|
+
const StatusType = [...STATUS_VALUES];
|
|
1599
|
+
/**
|
|
1600
|
+
* Check if a value is a valid status
|
|
1601
|
+
*/
|
|
1602
|
+
function isStatus(value) {
|
|
1603
|
+
return (typeof value === "string" &&
|
|
1604
|
+
STATUS_VALUES.includes(value));
|
|
1605
|
+
}
|
|
1606
|
+
|
|
1607
|
+
exports.APEX = APEX;
|
|
1608
|
+
exports.ARCHIVED_SUFFIX = ARCHIVED_SUFFIX;
|
|
1609
|
+
exports.BOOLEAN_TYPE = BOOLEAN_TYPE;
|
|
1610
|
+
exports.DATETIME_TYPE = DATETIME_TYPE;
|
|
1611
|
+
exports.DATE_TYPE = DATE_TYPE;
|
|
1612
|
+
exports.DEFAULT_INDEXES = DEFAULT_INDEXES;
|
|
1613
|
+
exports.DEFAULT_SORT_KEY = DEFAULT_SORT_KEY;
|
|
1614
|
+
exports.DELETED_SUFFIX = DELETED_SUFFIX;
|
|
1615
|
+
exports.DOLLARS_TYPE = DOLLARS_TYPE;
|
|
1616
|
+
exports.DateType = DateType;
|
|
1617
|
+
exports.ELEMENTARY_TYPES = ELEMENTARY_TYPES;
|
|
1618
|
+
exports.ELEMENTARY_TYPE_REGISTRY = ELEMENTARY_TYPE_REGISTRY;
|
|
1619
|
+
exports.FABRIC_MODEL_AUTO_FIELDS = FABRIC_MODEL_AUTO_FIELDS;
|
|
1620
|
+
exports.FABRIC_MODEL_FIELDS = FABRIC_MODEL_FIELDS;
|
|
1621
|
+
exports.FABRIC_MODEL_REQUIRED_FIELDS = FABRIC_MODEL_REQUIRED_FIELDS;
|
|
1622
|
+
exports.FABRIC_MODEL_TIMESTAMP_FIELDS = FABRIC_MODEL_TIMESTAMP_FIELDS;
|
|
1623
|
+
exports.FABRIC_VERSION = FABRIC_VERSION;
|
|
1624
|
+
exports.MULTISELECT_TYPE = MULTISELECT_TYPE;
|
|
1625
|
+
exports.NUMBER_TYPE = NUMBER_TYPE;
|
|
1626
|
+
exports.REFERENCE_TYPE = REFERENCE_TYPE;
|
|
1627
|
+
exports.SELECT_TYPE = SELECT_TYPE;
|
|
1628
|
+
exports.SEPARATOR = SEPARATOR;
|
|
1629
|
+
exports.STATUS_VALUES = STATUS_VALUES;
|
|
1630
|
+
exports.SYSTEM_MODELS = SYSTEM_MODELS;
|
|
1631
|
+
exports.StatusType = StatusType;
|
|
1632
|
+
exports.TEXTAREA_TYPE = TEXTAREA_TYPE;
|
|
1633
|
+
exports.TEXT_TYPE = TEXT_TYPE;
|
|
1634
|
+
exports.buildCompositeKey = buildCompositeKey;
|
|
1635
|
+
exports.calculateIndexSuffix = calculateIndexSuffix;
|
|
1636
|
+
exports.calculateScope = calculateScope;
|
|
1637
|
+
exports.clearRegistry = clearRegistry;
|
|
1638
|
+
exports.computeResolvedName = computeResolvedName;
|
|
1639
|
+
exports.createFabricModelInput = createFabricModelInput;
|
|
1640
|
+
exports.fabric = fabric;
|
|
1641
|
+
exports.fabricArray = fabricArray;
|
|
1642
|
+
exports.fabricBoolean = fabricBoolean;
|
|
1643
|
+
exports.fabricDate = fabricDate;
|
|
1644
|
+
exports.fabricNumber = fabricNumber;
|
|
1645
|
+
exports.fabricObject = fabricObject;
|
|
1646
|
+
exports.fabricService = fabricService;
|
|
1647
|
+
exports.fabricString = fabricString;
|
|
1648
|
+
exports.generateIndexName = generateIndexName;
|
|
1649
|
+
exports.getAllElementaryTypes = getAllElementaryTypes;
|
|
1650
|
+
exports.getAllRegisteredIndexes = getAllRegisteredIndexes;
|
|
1651
|
+
exports.getElementaryType = getElementaryType;
|
|
1652
|
+
exports.getModelIndexes = getModelIndexes;
|
|
1653
|
+
exports.getModelSchema = getModelSchema;
|
|
1654
|
+
exports.getRegisteredModels = getRegisteredModels;
|
|
1655
|
+
exports.hasFabricModelShape = hasFabricModelShape;
|
|
1656
|
+
exports.isAutoField = isAutoField;
|
|
1657
|
+
exports.isDateType = isDateType;
|
|
1658
|
+
exports.isElementaryType = isElementaryType;
|
|
1659
|
+
exports.isFabricModel = isFabricModel;
|
|
1660
|
+
exports.isFieldDefinition = isFieldDefinition;
|
|
1661
|
+
exports.isModelRegistered = isModelRegistered;
|
|
1662
|
+
exports.isStatus = isStatus;
|
|
1663
|
+
exports.isTimestampField = isTimestampField;
|
|
1664
|
+
exports.isValidDate = isValidDate;
|
|
1665
|
+
exports.pickFabricModelFields = pickFabricModelFields;
|
|
1666
|
+
exports.populateIndexKeys = populateIndexKeys;
|
|
1667
|
+
exports.registerModel = registerModel;
|
|
1668
|
+
exports.resolveFromArray = resolveFromArray;
|
|
1669
|
+
exports.resolveFromDate = resolveFromDate;
|
|
1670
|
+
exports.resolveFromObject = resolveFromObject;
|
|
1671
|
+
exports.resolveService = resolveService;
|
|
1672
|
+
exports.resolveWithFallback = resolveWithFallback;
|
|
1673
|
+
exports.tryBuildCompositeKey = tryBuildCompositeKey;
|
|
1674
|
+
//# sourceMappingURL=index.cjs.map
|