@hubspot/project-parsing-lib 0.0.7 → 0.0.8

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": "@hubspot/project-parsing-lib",
3
- "version": "0.0.7",
3
+ "version": "0.0.8",
4
4
  "description": "Parsing library for converting projects directory structures to their intermediate representation",
5
5
  "license": "Apache-2.0",
6
6
  "main": "src/index.js",
package/src/index.js CHANGED
@@ -5,7 +5,6 @@ exports.translate = translate;
5
5
  const files_1 = require("./lib/files");
6
6
  const validation_1 = require("./lib/validation");
7
7
  const transform_1 = require("./lib/transform");
8
- const errors_1 = require("./lib/errors");
9
8
  const copy_1 = require("./lang/copy");
10
9
  const defaultOptions = {
11
10
  skipValidation: false,
@@ -19,12 +18,9 @@ async function translate(translationContext, translationOptions = defaultOptions
19
18
  const transformation = (0, transform_1.transform)(metafileContents);
20
19
  const intermediateRepresentation = (0, transform_1.getIntermediateRepresentation)(transformation);
21
20
  if (!skipValidation) {
22
- const { valid, errors } = await (0, validation_1.validateIntermediateRepresentation)(intermediateRepresentation, transformation, translationContext);
23
- if (!valid) {
24
- throw new errors_1.TranslationError(copy_1.errorMessages.project.failedToTranslateProject, errors);
25
- }
21
+ await (0, validation_1.validateIntermediateRepresentation)(intermediateRepresentation, transformation, translationContext);
26
22
  }
27
23
  return intermediateRepresentation;
28
24
  }
29
- var errors_2 = require("./lib/errors");
30
- Object.defineProperty(exports, "isTranslationError", { enumerable: true, get: function () { return errors_2.isTranslationError; } });
25
+ var errors_1 = require("./lib/errors");
26
+ Object.defineProperty(exports, "isTranslationError", { enumerable: true, get: function () { return errors_1.isTranslationError; } });
@@ -1,3 +1,4 @@
1
+ import { ComponentMetadata } from '../lib/constants';
1
2
  export declare const errorMessages: {
2
3
  api: {
3
4
  failedToFetchSchemas: string;
@@ -7,14 +8,16 @@ export declare const errorMessages: {
7
8
  failedToTranslateProject: string;
8
9
  duplicateUid: (uid: string, files: string[]) => string;
9
10
  };
10
- file: {
11
- errorWithFileHeader: (file: string) => string;
11
+ validation: {
12
+ errorWithFileHeader: (file: string, errors: string[]) => string;
12
13
  missingRequiredField: (field: string) => string;
13
14
  missingUid: string;
14
15
  missingType: string;
16
+ missingConfig: string;
15
17
  unsupportedType: (type: string) => string;
16
18
  errorWithField: (field: string, error: string | undefined) => string;
17
19
  invalidJson: string;
20
+ wrongDirectoryForComponent: (directory: string, componentType: string, componentMetadata: ComponentMetadata, correctDir: string) => string;
18
21
  };
19
22
  };
20
23
  export declare const logMessages: {
package/src/lang/copy.js CHANGED
@@ -6,18 +6,22 @@ exports.errorMessages = {
6
6
  failedToFetchSchemas: 'Failed to fetch schemas',
7
7
  },
8
8
  project: {
9
- noHsMetaFiles: 'No *-hsmeta.json files found, make sure you are inside a project',
10
- failedToTranslateProject: 'Failed to translate project',
11
- duplicateUid: (uid, files) => `Duplicate uid '${uid}' found in ${files.join(', ')}`,
9
+ noHsMetaFiles: 'No *-hsmeta.json files found in the current directory. Please make sure you are inside the correct project directory.',
10
+ failedToTranslateProject: 'Project validation failed',
11
+ duplicateUid: (uid, files) => `Duplicate uid '${uid}' found in:\n- ${files.join('\n- ')}`,
12
12
  },
13
- file: {
14
- errorWithFileHeader: (file) => `Encountered the following errors for ${file}:`,
13
+ validation: {
14
+ errorWithFileHeader: (file, errors) => `\n\nEncountered the following errors for ${file}:\n\t- ${errors.join('\n\t- ')}`,
15
15
  missingRequiredField: (field) => `Missing required field: '${field}'`,
16
16
  missingUid: `Missing required field: 'uid'`,
17
17
  missingType: `Missing required field: 'type'`,
18
+ missingConfig: `Missing required field: 'config'`,
18
19
  unsupportedType: (type) => `Unsupported type: ${type.toLowerCase()}`,
19
20
  errorWithField: (field, error) => `Error with ${field}: ${error || 'Unknown error'}`,
20
21
  invalidJson: 'Invalid JSON',
22
+ wrongDirectoryForComponent: (directory, componentType, componentMetadata, correctDir) =>
23
+ // Double check this string with Jono
24
+ `The directory '${directory}' is incorrect for type '${componentType}'. ${componentMetadata.userFriendlyName} ${componentMetadata.userFriendlyTypePlural} should only be placed in the '${correctDir}' directory`,
21
25
  },
22
26
  };
23
27
  exports.logMessages = {
@@ -11,13 +11,17 @@ export declare const TimelineEventsKey = "timeline-event";
11
11
  export declare const VideoConferencingKey = "video-conferencing";
12
12
  export declare const WebhooksKey = "webhooks";
13
13
  export declare const WorkflowActionsKey = "workflow-action";
14
- interface ComponentMetadata {
14
+ export interface ComponentMetadata {
15
15
  dir: string;
16
- isToplevel?: boolean;
16
+ isToplevel: boolean;
17
17
  parentComponent?: string;
18
+ userFriendlyName: string;
19
+ userFriendlyType: string;
20
+ userFriendlyTypePlural: string;
18
21
  }
19
22
  export declare const Components: Record<string, ComponentMetadata>;
20
- export declare const externalTypeToInternalType: Record<string, string>;
23
+ export declare const userFacingToInternalType: Record<string, string>;
24
+ export declare const internalTypeToUserFacing: Record<string, string>;
21
25
  export declare const metafileExtension = "-hsmeta.json";
22
26
  export declare const allowedAppSubComponentsDirs: string[];
23
27
  export declare const allowedThemeSubComponentsDirs: string[];
@@ -27,4 +31,3 @@ export declare const ProjectStructure: {
27
31
  };
28
32
  export declare const allowedComponentDirectories: string[];
29
33
  export declare const allowedSubComponentDirectories: string[];
30
- export {};
@@ -33,7 +33,7 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.allowedSubComponentDirectories = exports.allowedComponentDirectories = exports.ProjectStructure = exports.allowedThemeSubComponentsDirs = exports.allowedAppSubComponentsDirs = exports.metafileExtension = exports.externalTypeToInternalType = exports.Components = exports.WorkflowActionsKey = exports.WebhooksKey = exports.VideoConferencingKey = exports.TimelineEventsKey = exports.MediaBridgeKey = exports.MarketingEventsKey = exports.FunctionsKey = exports.CardsKey = exports.CallingKey = exports.AppObjectAssociationKey = exports.AppObjectKey = exports.ThemeKey = exports.AppKey = void 0;
36
+ exports.allowedSubComponentDirectories = exports.allowedComponentDirectories = exports.ProjectStructure = exports.allowedThemeSubComponentsDirs = exports.allowedAppSubComponentsDirs = exports.metafileExtension = exports.internalTypeToUserFacing = exports.userFacingToInternalType = exports.Components = exports.WorkflowActionsKey = exports.WebhooksKey = exports.VideoConferencingKey = exports.TimelineEventsKey = exports.MediaBridgeKey = exports.MarketingEventsKey = exports.FunctionsKey = exports.CardsKey = exports.CallingKey = exports.AppObjectAssociationKey = exports.AppObjectKey = exports.ThemeKey = exports.AppKey = void 0;
37
37
  // Top Level Component types
38
38
  const path = __importStar(require("path"));
39
39
  // Component types
@@ -51,63 +51,99 @@ exports.TimelineEventsKey = 'timeline-event';
51
51
  exports.VideoConferencingKey = 'video-conferencing';
52
52
  exports.WebhooksKey = 'webhooks';
53
53
  exports.WorkflowActionsKey = 'workflow-action';
54
+ const TopLevelComponentFields = {
55
+ isToplevel: true,
56
+ userFriendlyType: 'component',
57
+ userFriendlyTypePlural: 'components',
58
+ };
59
+ const SubComponentFields = {
60
+ isToplevel: false,
61
+ userFriendlyType: 'feature',
62
+ userFriendlyTypePlural: 'features',
63
+ };
54
64
  exports.Components = {
55
65
  [exports.AppKey]: {
56
66
  dir: exports.AppKey,
57
- isToplevel: true,
67
+ userFriendlyName: 'App',
68
+ ...TopLevelComponentFields,
58
69
  },
59
70
  [exports.AppObjectKey]: {
60
71
  dir: 'app-objects',
61
72
  parentComponent: exports.AppKey,
73
+ ...SubComponentFields,
74
+ userFriendlyName: 'App Object',
62
75
  },
63
76
  [exports.AppObjectAssociationKey]: {
64
77
  dir: 'app-object-associations',
65
78
  parentComponent: exports.AppKey,
79
+ ...SubComponentFields,
80
+ userFriendlyName: 'App Object Association',
66
81
  },
67
82
  [exports.ThemeKey]: {
68
83
  dir: exports.ThemeKey,
69
- isToplevel: true,
84
+ userFriendlyName: 'Theme',
85
+ ...TopLevelComponentFields,
70
86
  },
71
87
  [exports.CallingKey]: {
72
88
  dir: exports.CallingKey,
73
89
  parentComponent: exports.AppKey,
90
+ userFriendlyName: 'Calling',
91
+ ...SubComponentFields,
74
92
  },
75
93
  [exports.CardsKey]: {
76
94
  dir: 'cards',
77
95
  parentComponent: exports.AppKey,
96
+ userFriendlyName: 'Card',
97
+ ...SubComponentFields,
78
98
  },
79
99
  [exports.FunctionsKey]: {
80
100
  dir: 'functions',
81
101
  parentComponent: exports.AppKey,
102
+ userFriendlyName: 'Function',
103
+ ...SubComponentFields,
82
104
  },
83
105
  [exports.MarketingEventsKey]: {
84
106
  dir: 'marketing-events',
85
107
  parentComponent: exports.AppKey,
108
+ userFriendlyName: 'Marketing Event',
109
+ ...SubComponentFields,
86
110
  },
87
111
  MediaBridgeKey: {
88
112
  dir: exports.MediaBridgeKey,
89
113
  parentComponent: exports.AppKey,
114
+ userFriendlyName: 'Media Bridge',
115
+ ...SubComponentFields,
90
116
  },
91
117
  [exports.TimelineEventsKey]: {
92
118
  dir: 'timeline-events',
93
119
  parentComponent: exports.AppKey,
120
+ userFriendlyName: 'Timeline Event',
121
+ ...SubComponentFields,
94
122
  },
95
123
  [exports.VideoConferencingKey]: {
96
124
  dir: exports.VideoConferencingKey,
97
125
  parentComponent: exports.AppKey,
126
+ userFriendlyName: 'Video Conferencing',
127
+ ...SubComponentFields,
98
128
  },
99
129
  [exports.WebhooksKey]: {
100
130
  dir: exports.WebhooksKey,
101
131
  parentComponent: exports.AppKey,
132
+ userFriendlyName: 'Webhooks',
133
+ ...SubComponentFields,
102
134
  },
103
135
  [exports.WorkflowActionsKey]: {
104
136
  dir: 'workflow-actions',
105
137
  parentComponent: exports.AppKey,
138
+ userFriendlyName: 'Workflow Action',
139
+ ...SubComponentFields,
106
140
  },
107
141
  };
108
- exports.externalTypeToInternalType = {
109
- [exports.AppKey]: 'application',
142
+ const internalAppKey = 'APPLICATION';
143
+ exports.userFacingToInternalType = {
144
+ [exports.AppKey]: internalAppKey,
110
145
  };
146
+ exports.internalTypeToUserFacing = Object.fromEntries(Object.entries(exports.userFacingToInternalType).map(([key, value]) => [value, key]));
111
147
  exports.metafileExtension = '-hsmeta.json';
112
148
  function getSubComponentDirsForParentType(parentComponent) {
113
149
  return Object.values(exports.Components).reduce((acc, item) => {
@@ -1,8 +1,10 @@
1
- import { CompiledError, Transformation } from './types';
1
+ import { CompiledError, Transformation, TranslationContext } from './types';
2
+ import { ErrorObject } from 'ajv-draft-04';
3
+ export declare function isTranslationError(error: unknown): error is TranslationError;
4
+ export declare function compileError(validatedTransformation: Transformation): CompiledError;
2
5
  export declare class TranslationError extends Error {
3
6
  private errors;
4
- constructor(message: string, errors: CompiledError[]);
7
+ private translationContext;
8
+ constructor(message: string, transformations: Transformation[], errors: (ErrorObject[] | null | undefined)[], translationContext: TranslationContext);
5
9
  toString(): string;
6
10
  }
7
- export declare function isTranslationError(error: unknown): error is TranslationError;
8
- export declare function compileError(validatedTransformation: Transformation): CompiledError;
package/src/lib/errors.js CHANGED
@@ -1,29 +1,152 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.TranslationError = void 0;
4
7
  exports.isTranslationError = isTranslationError;
5
8
  exports.compileError = compileError;
6
9
  const copy_1 = require("../lang/copy");
10
+ const path_1 = __importDefault(require("path"));
11
+ function isTranslationError(error) {
12
+ return error instanceof TranslationError;
13
+ }
14
+ function compileError(validatedTransformation) {
15
+ const { fileParseResult } = validatedTransformation;
16
+ const { errors } = fileParseResult;
17
+ return {
18
+ errors,
19
+ };
20
+ }
7
21
  class TranslationError extends Error {
8
- errors;
9
- constructor(message, errors) {
22
+ errors = [];
23
+ translationContext;
24
+ constructor(message, transformations, errors, translationContext) {
10
25
  super(message);
11
26
  this.name = 'TranslationError';
12
- this.errors = errors;
27
+ this.translationContext = translationContext;
28
+ this.errors = transformations.map((transformation, index) => compileTranslationErrors(transformation, errors[index]));
13
29
  }
30
+ // Returns a formatted string for all the errors in all the files
14
31
  toString() {
15
- return `${this.message}: ${this.errors.map(({ message, errors }) => `\n\n${message} \n\t- ${errors.join('\n\t- ')}`)}`;
32
+ const listOfErrors = this.errors.map(({ file, errors }) => {
33
+ if (errors.length === 0) {
34
+ return '';
35
+ }
36
+ return copy_1.errorMessages.validation.errorWithFileHeader(path_1.default.join(this.translationContext.projectSourceDir, file), errors);
37
+ });
38
+ return `${this.message}: ${listOfErrors}`;
16
39
  }
17
40
  }
18
41
  exports.TranslationError = TranslationError;
19
- function isTranslationError(error) {
20
- return error instanceof TranslationError;
42
+ function generateDotNotationPath(error) {
43
+ const { instancePath } = error;
44
+ const errorPath = instancePath
45
+ .replace(/\/nodes\//, '')
46
+ .split('/')
47
+ .filter(subPath => subPath !== '')
48
+ .join('.');
49
+ if (errorPath === '') {
50
+ // This is a top level error
51
+ return `config`;
52
+ }
53
+ return `config.${errorPath}`;
21
54
  }
22
- function compileError(validatedTransformation) {
23
- const { fileParseResult } = validatedTransformation;
24
- const { errors, file: filePath } = fileParseResult;
55
+ function compileTranslationErrors(transformation, schemaErrors) {
56
+ const hasOneOfErrors = schemaErrors?.some(error => isOneOfError(error));
57
+ const { errors: existingErrors, file } = transformation.fileParseResult;
58
+ const errors = [...existingErrors];
59
+ // If there is a one of error, we need to preprocess the errors to group them by instancePath and keyword
60
+ // This allows us to group data from the errors that correspond to the same field
61
+ if (hasOneOfErrors) {
62
+ errors.push(...preprocessSpecialErrors(schemaErrors));
63
+ }
64
+ else {
65
+ schemaErrors?.forEach(error => {
66
+ errors.push(generateErrorMessage(error));
67
+ });
68
+ }
69
+ return { file, errors };
70
+ }
71
+ function preprocessSpecialErrors(schemaErrors) {
72
+ const errors = [];
73
+ const preprocessedErrors = {};
74
+ schemaErrors?.forEach(error => {
75
+ // Filter out the oneOf errors, they are a secondary error caused by other errors
76
+ // and don't add any additional actionable context to the user
77
+ if (isOneOfError(error)) {
78
+ return;
79
+ }
80
+ const errorKey = `${error.instancePath}::${error.keyword}`;
81
+ if (preprocessedErrors[errorKey]) {
82
+ preprocessedErrors[errorKey].push(error);
83
+ }
84
+ else {
85
+ preprocessedErrors[errorKey] = [error];
86
+ }
87
+ });
88
+ Object.values(preprocessedErrors)?.forEach(value => {
89
+ const newValue = value.reduce((cur, next) => {
90
+ if (isEnumError(cur)) {
91
+ return mergeEnumErrors(cur, next);
92
+ }
93
+ return cur;
94
+ });
95
+ errors.push(generateErrorMessage(newValue));
96
+ });
97
+ return errors;
98
+ }
99
+ function generateErrorMessage(error) {
100
+ const errorPath = generateDotNotationPath(error);
101
+ const errorMessage = copy_1.errorMessages.validation.errorWithField(errorPath, error.message);
102
+ const params = Object.entries(error.params);
103
+ if (params.length === 0) {
104
+ return errorMessage;
105
+ }
106
+ const additionalContext = params
107
+ .filter(([_, value]) => value)
108
+ .map(([key, value]) => `${key}: ${Array.isArray(value) ? value.join(', ') : value}`);
109
+ if (isRequiredError(error)) {
110
+ return copy_1.errorMessages.validation.missingRequiredField(`${errorPath}.${error.params.missingProperty}`);
111
+ }
112
+ else if (isTypeError(error)) {
113
+ return copy_1.errorMessages.validation.errorWithField(generateDotNotationPath(error), error.message);
114
+ }
115
+ // Default case, it is not an error we know how to deal with
116
+ return `${errorMessage} ${additionalContext.length > 0
117
+ ? `\n\t\t- ${additionalContext.join('\n\t\t- ')}`
118
+ : ''}`;
119
+ }
120
+ function mergeEnumErrors(cur, next) {
25
121
  return {
26
- message: copy_1.errorMessages.file.errorWithFileHeader(filePath),
27
- errors,
122
+ ...cur,
123
+ // Overwrite the schema path so we know it's been modified
124
+ schemaPath: 'CUSTOM',
125
+ params: {
126
+ ...cur.params,
127
+ // Merge the allowed values from the enum errors
128
+ allowedValues: [
129
+ ...cur.params.allowedValues,
130
+ ...next.params.allowedValues,
131
+ ],
132
+ },
28
133
  };
29
134
  }
135
+ const JSON_SCHEMA_VALIDATION_KEYWORDS = {
136
+ required: 'required',
137
+ type: 'type',
138
+ oneOf: 'oneOf',
139
+ enum: 'enum',
140
+ };
141
+ function isOneOfError(error) {
142
+ return error.keyword === JSON_SCHEMA_VALIDATION_KEYWORDS.oneOf;
143
+ }
144
+ function isRequiredError(error) {
145
+ return error.keyword === JSON_SCHEMA_VALIDATION_KEYWORDS.required;
146
+ }
147
+ function isEnumError(error) {
148
+ return error.keyword === JSON_SCHEMA_VALIDATION_KEYWORDS.enum;
149
+ }
150
+ function isTypeError(error) {
151
+ return error.keyword === JSON_SCHEMA_VALIDATION_KEYWORDS.type;
152
+ }
package/src/lib/files.js CHANGED
@@ -71,7 +71,7 @@ function parseFile(fileLoadResult) {
71
71
  parsedFileContents = JSON.parse(fileLoadResult.content);
72
72
  }
73
73
  catch (_e) {
74
- fileLoadResult.errors?.push(copy_1.errorMessages.file.invalidJson);
74
+ fileLoadResult.errors?.push(copy_1.errorMessages.validation.invalidJson);
75
75
  }
76
76
  return { ...fileLoadResult, content: parsedFileContents };
77
77
  }
@@ -1,3 +1,3 @@
1
- import { AnySchema } from 'ajv';
1
+ import { AnySchema } from 'ajv-draft-04';
2
2
  import { TranslationContext } from './types';
3
3
  export declare function getIntermediateRepresentationSchema(translationContext: TranslationContext): Promise<Record<string, AnySchema>>;
@@ -1,3 +1,4 @@
1
1
  import { FileParseResult, IntermediateRepresentation, Transformation } from './types';
2
+ export declare function mapToUserFacingType(type: string): string;
2
3
  export declare function transform(fileParseResults: FileParseResult[]): Transformation[];
3
4
  export declare function getIntermediateRepresentation(transformations: Transformation[]): IntermediateRepresentation;
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.mapToUserFacingType = mapToUserFacingType;
3
4
  exports.transform = transform;
4
5
  exports.getIntermediateRepresentation = getIntermediateRepresentation;
5
6
  const constants_1 = require("./constants");
@@ -24,9 +25,14 @@ function calculateComponentDeps(fileValidationResult, parentComponents, appObjec
24
25
  return dependencies;
25
26
  }
26
27
  function mapToInternalType(type) {
27
- const resolvedType = constants_1.externalTypeToInternalType[type] || type || '';
28
+ const resolvedType = constants_1.userFacingToInternalType[type] || type || '';
28
29
  return resolvedType.toUpperCase().replace(/-/g, '_');
29
30
  }
31
+ function mapToUserFacingType(type) {
32
+ return (constants_1.internalTypeToUserFacing[type] || type || '')
33
+ .toLowerCase()
34
+ .replace(/_/g, '-');
35
+ }
30
36
  function transform(fileParseResults) {
31
37
  const parentTypes = Object.keys(constants_1.ProjectStructure);
32
38
  const parentComponents = {};
@@ -61,6 +67,9 @@ function transform(fileParseResults) {
61
67
  }
62
68
  function getIntermediateRepresentation(transformations) {
63
69
  const nodes = transformations.reduce((acc, current) => {
70
+ if (!current.intermediateRepresentation) {
71
+ return acc;
72
+ }
64
73
  const { uid } = current.intermediateRepresentation;
65
74
  if (acc[uid]) {
66
75
  const duplicates = transformations
@@ -1,4 +1,5 @@
1
1
  export type Dependencies = Record<string, string | string[]>;
2
+ import { ErrorObject } from 'ajv-draft-04';
2
3
  export interface Components {
3
4
  uid: string;
4
5
  type: string;
@@ -32,9 +33,9 @@ export interface IntermediateRepresentation {
32
33
  export type Transformation = {
33
34
  intermediateRepresentation?: IntermediateRepresentationNode | null;
34
35
  fileParseResult: FileParseResult;
36
+ schemaValidationErrors?: ErrorObject[] | null;
35
37
  };
36
38
  export type CompiledError = {
37
- message: string;
38
39
  errors: string[];
39
40
  };
40
41
  export interface TranslationContext {
@@ -1,9 +1,13 @@
1
1
  import { CompiledError, IntermediateRepresentation, Transformation, TranslationContext } from './types';
2
- export type ValidationResults = {
3
- valid: false;
4
- errors: CompiledError[];
5
- } | {
2
+ import { ValidateFunction } from 'ajv-draft-04';
3
+ export type ValidResult = {
6
4
  valid: true;
7
5
  errors?: null;
6
+ schemaValidationErrors?: null;
8
7
  };
9
- export declare function validateIntermediateRepresentation(intermediateRepresentation: IntermediateRepresentation, transformation: Transformation[], translationContext: TranslationContext): Promise<ValidationResults>;
8
+ export type ValidationResults = {
9
+ valid: false;
10
+ errors?: CompiledError;
11
+ schemaValidationErrors?: ValidateFunction['errors'];
12
+ } | ValidResult;
13
+ export declare function validateIntermediateRepresentation(intermediateRepresentation: IntermediateRepresentation, transformation: Transformation[], translationContext: TranslationContext): Promise<ValidResult>;
@@ -8,90 +8,84 @@ const schemas_1 = require("./schemas");
8
8
  const ajv_draft_04_1 = __importDefault(require("ajv-draft-04"));
9
9
  const errors_1 = require("./errors");
10
10
  const copy_1 = require("../lang/copy");
11
- async function validateIntermediateRepresentation(intermediateRepresentation, transformation, translationContext) {
12
- const schema = await (0, schemas_1.getIntermediateRepresentationSchema)(translationContext);
13
- const results = Object.values(intermediateRepresentation.intermediateNodesIndexedByUid).map((irNode, index) => {
14
- const ajv = new ajv_draft_04_1.default({ allErrors: true });
15
- if (!irNode.uid) {
16
- transformation[index].fileParseResult.errors.push(copy_1.errorMessages.file.missingUid);
11
+ const constants_1 = require("./constants");
12
+ const path_1 = __importDefault(require("path"));
13
+ const transform_1 = require("./transform");
14
+ function validateIntermediateRepresentationNode(schema, transformation, irNode, index, translationContext) {
15
+ if (transformation[index].fileParseResult.errors.length > 0) {
16
+ return {
17
+ valid: false,
18
+ errors: (0, errors_1.compileError)(transformation[index]),
19
+ };
20
+ }
21
+ const ajv = new ajv_draft_04_1.default({ allErrors: true });
22
+ let shouldSkipValidation = false;
23
+ if (!irNode.uid) {
24
+ transformation[index].fileParseResult.errors.push(copy_1.errorMessages.validation.missingUid);
25
+ }
26
+ if (!irNode.config) {
27
+ transformation[index].fileParseResult.errors.push(copy_1.errorMessages.validation.missingConfig);
28
+ // If there is no config block, there is nothing to validation
29
+ shouldSkipValidation = true;
30
+ }
31
+ if (!schema[irNode.componentType]) {
32
+ if (!irNode.componentType) {
33
+ transformation[index].fileParseResult.errors.push(copy_1.errorMessages.validation.missingType);
17
34
  }
18
- if (!schema[irNode.componentType]) {
19
- if (!irNode.componentType) {
20
- transformation[index].fileParseResult.errors.push(copy_1.errorMessages.file.missingType);
21
- }
22
- transformation[index].fileParseResult.errors.push(copy_1.errorMessages.file.unsupportedType(irNode.componentType));
23
- return {
24
- valid: false,
25
- errors: (0, errors_1.compileError)(transformation[index]),
26
- };
35
+ else {
36
+ transformation[index].fileParseResult.errors.push(copy_1.errorMessages.validation.unsupportedType(irNode.componentType));
27
37
  }
28
- const validate = ajv.compile(schema[irNode.componentType]);
29
- const valid = validate(irNode.config);
30
- if (valid) {
31
- const { errors } = transformation[index].fileParseResult;
32
- return errors.length === 0
33
- ? {
34
- valid: true,
35
- }
36
- : {
37
- valid: false,
38
- errors: (0, errors_1.compileError)(transformation[index]),
39
- };
38
+ // If there is no schema for the component type, there is no way to validate
39
+ shouldSkipValidation = true;
40
+ }
41
+ const userFacingType = (0, transform_1.mapToUserFacingType)(irNode.componentType);
42
+ const component = constants_1.Components[userFacingType];
43
+ if (userFacingType && component) {
44
+ const expectedParentDir = component.parentComponent
45
+ ? constants_1.Components[component.parentComponent].dir
46
+ : '';
47
+ const expectedLocation = path_1.default.join(expectedParentDir, component.dir);
48
+ const actualLocation = path_1.default.dirname(transformation[index].fileParseResult.file);
49
+ if (expectedLocation !== actualLocation) {
50
+ transformation[index].fileParseResult.errors.push(copy_1.errorMessages.validation.wrongDirectoryForComponent(actualLocation, userFacingType, component, path_1.default.join(translationContext.projectSourceDir, expectedLocation)));
40
51
  }
41
- const transformationWithUpdatedErrors = hydrateValidationErrorsIntoTransformation(transformation[index], validate.errors);
52
+ }
53
+ if (shouldSkipValidation) {
42
54
  return {
43
55
  valid: false,
44
- errors: (0, errors_1.compileError)(transformationWithUpdatedErrors),
56
+ errors: (0, errors_1.compileError)(transformation[index]),
45
57
  };
46
- });
47
- const valid = results.every(result => result.valid);
58
+ }
59
+ const validate = ajv.compile(schema[irNode.componentType]);
60
+ const valid = validate(irNode.config);
48
61
  if (valid) {
49
- return {
50
- valid,
51
- };
62
+ const { errors } = transformation[index].fileParseResult;
63
+ // Even through it passed the schema validation, it may have had other errors along the way
64
+ return errors.length === 0
65
+ ? {
66
+ valid: true,
67
+ }
68
+ : {
69
+ valid: false,
70
+ errors: (0, errors_1.compileError)(transformation[index]),
71
+ };
52
72
  }
53
- const errors = results
54
- .filter(item => item.errors !== undefined)
55
- .map(result => result.errors);
56
73
  return {
57
- valid,
58
- errors,
74
+ valid: false,
75
+ schemaValidationErrors: validate.errors,
59
76
  };
60
77
  }
61
- function hydrateValidationErrorsIntoTransformation(transformation, errors) {
62
- if (!errors) {
63
- return transformation;
64
- }
65
- errors.forEach(error => {
66
- const { intermediateRepresentation, fileParseResult } = transformation;
67
- fileParseResult.errors.push(generateErrorMessage(transformInstancePath(error.instancePath), error));
68
- transformation = { intermediateRepresentation, fileParseResult };
78
+ async function validateIntermediateRepresentation(intermediateRepresentation, transformation, translationContext) {
79
+ const schema = await (0, schemas_1.getIntermediateRepresentationSchema)(translationContext);
80
+ const results = Object.values(intermediateRepresentation.intermediateNodesIndexedByUid).map((irNode, index) => {
81
+ return validateIntermediateRepresentationNode(schema, transformation, irNode, index, translationContext);
69
82
  });
70
- return transformation;
71
- }
72
- function transformInstancePath(instancePath) {
73
- return instancePath.replace(/\/nodes\//, '').split('/');
74
- }
75
- const missingRequiredFieldRegex = /must have required property '(.+)'/;
76
- // TODO: This needs cleanup and better error messaging
77
- function generateErrorMessage(path, error) {
78
- let errorMessage = '';
79
- const dotNotationPath = path.length === 0 || path[0] === '' ? 'Root Level' : path.join('.');
80
- errorMessage = copy_1.errorMessages.file.errorWithField(dotNotationPath, error.message);
81
- const params = Object.entries(error.params);
82
- if (params.length > 0) {
83
- const additionalContext = params
84
- .filter(([_, value]) => value)
85
- .map(([key, value]) => `${key}: ${value}`);
86
- if (error.message &&
87
- missingRequiredFieldRegex.test(error.message) &&
88
- error.params) {
89
- // TODO: This error message doesn't work well for nested objects, it makes it seem like the field is missing from the root object
90
- return copy_1.errorMessages.file.missingRequiredField(error.params.missingProperty);
91
- }
92
- errorMessage += `${additionalContext.length > 0
93
- ? `\n\t\t- ${additionalContext.join('\n\t\t- ')}`
94
- : ''}`;
83
+ const valid = results.every(result => result.valid);
84
+ if (valid) {
85
+ return {
86
+ valid,
87
+ };
95
88
  }
96
- return errorMessage;
89
+ const schemaValidationErrors = results.map(result => result.schemaValidationErrors);
90
+ throw new errors_1.TranslationError(copy_1.errorMessages.project.failedToTranslateProject, transformation, schemaValidationErrors, translationContext);
97
91
  }