/
generic-type.utils.ts
219 lines (183 loc) · 7.45 KB
/
generic-type.utils.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
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
import type { ElementNode, ExtendedJsonSchema, PreparedNodeData, Schemata } from './typing/generic-node-type';
import { CompilerError, allRequired, expansionType, generateDtsFromSchema, mainTypeName } from './json-schema-type-util';
import { getTypes, validate } from './validation/watcher';
import { nodeDescriptor, nodeTypeName } from './element-node';
import { typeData } from './generic-node-constants';
import { SchemaMatchingError, validateJsonSchema } from './validation/json-schema-type.validator';
import { logKibana } from '../../util/log';
import { generateSchema } from 'typescript-json-schema';
import type { Diagnostic, DiagnosticMessageChain, DiagnosticRelatedInformation } from 'typescript';
import { writeFile } from "fs/promises"
import { join } from 'path';
/*
export async function parseTypeSafe(node: ElementNode<unknown>, data: unknown) {
let validator = schemaMap[node.uuid]?.zodValidator
if (!validator) {
const schema = await getComputeSchema(node)
if (schema === null) {
throw new Error("trying to get zod validator but no schema")
}
validator = schema!.zodValidator
}
try {
return validator.parse(data)
} catch (e) {
debugger;
throw e;
}
}*/
/*
async function getComputeSchema(node: ElementNode<unknown>) {
if (!node.runtimeContext?.outputSchema?.jsonSChema) {
return null
}
const schemaString = JSON.stringify(node.runtimeContext?.outputSchema?.jsonSChema)
let nodeCahce = schemaMap[node.uuid]
if (!nodeCahce || schemaString !== nodeCahce.schemaCache) {
const [dts] = await Promise.all([
generateDtsFromSchema(node.runtimeContext?.outputSchema?.jsonSChema),
// generateZodTypeFromSchema(node.runtimeContext?.outputSchema?.jsonSChema)
])
nodeCahce = schemaMap[node.uuid] = {
schemaCache: schemaString,
dts: dts,
//zodValidator: zodParser,
mainTypeName: mainTypeName
}
const target = join(typeData, node.uuid + ".ts");
await mkdir(dirname(target), { recursive: true })
await writeFile(target, dts)
}
return nodeCahce
}*/
export async function updateTypeSchema(node: ElementNode, nodeData: PreparedNodeData) {
let schema: Schemata | null = null
const connectionsTargetingCurrentNode = nodeData.targetConnectorMap[node.uuid];
if (connectionsTargetingCurrentNode) {
const allConnectorsToConnection0 = connectionsTargetingCurrentNode[0]
const schemata = await Promise.all(allConnectorsToConnection0.map(async con => {
const connectionNode = nodeData.nodeMap[con.uuid]
const compSchema = connectionNode.runtimeContext.outputSchema
if (compSchema?.dts && node.runtimeContext.inputSchema) {
try {
const nodeTypePrefix = nodeTypeName(node)
const connectionNodePrefi = nodeTypeName(connectionNode)
validateJsonSchema({
target: node.runtimeContext.inputSchema.jsonSchema,
assigning: compSchema.jsonSchema,
path: []
})
const str = `
namespace ${nodeTypePrefix}_NodeWrapper {
namespace ConnectionInput {
${compSchema?.dts}
}
namespace ${nodeTypePrefix}_NodeInput {
${node.runtimeContext.inputSchema.dts}
}
${expansionType}
type ${connectionNodePrefi}_ExpandedConInput = ExpandRecursively<ConnectionInput.${mainTypeName}>
type ${nodeTypePrefix}_ExpandedNodeInput = ExpandRecursively<${nodeTypePrefix}_NodeInput.${mainTypeName}>
declare let cinInput:${connectionNodePrefi}_ExpandedConInput
const nodeInput: ${nodeTypePrefix}_ExpandedNodeInput = cinInput
type ResultType=${nodeTypePrefix}_NodeInput.${mainTypeName}
}
`;
// writeFile(join(typeData, `${node.uuid}__${connectionNode.uuid}.ts`), str)
await validate(`connections_to_${node.uuid}`, str, `${node.type}-${node.uuid}-con input check`)
delete con.error
} catch (e) {
if (e instanceof SchemaMatchingError) {
con.error = e.toMessageString()
} else {
let firstError = e as DiagnosticRelatedInformation | DiagnosticMessageChain
if (e instanceof CompilerError) {
firstError = e.error_diagnostics[0] as Diagnostic
}
while (typeof firstError.messageText != "string" && firstError.messageText?.next?.[0]) {
firstError = firstError.messageText.next?.[0]
}
if (typeof firstError.messageText == "string") {
let messageText = firstError.messageText
for (const subType of ["ExpandedConInput", "ExpandedNodeInput"])
if (messageText.includes(subType)) {
const subSchema = generateSchema(e.program, subType, { ignoreErrors: true })
if (subSchema) {
let dtsrelace = await generateDtsFromSchema(subSchema as ExtendedJsonSchema, `${node.type}-${node.uuid}-err handling resolve`)
dtsrelace = dtsrelace.trim().replace("export type Main = ", "").replace(/;$/, "").trim()
messageText = messageText.replace(subType, dtsrelace)
}
}
con.error = messageText
} else {
debugger;
}
}
}
}
return {
schema: compSchema,
nodeUuidType: nodeTypeName(connectionNode)
}
}))
const filteredSchemas = schemata.filter((sch): sch is NonNullable<typeof sch> => !!sch?.schema)
if (filteredSchemas.length > 0) {
schema = filteredSchemas[0].schema || null
if (filteredSchemas.length > 1) {
const schemaDtss = filteredSchemas.map(schema => `
namespace ${schema.nodeUuidType} {
${schema.schema?.dts}
}
`)
const mergingDts = `
${schemaDtss.join("\n\n")}
type ${mainTypeName}=${filteredSchemas.map(s => `${s.nodeUuidType}.${mainTypeName}`).join("|")}
`
try {
const mergedSchema = await getTypes(mergingDts, mainTypeName, `connection-type-merge-${node.uuid}`)
allRequired(mergedSchema)
schema = {
jsonSchema: mergedSchema,
mainTypeName: mainTypeName,
dts: await generateDtsFromSchema(mergedSchema)
}
} catch (e) {
const err = new Error("error getting merged type for " + filteredSchemas.length + " connections on node " + nodeDescriptor(node), { cause: e, });
err["mergingDts"] = mergingDts
throw err
}
}
}
}
if (schema == null) {
schema = {
dts: `type ${mainTypeName}=any`,
//zodValidator: z.never(),
jsonSchema: {},
mainTypeName: "Main"
}
}
if (!schema?.dts) {
logKibana("WARN", "no schema")
return
}
const nodeTypeImplemenations = nodeData.typeImpls[node.type]
await nodeTypeImplemenations.connectionTypeChanged?.(node, schema);
if (node.runtimeContext?.editorSchema?.dts) {
writeFile(join(typeData, `editorschema_${node.uuid}.ts`), node.runtimeContext?.editorSchema.dts)
}
const outConnections = nodeData.connectorMap[node.uuid]
if (outConnections) {
for (const connectorIndex in outConnections) {
for (const connector of outConnections[connectorIndex]) {
try {
await updateTypeSchema(nodeData.nodeMap[connector.uuid], nodeData)
} catch (e) {
throw new Error("error validating node " + connector.uuid, {
cause: e
})
}
}
}
}
}