-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathrules-helper.ts
167 lines (147 loc) · 5.49 KB
/
rules-helper.ts
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
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ISwaggerInventory } from "@microsoft.azure/openapi-validator-core"
import { JSONPath } from "jsonpath-plus"
import { crawlReference } from "./ref-helper"
import { SwaggerWalker } from "./swagger-walker"
import { Workspace } from "./swagger-workspace"
const matchAll = require("string.prototype.matchall")
export function getSuccessfulResponseSchema(node: any, doc: any, inventory?: ISwaggerInventory): any {
if (!node.responses) {
return undefined
}
const responses = Object.keys(node.responses)
const response = getMostSuccessfulResponseKey(responses)
return getResponseSchema(node.responses[response], doc, inventory)
}
export function getMostSuccessfulResponseKey(responses: string[]): string {
let response = "default"
if (responses.includes("200")) {
response = "200"
} else {
const twoHundreds: string[] = []
responses.forEach(function (value) {
if (value.startsWith("2")) {
twoHundreds.push(value)
}
})
if (twoHundreds.length > 0) {
response = twoHundreds[0]
}
}
return response
}
export function getResponseSchema(response: object, doc: any, inventory?: ISwaggerInventory): any {
let schema = (response as any)?.schema
if (schema === undefined || schema === null) {
return
}
if ("$ref" in schema) {
schema = crawlReference(doc, schema, inventory)
if (!schema) {
return
}
}
return schema
}
export function getAllResourceProvidersFromPath(path: string): string[] {
const resourceProviderRegex = new RegExp(/providers\/([\w.]+)/, "g")
return Array.from(matchAll(path, resourceProviderRegex), (m: any) => m[1])
}
export function getProviderNamespace(apiPath: string) {
const matches = getAllResourceProvidersFromPath(apiPath)
if (matches.length) {
return matches.pop()
}
return undefined
}
export function getProviderNamespaceFromPath(filePath: string) {
if (!filePath) {
return undefined
}
const resourceProviderRegex = new RegExp(/\/(Microsoft\.\w+)\//i, "g")
const match = Array.from(matchAll(filePath.replace(/\\/g, "/"), resourceProviderRegex), (m: any) => m[1])
if (match) {
return match[0]
}
return undefined
}
export function getAllWordsFromPath(path: string): string[] {
const wordRegex = new RegExp(/([\w.]+)/, "g")
return Array.from(matchAll(path, wordRegex), (m: any) => m[1])
}
export function resourceProviderMustPascalCase(resourceProvider: string): boolean {
if (resourceProvider.length === 0) {
return false
}
// refer https://docs.microsoft.com/en-us/previous-versions/dotnet/netframework-1.1/141e06ef(v=vs.71)?redirectedfrom=MSDN
const pascalCase = new RegExp(`^[A-Z][a-z0-9]+(.([A-Z]{1,3}[a-z0-9]+)+[A-Z]{0,2})+$`)
return pascalCase.test(resourceProvider)
}
export function resourceTypeMustCamelCase(resourceType: string): boolean {
if (resourceType.length === 0) {
return true
}
const pascalCase = new RegExp("^[a-z][a-z0-9]+([A-Z]+[a-z0-9]*)*$")
return pascalCase.test(resourceType)
}
export function isValidOperation(operation: string): boolean {
const validOperations = ["put", "get", "patch", "post", "head", "options", "delete"]
return validOperations.indexOf(operation.toLowerCase()) !== -1
}
export function isValidEnum(node: any) {
if (!node || !node.type || typeof node.type !== "string") {
return false
}
return ["boolean", "integer", "number", "string"].indexOf(node.type) !== -1 && Array.isArray(node.enum)
}
export function transformEnum(type: string, enumEntries: any) {
return enumEntries.map((v: any) => {
if (v === null) {
return ""
}
return v.toString()
})
}
export function getResolvedSchemaByPath(path: string[], specPath: string, inventory: ISwaggerInventory) {
const result = Workspace.jsonPath(path, inventory.getDocuments(specPath))
if (result) {
return Workspace.resolveRef({ value: result, file: specPath }, inventory)
}
return undefined
}
export function nodes(obj: any, pathExpression: string) {
const result = JSONPath({ json: obj, path: pathExpression, resultType: "all" })
return result.map((v: any) => ({ path: JSONPath.toPathArray(v.path), value: v.value, parent: v.parent }))
}
export function stringify(path: string[]) {
const pathWithRoot = ["$", ...path]
return JSONPath.toPathString(pathWithRoot)
}
export function isListOperationPath(path: string) {
if (path.includes(".")) {
// Get the portion of the api path to the right of the provider namespace by splitting the path by '.' and taking the last element
const splitNamespace = path.split(".")
if (path.includes("/")) {
const segments = splitNamespace[splitNamespace.length - 1].split("/")
// If the last segment split by '/' has even segments, then the operation is a list operation
if (segments.length % 2 == 0) {
return true
}
}
}
return false
}
export function getResourceProvider(inventory: ISwaggerInventory) {
const walker = new SwaggerWalker(inventory)
let result: string[] = []
walker.warkAll(["$.paths.*"], (path: string[]) => {
const apiPath = path[2] as string
if (result.length === 0) {
result = [...getAllResourceProvidersFromPath(apiPath)]
}
})
return result.length ? result.pop() || "" : ""
}