@izara_project/izara-core-generate-service-code 1.0.103 → 1.0.105

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@izara_project/izara-core-generate-service-code",
3
- "version": "1.0.103",
3
+ "version": "1.0.105",
4
4
  "description": "Code for locally generating per service files",
5
5
  "homepage": "https://bitbucket.org/izara-core-support-services/izara-core-support-services-generate-service-code#readme",
6
6
  "repository": {
@@ -99,6 +99,53 @@ export async function loadLocalSchemaDirectory(
99
99
  );
100
100
  if (loadedSchemas.length === 0) continue;
101
101
 
102
+ if (directoryName === 'ObjectSchemas') {
103
+ for (let i = 0; i < loadedSchemas.length; i++) {
104
+ let schema = loadedSchemas[i];
105
+ if (
106
+ schema &&
107
+ typeof schema === 'object' &&
108
+ 'result' in schema &&
109
+ schema.result &&
110
+ typeof schema.result === 'object'
111
+ ) {
112
+ schema = schema.result;
113
+ loadedSchemas[i] = schema;
114
+ }
115
+ if (!Object.prototype.hasOwnProperty.call(schema, '_sourceFile')) {
116
+ Object.defineProperty(schema, '_sourceFile', {
117
+ value: entry.name,
118
+ enumerable: false,
119
+ writable: true,
120
+ configurable: true
121
+ });
122
+ }
123
+ if (
124
+ !schema.objectType ||
125
+ typeof schema.objectType !== 'string' ||
126
+ schema.objectType.trim() === ''
127
+ ) {
128
+ const keys = Object.keys(schema || {});
129
+ let hint = '';
130
+ if (
131
+ keys.length === 1 &&
132
+ typeof schema[keys[0]] === 'object' &&
133
+ schema[keys[0]] !== null
134
+ ) {
135
+ const outerKey = keys[0];
136
+ hint =
137
+ ` Schema appears to be wrapped in key '${outerKey}'. ` +
138
+ `ObjectSchemas must not wrap with the object name; ` +
139
+ `export [{ objectType: '${outerKey}', ... }] directly.`;
140
+ }
141
+ throw new Error(
142
+ `Invalid ObjectSchema in ${entry.name}: 'objectType' is required ` +
143
+ `and must be a non-empty string.${hint}`
144
+ );
145
+ }
146
+ }
147
+ }
148
+
102
149
  if (directoryName === 'ErrorSchemas') {
103
150
  for (const schema of loadedSchemas) {
104
151
  if (!schema._sourceFile) {
@@ -20,11 +20,13 @@ const consoleLogger = {
20
20
  */
21
21
  export async function resolveExtendedObjectSchemas(
22
22
  objectSchemas,
23
- bucketName = process.env.iz_serviceSchemaBucketName
23
+ bucketName = process.env.iz_serviceSchemaBucketName,
24
+ dependencies = {}
24
25
  ) {
25
26
  if (!Array.isArray(objectSchemas)) {
26
27
  throw new TypeError('objectSchemas must be an array');
27
28
  }
29
+ const getObjectSchemaLib = dependencies.getObjectSchema || getObjectSchema;
28
30
  const resolvedSchemas = [];
29
31
  for (const schema of objectSchemas) {
30
32
  let currentSchema = schema;
@@ -36,15 +38,31 @@ export async function resolveExtendedObjectSchemas(
36
38
  { extendObjType: currentSchema.extendObjType }
37
39
  );
38
40
  const initialResources = currentSchema.storageResources || {};
39
- const childStorageResourceKeys = new Set(Object.keys(initialResources));
41
+ const initialResourceKeys = Object.keys(initialResources);
42
+ const childStorageResourceKeys = new Set(initialResourceKeys);
40
43
  const parentServiceTag = currentSchema.extendObjType.serviceTag;
41
44
 
42
- const mergedSchema = await getObjectSchema.mergeExtendObjSchema(
45
+ const mergeResult = await getObjectSchemaLib.mergeExtendObjSchema(
43
46
  { logger: consoleLogger },
44
47
  currentSchema,
45
48
  bucketName
46
49
  );
47
50
 
51
+ if (
52
+ mergeResult &&
53
+ typeof mergeResult === 'object' &&
54
+ Array.isArray(mergeResult.errorsFound) &&
55
+ mergeResult.errorsFound.length > 0
56
+ ) {
57
+ const errMsg = mergeResult.errorsFound.join('; ');
58
+ throw new Error(
59
+ `[resolveExtendedObjectSchemas] Failed to merge extendObjType ` +
60
+ `for objectType=${currentSchema.objectType}: ${errMsg}`
61
+ );
62
+ }
63
+
64
+ const mergedSchema = _unwrapSchemaResult(mergeResult);
65
+
48
66
  const externalDynamoResources = [];
49
67
  const ownStorageResources = {};
50
68
  const mergedStorageResources = mergedSchema.storageResources || {};
@@ -102,12 +120,13 @@ export async function resolveExtendedObjectSchemas(
102
120
  serviceTag: belongToTarget.serviceTag,
103
121
  objectType: belongToTarget.objectType
104
122
  };
105
- const belongToSchema = await getObjectSchema.getObjSchemaS3(
123
+ const belongToResult = await getObjectSchemaLib.getObjSchemaS3(
106
124
  { logger: consoleLogger },
107
125
  belongToObjType,
108
126
  false,
109
127
  bucketName
110
128
  );
129
+ const belongToSchema = _unwrapSchemaResult(belongToResult);
111
130
  currentSchema.belongToSchema = belongToSchema;
112
131
  console.log(
113
132
  `[DEBUG] [resolveExtendedObjectSchemas] Successfully fetched ` +
@@ -124,11 +143,26 @@ export async function resolveExtendedObjectSchemas(
124
143
  }
125
144
  }
126
145
 
146
+ currentSchema = _unwrapSchemaResult(currentSchema);
127
147
  resolvedSchemas.push(currentSchema);
128
148
  }
129
149
  return resolvedSchemas;
130
150
  }
131
151
 
152
+ function _unwrapSchemaResult(schemaOrResult) {
153
+ if (!schemaOrResult || typeof schemaOrResult !== 'object') {
154
+ return schemaOrResult;
155
+ }
156
+ if (
157
+ 'result' in schemaOrResult &&
158
+ schemaOrResult.result &&
159
+ typeof schemaOrResult.result === 'object'
160
+ ) {
161
+ return schemaOrResult.result;
162
+ }
163
+ return schemaOrResult;
164
+ }
165
+
132
166
  export async function resolveGraphServiceTags(
133
167
  schemas,
134
168
  bucketName = process.env.iz_serviceSchemaBucketName
@@ -144,6 +144,9 @@ export function setupBasicValidatorSchema(targetSchema = basicValidatorSchema) {
144
144
  item.required = item.required.filter((r) => r !== 'billalble');
145
145
  }
146
146
  }
147
+ if (item?.properties?.type?.enum?.includes('ledger')) {
148
+ item.properties.entryObject = { type: 'boolean' };
149
+ }
147
150
  }
148
151
  }
149
152
  }
@@ -29,6 +29,19 @@ export async function emitCrudApplicationArtifacts({
29
29
  if (!Array.isArray(objects) || !Array.isArray(flows)) {
30
30
  throw new TypeError('objects and flows must be arrays');
31
31
  }
32
+ const malformedObj = objects.find(
33
+ (obj) =>
34
+ !obj ||
35
+ typeof obj.objectType !== 'string' ||
36
+ obj.objectType.trim() === ''
37
+ );
38
+ if (malformedObj) {
39
+ throw new Error(
40
+ `[CRUD Application] Malformed ObjectSchema: 'objectType' is required ` +
41
+ `and must be a non-empty string.`
42
+ );
43
+ }
44
+
32
45
  if (!objects.some(isCrudObject)) {
33
46
  if (objects.length > 0) {
34
47
  const summary = objects.map((obj) => ({
@@ -23,6 +23,19 @@ export function emitDynamicCrudFlowSchemas({
23
23
  if (!Array.isArray(objects) || !Array.isArray(flows)) {
24
24
  throw new TypeError('objects and flows must be arrays');
25
25
  }
26
+ const malformedObj = objects.find(
27
+ (obj) =>
28
+ !obj ||
29
+ typeof obj.objectType !== 'string' ||
30
+ obj.objectType.trim() === ''
31
+ );
32
+ if (malformedObj) {
33
+ throw new Error(
34
+ `[CRUD FlowSchemas] Malformed ObjectSchema: 'objectType' is required ` +
35
+ `and must be a non-empty string.`
36
+ );
37
+ }
38
+
26
39
  if (!objects.some(isCrudObject)) {
27
40
  if (objects.length > 0) {
28
41
  const summary = objects.map((obj) => ({
@@ -167,9 +167,9 @@ export async function resolveAndGenerateIdentifiers(
167
167
  const targetIdentifiers = requestParams.targetIdentifiers;
168
168
 
169
169
  const objectSchemas =
170
- uploadUseCase.generateObjectSchemaForCombineFieldNames(
170
+ await getObjectSchema.getObjectSchemaCombineFieldNamesWithCache(
171
171
  _izContext,
172
- objectSchema
172
+ objType
173
173
  );
174
174
  _izContext.logger.debug(
175
175
  `[${process.env.iz_serviceTag}:<%- flowTag %>] objectSchemas:`,
@@ -997,32 +997,29 @@ export async function publishCompletionMessage(_izContext, message, messageAttri
997
997
  * Resolves and combines object schemas from S3/hierarchy
998
998
  * @param {Object} _izContext - Izara context object
999
999
  * @param {string} objectType - Object type identifier
1000
- * @returns {Promise<{ objType: Object, objectSchema: Object, objectSchemas: Object, parentObject?: Object }>}
1000
+ * @returns {Promise<{ objType: Object, objectSchemas: Object, parentObject?: Object }>}
1001
1001
  */
1002
1002
  export async function resolveObjectSchemas(_izContext, objectType) {
1003
1003
  const objType = createObjType(objectType);
1004
- const objectSchema = await getObjectSchema.getObjSchemaS3WithHierarchy(
1005
- _izContext,
1006
- objType
1007
- );
1008
- _izContext.logger.debug(`[${process.env.iz_serviceTag}:<%- flowTag %>LogicalLib] objectSchema:`, objectSchema);
1009
-
1010
1004
  const objectSchemas =
1011
- uploadUseCase.generateObjectSchemaForCombineFieldNames(
1005
+ await getObjectSchema.getObjectSchemaCombineFieldNamesWithCache(
1012
1006
  _izContext,
1013
- objectSchema
1007
+ objType
1014
1008
  );
1015
- _izContext.logger.debug(`[${process.env.iz_serviceTag}:<%- flowTag %>LogicalLib] objectSchemas:`, objectSchemas);
1009
+ _izContext.logger.debug(
1010
+ `[${process.env.iz_serviceTag}:<%- flowTag %>LogicalLib] objectSchemas:`,
1011
+ objectSchemas
1012
+ );
1016
1013
 
1017
1014
  let parentObject;
1018
1015
  if (objectSchemas.hasOwnProperty('extendObjType')) {
1019
1016
  parentObject = await getObjectSchema.getObjSchemaS3WithHierarchy(
1020
1017
  _izContext,
1021
- objectSchema.extendObjType
1018
+ objectSchemas.extendObjType
1022
1019
  );
1023
1020
  }
1024
1021
 
1025
- return { objType, objectSchema, objectSchemas, parentObject };
1022
+ return { objType, objectSchemas, parentObject };
1026
1023
  }
1027
1024
 
1028
1025
  /**
@@ -1473,7 +1470,7 @@ export async function <%- flowTag %>LogicalLib(
1473
1470
  //(</beforeCreateMainLogical>)
1474
1471
 
1475
1472
  // 1. Load and resolve Schema
1476
- const { objType, objectSchema, objectSchemas, parentObject } =
1473
+ const { objType, objectSchemas, parentObject } =
1477
1474
  await resolveObjectSchemas(_izContext, requestParams.objectType);
1478
1475
 
1479
1476
  const directInvoke =
@@ -1551,7 +1548,7 @@ export async function <%- flowTag %>LogicalLib(
1551
1548
  const identifiersForCreateData =
1552
1549
  await dynamoDbIdentifiersByStorageResource(
1553
1550
  _izContext,
1554
- objectSchema,
1551
+ objectSchemas,
1555
1552
  createDataDetails,
1556
1553
  objInstanceFullForDynamoDb.identifiers
1557
1554
  );
@@ -1591,7 +1588,7 @@ export async function <%- flowTag %>LogicalLib(
1591
1588
 
1592
1589
  // Auto-provision owner TargetRole for DynamoDB-only
1593
1590
  await autoProvisionOwnerTargetRoleForDynamoOnly(_izContext, {
1594
- objectSchema,
1591
+ objectSchema: objectSchemas,
1595
1592
  identifiersForCreateData,
1596
1593
  requestParams
1597
1594
  });
@@ -126,7 +126,6 @@ function _buildParentToEntryLinks({
126
126
  objectType: parentObjectType
127
127
  },
128
128
  linkType: 'many',
129
- requiredOnCreate: false,
130
129
  belongTo: true
131
130
  },
132
131
  to: {
@@ -134,8 +133,7 @@ function _buildParentToEntryLinks({
134
133
  serviceTag: effectiveServiceTag,
135
134
  objectType: entryObjectType
136
135
  },
137
- linkType: 'one',
138
- requiredOnCreate: false
136
+ linkType: 'one'
139
137
  }
140
138
  }
141
139
  ];
@@ -145,7 +143,10 @@ export function ledgerObjectSchemaManagedPaths(objects = []) {
145
143
  const ledgers = _extractLedgers(objects);
146
144
  const paths = [];
147
145
 
148
- for (const { component } of ledgers) {
146
+ for (const { component, addOn } of ledgers) {
147
+ if (addOn?.entryObject === false) {
148
+ continue;
149
+ }
149
150
  paths.push(
150
151
  `app/src/schemas/ObjectSchemas/generatedLedger/${component.objectType}.js`
151
152
  );
@@ -198,6 +199,9 @@ export async function emitLedgerObjectSchemas({ objects = [] } = {}) {
198
199
  const artifacts = [];
199
200
 
200
201
  for (const { parentObject, addOn, component } of ledgers) {
202
+ if (addOn?.entryObject === false) {
203
+ continue;
204
+ }
201
205
  const objectType = component.objectType;
202
206
  const graphStorageResources = _extractGraphStorageResources(
203
207
  parentObject,
@@ -362,16 +366,14 @@ export async function emitLedgerRelationshipSchemas({
362
366
  serviceTag: effectiveServiceTag,
363
367
  objectType: component.objectType
364
368
  },
365
- linkType: 'many',
366
- requiredOnCreate: false
369
+ linkType: 'many'
367
370
  },
368
371
  to: {
369
372
  objType: {
370
373
  serviceTag: targetServiceTag,
371
374
  objectType: target.objectType
372
375
  },
373
- linkType: 'one',
374
- requiredOnCreate: false
376
+ linkType: 'one'
375
377
  }
376
378
  });
377
379
  }
@@ -379,6 +381,7 @@ export async function emitLedgerRelationshipSchemas({
379
381
  const isRel = {
380
382
  generatedBy: 'systemNoUser',
381
383
  storageResources: graphStorageResources,
384
+ fieldNames: {},
382
385
  links: isLinks
383
386
  };
384
387
  artifacts.push({
@@ -1,3 +1,19 @@
1
1
  export default [
2
- <%- JSON.stringify(schema, null, 2).replace(/\n/g, '\n ') %>
2
+ {
3
+ "objectType": "<%= schema.objectType %>",
4
+ "generatedBy": "systemNoUser",
5
+ "canDelete": false,
6
+ "storageResources": <%- JSON.stringify(schema.storageResources, null, 4).replace(/\n/g, '\n ') %>,
7
+ "fieldNames": {
8
+ "<%= schema.objectType %>Id": <%- JSON.stringify(schema.fieldNames[schema.objectType + 'Id'], null, 6).replace(/\n/g, '\n ') %>,
9
+ //(<<%= schema.objectType %>HookCode>)
10
+ //(</<%= schema.objectType %>HookCode>)
11
+ },
12
+ "identifiers": [
13
+ {
14
+ "type": "identifier",
15
+ "fieldName": "<%= schema.objectType %>Id"
16
+ }
17
+ ]
18
+ }
3
19
  ];
@@ -1 +1,37 @@
1
- export default <%- JSON.stringify(wrapper, null, 2) %>;
1
+ export default [
2
+ {
3
+ "<%= relationshipTag %>": {
4
+ <% Object.entries(content).forEach(([key, val]) => { -%>
5
+ <% if (key === 'links' && Array.isArray(val)) { -%>
6
+ "links": [
7
+ <% val.forEach((link) => { -%>
8
+ <%- JSON.stringify(link, null, 6).replace(/\n/g, '\n ') %>,
9
+ <% }); -%>
10
+ //(<<%= relationshipTag %>LinksHookCode>)
11
+ //(</<%= relationshipTag %>LinksHookCode>)
12
+ ],
13
+ <% } else if (key === 'storageResources' && typeof val === 'object' && val !== null) { -%>
14
+ "storageResources": {
15
+ <% Object.entries(val).forEach(([resKey, resVal]) => { -%>
16
+ "<%- resKey %>": <%- JSON.stringify(resVal, null, 6).replace(/\n/g, '\n ') %>,
17
+ <% }); -%>
18
+ //(<<%= relationshipTag %>StorageResourcesHookCode>)
19
+ //(</<%= relationshipTag %>StorageResourcesHookCode>)
20
+ },
21
+ <% } else if (key === 'fieldNames' && typeof val === 'object' && val !== null) { -%>
22
+ "fieldNames": {
23
+ <% Object.entries(val).forEach(([fKey, fVal]) => { -%>
24
+ "<%- fKey %>": <%- JSON.stringify(fVal, null, 6).replace(/\n/g, '\n ') %>,
25
+ <% }); -%>
26
+ //(<<%= relationshipTag %>FieldNamesHookCode>)
27
+ //(</<%= relationshipTag %>FieldNamesHookCode>)
28
+ },
29
+ <% } else { -%>
30
+ "<%- key %>": <%- JSON.stringify(val, null, 6).replace(/\n/g, '\n ') %>,
31
+ <% } -%>
32
+ <% }); -%>
33
+ //(<<%= relationshipTag %>HookCode>)
34
+ //(</<%= relationshipTag %>HookCode>)
35
+ }
36
+ }
37
+ ];
package/src/generate.js CHANGED
@@ -42,10 +42,22 @@ export async function generate(rootPath, options = {}) {
42
42
  options.schemaBucketName ||
43
43
  project.schemaBucketName ||
44
44
  process.env.iz_serviceSchemaBucketName;
45
- const objects = await resolveExtendedObjectSchemas(
45
+ const resolvedObjects = await resolveExtendedObjectSchemas(
46
46
  rawObjects,
47
47
  schemaBucketName
48
48
  );
49
+ const objects = resolvedObjects.map((obj) => {
50
+ if (
51
+ obj &&
52
+ typeof obj === 'object' &&
53
+ 'result' in obj &&
54
+ obj.result &&
55
+ typeof obj.result === 'object'
56
+ ) {
57
+ return obj.result;
58
+ }
59
+ return obj;
60
+ });
49
61
  const objectGraphServiceTags = await resolveGraphServiceTags(
50
62
  objects,
51
63
  schemaBucketName
@@ -93,16 +105,35 @@ export async function generate(rootPath, options = {}) {
93
105
  console.log(
94
106
  `[INFO] [Generate] STATUS=ARTIFACTS_EMITTED | ${emittedScopeSummary}`
95
107
  );
108
+ const allArtifacts = groups.flatMap((group) => group.artifacts);
109
+ const dirSummary = _summarizeArtifactDirectories(allArtifacts);
110
+ const summaryEntries = Object.entries(dirSummary);
111
+ if (summaryEntries.length > 0) {
112
+ const summaryItems = summaryEntries
113
+ .map(([dir, count]) => `${dir}=${count}`)
114
+ .join(' ');
115
+ console.log(`[INFO] [Generate] OUTPUT_SUMMARY | ${summaryItems}`);
116
+ }
96
117
  let files = [];
97
118
  if (groups.length > 0) {
98
119
  files = await commitArtifacts(
99
120
  buildGenerationPlan(
100
121
  project,
101
- groups.flatMap((group) => group.artifacts),
122
+ allArtifacts,
102
123
  {
103
124
  managedScopes: Object.fromEntries(
104
125
  groups.map((group) => [group.scope, group.managedPaths])
105
- )
126
+ ),
127
+ scopeGuards: {
128
+ hasMalformedSchemas:
129
+ objects.some(
130
+ (obj) =>
131
+ !obj ||
132
+ typeof obj.objectType !== 'string' ||
133
+ obj.objectType.trim() === ''
134
+ ) ||
135
+ relationships.some((rel) => !rel || typeof rel !== 'object')
136
+ }
106
137
  }
107
138
  )
108
139
  );
@@ -123,3 +154,19 @@ export async function generate(rootPath, options = {}) {
123
154
  throw error;
124
155
  }
125
156
  }
157
+
158
+ function _summarizeArtifactDirectories(artifacts) {
159
+ const dirCounts = {};
160
+ for (const artifact of artifacts) {
161
+ const parts = artifact.path.split('/');
162
+ let category = parts.slice(0, 3).join('/');
163
+ if (parts.length < 3) {
164
+ category = parts.slice(0, -1).join('/');
165
+ if (!category) {
166
+ category = '.';
167
+ }
168
+ }
169
+ dirCounts[category] = (dirCounts[category] || 0) + 1;
170
+ }
171
+ return dirCounts;
172
+ }
@@ -42,8 +42,17 @@ export async function commitArtifacts(plan) {
42
42
  const stalePaths = _staleManagedPaths(
43
43
  managedScopes,
44
44
  managedArtifacts,
45
- artifacts
45
+ artifacts,
46
+ plan.scopeGuards
46
47
  );
48
+ if (stalePaths.length > 0) {
49
+ console.log(
50
+ `[WARN] [Commit] REMOVED_STALE | count=${stalePaths.length} files:`
51
+ );
52
+ for (const path of stalePaths) {
53
+ console.log(` - ${path}`);
54
+ }
55
+ }
47
56
  const mergedArtifacts = await mergeHooks(physicalOutputRoot, artifacts);
48
57
  const stagedRoot = await mkdtemp(join(physicalOutputRoot, STAGING_PREFIX));
49
58
 
@@ -67,6 +76,10 @@ export async function commitArtifacts(plan) {
67
76
  const snapshots = await _snapshotChanges(changes, stagedRoot);
68
77
  try {
69
78
  await _applyChanges(changes);
79
+ console.log(
80
+ `[INFO] [Commit] STATUS=APPLIED | written=${artifacts.length} ` +
81
+ `removed=${stalePaths.length}`
82
+ );
70
83
  } catch (error) {
71
84
  await _rollbackChanges(changes, snapshots);
72
85
  throw error;
@@ -90,7 +103,12 @@ function _normalizeManagedScopes(plan) {
90
103
  };
91
104
  }
92
105
 
93
- function _staleManagedPaths(managedScopes, managedArtifacts, artifacts) {
106
+ function _staleManagedPaths(
107
+ managedScopes,
108
+ managedArtifacts,
109
+ artifacts,
110
+ scopeGuards
111
+ ) {
94
112
  if (!managedScopes) {
95
113
  return [];
96
114
  }
@@ -100,7 +118,28 @@ function _staleManagedPaths(managedScopes, managedArtifacts, artifacts) {
100
118
  if (!Object.hasOwn(managedArtifacts, scope)) {
101
119
  continue;
102
120
  }
103
- for (const path of [...declaredPaths, ...managedArtifacts[scope]]) {
121
+ const previousPaths = managedArtifacts[scope] || [];
122
+ if (previousPaths.length > 0) {
123
+ const scopeEmittedCount = declaredPaths.filter((path) =>
124
+ emittedPaths.has(path)
125
+ ).length;
126
+ if (scopeEmittedCount === 0) {
127
+ if (scopeGuards?.hasMalformedSchemas) {
128
+ throw new Error(
129
+ `[SAFETY_GUARD] Refusing to delete all artifacts in managed ` +
130
+ `scope '${scope}'. Malformed schemas were detected in the ` +
131
+ `project.`
132
+ );
133
+ }
134
+ if (scopeGuards?.protectedScopes?.includes(scope)) {
135
+ throw new Error(
136
+ `[SAFETY_GUARD] Refusing to delete all artifacts in protected ` +
137
+ `scope '${scope}'.`
138
+ );
139
+ }
140
+ }
141
+ }
142
+ for (const path of [...declaredPaths, ...previousPaths]) {
104
143
  if (!emittedPaths.has(path)) {
105
144
  stalePaths.add(path);
106
145
  }
@@ -6,7 +6,7 @@ import {
6
6
  export function buildGenerationPlan(
7
7
  project,
8
8
  artifacts = [],
9
- { managedPaths = [], managedScope, managedScopes } = {}
9
+ { managedPaths = [], managedScope, managedScopes, scopeGuards } = {}
10
10
  ) {
11
11
  if (!project?.rootPath || !project?.outputPath) {
12
12
  throw new TypeError('ProjectModel must include rootPath and outputPath');
@@ -21,7 +21,8 @@ export function buildGenerationPlan(
21
21
  artifacts: validateArtifacts(artifacts),
22
22
  managedPaths: normalizeArtifactPaths(managedPaths),
23
23
  managedScope: _normalizeManagedScope(managedScope),
24
- managedScopes: _normalizeManagedScopes(managedScopes)
24
+ managedScopes: _normalizeManagedScopes(managedScopes),
25
+ scopeGuards: scopeGuards ? Object.freeze({ ...scopeGuards }) : null
25
26
  });
26
27
  }
27
28
 
@@ -229,3 +229,34 @@ test('rejects a failed output transaction without partial files, hooks, or stagi
229
229
  );
230
230
  assert.equal((await readdir(outputPath)).includes('.bak'), false);
231
231
  });
232
+
233
+ test('commitArtifacts throws SAFETY_GUARD error when hasMalformedSchemas is true and scope would be wiped', async () => {
234
+ const outputPath = await mkdtemp(
235
+ join(tmpdir(), 'generate-service-code-v2-safety-guard-')
236
+ );
237
+ const project = compileProject({ rootPath: outputPath });
238
+ const managedScopes = {
239
+ 'crud-application': ['app/sls_yaml/generatedCode/source/flow-objects.yml']
240
+ };
241
+ await commitArtifacts(
242
+ buildGenerationPlan(
243
+ project,
244
+ [{ path: 'app/sls_yaml/generatedCode/source/flow-objects.yml', content: 'content\n' }],
245
+ { managedScopes }
246
+ )
247
+ );
248
+
249
+ await assert.rejects(
250
+ commitArtifacts(
251
+ buildGenerationPlan(project, [], {
252
+ managedScopes,
253
+ scopeGuards: { hasMalformedSchemas: true }
254
+ })
255
+ ),
256
+ /\[SAFETY_GUARD\] Refusing to delete all artifacts in managed scope 'crud-application'/
257
+ );
258
+ assert.equal(
259
+ await readFile(join(outputPath, 'app/sls_yaml/generatedCode/source/flow-objects.yml'), 'utf8'),
260
+ 'content\n'
261
+ );
262
+ });
@@ -8,6 +8,7 @@ import test, { after } from 'node:test';
8
8
  process.env.NODE_ENV = 'test';
9
9
 
10
10
  import { generateCrudApplicationArtifacts } from '../../../src/emit/application/crud/generateCrudApplicationArtifacts.js';
11
+ import { emitCrudApplicationArtifacts } from '../../../src/emit/application/crud/emitCrudApplicationArtifacts.js';
11
12
 
12
13
  const roots = new Set();
13
14
  after(() =>
@@ -1464,6 +1465,15 @@ test('emits async before-hook callback and SNS publish in Create_Main when event
1464
1465
  assert.match(callbackHandler, /CreateBeforeHookCallback_Main/);
1465
1466
  });
1466
1467
 
1468
+ test('emitCrudApplicationArtifacts throws error when an object is malformed', async () => {
1469
+ await assert.rejects(
1470
+ emitCrudApplicationArtifacts({
1471
+ objects: [{ generatedBy: 'user' }]
1472
+ }),
1473
+ /Malformed ObjectSchema: 'objectType' is required/
1474
+ );
1475
+ });
1476
+
1467
1477
  async function createProject(withCrudObject) {
1468
1478
  const rootPath = await mkdtemp(
1469
1479
  join(tmpdir(), 'generate-service-code-v2-crud-application-')
@@ -6,6 +6,7 @@ import test from 'node:test';
6
6
  import { pathToFileURL } from 'node:url';
7
7
 
8
8
  import { generateDynamicCrudFlowSchemas } from '../../../src/emit/application/crud/generateDynamicCrudFlowSchemas.js';
9
+ import { emitDynamicCrudFlowSchemas } from '../../../src/emit/application/crud/emitDynamicCrudFlowSchemas.js';
9
10
  import { createCrudActionPlans } from '../../../src/emit/application/crud/crudActionPlan.js';
10
11
 
11
12
  test('generates dynamic CRUD schemas from local schema modules', async () => {
@@ -422,3 +423,39 @@ test('throws error when ObjectSchema validation fails with validateSchemas: true
422
423
  );
423
424
  });
424
425
 
426
+ test('throws error when ObjectSchema is missing objectType', async () => {
427
+ const rootPath = await createProject({ generatedBy: 'user' });
428
+ await writeFile(
429
+ join(rootPath, 'app/src/schemas/ObjectSchemas/Order.js'),
430
+ "export default [{ generatedBy: 'user' }];\n"
431
+ );
432
+
433
+ await assert.rejects(
434
+ generateDynamicCrudFlowSchemas(rootPath),
435
+ /Invalid ObjectSchema in Order\.js: 'objectType' is required/
436
+ );
437
+ });
438
+
439
+ test('throws helpful error when ObjectSchema is wrapped in outer key', async () => {
440
+ const rootPath = await createProject({ generatedBy: 'user' });
441
+ await writeFile(
442
+ join(rootPath, 'app/src/schemas/ObjectSchemas/Order.js'),
443
+ "export default [{ order: { objectType: 'order', generatedBy: 'user' } }];\n"
444
+ );
445
+
446
+ await assert.rejects(
447
+ generateDynamicCrudFlowSchemas(rootPath),
448
+ /Schema appears to be wrapped in key 'order'/
449
+ );
450
+ });
451
+
452
+ test('emitDynamicCrudFlowSchemas throws error when an object is malformed', () => {
453
+ assert.throws(
454
+ () =>
455
+ emitDynamicCrudFlowSchemas({
456
+ objects: [{ generatedBy: 'user' }]
457
+ }),
458
+ /Malformed ObjectSchema: 'objectType' is required/
459
+ );
460
+ });
461
+
@@ -79,6 +79,10 @@ test('emitLedgerObjectSchemas returns 1 object schema per ledger addOn', async (
79
79
  assert.match(entryArtifact.content, /"generatedBy": "systemNoUser"/);
80
80
  assert.match(entryArtifact.content, /"canDelete": false/);
81
81
  assert.match(entryArtifact.content, /GraphHandler/);
82
+ assert.match(
83
+ entryArtifact.content,
84
+ /\/\/\(<unitStandardSupplyLocationEntryHookCode>\)[\s\S]*?\/\/\(<\/unitStandardSupplyLocationEntryHookCode>\)/
85
+ );
82
86
  });
83
87
 
84
88
  test('emitLedgerRelationshipSchemas returns current, old, and is relationship schemas per ledger addOn', async () => {
@@ -157,30 +161,82 @@ test('emitLedgerRelationshipSchemas returns current, old, and is relationship sc
157
161
  assert.match(isRel.content, /"supplyLocation"/);
158
162
  assert.match(isRel.content, /"unitPacking"/);
159
163
 
160
- // 4. Verify requiredOnCreate is false in links
164
+ // 4. Verify hookCode in relationship schemas
165
+ assert.match(
166
+ currentRel.content,
167
+ /\/\/\(<currentUnitStandardSupplyLocationHookCode>\)[\s\S]*?\/\/\(<\/currentUnitStandardSupplyLocationHookCode>\)/
168
+ );
169
+ assert.match(
170
+ currentRel.content,
171
+ /\/\/\(<currentUnitStandardSupplyLocationStorageResourcesHookCode>\)[\s\S]*?\/\/\(<\/currentUnitStandardSupplyLocationStorageResourcesHookCode>\)/
172
+ );
173
+ assert.match(
174
+ currentRel.content,
175
+ /\/\/\(<currentUnitStandardSupplyLocationFieldNamesHookCode>\)[\s\S]*?\/\/\(<\/currentUnitStandardSupplyLocationFieldNamesHookCode>\)/
176
+ );
177
+ assert.match(
178
+ currentRel.content,
179
+ /\/\/\(<currentUnitStandardSupplyLocationLinksHookCode>\)[\s\S]*?\/\/\(<\/currentUnitStandardSupplyLocationLinksHookCode>\)/
180
+ );
181
+ assert.match(
182
+ oldRel.content,
183
+ /\/\/\(<oldUnitStandardSupplyLocationHookCode>\)[\s\S]*?\/\/\(<\/oldUnitStandardSupplyLocationHookCode>\)/
184
+ );
185
+ assert.match(
186
+ oldRel.content,
187
+ /\/\/\(<oldUnitStandardSupplyLocationStorageResourcesHookCode>\)[\s\S]*?\/\/\(<\/oldUnitStandardSupplyLocationStorageResourcesHookCode>\)/
188
+ );
189
+ assert.match(
190
+ oldRel.content,
191
+ /\/\/\(<oldUnitStandardSupplyLocationFieldNamesHookCode>\)[\s\S]*?\/\/\(<\/oldUnitStandardSupplyLocationFieldNamesHookCode>\)/
192
+ );
193
+ assert.match(
194
+ oldRel.content,
195
+ /\/\/\(<oldUnitStandardSupplyLocationLinksHookCode>\)[\s\S]*?\/\/\(<\/oldUnitStandardSupplyLocationLinksHookCode>\)/
196
+ );
197
+ assert.match(
198
+ isRel.content,
199
+ /\/\/\(<isUnitStandardSupplyLocationEntryHookCode>\)[\s\S]*?\/\/\(<\/isUnitStandardSupplyLocationEntryHookCode>\)/
200
+ );
201
+ assert.match(
202
+ isRel.content,
203
+ /\/\/\(<isUnitStandardSupplyLocationEntryStorageResourcesHookCode>\)[\s\S]*?\/\/\(<\/isUnitStandardSupplyLocationEntryStorageResourcesHookCode>\)/
204
+ );
205
+ assert.match(
206
+ isRel.content,
207
+ /\/\/\(<isUnitStandardSupplyLocationEntryFieldNamesHookCode>\)[\s\S]*?\/\/\(<\/isUnitStandardSupplyLocationEntryFieldNamesHookCode>\)/
208
+ );
209
+ assert.match(
210
+ isRel.content,
211
+ /\/\/\(<isUnitStandardSupplyLocationEntryLinksHookCode>\)[\s\S]*?\/\/\(<\/isUnitStandardSupplyLocationEntryLinksHookCode>\)/
212
+ );
213
+
214
+ // 5. Verify requiredOnCreate is removed from links
161
215
  const _parseRel = (content) => {
162
216
  const raw = content
163
217
  .replace(/^export default\s+/, '')
164
- .replace(/;\s*$/, '');
218
+ .replace(/;\s*$/, '')
219
+ .replace(/\/\/.*/g, '')
220
+ .replace(/,(\s*[}\]])/g, '$1');
165
221
  return JSON.parse(raw)[0];
166
222
  };
167
223
 
168
224
  const currentRelData = Object.values(_parseRel(currentRel.content))[0];
169
225
  for (const link of currentRelData.links) {
170
- assert.equal(link.from.requiredOnCreate, false);
171
- assert.equal(link.to.requiredOnCreate, false);
226
+ assert.equal(link.from.requiredOnCreate, undefined);
227
+ assert.equal(link.to.requiredOnCreate, undefined);
172
228
  }
173
229
 
174
230
  const oldRelData = Object.values(_parseRel(oldRel.content))[0];
175
231
  for (const link of oldRelData.links) {
176
- assert.equal(link.from.requiredOnCreate, false);
177
- assert.equal(link.to.requiredOnCreate, false);
232
+ assert.equal(link.from.requiredOnCreate, undefined);
233
+ assert.equal(link.to.requiredOnCreate, undefined);
178
234
  }
179
235
 
180
236
  const isRelData = Object.values(_parseRel(isRel.content))[0];
181
237
  for (const link of isRelData.links) {
182
- assert.equal(link.from.requiredOnCreate, false);
183
- assert.equal(link.to.requiredOnCreate, false);
238
+ assert.equal(link.from.requiredOnCreate, undefined);
239
+ assert.equal(link.to.requiredOnCreate, undefined);
184
240
  }
185
241
  });
186
242
 
@@ -221,10 +277,137 @@ test('generate commits and cleans up ledger dynamic schemas', async () => {
221
277
  });
222
278
  });
223
279
 
280
+ test('generate preserves user hooks in ledger ObjectSchemas and RelationshipSchemas across regeneration', async () => {
281
+ const rootPath = await createProjectWithLedger({ hasAddOn: true });
282
+ await generate(rootPath);
283
+
284
+ const objectRelPath =
285
+ 'app/src/schemas/ObjectSchemas/generatedLedger/unitStandardSupplyLocationEntry.js';
286
+ const relRelPath =
287
+ 'app/src/schemas/RelationshipSchemas/generatedLedger/currentUnitStandardSupplyLocation.js';
288
+
289
+ // Inject custom code into dynamic hook tags
290
+ let objectContent = await readProjectFile(rootPath, objectRelPath);
291
+ objectContent = objectContent.replace(
292
+ '//(<unitStandardSupplyLocationEntryHookCode>)\n //(</unitStandardSupplyLocationEntryHookCode>)',
293
+ '//(<unitStandardSupplyLocationEntryHookCode>)\n "customField": { "type": "string" },\n //(</unitStandardSupplyLocationEntryHookCode>)'
294
+ );
295
+ await writeProjectFile(rootPath, objectRelPath, objectContent);
296
+
297
+ let relContent = await readProjectFile(rootPath, relRelPath);
298
+ relContent = relContent.replace(
299
+ '//(<currentUnitStandardSupplyLocationHookCode>)\n //(</currentUnitStandardSupplyLocationHookCode>)',
300
+ '//(<currentUnitStandardSupplyLocationHookCode>)\n "customRelProp": true,\n //(</currentUnitStandardSupplyLocationHookCode>)'
301
+ );
302
+ relContent = relContent.replace(
303
+ '//(<currentUnitStandardSupplyLocationStorageResourcesHookCode>)\n //(</currentUnitStandardSupplyLocationStorageResourcesHookCode>)',
304
+ '//(<currentUnitStandardSupplyLocationStorageResourcesHookCode>)\n "customRes": { "storageType": "graph" },\n //(</currentUnitStandardSupplyLocationStorageResourcesHookCode>)'
305
+ );
306
+ relContent = relContent.replace(
307
+ '//(<currentUnitStandardSupplyLocationFieldNamesHookCode>)\n //(</currentUnitStandardSupplyLocationFieldNamesHookCode>)',
308
+ '//(<currentUnitStandardSupplyLocationFieldNamesHookCode>)\n "customRelField": { "type": "string" },\n //(</currentUnitStandardSupplyLocationFieldNamesHookCode>)'
309
+ );
310
+ relContent = relContent.replace(
311
+ '//(<currentUnitStandardSupplyLocationLinksHookCode>)\n //(</currentUnitStandardSupplyLocationLinksHookCode>)',
312
+ '//(<currentUnitStandardSupplyLocationLinksHookCode>)\n { "customLinkProp": true },\n //(</currentUnitStandardSupplyLocationLinksHookCode>)'
313
+ );
314
+ await writeProjectFile(rootPath, relRelPath, relContent);
315
+
316
+ // Re-run generate
317
+ await generate(rootPath);
318
+
319
+ const preservedObjectContent = await readProjectFile(rootPath, objectRelPath);
320
+ assert.match(preservedObjectContent, /"customField": \{ "type": "string" \}/);
321
+
322
+ const preservedRelContent = await readProjectFile(rootPath, relRelPath);
323
+ assert.match(preservedRelContent, /"customRelProp": true/);
324
+ assert.match(preservedRelContent, /"customRes": \{ "storageType": "graph" \}/);
325
+ assert.match(preservedRelContent, /"customRelField": \{ "type": "string" \}/);
326
+ assert.match(preservedRelContent, /"customLinkProp": true/);
327
+ });
328
+
329
+ test('emitLedgerObjectSchemas and managedPaths skip when entryObject is false', async () => {
330
+ const objects = [
331
+ {
332
+ objectType: 'unitStandard',
333
+ serviceTag: 'UnitStandard',
334
+ storageResources: {
335
+ graph: {
336
+ storageType: 'graph',
337
+ graphServerTag: 'GraphHandler'
338
+ }
339
+ },
340
+ addOnDataStructure: [
341
+ {
342
+ type: 'ledger',
343
+ prefix: 'unitStandardSupplyLocation',
344
+ storageResourceTag: 'graph',
345
+ ledgerType: 'movable',
346
+ entryObject: false,
347
+ targetObjType: {
348
+ serviceTag: 'SupplyLocationStandard',
349
+ objectType: 'supplyLocation'
350
+ }
351
+ }
352
+ ]
353
+ }
354
+ ];
355
+
356
+ const artifacts = await emitLedgerObjectSchemas({ objects });
357
+ assert.equal(artifacts.length, 0);
358
+
359
+ const managedPaths = ledgerObjectSchemaManagedPaths(objects);
360
+ assert.deepEqual(managedPaths, []);
361
+
362
+ const relArtifacts = await emitLedgerRelationshipSchemas({
363
+ objects,
364
+ serviceTag: 'UnitStandard'
365
+ });
366
+ assert.equal(relArtifacts.length, 3);
367
+ const relPaths = ledgerRelationshipSchemaManagedPaths(objects);
368
+ assert.equal(relPaths.length, 3);
369
+ });
370
+
371
+ test('generate cleans up entry ObjectSchema when entryObject is set to false', async () => {
372
+ const rootPath = await createProjectWithLedger({
373
+ hasAddOn: true,
374
+ entryObject: true
375
+ });
376
+ await generate(rootPath);
377
+
378
+ const objectRelPath =
379
+ 'app/src/schemas/ObjectSchemas/generatedLedger/unitStandardSupplyLocationEntry.js';
380
+ const relRelPath =
381
+ 'app/src/schemas/RelationshipSchemas/generatedLedger/currentUnitStandardSupplyLocation.js';
382
+
383
+ const initialObj = await readProjectFile(rootPath, objectRelPath);
384
+ assert.ok(initialObj);
385
+ const initialRel = await readProjectFile(rootPath, relRelPath);
386
+ assert.ok(initialRel);
387
+
388
+ await createProjectWithLedger({
389
+ rootPath,
390
+ hasAddOn: true,
391
+ entryObject: false
392
+ });
393
+ await generate(rootPath);
394
+
395
+ await assert.rejects(readProjectFile(rootPath, objectRelPath), {
396
+ code: 'ENOENT'
397
+ });
398
+ const preservedRel = await readProjectFile(rootPath, relRelPath);
399
+ assert.ok(preservedRel);
400
+ });
401
+
224
402
  async function createProjectWithLedger({
225
403
  rootPath: existingRoot,
226
- hasAddOn = true
404
+ hasAddOn = true,
405
+ entryObject = true
227
406
  } = {}) {
407
+ let entryObjectLine = '';
408
+ if (entryObject === false) {
409
+ entryObjectLine = '\n entryObject: false,';
410
+ }
228
411
  const addOnContent = hasAddOn
229
412
  ? `
230
413
  addOnDataStructure: [
@@ -232,7 +415,7 @@ async function createProjectWithLedger({
232
415
  type: 'ledger',
233
416
  prefix: 'unitStandardSupplyLocation',
234
417
  storageResourceTag: 'graph',
235
- ledgerType: 'movable',
418
+ ledgerType: 'movable',${entryObjectLine}
236
419
  targetObjType: {
237
420
  serviceTag: 'SupplyLocationStandard',
238
421
  objectType: 'supplyLocation'
@@ -0,0 +1,136 @@
1
+ import assert from 'node:assert/strict';
2
+ import test from 'node:test';
3
+
4
+ import {
5
+ resolveExtendedObjectSchemas
6
+ } from '../../../src/compile/loadSchemasRemote.js';
7
+
8
+ test(
9
+ 'resolveExtendedObjectSchemas unwraps result from mergeExtendObjSchema',
10
+ async () => {
11
+ const mockServiceSchemas = {
12
+ mergeExtendObjSchema: async () => {
13
+ return {
14
+ errorsFound: [],
15
+ result: {
16
+ objectType: 'unitStandard',
17
+ generatedBy: 'user',
18
+ storageResources: {
19
+ dynamo1: {
20
+ tableName: 'UnitStandards',
21
+ storageType: 'dynamo'
22
+ },
23
+ childDynamo: {
24
+ tableName: 'ChildTable',
25
+ storageType: 'dynamo'
26
+ }
27
+ }
28
+ }
29
+ };
30
+ }
31
+ };
32
+
33
+ const inputSchemas = [
34
+ {
35
+ objectType: 'unitStandard',
36
+ generatedBy: 'user',
37
+ extendObjType: {
38
+ serviceTag: 'CoreService',
39
+ objectType: 'standard'
40
+ },
41
+ storageResources: {
42
+ childDynamo: {
43
+ tableName: 'ChildTable',
44
+ storageType: 'dynamo'
45
+ }
46
+ }
47
+ }
48
+ ];
49
+
50
+ const resolved = await resolveExtendedObjectSchemas(
51
+ inputSchemas,
52
+ 'bucket',
53
+ { getObjectSchema: mockServiceSchemas }
54
+ );
55
+ assert.equal(resolved.length, 1);
56
+ const resolvedObject = resolved[0];
57
+ assert.equal(resolvedObject.objectType, 'unitStandard');
58
+ assert.equal(resolvedObject.result, undefined);
59
+ assert.equal(resolvedObject.errorsFound, undefined);
60
+ assert.ok(resolvedObject.storageResources);
61
+ assert.ok(resolvedObject.storageResources.childDynamo);
62
+ assert.ok(resolvedObject.externalDynamoResources);
63
+ assert.equal(resolvedObject.externalDynamoResources.length, 1);
64
+ assert.equal(
65
+ resolvedObject.externalDynamoResources[0].tableName,
66
+ 'UnitStandards'
67
+ );
68
+ }
69
+ );
70
+
71
+ test(
72
+ 'resolveExtendedObjectSchemas throws if merge returns errorsFound',
73
+ async () => {
74
+ const mockServiceSchemas = {
75
+ mergeExtendObjSchema: async () => {
76
+ return {
77
+ errorsFound: ['Parent schema not found in S3'],
78
+ result: null
79
+ };
80
+ }
81
+ };
82
+
83
+ const inputSchemas = [
84
+ {
85
+ objectType: 'unitStandard',
86
+ extendObjType: {
87
+ serviceTag: 'CoreService',
88
+ objectType: 'missing'
89
+ }
90
+ }
91
+ ];
92
+
93
+ await assert.rejects(
94
+ resolveExtendedObjectSchemas(inputSchemas, 'bucket', {
95
+ getObjectSchema: mockServiceSchemas
96
+ }),
97
+ /Parent schema not found in S3/
98
+ );
99
+ }
100
+ );
101
+
102
+ test(
103
+ 'resolveExtendedObjectSchemas unwraps belongToSchema from getObjSchemaS3',
104
+ async () => {
105
+ const mockServiceSchemas = {
106
+ getObjSchemaS3: async () => {
107
+ return {
108
+ errorsFound: [],
109
+ result: {
110
+ objectType: 'organization',
111
+ generatedBy: 'user'
112
+ }
113
+ };
114
+ }
115
+ };
116
+
117
+ const inputSchemas = [
118
+ {
119
+ objectType: 'member',
120
+ belongTo: {
121
+ serviceTag: 'OrgService',
122
+ objectType: 'organization'
123
+ }
124
+ }
125
+ ];
126
+
127
+ const resolved = await resolveExtendedObjectSchemas(
128
+ inputSchemas,
129
+ 'bucket',
130
+ { getObjectSchema: mockServiceSchemas }
131
+ );
132
+ assert.equal(resolved.length, 1);
133
+ assert.equal(resolved[0].belongToSchema?.objectType, 'organization');
134
+ assert.equal(resolved[0].belongToSchema?.result, undefined);
135
+ }
136
+ );