-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathvalidate_templates.ts
More file actions
354 lines (304 loc) · 17.3 KB
/
Copy pathvalidate_templates.ts
File metadata and controls
354 lines (304 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import { program } from 'commander';
import { z } from "zod";
import { existsSync, readFileSync, readdirSync, statSync } from 'fs';
import path from 'path';
import { fromError } from 'zod-validation-error';
const allowedCategories = ["Design Patterns", "AI", "B2B", "EDI", "Approval", "RAG", "Automation", "BizTalk Migration", "Mainframe Modernization"];
const templateManifestSchema = z.object({
id: z.string(),
title: z.string(),
summary: z.string(),
description: z.string().optional(),
artifacts: z.array(z.object({
type: z.union([z.literal('map'), z.literal('schema'), z.literal('assembly')]),
file: z.string().regex(/^\S+\.\S+$/, {
message: 'File field must not contain spaces and must have an extension'
})
})).optional(),
skus: z.array(z.union([z.literal('standard'), z.literal('consumption')])),
workflows: z.record(
z.string().regex(/^[a-z-]+$/, {
message: 'Workflow key must only contain lowercase letters and hyphens'
}),
z.object({
name: z.string().transform((val) =>
val.replace(/-([a-z])/g, (_, letter) => `_${letter.toUpperCase()}`)
.replace(/^[a-z]/, (letter) => letter.toUpperCase())
),
})
),
featuredConnectors: z.array(
z.object({
id: z.string().regex(/^(\/.*|connectionProviders.*)$/, {
message: 'Connections "id" field must start with a forward slash or with "connectionProviders" (builtin connectors)'
}),
kind: z.union([z.literal('inapp'), z.literal('shared'), z.literal('custom'), z.literal('builtin')])
})
),
details: z.object({
By: z.string().regex(/^[A-Z].*$/, {
message: 'By field must start with the first letter capitalized'
}),
Type: z.union([z.literal('Workflow'), z.literal('Accelerator')]),
Category: z.string().optional(),
Trigger: z.union([z.literal('Request'), z.literal('Recurrence'), z.literal('Event'), z.literal('Automated'), z.literal('Scheduled')]).optional(),
}),
tags: z.array(z.string()).optional(),
});
const workflowManifestSchema = z.object({
id: z.string(),
title: z.string(),
summary: z.string(),
description: z.string().optional(),
prerequisites: z.string().optional(),
kinds: z.array(z.union([z.literal('stateful'), z.literal('stateless')])).optional(),
artifacts: z.array(z.object({
type: z.literal('workflow'),
file: z.string().regex(/^\S+\.\S+$/, {
message: 'Workflow File field must not contain spaces and must have an extension'
})
})).optional(),
images: z.object({
light: z.string().regex(/^[a-z-_]+$/, {
message: 'Image field must only contain lowercase letters, hyphens, and underscore'
}),
dark: z.string().regex(/^[a-z-_]+$/, {
message: 'Image field must only contain lowercase letters, hyphens, and underscore'
})
}),
parameters: z.array(
z.object({
name: z.string().regex(/^\S*_#workflowname#$/, {
message: 'parameters "name" field must end with _#workflowname#'
}),
displayName: z.string().regex(/^[A-Z].*$/, {
message: 'parameters "displayName" field must start with the first letter capitalized. Suggested naming convention: "Display Name" (O), "display-name" (X)'
}),
type: z.union([z.literal('String'), z.literal('Bool'), z.literal('Array'), z.literal('Float'), z.literal('Int'), z.literal('Object')]),
description: z.string(),
required: z.boolean(),
allowedValues: z.array(
z.object({ value: z.string(), displayName: z.string() })
).optional()
})
),
connections: z.record(
z.string().regex(/^\S*_#workflowname#$/, {
message: 'connections "name" field must end with _#workflowname#'
}),
z.object({
connectorId: z.string().regex(/^\/.*/, {
message: 'Connections "connectorId" field must start with a forward slash'
}),
kind: z.union([z.literal('inapp'), z.literal('shared'), z.literal('custom')]),
})),
});
program.parse();
const manifestNamesList: string[] = JSON.parse(readFileSync(path.resolve('./manifest.json'), {
encoding: 'utf-8'
}));
const allManifestDirectories = readdirSync("./").filter(file =>
statSync(path.join("./", file)).isDirectory() && existsSync(path.join("./", file, "manifest.json"))
);
const checkFilesExistCaseSensitive = (fileNamesInFolder: string[], folderName: string, listedFileNames: string[]) => {
for (const fileName of listedFileNames) {
if (!fileNamesInFolder.includes(fileName)) {
console.error(`Template Failed Validation: ${`./${folderName}/${fileName}`} not found`);
throw '';
}
}
}
const invalidLinkPatternMD = z.string().regex(/^.*\[\S+\]\s+\(\S+\).*$/);
const validateTemplateManifest = (folderName: string, templateManifest) => {
const summaryInvalidPattern = invalidLinkPatternMD.safeParse(templateManifest?.summary ?? "");
const detailsDescriptionInvalidPattern = invalidLinkPatternMD.safeParse(templateManifest?.description ?? "");
if (summaryInvalidPattern.success) {
console.error(`Template Manifest "${folderName}" Failed Validation: summary link is invalid, ensure no space between the [text] and the (link)`);
throw '';
}
if (detailsDescriptionInvalidPattern.success) {
console.error(`Template Manifest "${folderName}" Failed Validation: description link is invalid, ensure no space between the [text] and the (link)`);
throw '';
}
const workflowsCount = Object.keys(templateManifest?.workflows ??{}).length;
const workflowTypeByCount = workflowsCount === 1 ? "Workflow" : workflowsCount > 1 ? "Accelerator" : undefined;
if (templateManifest.details.Type !== workflowTypeByCount) {
console.error(`Template Manifest "${folderName}" Failed Validation: ${
workflowsCount ? `There are ${workflowsCount} workflows, please ensure "details.Type" is ${workflowTypeByCount}` : "None of the workflows are registered in the manifest.json."
}`);
throw '';
}
if (templateManifest.details?.Category) {
for (const category of templateManifest.details?.Category?.split(",") ?? []) {
if (!allowedCategories.includes(category)) {
console.error(`Template Manifest "${folderName}" Failed Validation: Category "${category}" is invalid`);
throw '';
}
}
}
if (templateManifest.tags?.some((tag) => tag.includes(","))) {
console.error(`Template Manifest "${folderName}" Failed Validation: Tags should be separate strings, not one string separated by ","`);
throw '';
}
// Check all artifacts/images listed in manifest.json exist (case sensitive check)
const fileNamesInFolder = readdirSync(path.resolve(`./${folderName}`));
checkFilesExistCaseSensitive(fileNamesInFolder, folderName, templateManifest?.artifacts?.map((artifact) => artifact.file) ?? []);
// Note: Disabled the check for now as we have "sample" artifacts that don't fall under the defined artifact types
// const allArtifactsInFolder = readdirSync(`./${folderName}`).filter(file =>
// !file.endsWith(".png") && file !== "manifest.json"
// );
// // Give warning if all the artifacts in the template/manifest.json is not registered
// const allRegisteredArtifacts = manifestFile.artifacts.map(artifact => artifact.file);
// const artifactsNotRegistered = allArtifactsInFolder.filter(item => !allRegisteredArtifacts.includes(item));
// if (artifactsNotRegistered.length) {
// console.error(`Artifacts(s) ${JSON.stringify(artifactsNotRegistered)} found in the repository not registered in ${folderName}/manifest.json.`);
// throw '';
// }
}
const getUnusedConnectors = (workflowConnections, featuredConnectors) => {
return featuredConnectors.filter(value => value.kind !== "builtin" && !workflowConnections.some((item: any) => item.connectorId === value.id && item.kind === value.kind));
}
const validateWorkflowManifest = (folderName: string, isWorkflowTemplate: boolean, templateSkus: string[] | undefined, workflowManifest) => {
const prerequisitesInvalidPattern = invalidLinkPatternMD.safeParse(workflowManifest?.prerequisites ?? "");
const summaryInvalidPattern = invalidLinkPatternMD.safeParse(workflowManifest?.summary ?? "");
const detailsDescriptionInvalidPattern = invalidLinkPatternMD.safeParse(workflowManifest?.description ?? "");
if (prerequisitesInvalidPattern.success) {
console.error(`Workflow Manifest "${folderName}" Failed Validation: prerequisites link is invalid, ensure no space between the [text] and the (link)`);
throw '';
}
if (summaryInvalidPattern.success) {
console.error(`Workflow Manifest "${folderName}" Failed Validation: summary link is invalid, ensure no space between the [text] and the (link)`);
throw '';
}
if (detailsDescriptionInvalidPattern.success) {
console.error(`Workflow Manifest "${folderName}" Failed Validation: description link is invalid, ensure no space between the [text] and the (link)`);
throw '';
}
// Check all artifacts/images listed in manifest.json exist (case sensitive check)
const fileNamesInFolder = readdirSync(path.resolve(`./${folderName}`));
checkFilesExistCaseSensitive(fileNamesInFolder, folderName, workflowManifest?.artifacts?.map((artifact) => artifact.file) ?? []);
checkFilesExistCaseSensitive(fileNamesInFolder, folderName, [`${workflowManifest.images.light}.png`, `${workflowManifest.images.dark}.png`]);
const workflowFilePath = workflowManifest.artifacts.find((artifact) => artifact.type === "workflow")?.file;
if (!workflowFilePath) {
console.error(`Workflow Manifest "${folderName}" Failed Validation: workflow file not found`);
throw '';
}
const workflowFile = JSON.parse(readFileSync(path.resolve(`./${folderName}/${workflowFilePath}`), {
encoding: 'utf-8'
}));
if (workflowFile.definition || workflowFile.kind) {
console.error(`Workflow "./${folderName}/${workflowFilePath}" Failed Validation: workflow.json is invalid - please only keep what's under "definition"`);
throw '';
}
const workflowFileString = JSON.stringify(workflowFile);
const parameterNames = workflowManifest.parameters.map(parameter => parameter.name);
const connectionNames = Object.keys(workflowManifest.connections);
const parameterMatches = workflowFileString.matchAll(/parameters\('\s*(?!\$connections)([^"']+)\s*'\)/g);
for (const match of parameterMatches) {
if (!parameterNames.includes(match[1])) {
console.error(`Workflow "${folderName}" Failed Validation: parameter "${match[1]}" not found in manifest.json. Hint: Make sure the parameter name is in the format <parameterName>_#workflowname#`);
throw '';
}
}
const connectionReferenceMatches = workflowFileString.matchAll(/"connection":\s*\{\s*"referenceName":\s*"([^"]+)"\}/g);
for (const match of connectionReferenceMatches) {
if (!connectionNames.includes(match[1])) {
console.error(`Workflow "${folderName}" Failed Validation: connection used in "referenceName": "${match[1]}" not found in manifest.json. Hint: Make sure the connection name is in the format <connectionName>_#workflowname#`);
throw '';
}
}
const connectionNameMatches = workflowFileString.matchAll(/"connectionName":\s*"([^"]+)"/g);
for (const match of connectionNameMatches) {
if (!connectionNames.includes(match[1])) {
console.error(`Workflow "${folderName}" Failed Validation: connection used in "connectionName": "${match[1]}" not found in manifest.json. Hint: Make sure the connection name is in the format <connectionName>_#workflowname#`);
throw '';
}
}
const parameterConnectionsMatches = [...workflowFileString.matchAll(/parameters\('\$connections'\)\['([^']+)'\]\['connectionId'\]/g)];
// If skus is not defined, it supports both
if (parameterConnectionsMatches?.length && (!isWorkflowTemplate || (templateSkus?.includes("standard") ?? true))) {
console.error(`Workflow "${folderName}" Failed Validation: parameters('$connections') is invalid for standard workflows. Either remove the parameters('$connections') or set the sku to "consumption" in manifest.json`);
throw '';
}
for (const match of parameterConnectionsMatches) {
if (!connectionNames.includes(match[1])) {
console.error(`Workflow "${folderName}" Failed Validation: parameters('$connections') "${match[1]}" not found in manifest.json. Hint: Make sure the connection name is in the format <connectionName>_#workflowname#`);
throw '';
}
}
}
const checkTitleDescriptionToBeEqual = (folderName, templateManifest, workflowManifest) => {
if (templateManifest.title !== workflowManifest.title) {
console.error(`Template "${folderName}" Failed Validation: Template title and Workflow title must be identical`);
throw '';
}
if (templateManifest.summary !== workflowManifest.summary) {
console.error(`Template "${folderName}" Failed Validation: Template summary and Workflow summary must be identical`);
throw '';
}
}
const checkFolderNameEqualToId = (folderName: string, manifestId: string, relativePath: string, manifestType: "Workflow" | "Template") => {
if (manifestId !== folderName) {
console.error(`${manifestType} Manifest "${relativePath}" Failed Validation: ${manifestType} manifest id and folder name must be identical`);
throw '';
}
}
const manifestNamesSet = new Set(manifestNamesList);
if (manifestNamesSet.size !== manifestNamesList.length) {
console.error(`manifest.json contains ${manifestNamesList.length - manifestNamesSet.size} duplicate Template name(s)`);
throw '';
}
// Check all registered folders in manifest.json exist with another manifest.json
const registeredNotExisting = manifestNamesList.filter(item => !allManifestDirectories.includes(item));
if (registeredNotExisting.length) {
console.error(`Template(s) registered in manifest.json: ${JSON.stringify(registeredNotExisting)} not found in the repository`);
throw '';
}
// Give warning if all the folders in the repo is registered in the main manifest.json
const templatesNotRegistered = allManifestDirectories.filter(item => !manifestNamesList.includes(item));
if (templatesNotRegistered.length) {
console.error(`Template(s) ${JSON.stringify(templatesNotRegistered)} found in the repository are not registered in manifest.json.`);
// throw ''; // Disabling error throwing, considering purposefully non-registered templates
}
for (const folderName of manifestNamesList) {
const templateManifest = JSON.parse(readFileSync(path.resolve(`./${folderName}/manifest.json`), {
encoding: 'utf-8'
}));
const result = templateManifestSchema.safeParse(templateManifest);
if (!result.success) {
console.log(`Template Manifest "${folderName}" Failed Validation`);
const validationError = fromError(result.error);
console.error(validationError.toString());
throw '';
}
validateTemplateManifest(folderName, templateManifest);
const isWorkflowTemplate = templateManifest.details.Type === "Workflow";
checkFolderNameEqualToId(folderName, templateManifest.id, `${folderName}/manifest.json`, "Workflow");
let unregistered_featuredConnectors = [...(templateManifest?.featuredConnectors ?? [])];
for (const workflowFolder of Object.keys(templateManifest.workflows)) {
const workflowManifest = JSON.parse(readFileSync(path.resolve(`./${folderName}/${workflowFolder}/manifest.json`), {
encoding: 'utf-8'
}));
if (isWorkflowTemplate) {
checkTitleDescriptionToBeEqual(folderName, templateManifest, workflowManifest);
if (workflowFolder !== 'default' || workflowManifest.id !== 'default') {
console.error(`Workflow Manifest "${folderName}/${workflowFolder}" Failed Validation: Workflow folder name and workflow manifest id must be "default" for single workflow template`);
}
}
const workflowManifestResult = workflowManifestSchema.safeParse(workflowManifest);
if (!workflowManifestResult.success) {
console.log(`Workflow Manifest "${folderName}/${workflowFolder}" Failed Validation`);
const validationError = fromError(workflowManifestResult.error);
console.error(validationError.toString());
throw '';
}
checkFolderNameEqualToId(workflowFolder, workflowManifest.id, `${folderName}/${workflowFolder}/manifest.json`, "Workflow");
validateWorkflowManifest(`${folderName}/${workflowFolder}`, isWorkflowTemplate, templateManifest.skus, workflowManifest);
unregistered_featuredConnectors = getUnusedConnectors(Object.values(workflowManifest.connections), unregistered_featuredConnectors);
}
if (unregistered_featuredConnectors?.length) {
console.error(`Template Manifest "${folderName}" Failed Validation: Featured connectors ${JSON.stringify(unregistered_featuredConnectors)} are not used in any workflow`);
throw '';
}
}
console.log("Test Passed");